• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  X.509 common functions for parsing and verification
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 /*
8  *  The ITU-T X.509 standard defines a certificate format for PKI.
9  *
10  *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
11  *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
12  *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
13  *
14  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
15  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
16  */
17 
18 #include "common.h"
19 
20 #if defined(MBEDTLS_X509_USE_C)
21 
22 #include "mbedtls/x509.h"
23 #include "mbedtls/asn1.h"
24 #include "mbedtls/error.h"
25 #include "mbedtls/oid.h"
26 
27 #include <stdio.h>
28 #include <string.h>
29 
30 #if defined(MBEDTLS_PEM_PARSE_C)
31 #include "mbedtls/pem.h"
32 #endif
33 
34 #include "mbedtls/platform.h"
35 
36 #if defined(MBEDTLS_HAVE_TIME)
37 #include "mbedtls/platform_time.h"
38 #endif
39 #if defined(MBEDTLS_HAVE_TIME_DATE)
40 #include "mbedtls/platform_util.h"
41 #include <time.h>
42 #endif
43 
44 #define CHECK(code)                                     \
45     do {                                                \
46         if ((ret = (code)) != 0) {                      \
47             return ret;                                 \
48         }                                               \
49     } while (0)
50 
51 #define CHECK_RANGE(min, max, val)                      \
52     do {                                                \
53         if ((val) < (min) || (val) > (max)) {           \
54             return ret;                                 \
55         }                                               \
56     } while (0)
57 
58 /*
59  *  CertificateSerialNumber  ::=  INTEGER
60  */
mbedtls_x509_get_serial(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * serial)61 int mbedtls_x509_get_serial(unsigned char **p, const unsigned char *end,
62                             mbedtls_x509_buf *serial)
63 {
64     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
65 
66     if ((end - *p) < 1) {
67         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL,
68                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
69     }
70 
71     if (**p != (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2) &&
72         **p !=   MBEDTLS_ASN1_INTEGER) {
73         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL,
74                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
75     }
76 
77     serial->tag = *(*p)++;
78 
79     if ((ret = mbedtls_asn1_get_len(p, end, &serial->len)) != 0) {
80         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL, ret);
81     }
82 
83     serial->p = *p;
84     *p += serial->len;
85 
86     return 0;
87 }
88 
89 /* Get an algorithm identifier without parameters (eg for signatures)
90  *
91  *  AlgorithmIdentifier  ::=  SEQUENCE  {
92  *       algorithm               OBJECT IDENTIFIER,
93  *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
94  */
mbedtls_x509_get_alg_null(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg)95 int mbedtls_x509_get_alg_null(unsigned char **p, const unsigned char *end,
96                               mbedtls_x509_buf *alg)
97 {
98     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
99 
100     if ((ret = mbedtls_asn1_get_alg_null(p, end, alg)) != 0) {
101         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
102     }
103 
104     return 0;
105 }
106 
107 /*
108  * Parse an algorithm identifier with (optional) parameters
109  */
mbedtls_x509_get_alg(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg,mbedtls_x509_buf * params)110 int mbedtls_x509_get_alg(unsigned char **p, const unsigned char *end,
111                          mbedtls_x509_buf *alg, mbedtls_x509_buf *params)
112 {
113     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
114 
115     if ((ret = mbedtls_asn1_get_alg(p, end, alg, params)) != 0) {
116         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
117     }
118 
119     return 0;
120 }
121 
122 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
123 /*
124  * HashAlgorithm ::= AlgorithmIdentifier
125  *
126  * AlgorithmIdentifier  ::=  SEQUENCE  {
127  *      algorithm               OBJECT IDENTIFIER,
128  *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
129  *
130  * For HashAlgorithm, parameters MUST be NULL or absent.
131  */
x509_get_hash_alg(const mbedtls_x509_buf * alg,mbedtls_md_type_t * md_alg)132 static int x509_get_hash_alg(const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg)
133 {
134     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
135     unsigned char *p;
136     const unsigned char *end;
137     mbedtls_x509_buf md_oid;
138     size_t len;
139 
140     /* Make sure we got a SEQUENCE and setup bounds */
141     if (alg->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
142         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
143                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
144     }
145 
146     p = alg->p;
147     end = p + alg->len;
148 
149     if (p >= end) {
150         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
151                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
152     }
153 
154     /* Parse md_oid */
155     md_oid.tag = *p;
156 
157     if ((ret = mbedtls_asn1_get_tag(&p, end, &md_oid.len, MBEDTLS_ASN1_OID)) != 0) {
158         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
159     }
160 
161     md_oid.p = p;
162     p += md_oid.len;
163 
164     /* Get md_alg from md_oid */
165     if ((ret = mbedtls_oid_get_md_alg(&md_oid, md_alg)) != 0) {
166         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
167     }
168 
169     /* Make sure params is absent of NULL */
170     if (p == end) {
171         return 0;
172     }
173 
174     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_NULL)) != 0 || len != 0) {
175         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
176     }
177 
178     if (p != end) {
179         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
180                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
181     }
182 
183     return 0;
184 }
185 
186 /*
187  *    RSASSA-PSS-params  ::=  SEQUENCE  {
188  *       hashAlgorithm     [0] HashAlgorithm DEFAULT sha1Identifier,
189  *       maskGenAlgorithm  [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
190  *       saltLength        [2] INTEGER DEFAULT 20,
191  *       trailerField      [3] INTEGER DEFAULT 1  }
192  *    -- Note that the tags in this Sequence are explicit.
193  *
194  * RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value
195  * of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other
196  * option. Enforce this at parsing time.
197  */
mbedtls_x509_get_rsassa_pss_params(const mbedtls_x509_buf * params,mbedtls_md_type_t * md_alg,mbedtls_md_type_t * mgf_md,int * salt_len)198 int mbedtls_x509_get_rsassa_pss_params(const mbedtls_x509_buf *params,
199                                        mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
200                                        int *salt_len)
201 {
202     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
203     unsigned char *p;
204     const unsigned char *end, *end2;
205     size_t len;
206     mbedtls_x509_buf alg_id, alg_params;
207 
208     /* First set everything to defaults */
209     *md_alg = MBEDTLS_MD_SHA1;
210     *mgf_md = MBEDTLS_MD_SHA1;
211     *salt_len = 20;
212 
213     /* Make sure params is a SEQUENCE and setup bounds */
214     if (params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
215         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
216                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
217     }
218 
219     p = (unsigned char *) params->p;
220     end = p + params->len;
221 
222     if (p == end) {
223         return 0;
224     }
225 
226     /*
227      * HashAlgorithm
228      */
229     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
230                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
231                                     0)) == 0) {
232         end2 = p + len;
233 
234         /* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */
235         if ((ret = mbedtls_x509_get_alg_null(&p, end2, &alg_id)) != 0) {
236             return ret;
237         }
238 
239         if ((ret = mbedtls_oid_get_md_alg(&alg_id, md_alg)) != 0) {
240             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
241         }
242 
243         if (p != end2) {
244             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
245                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
246         }
247     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
248         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
249     }
250 
251     if (p == end) {
252         return 0;
253     }
254 
255     /*
256      * MaskGenAlgorithm
257      */
258     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
259                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
260                                     1)) == 0) {
261         end2 = p + len;
262 
263         /* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */
264         if ((ret = mbedtls_x509_get_alg(&p, end2, &alg_id, &alg_params)) != 0) {
265             return ret;
266         }
267 
268         /* Only MFG1 is recognised for now */
269         if (MBEDTLS_OID_CMP(MBEDTLS_OID_MGF1, &alg_id) != 0) {
270             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE,
271                                      MBEDTLS_ERR_OID_NOT_FOUND);
272         }
273 
274         /* Parse HashAlgorithm */
275         if ((ret = x509_get_hash_alg(&alg_params, mgf_md)) != 0) {
276             return ret;
277         }
278 
279         if (p != end2) {
280             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
281                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
282         }
283     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
284         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
285     }
286 
287     if (p == end) {
288         return 0;
289     }
290 
291     /*
292      * salt_len
293      */
294     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
295                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
296                                     2)) == 0) {
297         end2 = p + len;
298 
299         if ((ret = mbedtls_asn1_get_int(&p, end2, salt_len)) != 0) {
300             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
301         }
302 
303         if (p != end2) {
304             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
305                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
306         }
307     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
308         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
309     }
310 
311     if (p == end) {
312         return 0;
313     }
314 
315     /*
316      * trailer_field (if present, must be 1)
317      */
318     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
319                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
320                                     3)) == 0) {
321         int trailer_field;
322 
323         end2 = p + len;
324 
325         if ((ret = mbedtls_asn1_get_int(&p, end2, &trailer_field)) != 0) {
326             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
327         }
328 
329         if (p != end2) {
330             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
331                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
332         }
333 
334         if (trailer_field != 1) {
335             return MBEDTLS_ERR_X509_INVALID_ALG;
336         }
337     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
338         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
339     }
340 
341     if (p != end) {
342         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
343                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
344     }
345 
346     return 0;
347 }
348 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
349 
350 /*
351  *  AttributeTypeAndValue ::= SEQUENCE {
352  *    type     AttributeType,
353  *    value    AttributeValue }
354  *
355  *  AttributeType ::= OBJECT IDENTIFIER
356  *
357  *  AttributeValue ::= ANY DEFINED BY AttributeType
358  */
x509_get_attr_type_value(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)359 static int x509_get_attr_type_value(unsigned char **p,
360                                     const unsigned char *end,
361                                     mbedtls_x509_name *cur)
362 {
363     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
364     size_t len;
365     mbedtls_x509_buf *oid;
366     mbedtls_x509_buf *val;
367 
368     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
369                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
370         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
371     }
372 
373     end = *p + len;
374 
375     if ((end - *p) < 1) {
376         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
377                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
378     }
379 
380     oid = &cur->oid;
381     oid->tag = **p;
382 
383     if ((ret = mbedtls_asn1_get_tag(p, end, &oid->len, MBEDTLS_ASN1_OID)) != 0) {
384         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
385     }
386 
387     oid->p = *p;
388     *p += oid->len;
389 
390     if ((end - *p) < 1) {
391         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
392                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
393     }
394 
395     if (**p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING      &&
396         **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING &&
397         **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING &&
398         **p != MBEDTLS_ASN1_BIT_STRING) {
399         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
400                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
401     }
402 
403     val = &cur->val;
404     val->tag = *(*p)++;
405 
406     if ((ret = mbedtls_asn1_get_len(p, end, &val->len)) != 0) {
407         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
408     }
409 
410     val->p = *p;
411     *p += val->len;
412 
413     if (*p != end) {
414         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
415                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
416     }
417 
418     cur->next = NULL;
419 
420     return 0;
421 }
422 
423 /*
424  *  Name ::= CHOICE { -- only one possibility for now --
425  *       rdnSequence  RDNSequence }
426  *
427  *  RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
428  *
429  *  RelativeDistinguishedName ::=
430  *    SET OF AttributeTypeAndValue
431  *
432  *  AttributeTypeAndValue ::= SEQUENCE {
433  *    type     AttributeType,
434  *    value    AttributeValue }
435  *
436  *  AttributeType ::= OBJECT IDENTIFIER
437  *
438  *  AttributeValue ::= ANY DEFINED BY AttributeType
439  *
440  * The data structure is optimized for the common case where each RDN has only
441  * one element, which is represented as a list of AttributeTypeAndValue.
442  * For the general case we still use a flat list, but we mark elements of the
443  * same set so that they are "merged" together in the functions that consume
444  * this list, eg mbedtls_x509_dn_gets().
445  *
446  * On success, this function may allocate a linked list starting at cur->next
447  * that must later be free'd by the caller using mbedtls_free(). In error
448  * cases, this function frees all allocated memory internally and the caller
449  * has no freeing responsibilities.
450  */
mbedtls_x509_get_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)451 int mbedtls_x509_get_name(unsigned char **p, const unsigned char *end,
452                           mbedtls_x509_name *cur)
453 {
454     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
455     size_t set_len;
456     const unsigned char *end_set;
457     mbedtls_x509_name *head = cur;
458     mbedtls_x509_name *prev, *allocated;
459 
460     /* don't use recursion, we'd risk stack overflow if not optimized */
461     while (1) {
462         /*
463          * parse SET
464          */
465         if ((ret = mbedtls_asn1_get_tag(p, end, &set_len,
466                                         MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET)) != 0) {
467             ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
468             goto error;
469         }
470 
471         end_set  = *p + set_len;
472 
473         while (1) {
474             if ((ret = x509_get_attr_type_value(p, end_set, cur)) != 0) {
475                 goto error;
476             }
477 
478             if (*p == end_set) {
479                 break;
480             }
481 
482             /* Mark this item as being no the only one in a set */
483             cur->next_merged = 1;
484 
485             cur->next = mbedtls_calloc(1, sizeof(mbedtls_x509_name));
486 
487             if (cur->next == NULL) {
488                 ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
489                 goto error;
490             }
491 
492             cur = cur->next;
493         }
494 
495         /*
496          * continue until end of SEQUENCE is reached
497          */
498         if (*p == end) {
499             return 0;
500         }
501 
502         cur->next = mbedtls_calloc(1, sizeof(mbedtls_x509_name));
503 
504         if (cur->next == NULL) {
505             ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
506             goto error;
507         }
508 
509         cur = cur->next;
510     }
511 
512 error:
513     /* Skip the first element as we did not allocate it */
514     allocated = head->next;
515 
516     while (allocated != NULL) {
517         prev = allocated;
518         allocated = allocated->next;
519 
520         mbedtls_platform_zeroize(prev, sizeof(*prev));
521         mbedtls_free(prev);
522     }
523 
524     mbedtls_platform_zeroize(head, sizeof(*head));
525 
526     return ret;
527 }
528 
x509_parse_int(unsigned char ** p,size_t n,int * res)529 static int x509_parse_int(unsigned char **p, size_t n, int *res)
530 {
531     *res = 0;
532 
533     for (; n > 0; --n) {
534         if ((**p < '0') || (**p > '9')) {
535             return MBEDTLS_ERR_X509_INVALID_DATE;
536         }
537 
538         *res *= 10;
539         *res += (*(*p)++ - '0');
540     }
541 
542     return 0;
543 }
544 
x509_date_is_valid(const mbedtls_x509_time * t)545 static int x509_date_is_valid(const mbedtls_x509_time *t)
546 {
547     int ret = MBEDTLS_ERR_X509_INVALID_DATE;
548     int month_len;
549 
550     CHECK_RANGE(0, 9999, t->year);
551     CHECK_RANGE(0, 23,   t->hour);
552     CHECK_RANGE(0, 59,   t->min);
553     CHECK_RANGE(0, 59,   t->sec);
554 
555     switch (t->mon) {
556         case 1: case 3: case 5: case 7: case 8: case 10: case 12:
557             month_len = 31;
558             break;
559         case 4: case 6: case 9: case 11:
560             month_len = 30;
561             break;
562         case 2:
563             if ((!(t->year % 4) && t->year % 100) ||
564                 !(t->year % 400)) {
565                 month_len = 29;
566             } else {
567                 month_len = 28;
568             }
569             break;
570         default:
571             return ret;
572     }
573     CHECK_RANGE(1, month_len, t->day);
574 
575     return 0;
576 }
577 
578 /*
579  * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4)
580  * field.
581  */
x509_parse_time(unsigned char ** p,size_t len,size_t yearlen,mbedtls_x509_time * tm)582 static int x509_parse_time(unsigned char **p, size_t len, size_t yearlen,
583                            mbedtls_x509_time *tm)
584 {
585     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
586 
587     /*
588      * Minimum length is 10 or 12 depending on yearlen
589      */
590     if (len < yearlen + 8) {
591         return MBEDTLS_ERR_X509_INVALID_DATE;
592     }
593     len -= yearlen + 8;
594 
595     /*
596      * Parse year, month, day, hour, minute
597      */
598     CHECK(x509_parse_int(p, yearlen, &tm->year));
599     if (2 == yearlen) {
600         if (tm->year < 50) {
601             tm->year += 100;
602         }
603 
604         tm->year += 1900;
605     }
606 
607     CHECK(x509_parse_int(p, 2, &tm->mon));
608     CHECK(x509_parse_int(p, 2, &tm->day));
609     CHECK(x509_parse_int(p, 2, &tm->hour));
610     CHECK(x509_parse_int(p, 2, &tm->min));
611 
612     /*
613      * Parse seconds if present
614      */
615     if (len >= 2) {
616         CHECK(x509_parse_int(p, 2, &tm->sec));
617         len -= 2;
618     } else {
619         return MBEDTLS_ERR_X509_INVALID_DATE;
620     }
621 
622     /*
623      * Parse trailing 'Z' if present
624      */
625     if (1 == len && 'Z' == **p) {
626         (*p)++;
627         len--;
628     }
629 
630     /*
631      * We should have parsed all characters at this point
632      */
633     if (0 != len) {
634         return MBEDTLS_ERR_X509_INVALID_DATE;
635     }
636 
637     CHECK(x509_date_is_valid(tm));
638 
639     return 0;
640 }
641 
642 /*
643  *  Time ::= CHOICE {
644  *       utcTime        UTCTime,
645  *       generalTime    GeneralizedTime }
646  */
mbedtls_x509_get_time(unsigned char ** p,const unsigned char * end,mbedtls_x509_time * tm)647 int mbedtls_x509_get_time(unsigned char **p, const unsigned char *end,
648                           mbedtls_x509_time *tm)
649 {
650     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
651     size_t len, year_len;
652     unsigned char tag;
653 
654     if ((end - *p) < 1) {
655         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE,
656                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
657     }
658 
659     tag = **p;
660 
661     if (tag == MBEDTLS_ASN1_UTC_TIME) {
662         year_len = 2;
663     } else if (tag == MBEDTLS_ASN1_GENERALIZED_TIME) {
664         year_len = 4;
665     } else {
666         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE,
667                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
668     }
669 
670     (*p)++;
671     ret = mbedtls_asn1_get_len(p, end, &len);
672 
673     if (ret != 0) {
674         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE, ret);
675     }
676 
677     return x509_parse_time(p, len, year_len, tm);
678 }
679 
mbedtls_x509_get_sig(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * sig)680 int mbedtls_x509_get_sig(unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig)
681 {
682     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
683     size_t len;
684     int tag_type;
685 
686     if ((end - *p) < 1) {
687         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SIGNATURE,
688                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
689     }
690 
691     tag_type = **p;
692 
693     if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
694         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SIGNATURE, ret);
695     }
696 
697     sig->tag = tag_type;
698     sig->len = len;
699     sig->p = *p;
700 
701     *p += len;
702 
703     return 0;
704 }
705 
706 /*
707  * Get signature algorithm from alg OID and optional parameters
708  */
mbedtls_x509_get_sig_alg(const mbedtls_x509_buf * sig_oid,const mbedtls_x509_buf * sig_params,mbedtls_md_type_t * md_alg,mbedtls_pk_type_t * pk_alg,void ** sig_opts)709 int mbedtls_x509_get_sig_alg(const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
710                              mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
711                              void **sig_opts)
712 {
713     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
714 
715     if (*sig_opts != NULL) {
716         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
717     }
718 
719     if ((ret = mbedtls_oid_get_sig_alg(sig_oid, md_alg, pk_alg)) != 0) {
720         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG, ret);
721     }
722 
723 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
724     if (*pk_alg == MBEDTLS_PK_RSASSA_PSS) {
725         mbedtls_pk_rsassa_pss_options *pss_opts;
726 
727         pss_opts = mbedtls_calloc(1, sizeof(mbedtls_pk_rsassa_pss_options));
728         if (pss_opts == NULL) {
729             return MBEDTLS_ERR_X509_ALLOC_FAILED;
730         }
731 
732         ret = mbedtls_x509_get_rsassa_pss_params(sig_params,
733                                                  md_alg,
734                                                  &pss_opts->mgf1_hash_id,
735                                                  &pss_opts->expected_salt_len);
736         if (ret != 0) {
737             mbedtls_free(pss_opts);
738             return ret;
739         }
740 
741         *sig_opts = (void *) pss_opts;
742     } else
743 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
744     {
745         /* Make sure parameters are absent or NULL */
746         if ((sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0) ||
747             sig_params->len != 0) {
748             return MBEDTLS_ERR_X509_INVALID_ALG;
749         }
750     }
751 
752     return 0;
753 }
754 
755 /*
756  * X.509 Extensions (No parsing of extensions, pointer should
757  * be either manually updated or extensions should be parsed!)
758  */
mbedtls_x509_get_ext(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * ext,int tag)759 int mbedtls_x509_get_ext(unsigned char **p, const unsigned char *end,
760                          mbedtls_x509_buf *ext, int tag)
761 {
762     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
763     size_t len;
764 
765     /* Extension structure use EXPLICIT tagging. That is, the actual
766      * `Extensions` structure is wrapped by a tag-length pair using
767      * the respective context-specific tag. */
768     ret = mbedtls_asn1_get_tag(p, end, &ext->len,
769                                MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag);
770     if (ret != 0) {
771         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
772     }
773 
774     ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag;
775     ext->p   = *p;
776     end      = *p + ext->len;
777 
778     /*
779      * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
780      */
781     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
782                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
783         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
784     }
785 
786     if (end != *p + len) {
787         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
788                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
789     }
790 
791     return 0;
792 }
793 
794 /*
795  * Store the name in printable form into buf; no more
796  * than size characters will be written
797  */
mbedtls_x509_dn_gets(char * buf,size_t size,const mbedtls_x509_name * dn)798 int mbedtls_x509_dn_gets(char *buf, size_t size, const mbedtls_x509_name *dn)
799 {
800     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
801     size_t i, j, n;
802     unsigned char c, merge = 0;
803     const mbedtls_x509_name *name;
804     const char *short_name = NULL;
805     char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p;
806 
807     memset(s, 0, sizeof(s));
808 
809     name = dn;
810     p = buf;
811     n = size;
812 
813     while (name != NULL) {
814         if (!name->oid.p) {
815             name = name->next;
816             continue;
817         }
818 
819         if (name != dn) {
820             ret = mbedtls_snprintf(p, n, merge ? " + " : ", ");
821             MBEDTLS_X509_SAFE_SNPRINTF;
822         }
823 
824         ret = mbedtls_oid_get_attr_short_name(&name->oid, &short_name);
825 
826         if (ret == 0) {
827             ret = mbedtls_snprintf(p, n, "%s=", short_name);
828         } else {
829             ret = mbedtls_snprintf(p, n, "\?\?=");
830         }
831         MBEDTLS_X509_SAFE_SNPRINTF;
832 
833         for (i = 0, j = 0; i < name->val.len; i++, j++) {
834             if (j >= sizeof(s) - 1) {
835                 return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
836             }
837 
838             c = name->val.p[i];
839             // Special characters requiring escaping, RFC 1779
840             if (c && strchr(",=+<>#;\"\\", c)) {
841                 if (j + 1 >= sizeof(s) - 1) {
842                     return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
843                 }
844                 s[j++] = '\\';
845             }
846             if (c < 32 || c >= 127) {
847                 s[j] = '?';
848             } else {
849                 s[j] = c;
850             }
851         }
852         s[j] = '\0';
853         ret = mbedtls_snprintf(p, n, "%s", s);
854         MBEDTLS_X509_SAFE_SNPRINTF;
855 
856         merge = name->next_merged;
857         name = name->next;
858     }
859 
860     return (int) (size - n);
861 }
862 
863 /*
864  * Store the serial in printable form into buf; no more
865  * than size characters will be written
866  */
mbedtls_x509_serial_gets(char * buf,size_t size,const mbedtls_x509_buf * serial)867 int mbedtls_x509_serial_gets(char *buf, size_t size, const mbedtls_x509_buf *serial)
868 {
869     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
870     size_t i, n, nr;
871     char *p;
872 
873     p = buf;
874     n = size;
875 
876     nr = (serial->len <= 32)
877         ? serial->len  : 28;
878 
879     for (i = 0; i < nr; i++) {
880         if (i == 0 && nr > 1 && serial->p[i] == 0x0) {
881             continue;
882         }
883 
884         ret = mbedtls_snprintf(p, n, "%02X%s",
885                                serial->p[i], (i < nr - 1) ? ":" : "");
886         MBEDTLS_X509_SAFE_SNPRINTF;
887     }
888 
889     if (nr != serial->len) {
890         ret = mbedtls_snprintf(p, n, "....");
891         MBEDTLS_X509_SAFE_SNPRINTF;
892     }
893 
894     return (int) (size - n);
895 }
896 
897 /*
898  * Helper for writing signature algorithms
899  */
mbedtls_x509_sig_alg_gets(char * buf,size_t size,const mbedtls_x509_buf * sig_oid,mbedtls_pk_type_t pk_alg,mbedtls_md_type_t md_alg,const void * sig_opts)900 int mbedtls_x509_sig_alg_gets(char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
901                               mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
902                               const void *sig_opts)
903 {
904     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
905     char *p = buf;
906     size_t n = size;
907     const char *desc = NULL;
908 
909     ret = mbedtls_oid_get_sig_alg_desc(sig_oid, &desc);
910     if (ret != 0) {
911         ret = mbedtls_snprintf(p, n, "???");
912     } else {
913         ret = mbedtls_snprintf(p, n, "%s", desc);
914     }
915     MBEDTLS_X509_SAFE_SNPRINTF;
916 
917 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
918     if (pk_alg == MBEDTLS_PK_RSASSA_PSS) {
919         const mbedtls_pk_rsassa_pss_options *pss_opts;
920         const mbedtls_md_info_t *md_info, *mgf_md_info;
921 
922         pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts;
923 
924         md_info = mbedtls_md_info_from_type(md_alg);
925         mgf_md_info = mbedtls_md_info_from_type(pss_opts->mgf1_hash_id);
926 
927         ret = mbedtls_snprintf(p, n, " (%s, MGF1-%s, 0x%02X)",
928                                md_info ? mbedtls_md_get_name(md_info) : "???",
929                                mgf_md_info ? mbedtls_md_get_name(mgf_md_info) : "???",
930                                (unsigned int) pss_opts->expected_salt_len);
931         MBEDTLS_X509_SAFE_SNPRINTF;
932     }
933 #else
934     ((void) pk_alg);
935     ((void) md_alg);
936     ((void) sig_opts);
937 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
938 
939     return (int) (size - n);
940 }
941 
942 /*
943  * Helper for writing "RSA key size", "EC key size", etc
944  */
mbedtls_x509_key_size_helper(char * buf,size_t buf_size,const char * name)945 int mbedtls_x509_key_size_helper(char *buf, size_t buf_size, const char *name)
946 {
947     char *p = buf;
948     size_t n = buf_size;
949     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
950 
951     ret = mbedtls_snprintf(p, n, "%s key size", name);
952     MBEDTLS_X509_SAFE_SNPRINTF;
953 
954     return 0;
955 }
956 
957 #if defined(MBEDTLS_HAVE_TIME_DATE)
958 /*
959  * Set the time structure to the current time.
960  * Return 0 on success, non-zero on failure.
961  */
x509_get_current_time(mbedtls_x509_time * now)962 static int x509_get_current_time(mbedtls_x509_time *now)
963 {
964     struct tm *lt, tm_buf;
965     mbedtls_time_t tt;
966     int ret = 0;
967 
968     tt = mbedtls_time(NULL);
969     lt = mbedtls_platform_gmtime_r(&tt, &tm_buf);
970 
971     if (lt == NULL) {
972         ret = -1;
973     } else {
974         now->year = lt->tm_year + 1900;
975         now->mon  = lt->tm_mon  + 1;
976         now->day  = lt->tm_mday;
977         now->hour = lt->tm_hour;
978         now->min  = lt->tm_min;
979         now->sec  = lt->tm_sec;
980     }
981 
982     return ret;
983 }
984 
985 /*
986  * Return 0 if before <= after, 1 otherwise
987  */
x509_check_time(const mbedtls_x509_time * before,const mbedtls_x509_time * after)988 static int x509_check_time(const mbedtls_x509_time *before, const mbedtls_x509_time *after)
989 {
990     if (before->year  > after->year) {
991         return 1;
992     }
993 
994     if (before->year == after->year &&
995         before->mon   > after->mon) {
996         return 1;
997     }
998 
999     if (before->year == after->year &&
1000         before->mon  == after->mon  &&
1001         before->day   > after->day) {
1002         return 1;
1003     }
1004 
1005     if (before->year == after->year &&
1006         before->mon  == after->mon  &&
1007         before->day  == after->day  &&
1008         before->hour  > after->hour) {
1009         return 1;
1010     }
1011 
1012     if (before->year == after->year &&
1013         before->mon  == after->mon  &&
1014         before->day  == after->day  &&
1015         before->hour == after->hour &&
1016         before->min   > after->min) {
1017         return 1;
1018     }
1019 
1020     if (before->year == after->year &&
1021         before->mon  == after->mon  &&
1022         before->day  == after->day  &&
1023         before->hour == after->hour &&
1024         before->min  == after->min  &&
1025         before->sec   > after->sec) {
1026         return 1;
1027     }
1028 
1029     return 0;
1030 }
1031 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1032 int mbedtls_x509_time_is_past(const mbedtls_x509_time *to)
1033 {
1034     mbedtls_x509_time now;
1035 
1036     if (x509_get_current_time(&now) != 0) {
1037         return 1;
1038     }
1039 
1040     return x509_check_time(&now, to);
1041 }
1042 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1043 int mbedtls_x509_time_is_future(const mbedtls_x509_time *from)
1044 {
1045     mbedtls_x509_time now;
1046 
1047     if (x509_get_current_time(&now) != 0) {
1048         return 1;
1049     }
1050 
1051     return x509_check_time(from, &now);
1052 }
1053 
1054 #else  /* MBEDTLS_HAVE_TIME_DATE */
1055 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1056 int mbedtls_x509_time_is_past(const mbedtls_x509_time *to)
1057 {
1058     ((void) to);
1059     return 0;
1060 }
1061 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1062 int mbedtls_x509_time_is_future(const mbedtls_x509_time *from)
1063 {
1064     ((void) from);
1065     return 0;
1066 }
1067 #endif /* MBEDTLS_HAVE_TIME_DATE */
1068 
1069 #if defined(MBEDTLS_SELF_TEST)
1070 
1071 #include "mbedtls/x509_crt.h"
1072 #include "mbedtls/certs.h"
1073 
1074 /*
1075  * Checkup routine
1076  */
mbedtls_x509_self_test(int verbose)1077 int mbedtls_x509_self_test(int verbose)
1078 {
1079     int ret = 0;
1080 #if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C)
1081     uint32_t flags;
1082     mbedtls_x509_crt cacert;
1083     mbedtls_x509_crt clicert;
1084 
1085     if (verbose != 0) {
1086         mbedtls_printf("  X.509 certificate load: ");
1087     }
1088 
1089     mbedtls_x509_crt_init(&cacert);
1090     mbedtls_x509_crt_init(&clicert);
1091 
1092     ret = mbedtls_x509_crt_parse(&clicert, (const unsigned char *) mbedtls_test_cli_crt,
1093                                  mbedtls_test_cli_crt_len);
1094     if (ret != 0) {
1095         if (verbose != 0) {
1096             mbedtls_printf("failed\n");
1097         }
1098 
1099         goto cleanup;
1100     }
1101 
1102     ret = mbedtls_x509_crt_parse(&cacert, (const unsigned char *) mbedtls_test_ca_crt,
1103                                  mbedtls_test_ca_crt_len);
1104     if (ret != 0) {
1105         if (verbose != 0) {
1106             mbedtls_printf("failed\n");
1107         }
1108 
1109         goto cleanup;
1110     }
1111 
1112     if (verbose != 0) {
1113         mbedtls_printf("passed\n  X.509 signature verify: ");
1114     }
1115 
1116     ret = mbedtls_x509_crt_verify(&clicert, &cacert, NULL, NULL, &flags, NULL, NULL);
1117     if (ret != 0) {
1118         if (verbose != 0) {
1119             mbedtls_printf("failed\n");
1120         }
1121 
1122         goto cleanup;
1123     }
1124 
1125     if (verbose != 0) {
1126         mbedtls_printf("passed\n\n");
1127     }
1128 
1129 cleanup:
1130     mbedtls_x509_crt_free(&cacert);
1131     mbedtls_x509_crt_free(&clicert);
1132 #else
1133     ((void) verbose);
1134 #endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA256_C */
1135     return ret;
1136 }
1137 
1138 #endif /* MBEDTLS_SELF_TEST */
1139 
1140 #endif /* MBEDTLS_X509_USE_C */
1141