]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/net/https/axTLS/ssl/asn1.c
Merge pull request #34 from jackhumbert/tmk-master
[qmk_firmware.git] / tmk_core / tool / mbed / mbed-sdk / libraries / net / https / axTLS / ssl / asn1.c
1 /*
2  * Copyright (c) 2007, Cameron Rich
3  * 
4  * All rights reserved.
5  * 
6  * Redistribution and use in source and binary forms, with or without 
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * * Redistributions of source code must retain the above copyright notice, 
10  *   this list of conditions and the following disclaimer.
11  * * Redistributions in binary form must reproduce the above copyright notice, 
12  *   this list of conditions and the following disclaimer in the documentation 
13  *   and/or other materials provided with the distribution.
14  * * Neither the name of the axTLS project nor the names of its contributors 
15  *   may be used to endorse or promote products derived from this software 
16  *   without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 /**
32  * Some primitive asn methods for extraction ASN.1 data.
33  */
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39 #include "os_port.h"
40 #include "crypto.h"
41 #include "crypto_misc.h"
42 #include "config.h"
43
44 #define SIG_OID_PREFIX_SIZE 8
45 #define SIG_IIS6_OID_SIZE   5
46 #define SIG_SUBJECT_ALT_NAME_SIZE 3
47
48 /* Must be an RSA algorithm with either SHA1 or MD5 for verifying to work */
49 static const uint8_t sig_oid_prefix[SIG_OID_PREFIX_SIZE] = 
50 {
51     0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01
52 };
53
54 static const uint8_t sig_sha1WithRSAEncrypt[SIG_IIS6_OID_SIZE] =
55 {
56     0x2b, 0x0e, 0x03, 0x02, 0x1d
57 };
58
59 static const uint8_t sig_subject_alt_name[SIG_SUBJECT_ALT_NAME_SIZE] =
60 {
61     0x55, 0x1d, 0x11
62 };
63
64 /* CN, O, OU */
65 static const uint8_t g_dn_types[] = { 3, 10, 11 };
66
67 int get_asn1_length(const uint8_t *buf, int *offset)
68 {
69     int len, i;
70
71     if (!(buf[*offset] & 0x80)) /* short form */
72     {
73         len = buf[(*offset)++];
74     }
75     else  /* long form */
76     {
77         int length_bytes = buf[(*offset)++]&0x7f;
78         len = 0;
79         for (i = 0; i < length_bytes; i++)
80         {
81             len <<= 8;
82             len += buf[(*offset)++];
83         }
84     }
85
86     return len;
87 }
88
89 /**
90  * Skip the ASN1.1 object type and its length. Get ready to read the object's
91  * data.
92  */
93 int asn1_next_obj(const uint8_t *buf, int *offset, int obj_type)
94 {
95     if (buf[*offset] != obj_type)
96         return X509_NOT_OK;
97     (*offset)++;
98     int tmp = get_asn1_length(buf, offset);
99     return tmp;
100 }
101
102 /**
103  * Skip over an ASN.1 object type completely. Get ready to read the next
104  * object.
105  */
106 int asn1_skip_obj(const uint8_t *buf, int *offset, int obj_type)
107 {
108     int len;
109     if (buf[*offset] != obj_type)
110         return X509_NOT_OK;
111     (*offset)++;
112     len = get_asn1_length(buf, offset);
113     *offset += len;
114     return 0;
115 }
116
117 /**
118  * Read an integer value for ASN.1 data
119  * Note: This function allocates memory which must be freed by the user.
120  */
121 int asn1_get_int(const uint8_t *buf, int *offset, uint8_t **object)
122 {
123     int len;
124
125     if ((len = asn1_next_obj(buf, offset, ASN1_INTEGER)) < 0)
126         goto end_int_array;
127
128     if (len > 1 && buf[*offset] == 0x00)    /* ignore the negative byte */
129     {
130         len--;
131         (*offset)++;
132     }
133
134     *object = (uint8_t *)malloc(len);
135     memcpy(*object, &buf[*offset], len);
136     *offset += len;
137
138 end_int_array:
139     return len;
140 }
141
142 /**
143  * Get all the RSA private key specifics from an ASN.1 encoded file 
144  */
145 int asn1_get_private_key(const uint8_t *buf, int len, RSA_CTX **rsa_ctx)
146 {
147     int offset = 7;
148     uint8_t *modulus = NULL, *priv_exp = NULL, *pub_exp = NULL;
149     int mod_len, priv_len, pub_len;
150 #ifdef CONFIG_BIGINT_CRT
151     uint8_t *p = NULL, *q = NULL, *dP = NULL, *dQ = NULL, *qInv = NULL;
152     int p_len, q_len, dP_len, dQ_len, qInv_len;
153 #endif
154
155     /* not in der format */
156     if (buf[0] != ASN1_SEQUENCE) /* basic sanity check */
157     {
158 #ifdef CONFIG_SSL_FULL_MODE
159         printf("Error: This is not a valid ASN.1 file\n");
160 #endif
161         return X509_INVALID_PRIV_KEY;
162     }
163
164     /* Use the private key to mix up the RNG if possible. */
165     RNG_custom_init(buf, len);
166
167     mod_len = asn1_get_int(buf, &offset, &modulus);
168     pub_len = asn1_get_int(buf, &offset, &pub_exp);
169     priv_len = asn1_get_int(buf, &offset, &priv_exp);
170
171     if (mod_len <= 0 || pub_len <= 0 || priv_len <= 0)
172         return X509_INVALID_PRIV_KEY;
173
174 #ifdef CONFIG_BIGINT_CRT
175     p_len = asn1_get_int(buf, &offset, &p);
176     q_len = asn1_get_int(buf, &offset, &q);
177     dP_len = asn1_get_int(buf, &offset, &dP);
178     dQ_len = asn1_get_int(buf, &offset, &dQ);
179     qInv_len = asn1_get_int(buf, &offset, &qInv);
180
181     if (p_len <= 0 || q_len <= 0 || dP_len <= 0 || dQ_len <= 0 || qInv_len <= 0)
182         return X509_INVALID_PRIV_KEY;
183
184     RSA_priv_key_new(rsa_ctx, 
185             modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len,
186             p, p_len, q, p_len, dP, dP_len, dQ, dQ_len, qInv, qInv_len);
187
188     free(p);
189     free(q);
190     free(dP);
191     free(dQ);
192     free(qInv);
193 #else
194     RSA_priv_key_new(rsa_ctx, 
195             modulus, mod_len, pub_exp, pub_len, priv_exp, priv_len);
196 #endif
197
198     free(modulus);
199     free(priv_exp);
200     free(pub_exp);
201     return X509_OK;
202 }
203
204 /**
205  * Get the time of a certificate. Ignore hours/minutes/seconds.
206  */
207 static int asn1_get_utc_time(const uint8_t *buf, int *offset, time_t *t)
208 {
209     int ret = X509_NOT_OK, len, t_offset;
210     struct tm tm;
211
212     if (buf[(*offset)++] != ASN1_UTC_TIME)
213         goto end_utc_time;
214
215     len = get_asn1_length(buf, offset);
216     t_offset = *offset;
217
218     memset(&tm, 0, sizeof(struct tm));
219     tm.tm_year = (buf[t_offset] - '0')*10 + (buf[t_offset+1] - '0');
220
221     if (tm.tm_year <= 50)    /* 1951-2050 thing */
222     {
223         tm.tm_year += 100;
224     }
225
226     tm.tm_mon = (buf[t_offset+2] - '0')*10 + (buf[t_offset+3] - '0') - 1;
227     tm.tm_mday = (buf[t_offset+4] - '0')*10 + (buf[t_offset+5] - '0');
228     *t = mktime(&tm);
229     *offset += len;
230     ret = X509_OK;
231
232 end_utc_time:
233     return ret;
234 }
235
236 /**
237  * Get the version type of a certificate (which we don't actually care about)
238  */
239 int asn1_version(const uint8_t *cert, int *offset, X509_CTX *x509_ctx)
240 {
241     int ret = X509_NOT_OK;
242
243     (*offset) += 2;        /* get past explicit tag */
244     if (asn1_skip_obj(cert, offset, ASN1_INTEGER))
245         goto end_version;
246
247     ret = X509_OK;
248 end_version:
249     return ret;
250 }
251
252 /**
253  * Retrieve the notbefore and notafter certificate times.
254  */
255 int asn1_validity(const uint8_t *cert, int *offset, X509_CTX *x509_ctx)
256 {
257     return (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 ||
258               asn1_get_utc_time(cert, offset, &x509_ctx->not_before) ||
259               asn1_get_utc_time(cert, offset, &x509_ctx->not_after));
260 }
261
262 /**
263  * Get the components of a distinguished name 
264  */
265 static int asn1_get_oid_x520(const uint8_t *buf, int *offset)
266 {
267     int dn_type = 0;
268     int len;
269
270     if ((len = asn1_next_obj(buf, offset, ASN1_OID)) < 0)
271         goto end_oid;
272
273     /* expect a sequence of 2.5.4.[x] where x is a one of distinguished name 
274        components we are interested in. */
275     if (len == 3 && buf[(*offset)++] == 0x55 && buf[(*offset)++] == 0x04)
276         dn_type = buf[(*offset)++];
277     else
278     {
279         *offset += len;     /* skip over it */
280     }
281
282 end_oid:
283     return dn_type;
284 }
285
286 /**
287  * Obtain an ASN.1 printable string type.
288  */
289 static int asn1_get_printable_str(const uint8_t *buf, int *offset, char **str)
290 {
291     int len = X509_NOT_OK;
292     int asn1_type = buf[*offset];
293
294     /* some certs have this awful crud in them for some reason */
295     if (asn1_type != ASN1_PRINTABLE_STR &&  
296             asn1_type != ASN1_PRINTABLE_STR2 &&  
297             asn1_type != ASN1_TELETEX_STR &&  
298             asn1_type != ASN1_IA5_STR &&  
299             asn1_type != ASN1_UNICODE_STR)
300         goto end_pnt_str;
301
302     (*offset)++;
303     len = get_asn1_length(buf, offset);
304
305     if (asn1_type == ASN1_UNICODE_STR)
306     {
307         int i;
308         *str = (char *)malloc(len/2+1);     /* allow for null */
309
310         for (i = 0; i < len; i += 2)
311             (*str)[i/2] = buf[*offset + i + 1];
312
313         (*str)[len/2] = 0;                  /* null terminate */
314     }
315     else
316     {
317         *str = (char *)malloc(len+1);       /* allow for null */
318         memcpy(*str, &buf[*offset], len);
319         (*str)[len] = 0;                    /* null terminate */
320     }
321
322     *offset += len;
323
324 end_pnt_str:
325     return len;
326 }
327
328 /**
329  * Get the subject name (or the issuer) of a certificate.
330  */
331 int asn1_name(const uint8_t *cert, int *offset, char *dn[])
332 {
333     int ret = X509_NOT_OK;
334     int dn_type;
335     char *tmp;
336
337     if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0)
338         goto end_name;
339
340     while (asn1_next_obj(cert, offset, ASN1_SET) >= 0)
341     {
342         int i, found = 0;
343
344         if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 ||
345                (dn_type = asn1_get_oid_x520(cert, offset)) < 0)
346             goto end_name;
347
348         tmp = NULL;
349
350         if (asn1_get_printable_str(cert, offset, &tmp) < 0)
351         {
352             free(tmp);
353             goto end_name;
354         }
355
356         /* find the distinguished named type */
357         for (i = 0; i < X509_NUM_DN_TYPES; i++)
358         {
359             if (dn_type == g_dn_types[i])
360             {
361                 if (dn[i] == NULL)
362                 {
363                     dn[i] = tmp;
364                     found = 1;
365                     break;
366                 }
367             }
368         }
369
370         if (found == 0) /* not found so get rid of it */
371         {
372             free(tmp);
373         }
374     }
375
376     ret = X509_OK;
377 end_name:
378     return ret;
379 }
380
381 /**
382  * Read the modulus and public exponent of a certificate.
383  */
384 int asn1_public_key(const uint8_t *cert, int *offset, X509_CTX *x509_ctx)
385 {
386     int ret = X509_NOT_OK, mod_len, pub_len;
387     uint8_t *modulus = NULL, *pub_exp = NULL;
388
389     if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0 ||
390             asn1_skip_obj(cert, offset, ASN1_SEQUENCE) ||
391             asn1_next_obj(cert, offset, ASN1_BIT_STRING) < 0)
392         goto end_pub_key;
393
394     (*offset)++;        /* ignore the padding bit field */
395
396     if (asn1_next_obj(cert, offset, ASN1_SEQUENCE) < 0)
397         goto end_pub_key;
398     
399     mod_len = asn1_get_int(cert, offset, &modulus);
400     pub_len = asn1_get_int(cert, offset, &pub_exp);
401     RSA_pub_key_new(&x509_ctx->rsa_ctx, modulus, mod_len, pub_exp, pub_len);
402     free(modulus);
403     free(pub_exp);
404     ret = X509_OK;
405     
406 end_pub_key:
407     return ret;
408 }
409
410 #ifdef CONFIG_SSL_CERT_VERIFICATION
411 /**
412  * Read the signature of the certificate.
413  */
414 int asn1_signature(const uint8_t *cert, int *offset, X509_CTX *x509_ctx)
415 {
416     int ret = X509_NOT_OK;
417
418     if (cert[(*offset)++] != ASN1_BIT_STRING)
419         goto end_sig;
420
421     x509_ctx->sig_len = get_asn1_length(cert, offset)-1;
422     (*offset)++;            /* ignore bit string padding bits */
423     x509_ctx->signature = (uint8_t *)malloc(x509_ctx->sig_len);
424     memcpy(x509_ctx->signature, &cert[*offset], x509_ctx->sig_len);
425     *offset += x509_ctx->sig_len;
426     ret = X509_OK;
427
428 end_sig:
429     return ret;
430 }
431
432 /*
433  * Compare 2 distinguished name components for equality 
434  * @return 0 if a match
435  */
436 static int asn1_compare_dn_comp(const char *dn1, const char *dn2)
437 {
438     int ret;
439
440     if (dn1 == NULL && dn2 == NULL)
441         ret = 0;
442     else
443         ret = (dn1 && dn2) ? strcmp(dn1, dn2) : 1;
444
445     return ret;
446 }
447
448 /**
449  * Clean up all of the CA certificates.
450  */
451 void remove_ca_certs(CA_CERT_CTX *ca_cert_ctx)
452 {
453     int i = 0;
454
455     if (ca_cert_ctx == NULL)
456         return;
457
458     while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
459     {
460         x509_free(ca_cert_ctx->cert[i]);
461         ca_cert_ctx->cert[i++] = NULL;
462     }
463
464     free(ca_cert_ctx);
465 }
466
467 /*
468  * Compare 2 distinguished names for equality 
469  * @return 0 if a match
470  */
471 int asn1_compare_dn(char * const dn1[], char * const dn2[])
472 {
473     int i;
474
475     for (i = 0; i < X509_NUM_DN_TYPES; i++)
476     {
477         if (asn1_compare_dn_comp(dn1[i], dn2[i]))
478             return 1;
479     }
480
481     return 0;       /* all good */
482 }
483
484 int asn1_find_oid(const uint8_t* cert, int* offset, 
485                     const uint8_t* oid, int oid_length)
486 {
487     int seqlen;
488     if ((seqlen = asn1_next_obj(cert, offset, ASN1_SEQUENCE))> 0)
489     {
490         int end = *offset + seqlen;
491
492         while (*offset < end)
493         {
494             int type = cert[(*offset)++];
495             int length = get_asn1_length(cert, offset);
496             int noffset = *offset + length;
497
498             if (type == ASN1_SEQUENCE)
499             {
500                 type = cert[(*offset)++];
501                 length = get_asn1_length(cert, offset);
502
503                 if (type == ASN1_OID && length == oid_length && 
504                               memcmp(cert + *offset, oid, oid_length) == 0)
505                 {
506                     *offset += oid_length;
507                     return 1;
508                 }
509             }
510
511             *offset = noffset;
512         }
513     }
514
515     return 0;
516 }
517
518 int asn1_find_subjectaltname(const uint8_t* cert, int offset)
519 {
520     if (asn1_find_oid(cert, &offset, sig_subject_alt_name, 
521                                 SIG_SUBJECT_ALT_NAME_SIZE))
522     {
523         return offset;
524     }
525
526     return 0;
527 }
528
529 #endif /* CONFIG_SSL_CERT_VERIFICATION */
530
531 /**
532  * Read the signature type of the certificate. We only support RSA-MD5 and
533  * RSA-SHA1 signature types.
534  */
535 int asn1_signature_type(const uint8_t *cert, 
536                                 int *offset, X509_CTX *x509_ctx)
537 {
538     int ret = X509_NOT_OK, len;
539
540     if (cert[(*offset)++] != ASN1_OID)
541         goto end_check_sig;
542
543     len = get_asn1_length(cert, offset);
544
545     if (len == 5 && memcmp(sig_sha1WithRSAEncrypt, &cert[*offset], 
546                                     SIG_IIS6_OID_SIZE) == 0)
547     {
548         x509_ctx->sig_type = SIG_TYPE_SHA1;
549     }
550     else
551     {
552         if (memcmp(sig_oid_prefix, &cert[*offset], SIG_OID_PREFIX_SIZE))
553             goto end_check_sig;     /* unrecognised cert type */
554
555         x509_ctx->sig_type = cert[*offset + SIG_OID_PREFIX_SIZE];
556     }
557
558     *offset += len;
559     asn1_skip_obj(cert, offset, ASN1_NULL); /* if it's there */
560     ret = X509_OK;
561
562 end_check_sig:
563     return ret;
564 }
565