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     if( **p != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2 ) &&
81         **p !=   MBEDTLS_ASN1_INTEGER )
82         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SERIAL,
83                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
84 
85     serial->tag = *(*p)++;
86 
87     if( ( ret = mbedtls_asn1_get_len( p, end, &serial->len ) ) != 0 )
88         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SERIAL, ret ) );
89 
90     serial->p = *p;
91     *p += serial->len;
92 
93     return( 0 );
94 }
95 
96 /* Get an algorithm identifier without parameters (eg for signatures)
97  *
98  *  AlgorithmIdentifier  ::=  SEQUENCE  {
99  *       algorithm               OBJECT IDENTIFIER,
100  *       parameters              ANY DEFINED BY algorithm OPTIONAL  }
101  */
mbedtls_x509_get_alg_null(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg)102 int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,
103                        mbedtls_x509_buf *alg )
104 {
105     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
106 
107     if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 )
108         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
109 
110     return( 0 );
111 }
112 
113 /*
114  * Parse an algorithm identifier with (optional) parameters
115  */
mbedtls_x509_get_alg(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * alg,mbedtls_x509_buf * params)116 int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,
117                   mbedtls_x509_buf *alg, mbedtls_x509_buf *params )
118 {
119     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
120 
121     if( ( ret = mbedtls_asn1_get_alg( p, end, alg, params ) ) != 0 )
122         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
123 
124     return( 0 );
125 }
126 
127 /*
128  * Convert md type to string
129  */
md_type_to_string(mbedtls_md_type_t md_alg)130 static inline const char* md_type_to_string( mbedtls_md_type_t md_alg )
131 {
132     switch( md_alg )
133     {
134 #if defined(MBEDTLS_HAS_ALG_MD5_VIA_MD_OR_PSA)
135     case MBEDTLS_MD_MD5:
136         return( "MD5" );
137 #endif
138 #if defined(MBEDTLS_HAS_ALG_SHA_1_VIA_MD_OR_PSA)
139     case MBEDTLS_MD_SHA1:
140         return( "SHA1" );
141 #endif
142 #if defined(MBEDTLS_HAS_ALG_SHA_224_VIA_MD_OR_PSA)
143     case MBEDTLS_MD_SHA224:
144         return( "SHA224" );
145 #endif
146 #if defined(MBEDTLS_HAS_ALG_SHA_256_VIA_MD_OR_PSA)
147     case MBEDTLS_MD_SHA256:
148         return( "SHA256" );
149 #endif
150 #if defined(MBEDTLS_HAS_ALG_SHA_384_VIA_MD_OR_PSA)
151     case MBEDTLS_MD_SHA384:
152         return( "SHA384" );
153 #endif
154 #if defined(MBEDTLS_HAS_ALG_SHA_512_VIA_MD_OR_PSA)
155     case MBEDTLS_MD_SHA512:
156         return( "SHA512" );
157 #endif
158 #if defined(MBEDTLS_HAS_ALG_RIPEMD160_VIA_MD_OR_PSA)
159     case MBEDTLS_MD_RIPEMD160:
160         return( "RIPEMD160" );
161 #endif
162     case MBEDTLS_MD_NONE:
163         return( NULL );
164     default:
165         return( NULL );
166     }
167 }
168 
169 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
170 /*
171  * HashAlgorithm ::= AlgorithmIdentifier
172  *
173  * AlgorithmIdentifier  ::=  SEQUENCE  {
174  *      algorithm               OBJECT IDENTIFIER,
175  *      parameters              ANY DEFINED BY algorithm OPTIONAL  }
176  *
177  * For HashAlgorithm, parameters MUST be NULL or absent.
178  */
x509_get_hash_alg(const mbedtls_x509_buf * alg,mbedtls_md_type_t * md_alg)179 static int x509_get_hash_alg( const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg )
180 {
181     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
182     unsigned char *p;
183     const unsigned char *end;
184     mbedtls_x509_buf md_oid;
185     size_t len;
186 
187     /* Make sure we got a SEQUENCE and setup bounds */
188     if( alg->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
189         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
190                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
191 
192     p = alg->p;
193     end = p + alg->len;
194 
195     if( p >= end )
196         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
197                 MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
198 
199     /* Parse md_oid */
200     md_oid.tag = *p;
201 
202     if( ( ret = mbedtls_asn1_get_tag( &p, end, &md_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
203         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
204 
205     md_oid.p = p;
206     p += md_oid.len;
207 
208     /* Get md_alg from md_oid */
209     if( ( ret = mbedtls_oid_get_md_alg( &md_oid, md_alg ) ) != 0 )
210         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
211 
212     /* Make sure params is absent of NULL */
213     if( p == end )
214         return( 0 );
215 
216     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_NULL ) ) != 0 || len != 0 )
217         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
218 
219     if( p != end )
220         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
221                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
222 
223     return( 0 );
224 }
225 
226 /*
227  *    RSASSA-PSS-params  ::=  SEQUENCE  {
228  *       hashAlgorithm     [0] HashAlgorithm DEFAULT sha1Identifier,
229  *       maskGenAlgorithm  [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
230  *       saltLength        [2] INTEGER DEFAULT 20,
231  *       trailerField      [3] INTEGER DEFAULT 1  }
232  *    -- Note that the tags in this Sequence are explicit.
233  *
234  * RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value
235  * of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other
236  * option. Enforce this at parsing time.
237  */
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)238 int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,
239                                 mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
240                                 int *salt_len )
241 {
242     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
243     unsigned char *p;
244     const unsigned char *end, *end2;
245     size_t len;
246     mbedtls_x509_buf alg_id, alg_params;
247 
248     /* First set everything to defaults */
249     *md_alg = MBEDTLS_MD_SHA1;
250     *mgf_md = MBEDTLS_MD_SHA1;
251     *salt_len = 20;
252 
253     /* Make sure params is a SEQUENCE and setup bounds */
254     if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
255         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
256                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
257 
258     p = (unsigned char *) params->p;
259     end = p + params->len;
260 
261     if( p == end )
262         return( 0 );
263 
264     /*
265      * HashAlgorithm
266      */
267     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
268                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )
269     {
270         end2 = p + len;
271 
272         /* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */
273         if( ( ret = mbedtls_x509_get_alg_null( &p, end2, &alg_id ) ) != 0 )
274             return( ret );
275 
276         if( ( ret = mbedtls_oid_get_md_alg( &alg_id, md_alg ) ) != 0 )
277             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
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     if( p == end )
287         return( 0 );
288 
289     /*
290      * MaskGenAlgorithm
291      */
292     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
293                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )
294     {
295         end2 = p + len;
296 
297         /* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */
298         if( ( ret = mbedtls_x509_get_alg( &p, end2, &alg_id, &alg_params ) ) != 0 )
299             return( ret );
300 
301         /* Only MFG1 is recognised for now */
302         if( MBEDTLS_OID_CMP( MBEDTLS_OID_MGF1, &alg_id ) != 0 )
303             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE,
304                     MBEDTLS_ERR_OID_NOT_FOUND ) );
305 
306         /* Parse HashAlgorithm */
307         if( ( ret = x509_get_hash_alg( &alg_params, mgf_md ) ) != 0 )
308             return( ret );
309 
310         if( p != end2 )
311             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
312                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
313     }
314     else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
315         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
316 
317     if( p == end )
318         return( 0 );
319 
320     /*
321      * salt_len
322      */
323     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
324                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 2 ) ) == 0 )
325     {
326         end2 = p + len;
327 
328         if( ( ret = mbedtls_asn1_get_int( &p, end2, salt_len ) ) != 0 )
329             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
330 
331         if( p != end2 )
332             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
333                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
334     }
335     else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
336         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
337 
338     if( p == end )
339         return( 0 );
340 
341     /*
342      * trailer_field (if present, must be 1)
343      */
344     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
345                     MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 3 ) ) == 0 )
346     {
347         int trailer_field;
348 
349         end2 = p + len;
350 
351         if( ( ret = mbedtls_asn1_get_int( &p, end2, &trailer_field ) ) != 0 )
352             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
353 
354         if( p != end2 )
355             return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
356                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
357 
358         if( trailer_field != 1 )
359             return( MBEDTLS_ERR_X509_INVALID_ALG );
360     }
361     else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
362         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
363 
364     if( p != end )
365         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
366                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
367 
368     return( 0 );
369 }
370 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
371 
372 /*
373  *  AttributeTypeAndValue ::= SEQUENCE {
374  *    type     AttributeType,
375  *    value    AttributeValue }
376  *
377  *  AttributeType ::= OBJECT IDENTIFIER
378  *
379  *  AttributeValue ::= ANY DEFINED BY AttributeType
380  */
x509_get_attr_type_value(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)381 static int x509_get_attr_type_value( unsigned char **p,
382                                      const unsigned char *end,
383                                      mbedtls_x509_name *cur )
384 {
385     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
386     size_t len;
387     mbedtls_x509_buf *oid;
388     mbedtls_x509_buf *val;
389 
390     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
391             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
392         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
393 
394     end = *p + len;
395 
396     if( ( end - *p ) < 1 )
397         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
398                 MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
399 
400     oid = &cur->oid;
401     oid->tag = **p;
402 
403     if( ( ret = mbedtls_asn1_get_tag( p, end, &oid->len, MBEDTLS_ASN1_OID ) ) != 0 )
404         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
405 
406     oid->p = *p;
407     *p += oid->len;
408 
409     if( ( end - *p ) < 1 )
410         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
411                 MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
412 
413     if( **p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING      &&
414         **p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING &&
415         **p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING &&
416         **p != MBEDTLS_ASN1_BIT_STRING )
417         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
418                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
419 
420     val = &cur->val;
421     val->tag = *(*p)++;
422 
423     if( ( ret = mbedtls_asn1_get_len( p, end, &val->len ) ) != 0 )
424         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
425 
426     val->p = *p;
427     *p += val->len;
428 
429     if( *p != end )
430     {
431         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
432                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
433     }
434 
435     cur->next = NULL;
436 
437     return( 0 );
438 }
439 
440 /*
441  *  Name ::= CHOICE { -- only one possibility for now --
442  *       rdnSequence  RDNSequence }
443  *
444  *  RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
445  *
446  *  RelativeDistinguishedName ::=
447  *    SET OF AttributeTypeAndValue
448  *
449  *  AttributeTypeAndValue ::= SEQUENCE {
450  *    type     AttributeType,
451  *    value    AttributeValue }
452  *
453  *  AttributeType ::= OBJECT IDENTIFIER
454  *
455  *  AttributeValue ::= ANY DEFINED BY AttributeType
456  *
457  * The data structure is optimized for the common case where each RDN has only
458  * one element, which is represented as a list of AttributeTypeAndValue.
459  * For the general case we still use a flat list, but we mark elements of the
460  * same set so that they are "merged" together in the functions that consume
461  * this list, eg mbedtls_x509_dn_gets().
462  *
463  * On success, this function may allocate a linked list starting at cur->next
464  * that must later be free'd by the caller using mbedtls_free(). In error
465  * cases, this function frees all allocated memory internally and the caller
466  * has no freeing responsibilities.
467  */
mbedtls_x509_get_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_name * cur)468 int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end,
469                    mbedtls_x509_name *cur )
470 {
471     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
472     size_t set_len;
473     const unsigned char *end_set;
474     mbedtls_x509_name *head = cur;
475 
476     /* don't use recursion, we'd risk stack overflow if not optimized */
477     while( 1 )
478     {
479         /*
480          * parse SET
481          */
482         if( ( ret = mbedtls_asn1_get_tag( p, end, &set_len,
483                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ) != 0 )
484         {
485             ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret );
486             goto error;
487         }
488 
489         end_set  = *p + set_len;
490 
491         while( 1 )
492         {
493             if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )
494                 goto error;
495 
496             if( *p == end_set )
497                 break;
498 
499             /* Mark this item as being no the only one in a set */
500             cur->next_merged = 1;
501 
502             cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );
503 
504             if( cur->next == NULL )
505             {
506                 ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
507                 goto error;
508             }
509 
510             cur = cur->next;
511         }
512 
513         /*
514          * continue until end of SEQUENCE is reached
515          */
516         if( *p == end )
517             return( 0 );
518 
519         cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );
520 
521         if( cur->next == NULL )
522         {
523             ret = MBEDTLS_ERR_X509_ALLOC_FAILED;
524             goto error;
525         }
526 
527         cur = cur->next;
528     }
529 
530 error:
531     /* Skip the first element as we did not allocate it */
532     mbedtls_asn1_free_named_data_list_shallow( head->next );
533     head->next = NULL;
534 
535     return( ret );
536 }
537 
x509_parse_int(unsigned char ** p,size_t n,int * res)538 static int x509_parse_int( unsigned char **p, size_t n, int *res )
539 {
540     *res = 0;
541 
542     for( ; n > 0; --n )
543     {
544         if( ( **p < '0') || ( **p > '9' ) )
545             return ( MBEDTLS_ERR_X509_INVALID_DATE );
546 
547         *res *= 10;
548         *res += ( *(*p)++ - '0' );
549     }
550 
551     return( 0 );
552 }
553 
x509_date_is_valid(const mbedtls_x509_time * t)554 static int x509_date_is_valid(const mbedtls_x509_time *t )
555 {
556     int ret = MBEDTLS_ERR_X509_INVALID_DATE;
557     int month_len;
558 
559     CHECK_RANGE( 0, 9999, t->year );
560     CHECK_RANGE( 0, 23,   t->hour );
561     CHECK_RANGE( 0, 59,   t->min  );
562     CHECK_RANGE( 0, 59,   t->sec  );
563 
564     switch( t->mon )
565     {
566         case 1: case 3: case 5: case 7: case 8: case 10: case 12:
567             month_len = 31;
568             break;
569         case 4: case 6: case 9: case 11:
570             month_len = 30;
571             break;
572         case 2:
573             if( ( !( t->year % 4 ) && t->year % 100 ) ||
574                 !( t->year % 400 ) )
575                 month_len = 29;
576             else
577                 month_len = 28;
578             break;
579         default:
580             return( ret );
581     }
582     CHECK_RANGE( 1, month_len, t->day );
583 
584     return( 0 );
585 }
586 
587 /*
588  * Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4)
589  * field.
590  */
x509_parse_time(unsigned char ** p,size_t len,size_t yearlen,mbedtls_x509_time * tm)591 static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
592                             mbedtls_x509_time *tm )
593 {
594     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
595 
596     /*
597      * Minimum length is 10 or 12 depending on yearlen
598      */
599     if ( len < yearlen + 8 )
600         return ( MBEDTLS_ERR_X509_INVALID_DATE );
601     len -= yearlen + 8;
602 
603     /*
604      * Parse year, month, day, hour, minute
605      */
606     CHECK( x509_parse_int( p, yearlen, &tm->year ) );
607     if ( 2 == yearlen )
608     {
609         if ( tm->year < 50 )
610             tm->year += 100;
611 
612         tm->year += 1900;
613     }
614 
615     CHECK( x509_parse_int( p, 2, &tm->mon ) );
616     CHECK( x509_parse_int( p, 2, &tm->day ) );
617     CHECK( x509_parse_int( p, 2, &tm->hour ) );
618     CHECK( x509_parse_int( p, 2, &tm->min ) );
619 
620     /*
621      * Parse seconds if present
622      */
623     if ( len >= 2 )
624     {
625         CHECK( x509_parse_int( p, 2, &tm->sec ) );
626         len -= 2;
627     }
628     else
629         return ( MBEDTLS_ERR_X509_INVALID_DATE );
630 
631     /*
632      * Parse trailing 'Z' if present
633      */
634     if ( 1 == len && 'Z' == **p )
635     {
636         (*p)++;
637         len--;
638     }
639 
640     /*
641      * We should have parsed all characters at this point
642      */
643     if ( 0 != len )
644         return ( MBEDTLS_ERR_X509_INVALID_DATE );
645 
646     CHECK( x509_date_is_valid( tm ) );
647 
648     return ( 0 );
649 }
650 
651 /*
652  *  Time ::= CHOICE {
653  *       utcTime        UTCTime,
654  *       generalTime    GeneralizedTime }
655  */
mbedtls_x509_get_time(unsigned char ** p,const unsigned char * end,mbedtls_x509_time * tm)656 int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
657                            mbedtls_x509_time *tm )
658 {
659     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
660     size_t len, year_len;
661     unsigned char tag;
662 
663     if( ( end - *p ) < 1 )
664         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE,
665                 MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
666 
667     tag = **p;
668 
669     if( tag == MBEDTLS_ASN1_UTC_TIME )
670         year_len = 2;
671     else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME )
672         year_len = 4;
673     else
674         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE,
675                 MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
676 
677     (*p)++;
678     ret = mbedtls_asn1_get_len( p, end, &len );
679 
680     if( ret != 0 )
681         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE, ret ) );
682 
683     return x509_parse_time( p, len, year_len, tm );
684 }
685 
mbedtls_x509_get_sig(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * sig)686 int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig )
687 {
688     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
689     size_t len;
690     int tag_type;
691 
692     if( ( end - *p ) < 1 )
693         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SIGNATURE,
694                 MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
695 
696     tag_type = **p;
697 
698     if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )
699         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SIGNATURE, ret ) );
700 
701     sig->tag = tag_type;
702     sig->len = len;
703     sig->p = *p;
704 
705     *p += len;
706 
707     return( 0 );
708 }
709 
710 /*
711  * Get signature algorithm from alg OID and optional parameters
712  */
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)713 int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
714                       mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
715                       void **sig_opts )
716 {
717     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
718 
719     if( *sig_opts != NULL )
720         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
721 
722     if( ( ret = mbedtls_oid_get_sig_alg( sig_oid, md_alg, pk_alg ) ) != 0 )
723         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG, ret ) );
724 
725 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
726     if( *pk_alg == MBEDTLS_PK_RSASSA_PSS )
727     {
728         mbedtls_pk_rsassa_pss_options *pss_opts;
729 
730         pss_opts = mbedtls_calloc( 1, sizeof( mbedtls_pk_rsassa_pss_options ) );
731         if( pss_opts == NULL )
732             return( MBEDTLS_ERR_X509_ALLOC_FAILED );
733 
734         ret = mbedtls_x509_get_rsassa_pss_params( sig_params,
735                                           md_alg,
736                                           &pss_opts->mgf1_hash_id,
737                                           &pss_opts->expected_salt_len );
738         if( ret != 0 )
739         {
740             mbedtls_free( pss_opts );
741             return( ret );
742         }
743 
744         *sig_opts = (void *) pss_opts;
745     }
746     else
747 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
748     {
749         /* Make sure parameters are absent or NULL */
750         if( ( sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0 ) ||
751               sig_params->len != 0 )
752         return( MBEDTLS_ERR_X509_INVALID_ALG );
753     }
754 
755     return( 0 );
756 }
757 
758 /*
759  * X.509 Extensions (No parsing of extensions, pointer should
760  * be either manually updated or extensions should be parsed!)
761  */
mbedtls_x509_get_ext(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * ext,int tag)762 int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
763                           mbedtls_x509_buf *ext, int tag )
764 {
765     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
766     size_t len;
767 
768     /* Extension structure use EXPLICIT tagging. That is, the actual
769      * `Extensions` structure is wrapped by a tag-length pair using
770      * the respective context-specific tag. */
771     ret = mbedtls_asn1_get_tag( p, end, &ext->len,
772               MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag );
773     if( ret != 0 )
774         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
775 
776     ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag;
777     ext->p   = *p;
778     end      = *p + ext->len;
779 
780     /*
781      * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
782      */
783     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
784             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
785         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
786 
787     if( end != *p + len )
788         return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
789                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
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     {
815         if( !name->oid.p )
816         {
817             name = name->next;
818             continue;
819         }
820 
821         if( name != dn )
822         {
823             ret = mbedtls_snprintf( p, n, merge ? " + " : ", " );
824             MBEDTLS_X509_SAFE_SNPRINTF;
825         }
826 
827         ret = mbedtls_oid_get_attr_short_name( &name->oid, &short_name );
828 
829         if( ret == 0 )
830             ret = mbedtls_snprintf( p, n, "%s=", short_name );
831         else
832             ret = mbedtls_snprintf( p, n, "\?\?=" );
833         MBEDTLS_X509_SAFE_SNPRINTF;
834 
835         for( i = 0, j = 0; i < name->val.len; i++, j++ )
836         {
837             if( j >= sizeof( s ) - 1 )
838                 return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
839 
840             c = name->val.p[i];
841             // Special characters requiring escaping, RFC 1779
842             if( c && strchr( ",=+<>#;\"\\", c ) )
843             {
844                 if( j + 1 >= sizeof( s ) - 1 )
845                     return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
846                 s[j++] = '\\';
847             }
848             if( c < 32 || c >= 127 )
849                  s[j] = '?';
850             else s[j] = c;
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     {
881         if( i == 0 && nr > 1 && serial->p[i] == 0x0 )
882             continue;
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     {
891         ret = mbedtls_snprintf( p, n, "...." );
892         MBEDTLS_X509_SAFE_SNPRINTF;
893     }
894 
895     return( (int) ( size - n ) );
896 }
897 
898 #if !defined(MBEDTLS_X509_REMOVE_INFO)
899 /*
900  * Helper for writing signature algorithms
901  */
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)902 int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
903                        mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
904                        const void *sig_opts )
905 {
906     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
907     char *p = buf;
908     size_t n = size;
909     const char *desc = NULL;
910 
911     ret = mbedtls_oid_get_sig_alg_desc( sig_oid, &desc );
912     if( ret != 0 )
913         ret = mbedtls_snprintf( p, n, "???"  );
914     else
915         ret = mbedtls_snprintf( p, n, "%s", desc );
916     MBEDTLS_X509_SAFE_SNPRINTF;
917 
918 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
919     if( pk_alg == MBEDTLS_PK_RSASSA_PSS )
920     {
921         const mbedtls_pk_rsassa_pss_options *pss_opts;
922 
923         pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts;
924 
925         const char *name = md_type_to_string( md_alg );
926         const char *mgf_name = md_type_to_string( pss_opts->mgf1_hash_id );
927 
928         ret = mbedtls_snprintf( p, n, " (%s, MGF1-%s, 0x%02X)",
929                               name ? name : "???",
930                               mgf_name ? mgf_name : "???",
931                               (unsigned int) pss_opts->expected_salt_len );
932         MBEDTLS_X509_SAFE_SNPRINTF;
933     }
934 #else
935     ((void) pk_alg);
936     ((void) md_alg);
937     ((void) sig_opts);
938 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
939 
940     return( (int)( size - n ) );
941 }
942 #endif /* MBEDTLS_X509_REMOVE_INFO */
943 
944 /*
945  * Helper for writing "RSA key size", "EC key size", etc
946  */
mbedtls_x509_key_size_helper(char * buf,size_t buf_size,const char * name)947 int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name )
948 {
949     char *p = buf;
950     size_t n = buf_size;
951     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
952 
953     ret = mbedtls_snprintf( p, n, "%s key size", name );
954     MBEDTLS_X509_SAFE_SNPRINTF;
955 
956     return( 0 );
957 }
958 
959 #if defined(MBEDTLS_HAVE_TIME_DATE)
960 /*
961  * Set the time structure to the current time.
962  * Return 0 on success, non-zero on failure.
963  */
x509_get_current_time(mbedtls_x509_time * now)964 static int x509_get_current_time( mbedtls_x509_time *now )
965 {
966     struct tm *lt, tm_buf;
967     mbedtls_time_t tt;
968     int ret = 0;
969 
970     tt = mbedtls_time( NULL );
971     lt = mbedtls_platform_gmtime_r( &tt, &tm_buf );
972 
973     if( lt == NULL )
974         ret = -1;
975     else
976     {
977         now->year = lt->tm_year + 1900;
978         now->mon  = lt->tm_mon  + 1;
979         now->day  = lt->tm_mday;
980         now->hour = lt->tm_hour;
981         now->min  = lt->tm_min;
982         now->sec  = lt->tm_sec;
983     }
984 
985     return( ret );
986 }
987 
988 /*
989  * Return 0 if before <= after, 1 otherwise
990  */
x509_check_time(const mbedtls_x509_time * before,const mbedtls_x509_time * after)991 static int x509_check_time( const mbedtls_x509_time *before, const mbedtls_x509_time *after )
992 {
993     if( before->year  > after->year )
994         return( 1 );
995 
996     if( before->year == after->year &&
997         before->mon   > after->mon )
998         return( 1 );
999 
1000     if( before->year == after->year &&
1001         before->mon  == after->mon  &&
1002         before->day   > after->day )
1003         return( 1 );
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     if( before->year == after->year &&
1012         before->mon  == after->mon  &&
1013         before->day  == after->day  &&
1014         before->hour == after->hour &&
1015         before->min   > after->min  )
1016         return( 1 );
1017 
1018     if( before->year == after->year &&
1019         before->mon  == after->mon  &&
1020         before->day  == after->day  &&
1021         before->hour == after->hour &&
1022         before->min  == after->min  &&
1023         before->sec   > after->sec  )
1024         return( 1 );
1025 
1026     return( 0 );
1027 }
1028 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1029 int mbedtls_x509_time_is_past( const mbedtls_x509_time *to )
1030 {
1031     mbedtls_x509_time now;
1032 
1033     if( x509_get_current_time( &now ) != 0 )
1034         return( 1 );
1035 
1036     return( x509_check_time( &now, to ) );
1037 }
1038 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1039 int mbedtls_x509_time_is_future( const mbedtls_x509_time *from )
1040 {
1041     mbedtls_x509_time now;
1042 
1043     if( x509_get_current_time( &now ) != 0 )
1044         return( 1 );
1045 
1046     return( x509_check_time( from, &now ) );
1047 }
1048 
1049 #else  /* MBEDTLS_HAVE_TIME_DATE */
1050 
mbedtls_x509_time_is_past(const mbedtls_x509_time * to)1051 int mbedtls_x509_time_is_past( const mbedtls_x509_time *to )
1052 {
1053     ((void) to);
1054     return( 0 );
1055 }
1056 
mbedtls_x509_time_is_future(const mbedtls_x509_time * from)1057 int mbedtls_x509_time_is_future( const mbedtls_x509_time *from )
1058 {
1059     ((void) from);
1060     return( 0 );
1061 }
1062 #endif /* MBEDTLS_HAVE_TIME_DATE */
1063 #endif /* MBEDTLS_X509_USE_C */
1064