1 /*
2  *  X.509 common functions for parsing and verification
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 /*
20  *  The ITU-T X.509 standard defines a certificate format for PKI.
21  *
22  *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
23  *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
24  *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
25  *
26  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
27  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
28  */
29 
30 #include "common.h"
31 
32 #if defined(MBEDTLS_X509_USE_C)
33 
34 #include "mbedtls/x509.h"
35 #include "mbedtls/asn1.h"
36 #include "mbedtls/error.h"
37 #include "mbedtls/oid.h"
38 
39 #include <stdio.h>
40 #include <string.h>
41 
42 #if defined(MBEDTLS_PEM_PARSE_C)
43 #include "mbedtls/pem.h"
44 #endif
45 
46 #include "mbedtls/platform.h"
47 
48 #if defined(MBEDTLS_HAVE_TIME)
49 #include "mbedtls/platform_time.h"
50 #endif
51 #if defined(MBEDTLS_HAVE_TIME_DATE)
52 #include "mbedtls/platform_util.h"
53 #include <time.h>
54 #endif
55 
56 #include "mbedtls/legacy_or_psa.h"
57 
58 #define CHECK(code) if ((ret = (code)) != 0) { return ret; }
59 #define CHECK_RANGE(min, max, val)                      \
60     do                                                  \
61     {                                                   \
62         if ((val) < (min) || (val) > (max))    \
63         {                                               \
64             return ret;                              \
65         }                                               \
66     } while (0)
67 
68 /*
69  *  CertificateSerialNumber  ::=  INTEGER
70  */
mbedtls_x509_get_serial(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * serial)71 int mbedtls_x509_get_serial(unsigned char **p, const unsigned char *end,
72                             mbedtls_x509_buf *serial)
73 {
74     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
75 
76     if ((end - *p) < 1) {
77         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL,
78                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
79     }
80 
81     if (**p != (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2) &&
82         **p !=   MBEDTLS_ASN1_INTEGER) {
83         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL,
84                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
85     }
86 
87     serial->tag = *(*p)++;
88 
89     if ((ret = mbedtls_asn1_get_len(p, end, &serial->len)) != 0) {
90         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SERIAL, ret);
91     }
92 
93     serial->p = *p;
94     *p += serial->len;
95 
96     return 0;
97 }
98 
99 /* Get an algorithm identifier without parameters (eg for signatures)
100  *
101  *  AlgorithmIdentifier  ::=  SEQUENCE  {
102  *       algorithm               OBJECT IDENTIFIER,
103  *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
104  */
mbedtls_x509_get_alg_null(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg)105 int mbedtls_x509_get_alg_null(unsigned char **p, const unsigned char *end,
106                               mbedtls_x509_buf *alg)
107 {
108     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
109 
110     if ((ret = mbedtls_asn1_get_alg_null(p, end, alg)) != 0) {
111         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
112     }
113 
114     return 0;
115 }
116 
117 /*
118  * Parse an algorithm identifier with (optional) parameters
119  */
mbedtls_x509_get_alg(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg,mbedtls_x509_buf * params)120 int mbedtls_x509_get_alg(unsigned char **p, const unsigned char *end,
121                          mbedtls_x509_buf *alg, mbedtls_x509_buf *params)
122 {
123     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
124 
125     if ((ret = mbedtls_asn1_get_alg(p, end, alg, params)) != 0) {
126         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
127     }
128 
129     return 0;
130 }
131 
132 /*
133  * Convert md type to string
134  */
md_type_to_string(mbedtls_md_type_t md_alg)135 static inline const char *md_type_to_string(mbedtls_md_type_t md_alg)
136 {
137     switch (md_alg) {
138 #if defined(MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA)
139         case MBEDTLS_MD_MD5:
140             return "MD5";
141 #endif
142 #if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA)
143         case MBEDTLS_MD_SHA1:
144             return "SHA1";
145 #endif
146 #if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_MD_OR_PSA)
147         case MBEDTLS_MD_SHA224:
148             return "SHA224";
149 #endif
150 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA)
151         case MBEDTLS_MD_SHA256:
152             return "SHA256";
153 #endif
154 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA)
155         case MBEDTLS_MD_SHA384:
156             return "SHA384";
157 #endif
158 #if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA)
159         case MBEDTLS_MD_SHA512:
160             return "SHA512";
161 #endif
162 #if defined(MBEDTLS_HAS_ALG_RIPEMD160_VIA_MD_OR_PSA)
163         case MBEDTLS_MD_RIPEMD160:
164             return "RIPEMD160";
165 #endif
166         case MBEDTLS_MD_NONE:
167             return NULL;
168         default:
169             return NULL;
170     }
171 }
172 
173 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
174 /*
175  * HashAlgorithm ::= AlgorithmIdentifier
176  *
177  * AlgorithmIdentifier  ::=  SEQUENCE  {
178  *      algorithm               OBJECT IDENTIFIER,
179  *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
180  *
181  * For HashAlgorithm, parameters MUST be NULL or absent.
182  */
x509_get_hash_alg(const mbedtls_x509_buf * alg,mbedtls_md_type_t * md_alg)183 static int x509_get_hash_alg(const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg)
184 {
185     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
186     unsigned char *p;
187     const unsigned char *end;
188     mbedtls_x509_buf md_oid;
189     size_t len;
190 
191     /* Make sure we got a SEQUENCE and setup bounds */
192     if (alg->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
193         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
194                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
195     }
196 
197     p = alg->p;
198     end = p + alg->len;
199 
200     if (p >= end) {
201         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
202                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
203     }
204 
205     /* Parse md_oid */
206     md_oid.tag = *p;
207 
208     if ((ret = mbedtls_asn1_get_tag(&p, end, &md_oid.len, MBEDTLS_ASN1_OID)) != 0) {
209         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
210     }
211 
212     md_oid.p = p;
213     p += md_oid.len;
214 
215     /* Get md_alg from md_oid */
216     if ((ret = mbedtls_oid_get_md_alg(&md_oid, md_alg)) != 0) {
217         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
218     }
219 
220     /* Make sure params is absent of NULL */
221     if (p == end) {
222         return 0;
223     }
224 
225     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_NULL)) != 0 || len != 0) {
226         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
227     }
228 
229     if (p != end) {
230         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
231                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
232     }
233 
234     return 0;
235 }
236 
237 /*
238  *    RSASSA-PSS-params  ::=  SEQUENCE  {
239  *       hashAlgorithm     [0] HashAlgorithm DEFAULT sha1Identifier,
240  *       maskGenAlgorithm  [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
241  *       saltLength        [2] INTEGER DEFAULT 20,
242  *       trailerField      [3] INTEGER DEFAULT 1  }
243  *    -- Note that the tags in this Sequence are explicit.
244  *
245  * RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value
246  * of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other
247  * option. Enforce this at parsing time.
248  */
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)249 int mbedtls_x509_get_rsassa_pss_params(const mbedtls_x509_buf *params,
250                                        mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
251                                        int *salt_len)
252 {
253     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
254     unsigned char *p;
255     const unsigned char *end, *end2;
256     size_t len;
257     mbedtls_x509_buf alg_id, alg_params;
258 
259     /* First set everything to defaults */
260     *md_alg = MBEDTLS_MD_SHA1;
261     *mgf_md = MBEDTLS_MD_SHA1;
262     *salt_len = 20;
263 
264     /* Make sure params is a SEQUENCE and setup bounds */
265     if (params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
266         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
267                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
268     }
269 
270     p = (unsigned char *) params->p;
271     end = p + params->len;
272 
273     if (p == end) {
274         return 0;
275     }
276 
277     /*
278      * HashAlgorithm
279      */
280     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
281                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
282                                     0)) == 0) {
283         end2 = p + len;
284 
285         /* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */
286         if ((ret = mbedtls_x509_get_alg_null(&p, end2, &alg_id)) != 0) {
287             return ret;
288         }
289 
290         if ((ret = mbedtls_oid_get_md_alg(&alg_id, md_alg)) != 0) {
291             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
292         }
293 
294         if (p != end2) {
295             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
296                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
297         }
298     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
299         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
300     }
301 
302     if (p == end) {
303         return 0;
304     }
305 
306     /*
307      * MaskGenAlgorithm
308      */
309     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
310                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
311                                     1)) == 0) {
312         end2 = p + len;
313 
314         /* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */
315         if ((ret = mbedtls_x509_get_alg(&p, end2, &alg_id, &alg_params)) != 0) {
316             return ret;
317         }
318 
319         /* Only MFG1 is recognised for now */
320         if (MBEDTLS_OID_CMP(MBEDTLS_OID_MGF1, &alg_id) != 0) {
321             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE,
322                                      MBEDTLS_ERR_OID_NOT_FOUND);
323         }
324 
325         /* Parse HashAlgorithm */
326         if ((ret = x509_get_hash_alg(&alg_params, mgf_md)) != 0) {
327             return ret;
328         }
329 
330         if (p != end2) {
331             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
332                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
333         }
334     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
335         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
336     }
337 
338     if (p == end) {
339         return 0;
340     }
341 
342     /*
343      * salt_len
344      */
345     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
346                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
347                                     2)) == 0) {
348         end2 = p + len;
349 
350         if ((ret = mbedtls_asn1_get_int(&p, end2, salt_len)) != 0) {
351             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
352         }
353 
354         if (p != end2) {
355             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
356                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
357         }
358     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
359         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
360     }
361 
362     if (p == end) {
363         return 0;
364     }
365 
366     /*
367      * trailer_field (if present, must be 1)
368      */
369     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
370                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED |
371                                     3)) == 0) {
372         int trailer_field;
373 
374         end2 = p + len;
375 
376         if ((ret = mbedtls_asn1_get_int(&p, end2, &trailer_field)) != 0) {
377             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
378         }
379 
380         if (p != end2) {
381             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
382                                      MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
383         }
384 
385         if (trailer_field != 1) {
386             return MBEDTLS_ERR_X509_INVALID_ALG;
387         }
388     } else if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
389         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG, ret);
390     }
391 
392     if (p != end) {
393         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_ALG,
394                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
395     }
396 
397     return 0;
398 }
399 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
400 
401 /*
402  *  AttributeTypeAndValue ::= SEQUENCE {
403  *    type     AttributeType,
404  *    value    AttributeValue }
405  *
406  *  AttributeType ::= OBJECT IDENTIFIER
407  *
408  *  AttributeValue ::= ANY DEFINED BY AttributeType
409  */
x509_get_attr_type_value(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)410 static int x509_get_attr_type_value(unsigned char **p,
411                                     const unsigned char *end,
412                                     mbedtls_x509_name *cur)
413 {
414     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
415     size_t len;
416     mbedtls_x509_buf *oid;
417     mbedtls_x509_buf *val;
418 
419     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
420                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
421         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
422     }
423 
424     end = *p + len;
425 
426     if ((end - *p) < 1) {
427         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
428                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
429     }
430 
431     oid = &cur->oid;
432     oid->tag = **p;
433 
434     if ((ret = mbedtls_asn1_get_tag(p, end, &oid->len, MBEDTLS_ASN1_OID)) != 0) {
435         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
436     }
437 
438     oid->p = *p;
439     *p += oid->len;
440 
441     if ((end - *p) < 1) {
442         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
443                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
444     }
445 
446     if (**p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING      &&
447         **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING &&
448         **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING &&
449         **p != MBEDTLS_ASN1_BIT_STRING) {
450         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
451                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
452     }
453 
454     val = &cur->val;
455     val->tag = *(*p)++;
456 
457     if ((ret = mbedtls_asn1_get_len(p, end, &val->len)) != 0) {
458         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
459     }
460 
461     val->p = *p;
462     *p += val->len;
463 
464     if (*p != end) {
465         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME,
466                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
467     }
468 
469     cur->next = NULL;
470 
471     return 0;
472 }
473 
474 /*
475  *  Name ::= CHOICE { -- only one possibility for now --
476  *       rdnSequence  RDNSequence }
477  *
478  *  RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
479  *
480  *  RelativeDistinguishedName ::=
481  *    SET OF AttributeTypeAndValue
482  *
483  *  AttributeTypeAndValue ::= SEQUENCE {
484  *    type     AttributeType,
485  *    value    AttributeValue }
486  *
487  *  AttributeType ::= OBJECT IDENTIFIER
488  *
489  *  AttributeValue ::= ANY DEFINED BY AttributeType
490  *
491  * The data structure is optimized for the common case where each RDN has only
492  * one element, which is represented as a list of AttributeTypeAndValue.
493  * For the general case we still use a flat list, but we mark elements of the
494  * same set so that they are "merged" together in the functions that consume
495  * this list, eg mbedtls_x509_dn_gets().
496  *
497  * On success, this function may allocate a linked list starting at cur->next
498  * that must later be free'd by the caller using mbedtls_free(). In error
499  * cases, this function frees all allocated memory internally and the caller
500  * has no freeing responsibilities.
501  */
mbedtls_x509_get_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)502 int mbedtls_x509_get_name(unsigned char **p, const unsigned char *end,
503                           mbedtls_x509_name *cur)
504 {
505     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
506     size_t set_len;
507     const unsigned char *end_set;
508     mbedtls_x509_name *head = cur;
509 
510     /* don't use recursion, we'd risk stack overflow if not optimized */
511     while (1) {
512         /*
513          * parse SET
514          */
515         if ((ret = mbedtls_asn1_get_tag(p, end, &set_len,
516                                         MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET)) != 0) {
517             ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_NAME, ret);
518             goto error;
519         }
520 
521         end_set  = *p + set_len;
522 
523         while (1) {
524             if ((ret = x509_get_attr_type_value(p, end_set, cur)) != 0) {
525                 goto error;
526             }
527 
528             if (*p == end_set) {
529                 break;
530             }
531 
532             /* Mark this item as being no the only one in a set */
533             cur->next_merged = 1;
534 
535             cur->next = mbedtls_calloc(1, sizeof(mbedtls_x509_name));
536 
537             if (cur->next == NULL) {
538                 ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
539                 goto error;
540             }
541 
542             cur = cur->next;
543         }
544 
545         /*
546          * continue until end of SEQUENCE is reached
547          */
548         if (*p == end) {
549             return 0;
550         }
551 
552         cur->next = mbedtls_calloc(1, sizeof(mbedtls_x509_name));
553 
554         if (cur->next == NULL) {
555             ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
556             goto error;
557         }
558 
559         cur = cur->next;
560     }
561 
562 error:
563     /* Skip the first element as we did not allocate it */
564     mbedtls_asn1_free_named_data_list_shallow(head->next);
565     head->next = NULL;
566 
567     return ret;
568 }
569 
x509_parse_int(unsigned char ** p,size_t n,int * res)570 static int x509_parse_int(unsigned char **p, size_t n, int *res)
571 {
572     *res = 0;
573 
574     for (; n > 0; --n) {
575         if ((**p < '0') || (**p > '9')) {
576             return MBEDTLS_ERR_X509_INVALID_DATE;
577         }
578 
579         *res *= 10;
580         *res += (*(*p)++ - '0');
581     }
582 
583     return 0;
584 }
585 
x509_date_is_valid(const mbedtls_x509_time * t)586 static int x509_date_is_valid(const mbedtls_x509_time *t)
587 {
588     int ret = MBEDTLS_ERR_X509_INVALID_DATE;
589     int month_len;
590 
591     CHECK_RANGE(0, 9999, t->year);
592     CHECK_RANGE(0, 23,   t->hour);
593     CHECK_RANGE(0, 59,   t->min);
594     CHECK_RANGE(0, 59,   t->sec);
595 
596     switch (t->mon) {
597         case 1: case 3: case 5: case 7: case 8: case 10: case 12:
598             month_len = 31;
599             break;
600         case 4: case 6: case 9: case 11:
601             month_len = 30;
602             break;
603         case 2:
604             if ((!(t->year % 4) && t->year % 100) ||
605                 !(t->year % 400)) {
606                 month_len = 29;
607             } else {
608                 month_len = 28;
609             }
610             break;
611         default:
612             return ret;
613     }
614     CHECK_RANGE(1, month_len, t->day);
615 
616     return 0;
617 }
618 
619 /*
620  * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4)
621  * field.
622  */
x509_parse_time(unsigned char ** p,size_t len,size_t yearlen,mbedtls_x509_time * tm)623 static int x509_parse_time(unsigned char **p, size_t len, size_t yearlen,
624                            mbedtls_x509_time *tm)
625 {
626     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
627 
628     /*
629      * Minimum length is 10 or 12 depending on yearlen
630      */
631     if (len < yearlen + 8) {
632         return MBEDTLS_ERR_X509_INVALID_DATE;
633     }
634     len -= yearlen + 8;
635 
636     /*
637      * Parse year, month, day, hour, minute
638      */
639     CHECK(x509_parse_int(p, yearlen, &tm->year));
640     if (2 == yearlen) {
641         if (tm->year < 50) {
642             tm->year += 100;
643         }
644 
645         tm->year += 1900;
646     }
647 
648     CHECK(x509_parse_int(p, 2, &tm->mon));
649     CHECK(x509_parse_int(p, 2, &tm->day));
650     CHECK(x509_parse_int(p, 2, &tm->hour));
651     CHECK(x509_parse_int(p, 2, &tm->min));
652 
653     /*
654      * Parse seconds if present
655      */
656     if (len >= 2) {
657         CHECK(x509_parse_int(p, 2, &tm->sec));
658         len -= 2;
659     } else {
660         return MBEDTLS_ERR_X509_INVALID_DATE;
661     }
662 
663     /*
664      * Parse trailing 'Z' if present
665      */
666     if (1 == len && 'Z' == **p) {
667         (*p)++;
668         len--;
669     }
670 
671     /*
672      * We should have parsed all characters at this point
673      */
674     if (0 != len) {
675         return MBEDTLS_ERR_X509_INVALID_DATE;
676     }
677 
678     CHECK(x509_date_is_valid(tm));
679 
680     return 0;
681 }
682 
683 /*
684  *  Time ::= CHOICE {
685  *       utcTime        UTCTime,
686  *       generalTime    GeneralizedTime }
687  */
mbedtls_x509_get_time(unsigned char ** p,const unsigned char * end,mbedtls_x509_time * tm)688 int mbedtls_x509_get_time(unsigned char **p, const unsigned char *end,
689                           mbedtls_x509_time *tm)
690 {
691     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
692     size_t len, year_len;
693     unsigned char tag;
694 
695     if ((end - *p) < 1) {
696         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE,
697                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
698     }
699 
700     tag = **p;
701 
702     if (tag == MBEDTLS_ASN1_UTC_TIME) {
703         year_len = 2;
704     } else if (tag == MBEDTLS_ASN1_GENERALIZED_TIME) {
705         year_len = 4;
706     } else {
707         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE,
708                                  MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
709     }
710 
711     (*p)++;
712     ret = mbedtls_asn1_get_len(p, end, &len);
713 
714     if (ret != 0) {
715         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_DATE, ret);
716     }
717 
718     return x509_parse_time(p, len, year_len, tm);
719 }
720 
mbedtls_x509_get_sig(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * sig)721 int mbedtls_x509_get_sig(unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig)
722 {
723     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
724     size_t len;
725     int tag_type;
726 
727     if ((end - *p) < 1) {
728         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SIGNATURE,
729                                  MBEDTLS_ERR_ASN1_OUT_OF_DATA);
730     }
731 
732     tag_type = **p;
733 
734     if ((ret = mbedtls_asn1_get_bitstring_null(p, end, &len)) != 0) {
735         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_SIGNATURE, ret);
736     }
737 
738     sig->tag = tag_type;
739     sig->len = len;
740     sig->p = *p;
741 
742     *p += len;
743 
744     return 0;
745 }
746 
747 /*
748  * Get signature algorithm from alg OID and optional parameters
749  */
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)750 int mbedtls_x509_get_sig_alg(const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
751                              mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
752                              void **sig_opts)
753 {
754     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
755 
756     if (*sig_opts != NULL) {
757         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
758     }
759 
760     if ((ret = mbedtls_oid_get_sig_alg(sig_oid, md_alg, pk_alg)) != 0) {
761         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG, ret);
762     }
763 
764 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
765     if (*pk_alg == MBEDTLS_PK_RSASSA_PSS) {
766         mbedtls_pk_rsassa_pss_options *pss_opts;
767 
768         pss_opts = mbedtls_calloc(1, sizeof(mbedtls_pk_rsassa_pss_options));
769         if (pss_opts == NULL) {
770             return MBEDTLS_ERR_X509_ALLOC_FAILED;
771         }
772 
773         ret = mbedtls_x509_get_rsassa_pss_params(sig_params,
774                                                  md_alg,
775                                                  &pss_opts->mgf1_hash_id,
776                                                  &pss_opts->expected_salt_len);
777         if (ret != 0) {
778             mbedtls_free(pss_opts);
779             return ret;
780         }
781 
782         *sig_opts = (void *) pss_opts;
783     } else
784 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
785     {
786         /* Make sure parameters are absent or NULL */
787         if ((sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0) ||
788             sig_params->len != 0) {
789             return MBEDTLS_ERR_X509_INVALID_ALG;
790         }
791     }
792 
793     return 0;
794 }
795 
796 /*
797  * X.509 Extensions (No parsing of extensions, pointer should
798  * be either manually updated or extensions should be parsed!)
799  */
mbedtls_x509_get_ext(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * ext,int tag)800 int mbedtls_x509_get_ext(unsigned char **p, const unsigned char *end,
801                          mbedtls_x509_buf *ext, int tag)
802 {
803     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
804     size_t len;
805 
806     /* Extension structure use EXPLICIT tagging. That is, the actual
807      * `Extensions` structure is wrapped by a tag-length pair using
808      * the respective context-specific tag. */
809     ret = mbedtls_asn1_get_tag(p, end, &ext->len,
810                                MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag);
811     if (ret != 0) {
812         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
813     }
814 
815     ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag;
816     ext->p   = *p;
817     end      = *p + ext->len;
818 
819     /*
820      * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
821      */
822     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
823                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
824         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
825     }
826 
827     if (end != *p + len) {
828         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
829                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
830     }
831 
832     return 0;
833 }
834 
835 /*
836  * Store the name in printable form into buf; no more
837  * than size characters will be written
838  */
mbedtls_x509_dn_gets(char * buf,size_t size,const mbedtls_x509_name * dn)839 int mbedtls_x509_dn_gets(char *buf, size_t size, const mbedtls_x509_name *dn)
840 {
841     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
842     size_t i, j, n;
843     unsigned char c, merge = 0;
844     const mbedtls_x509_name *name;
845     const char *short_name = NULL;
846     char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p;
847 
848     memset(s, 0, sizeof(s));
849 
850     name = dn;
851     p = buf;
852     n = size;
853 
854     while (name != NULL) {
855         if (!name->oid.p) {
856             name = name->next;
857             continue;
858         }
859 
860         if (name != dn) {
861             ret = mbedtls_snprintf(p, n, merge ? " + " : ", ");
862             MBEDTLS_X509_SAFE_SNPRINTF;
863         }
864 
865         ret = mbedtls_oid_get_attr_short_name(&name->oid, &short_name);
866 
867         if (ret == 0) {
868             ret = mbedtls_snprintf(p, n, "%s=", short_name);
869         } else {
870             ret = mbedtls_snprintf(p, n, "\?\?=");
871         }
872         MBEDTLS_X509_SAFE_SNPRINTF;
873 
874         for (i = 0, j = 0; i < name->val.len; i++, j++) {
875             if (j >= sizeof(s) - 1) {
876                 return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
877             }
878 
879             c = name->val.p[i];
880             // Special characters requiring escaping, RFC 1779
881             if (c && strchr(",=+<>#;\"\\", c)) {
882                 if (j + 1 >= sizeof(s) - 1) {
883                     return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
884                 }
885                 s[j++] = '\\';
886             }
887             if (c < 32 || c >= 127) {
888                 s[j] = '?';
889             } else {
890                 s[j] = c;
891             }
892         }
893         s[j] = '\0';
894         ret = mbedtls_snprintf(p, n, "%s", s);
895         MBEDTLS_X509_SAFE_SNPRINTF;
896 
897         merge = name->next_merged;
898         name = name->next;
899     }
900 
901     return (int) (size - n);
902 }
903 
904 /*
905  * Store the serial in printable form into buf; no more
906  * than size characters will be written
907  */
mbedtls_x509_serial_gets(char * buf,size_t size,const mbedtls_x509_buf * serial)908 int mbedtls_x509_serial_gets(char *buf, size_t size, const mbedtls_x509_buf *serial)
909 {
910     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
911     size_t i, n, nr;
912     char *p;
913 
914     p = buf;
915     n = size;
916 
917     nr = (serial->len <= 32)
918         ? serial->len  : 28;
919 
920     for (i = 0; i < nr; i++) {
921         if (i == 0 && nr > 1 && serial->p[i] == 0x0) {
922             continue;
923         }
924 
925         ret = mbedtls_snprintf(p, n, "%02X%s",
926                                serial->p[i], (i < nr - 1) ? ":" : "");
927         MBEDTLS_X509_SAFE_SNPRINTF;
928     }
929 
930     if (nr != serial->len) {
931         ret = mbedtls_snprintf(p, n, "....");
932         MBEDTLS_X509_SAFE_SNPRINTF;
933     }
934 
935     return (int) (size - n);
936 }
937 
938 #if !defined(MBEDTLS_X509_REMOVE_INFO)
939 /*
940  * Helper for writing signature algorithms
941  */
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)942 int mbedtls_x509_sig_alg_gets(char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
943                               mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
944                               const void *sig_opts)
945 {
946     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
947     char *p = buf;
948     size_t n = size;
949     const char *desc = NULL;
950 
951     ret = mbedtls_oid_get_sig_alg_desc(sig_oid, &desc);
952     if (ret != 0) {
953         ret = mbedtls_snprintf(p, n, "???");
954     } else {
955         ret = mbedtls_snprintf(p, n, "%s", desc);
956     }
957     MBEDTLS_X509_SAFE_SNPRINTF;
958 
959 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
960     if (pk_alg == MBEDTLS_PK_RSASSA_PSS) {
961         const mbedtls_pk_rsassa_pss_options *pss_opts;
962 
963         pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts;
964 
965         const char *name = md_type_to_string(md_alg);
966         const char *mgf_name = md_type_to_string(pss_opts->mgf1_hash_id);
967 
968         ret = mbedtls_snprintf(p, n, " (%s, MGF1-%s, 0x%02X)",
969                                name ? name : "???",
970                                mgf_name ? mgf_name : "???",
971                                (unsigned int) pss_opts->expected_salt_len);
972         MBEDTLS_X509_SAFE_SNPRINTF;
973     }
974 #else
975     ((void) pk_alg);
976     ((void) md_alg);
977     ((void) sig_opts);
978 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
979 
980     return (int) (size - n);
981 }
982 #endif /* MBEDTLS_X509_REMOVE_INFO */
983 
984 /*
985  * Helper for writing "RSA key size", "EC key size", etc
986  */
mbedtls_x509_key_size_helper(char * buf,size_t buf_size,const char * name)987 int mbedtls_x509_key_size_helper(char *buf, size_t buf_size, const char *name)
988 {
989     char *p = buf;
990     size_t n = buf_size;
991     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
992 
993     ret = mbedtls_snprintf(p, n, "%s key size", name);
994     MBEDTLS_X509_SAFE_SNPRINTF;
995 
996     return 0;
997 }
998 
999 #if defined(MBEDTLS_HAVE_TIME_DATE)
1000 /*
1001  * Set the time structure to the current time.
1002  * Return 0 on success, non-zero on failure.
1003  */
x509_get_current_time(mbedtls_x509_time * now)1004 static int x509_get_current_time(mbedtls_x509_time *now)
1005 {
1006     struct tm *lt, tm_buf;
1007     mbedtls_time_t tt;
1008     int ret = 0;
1009 
1010     tt = mbedtls_time(NULL);
1011     lt = mbedtls_platform_gmtime_r(&tt, &tm_buf);
1012 
1013     if (lt == NULL) {
1014         ret = -1;
1015     } else {
1016         now->year = lt->tm_year + 1900;
1017         now->mon  = lt->tm_mon  + 1;
1018         now->day  = lt->tm_mday;
1019         now->hour = lt->tm_hour;
1020         now->min  = lt->tm_min;
1021         now->sec  = lt->tm_sec;
1022     }
1023 
1024     return ret;
1025 }
1026 
1027 /*
1028  * Return 0 if before <= after, 1 otherwise
1029  */
x509_check_time(const mbedtls_x509_time * before,const mbedtls_x509_time * after)1030 static int x509_check_time(const mbedtls_x509_time *before, const mbedtls_x509_time *after)
1031 {
1032     if (before->year  > after->year) {
1033         return 1;
1034     }
1035 
1036     if (before->year == after->year &&
1037         before->mon   > after->mon) {
1038         return 1;
1039     }
1040 
1041     if (before->year == after->year &&
1042         before->mon  == after->mon  &&
1043         before->day   > after->day) {
1044         return 1;
1045     }
1046 
1047     if (before->year == after->year &&
1048         before->mon  == after->mon  &&
1049         before->day  == after->day  &&
1050         before->hour  > after->hour) {
1051         return 1;
1052     }
1053 
1054     if (before->year == after->year &&
1055         before->mon  == after->mon  &&
1056         before->day  == after->day  &&
1057         before->hour == after->hour &&
1058         before->min   > after->min) {
1059         return 1;
1060     }
1061 
1062     if (before->year == after->year &&
1063         before->mon  == after->mon  &&
1064         before->day  == after->day  &&
1065         before->hour == after->hour &&
1066         before->min  == after->min  &&
1067         before->sec   > after->sec) {
1068         return 1;
1069     }
1070 
1071     return 0;
1072 }
1073 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1074 int mbedtls_x509_time_is_past(const mbedtls_x509_time *to)
1075 {
1076     mbedtls_x509_time now;
1077 
1078     if (x509_get_current_time(&now) != 0) {
1079         return 1;
1080     }
1081 
1082     return x509_check_time(&now, to);
1083 }
1084 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1085 int mbedtls_x509_time_is_future(const mbedtls_x509_time *from)
1086 {
1087     mbedtls_x509_time now;
1088 
1089     if (x509_get_current_time(&now) != 0) {
1090         return 1;
1091     }
1092 
1093     return x509_check_time(from, &now);
1094 }
1095 
1096 #else  /* MBEDTLS_HAVE_TIME_DATE */
1097 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1098 int mbedtls_x509_time_is_past(const mbedtls_x509_time *to)
1099 {
1100     ((void) to);
1101     return 0;
1102 }
1103 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1104 int mbedtls_x509_time_is_future(const mbedtls_x509_time *from)
1105 {
1106     ((void) from);
1107     return 0;
1108 }
1109 #endif /* MBEDTLS_HAVE_TIME_DATE */
1110 
1111 /* Common functions for parsing CRT and CSR. */
1112 #if defined(MBEDTLS_X509_CRT_PARSE_C) || defined(MBEDTLS_X509_CSR_PARSE_C)
1113 /*
1114  * OtherName ::= SEQUENCE {
1115  *      type-id    OBJECT IDENTIFIER,
1116  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
1117  *
1118  * HardwareModuleName ::= SEQUENCE {
1119  *                           hwType OBJECT IDENTIFIER,
1120  *                           hwSerialNum OCTET STRING }
1121  *
1122  * NOTE: we currently only parse and use otherName of type HwModuleName,
1123  * as defined in RFC 4108.
1124  */
x509_get_other_name(const mbedtls_x509_buf * subject_alt_name,mbedtls_x509_san_other_name * other_name)1125 static int x509_get_other_name(const mbedtls_x509_buf *subject_alt_name,
1126                                mbedtls_x509_san_other_name *other_name)
1127 {
1128     int ret = 0;
1129     size_t len;
1130     unsigned char *p = subject_alt_name->p;
1131     const unsigned char *end = p + subject_alt_name->len;
1132     mbedtls_x509_buf cur_oid;
1133 
1134     if ((subject_alt_name->tag &
1135          (MBEDTLS_ASN1_TAG_CLASS_MASK | MBEDTLS_ASN1_TAG_VALUE_MASK)) !=
1136         (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME)) {
1137         /*
1138          * The given subject alternative name is not of type "othername".
1139          */
1140         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
1141     }
1142 
1143     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1144                                     MBEDTLS_ASN1_OID)) != 0) {
1145         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1146     }
1147 
1148     cur_oid.tag = MBEDTLS_ASN1_OID;
1149     cur_oid.p = p;
1150     cur_oid.len = len;
1151 
1152     /*
1153      * Only HwModuleName is currently supported.
1154      */
1155     if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME, &cur_oid) != 0) {
1156         return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
1157     }
1158 
1159     p += len;
1160     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1161                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_CONTEXT_SPECIFIC)) !=
1162         0) {
1163         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1164     }
1165 
1166     if (end != p + len) {
1167         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1168                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1169     }
1170 
1171     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1172                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1173         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1174     }
1175 
1176     if (end != p + len) {
1177         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1178                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1179     }
1180 
1181     if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OID)) != 0) {
1182         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1183     }
1184 
1185     other_name->value.hardware_module_name.oid.tag = MBEDTLS_ASN1_OID;
1186     other_name->value.hardware_module_name.oid.p = p;
1187     other_name->value.hardware_module_name.oid.len = len;
1188 
1189     p += len;
1190     if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
1191                                     MBEDTLS_ASN1_OCTET_STRING)) != 0) {
1192         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1193     }
1194 
1195     other_name->value.hardware_module_name.val.tag = MBEDTLS_ASN1_OCTET_STRING;
1196     other_name->value.hardware_module_name.val.p = p;
1197     other_name->value.hardware_module_name.val.len = len;
1198     p += len;
1199     if (p != end) {
1200         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1201                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1202     }
1203     return 0;
1204 }
1205 
1206 /*
1207  * SubjectAltName ::= GeneralNames
1208  *
1209  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1210  *
1211  * GeneralName ::= CHOICE {
1212  *      otherName                       [0]     OtherName,
1213  *      rfc822Name                      [1]     IA5String,
1214  *      dNSName                         [2]     IA5String,
1215  *      x400Address                     [3]     ORAddress,
1216  *      directoryName                   [4]     Name,
1217  *      ediPartyName                    [5]     EDIPartyName,
1218  *      uniformResourceIdentifier       [6]     IA5String,
1219  *      iPAddress                       [7]     OCTET STRING,
1220  *      registeredID                    [8]     OBJECT IDENTIFIER }
1221  *
1222  * OtherName ::= SEQUENCE {
1223  *      type-id    OBJECT IDENTIFIER,
1224  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
1225  *
1226  * EDIPartyName ::= SEQUENCE {
1227  *      nameAssigner            [0]     DirectoryString OPTIONAL,
1228  *      partyName               [1]     DirectoryString }
1229  *
1230  * We list all types, but use the following GeneralName types from RFC 5280:
1231  * "dnsName", "uniformResourceIdentifier" and "hardware_module_name"
1232  * of type "otherName", as defined in RFC 4108.
1233  */
mbedtls_x509_get_subject_alt_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * subject_alt_name)1234 int mbedtls_x509_get_subject_alt_name(unsigned char **p,
1235                                       const unsigned char *end,
1236                                       mbedtls_x509_sequence *subject_alt_name)
1237 {
1238     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1239     size_t len, tag_len;
1240     mbedtls_asn1_sequence *cur = subject_alt_name;
1241 
1242     /* Get main sequence tag */
1243     if ((ret = mbedtls_asn1_get_tag(p, end, &len,
1244                                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
1245         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1246     }
1247 
1248     if (*p + len != end) {
1249         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1250                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1251     }
1252 
1253     while (*p < end) {
1254         mbedtls_x509_subject_alternative_name dummy_san_buf;
1255         mbedtls_x509_buf tmp_san_buf;
1256         memset(&dummy_san_buf, 0, sizeof(dummy_san_buf));
1257 
1258         tmp_san_buf.tag = **p;
1259         (*p)++;
1260 
1261         if ((ret = mbedtls_asn1_get_len(p, end, &tag_len)) != 0) {
1262             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1263         }
1264 
1265         tmp_san_buf.p = *p;
1266         tmp_san_buf.len = tag_len;
1267 
1268         if ((tmp_san_buf.tag & MBEDTLS_ASN1_TAG_CLASS_MASK) !=
1269             MBEDTLS_ASN1_CONTEXT_SPECIFIC) {
1270             return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1271                                      MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
1272         }
1273 
1274         /*
1275          * Check that the SAN is structured correctly.
1276          */
1277         ret = mbedtls_x509_parse_subject_alt_name(&tmp_san_buf, &dummy_san_buf);
1278         /*
1279          * In case the extension is malformed, return an error,
1280          * and clear the allocated sequences.
1281          */
1282         if (ret != 0 && ret != MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) {
1283             mbedtls_asn1_sequence_free(subject_alt_name->next);
1284             subject_alt_name->next = NULL;
1285             return ret;
1286         }
1287 
1288         /* Allocate and assign next pointer */
1289         if (cur->buf.p != NULL) {
1290             if (cur->next != NULL) {
1291                 return MBEDTLS_ERR_X509_INVALID_EXTENSIONS;
1292             }
1293 
1294             cur->next = mbedtls_calloc(1, sizeof(mbedtls_asn1_sequence));
1295 
1296             if (cur->next == NULL) {
1297                 return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1298                                          MBEDTLS_ERR_ASN1_ALLOC_FAILED);
1299             }
1300 
1301             cur = cur->next;
1302         }
1303 
1304         cur->buf = tmp_san_buf;
1305         *p += tmp_san_buf.len;
1306     }
1307 
1308     /* Set final sequence entry's next pointer to NULL */
1309     cur->next = NULL;
1310 
1311     if (*p != end) {
1312         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1313                                  MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
1314     }
1315 
1316     return 0;
1317 }
1318 
mbedtls_x509_get_ns_cert_type(unsigned char ** p,const unsigned char * end,unsigned char * ns_cert_type)1319 int mbedtls_x509_get_ns_cert_type(unsigned char **p,
1320                                   const unsigned char *end,
1321                                   unsigned char *ns_cert_type)
1322 {
1323     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1324     mbedtls_x509_bitstring bs = { 0, 0, NULL };
1325 
1326     if ((ret = mbedtls_asn1_get_bitstring(p, end, &bs)) != 0) {
1327         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1328     }
1329 
1330     /* A bitstring with no flags set is still technically valid, as it will mean
1331        that the certificate has no designated purpose at the time of creation. */
1332     if (bs.len == 0) {
1333         *ns_cert_type = 0;
1334         return 0;
1335     }
1336 
1337     if (bs.len != 1) {
1338         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
1339                                  MBEDTLS_ERR_ASN1_INVALID_LENGTH);
1340     }
1341 
1342     /* Get actual bitstring */
1343     *ns_cert_type = *bs.p;
1344     return 0;
1345 }
1346 
mbedtls_x509_get_key_usage(unsigned char ** p,const unsigned char * end,unsigned int * key_usage)1347 int mbedtls_x509_get_key_usage(unsigned char **p,
1348                                const unsigned char *end,
1349                                unsigned int *key_usage)
1350 {
1351     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1352     size_t i;
1353     mbedtls_x509_bitstring bs = { 0, 0, NULL };
1354 
1355     if ((ret = mbedtls_asn1_get_bitstring(p, end, &bs)) != 0) {
1356         return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret);
1357     }
1358 
1359     /* A bitstring with no flags set is still technically valid, as it will mean
1360        that the certificate has no designated purpose at the time of creation. */
1361     if (bs.len == 0) {
1362         *key_usage = 0;
1363         return 0;
1364     }
1365 
1366     /* Get actual bitstring */
1367     *key_usage = 0;
1368     for (i = 0; i < bs.len && i < sizeof(unsigned int); i++) {
1369         *key_usage |= (unsigned int) bs.p[i] << (8*i);
1370     }
1371 
1372     return 0;
1373 }
1374 
mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf * san_buf,mbedtls_x509_subject_alternative_name * san)1375 int mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf *san_buf,
1376                                         mbedtls_x509_subject_alternative_name *san)
1377 {
1378     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1379     switch (san_buf->tag &
1380             (MBEDTLS_ASN1_TAG_CLASS_MASK |
1381              MBEDTLS_ASN1_TAG_VALUE_MASK)) {
1382         /*
1383          * otherName
1384          */
1385         case (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_OTHER_NAME):
1386         {
1387             mbedtls_x509_san_other_name other_name;
1388 
1389             ret = x509_get_other_name(san_buf, &other_name);
1390             if (ret != 0) {
1391                 return ret;
1392             }
1393 
1394             memset(san, 0, sizeof(mbedtls_x509_subject_alternative_name));
1395             san->type = MBEDTLS_X509_SAN_OTHER_NAME;
1396             memcpy(&san->san.other_name,
1397                    &other_name, sizeof(other_name));
1398 
1399         }
1400         break;
1401         /*
1402          * uniformResourceIdentifier
1403          */
1404         case (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER):
1405         {
1406             memset(san, 0, sizeof(mbedtls_x509_subject_alternative_name));
1407             san->type = MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER;
1408 
1409             memcpy(&san->san.unstructured_name,
1410                    san_buf, sizeof(*san_buf));
1411 
1412         }
1413         break;
1414         /*
1415          * dNSName
1416          */
1417         case (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_DNS_NAME):
1418         {
1419             memset(san, 0, sizeof(mbedtls_x509_subject_alternative_name));
1420             san->type = MBEDTLS_X509_SAN_DNS_NAME;
1421 
1422             memcpy(&san->san.unstructured_name,
1423                    san_buf, sizeof(*san_buf));
1424         }
1425         break;
1426 
1427         /*
1428          * RFC822 Name
1429          */
1430         case (MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_X509_SAN_RFC822_NAME):
1431         {
1432             memset(san, 0, sizeof(mbedtls_x509_subject_alternative_name));
1433             san->type = MBEDTLS_X509_SAN_RFC822_NAME;
1434             memcpy(&san->san.unstructured_name, san_buf, sizeof(*san_buf));
1435         }
1436         break;
1437 
1438         /*
1439          * Type not supported
1440          */
1441         default:
1442             return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
1443     }
1444     return 0;
1445 }
1446 
1447 #if !defined(MBEDTLS_X509_REMOVE_INFO)
mbedtls_x509_info_subject_alt_name(char ** buf,size_t * size,const mbedtls_x509_sequence * subject_alt_name,const char * prefix)1448 int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size,
1449                                        const mbedtls_x509_sequence
1450                                        *subject_alt_name,
1451                                        const char *prefix)
1452 {
1453     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1454     size_t i;
1455     size_t n = *size;
1456     char *p = *buf;
1457     const mbedtls_x509_sequence *cur = subject_alt_name;
1458     mbedtls_x509_subject_alternative_name san;
1459     int parse_ret;
1460 
1461     while (cur != NULL) {
1462         memset(&san, 0, sizeof(san));
1463         parse_ret = mbedtls_x509_parse_subject_alt_name(&cur->buf, &san);
1464         if (parse_ret != 0) {
1465             if (parse_ret == MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) {
1466                 ret = mbedtls_snprintf(p, n, "\n%s    <unsupported>", prefix);
1467                 MBEDTLS_X509_SAFE_SNPRINTF;
1468             } else {
1469                 ret = mbedtls_snprintf(p, n, "\n%s    <malformed>", prefix);
1470                 MBEDTLS_X509_SAFE_SNPRINTF;
1471             }
1472             cur = cur->next;
1473             continue;
1474         }
1475 
1476         switch (san.type) {
1477             /*
1478              * otherName
1479              */
1480             case MBEDTLS_X509_SAN_OTHER_NAME:
1481             {
1482                 mbedtls_x509_san_other_name *other_name = &san.san.other_name;
1483 
1484                 ret = mbedtls_snprintf(p, n, "\n%s    otherName :", prefix);
1485                 MBEDTLS_X509_SAFE_SNPRINTF;
1486 
1487                 if (MBEDTLS_OID_CMP(MBEDTLS_OID_ON_HW_MODULE_NAME,
1488                                     &other_name->value.hardware_module_name.oid) != 0) {
1489                     ret = mbedtls_snprintf(p, n, "\n%s        hardware module name :", prefix);
1490                     MBEDTLS_X509_SAFE_SNPRINTF;
1491                     ret =
1492                         mbedtls_snprintf(p, n, "\n%s            hardware type          : ", prefix);
1493                     MBEDTLS_X509_SAFE_SNPRINTF;
1494 
1495                     ret = mbedtls_oid_get_numeric_string(p,
1496                                                          n,
1497                                                          &other_name->value.hardware_module_name.oid);
1498                     MBEDTLS_X509_SAFE_SNPRINTF;
1499 
1500                     ret =
1501                         mbedtls_snprintf(p, n, "\n%s            hardware serial number : ", prefix);
1502                     MBEDTLS_X509_SAFE_SNPRINTF;
1503 
1504                     for (i = 0; i < other_name->value.hardware_module_name.val.len; i++) {
1505                         ret = mbedtls_snprintf(p,
1506                                                n,
1507                                                "%02X",
1508                                                other_name->value.hardware_module_name.val.p[i]);
1509                         MBEDTLS_X509_SAFE_SNPRINTF;
1510                     }
1511                 }/* MBEDTLS_OID_ON_HW_MODULE_NAME */
1512             }
1513             break;
1514             /*
1515              * uniformResourceIdentifier
1516              */
1517             case MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER:
1518             {
1519                 ret = mbedtls_snprintf(p, n, "\n%s    uniformResourceIdentifier : ", prefix);
1520                 MBEDTLS_X509_SAFE_SNPRINTF;
1521                 if (san.san.unstructured_name.len >= n) {
1522                     *p = '\0';
1523                     return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
1524                 }
1525 
1526                 memcpy(p, san.san.unstructured_name.p, san.san.unstructured_name.len);
1527                 p += san.san.unstructured_name.len;
1528                 n -= san.san.unstructured_name.len;
1529             }
1530             break;
1531             /*
1532              * dNSName
1533              * RFC822 Name
1534              */
1535             case MBEDTLS_X509_SAN_DNS_NAME:
1536             case MBEDTLS_X509_SAN_RFC822_NAME:
1537             {
1538                 const char *dns_name = "dNSName";
1539                 const char *rfc822_name = "rfc822Name";
1540 
1541                 ret = mbedtls_snprintf(p, n,
1542                                        "\n%s    %s : ",
1543                                        prefix,
1544                                        san.type ==
1545                                        MBEDTLS_X509_SAN_DNS_NAME ? dns_name : rfc822_name);
1546                 MBEDTLS_X509_SAFE_SNPRINTF;
1547                 if (san.san.unstructured_name.len >= n) {
1548                     *p = '\0';
1549                     return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
1550                 }
1551 
1552                 memcpy(p, san.san.unstructured_name.p, san.san.unstructured_name.len);
1553                 p += san.san.unstructured_name.len;
1554                 n -= san.san.unstructured_name.len;
1555             }
1556             break;
1557 
1558             /*
1559              * Type not supported, skip item.
1560              */
1561             default:
1562                 ret = mbedtls_snprintf(p, n, "\n%s    <unsupported>", prefix);
1563                 MBEDTLS_X509_SAFE_SNPRINTF;
1564                 break;
1565         }
1566 
1567         cur = cur->next;
1568     }
1569 
1570     *p = '\0';
1571 
1572     *size = n;
1573     *buf = p;
1574 
1575     return 0;
1576 }
1577 
1578 #define PRINT_ITEM(i)                           \
1579     {                                           \
1580         ret = mbedtls_snprintf(p, n, "%s" i, sep);    \
1581         MBEDTLS_X509_SAFE_SNPRINTF;                        \
1582         sep = ", ";                             \
1583     }
1584 
1585 #define CERT_TYPE(type, name)                    \
1586     if (ns_cert_type & (type))                 \
1587     PRINT_ITEM(name);
1588 
mbedtls_x509_info_cert_type(char ** buf,size_t * size,unsigned char ns_cert_type)1589 int mbedtls_x509_info_cert_type(char **buf, size_t *size,
1590                                 unsigned char ns_cert_type)
1591 {
1592     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1593     size_t n = *size;
1594     char *p = *buf;
1595     const char *sep = "";
1596 
1597     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT,         "SSL Client");
1598     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER,         "SSL Server");
1599     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_EMAIL,              "Email");
1600     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING,     "Object Signing");
1601     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_RESERVED,           "Reserved");
1602     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_SSL_CA,             "SSL CA");
1603     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA,           "Email CA");
1604     CERT_TYPE(MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA,  "Object Signing CA");
1605 
1606     *size = n;
1607     *buf = p;
1608 
1609     return 0;
1610 }
1611 
1612 #define KEY_USAGE(code, name)    \
1613     if (key_usage & (code))    \
1614     PRINT_ITEM(name);
1615 
mbedtls_x509_info_key_usage(char ** buf,size_t * size,unsigned int key_usage)1616 int mbedtls_x509_info_key_usage(char **buf, size_t *size,
1617                                 unsigned int key_usage)
1618 {
1619     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1620     size_t n = *size;
1621     char *p = *buf;
1622     const char *sep = "";
1623 
1624     KEY_USAGE(MBEDTLS_X509_KU_DIGITAL_SIGNATURE,    "Digital Signature");
1625     KEY_USAGE(MBEDTLS_X509_KU_NON_REPUDIATION,      "Non Repudiation");
1626     KEY_USAGE(MBEDTLS_X509_KU_KEY_ENCIPHERMENT,     "Key Encipherment");
1627     KEY_USAGE(MBEDTLS_X509_KU_DATA_ENCIPHERMENT,    "Data Encipherment");
1628     KEY_USAGE(MBEDTLS_X509_KU_KEY_AGREEMENT,        "Key Agreement");
1629     KEY_USAGE(MBEDTLS_X509_KU_KEY_CERT_SIGN,        "Key Cert Sign");
1630     KEY_USAGE(MBEDTLS_X509_KU_CRL_SIGN,             "CRL Sign");
1631     KEY_USAGE(MBEDTLS_X509_KU_ENCIPHER_ONLY,        "Encipher Only");
1632     KEY_USAGE(MBEDTLS_X509_KU_DECIPHER_ONLY,        "Decipher Only");
1633 
1634     *size = n;
1635     *buf = p;
1636 
1637     return 0;
1638 }
1639 #endif /* MBEDTLS_X509_REMOVE_INFO */
1640 #endif /* MBEDTLS_X509_CRT_PARSE_C || MBEDTLS_X509_CSR_PARSE_C */
1641 #endif /* MBEDTLS_X509_USE_C */
1642