1 /*
2  *  X.509 certificate parsing and verification
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: GPL-2.0
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License along
18  *  with this program; if not, write to the Free Software Foundation, Inc.,
19  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  *  This file is part of mbed TLS (https://tls.mbed.org)
22  */
23 /*
24  *  The ITU-T X.509 standard defines a certificate format for PKI.
25  *
26  *  http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
27  *  http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
28  *  http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
29  *
30  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
31  *  http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
32  *
33  *  [SIRO] https://cabforum.org/wp-content/uploads/Chunghwatelecom201503cabforumV4.pdf
34  */
35 
36 #if !defined(MBEDTLS_CONFIG_FILE)
37 #include "mbedtls/config.h"
38 #else
39 #include MBEDTLS_CONFIG_FILE
40 #endif
41 
42 #if defined(MBEDTLS_X509_CRT_PARSE_C)
43 
44 #include "mbedtls/x509_crt.h"
45 #include "mbedtls/oid.h"
46 #include "mbedtls/platform_util.h"
47 
48 #include <string.h>
49 
50 #if defined(MBEDTLS_PEM_PARSE_C)
51 #include "mbedtls/pem.h"
52 #endif
53 
54 #if defined(MBEDTLS_PLATFORM_C)
55 #include "mbedtls/platform.h"
56 #else
57 #include <stdio.h>
58 #include <stdlib.h>
59 #define mbedtls_free       free
60 #define mbedtls_calloc    calloc
61 #define mbedtls_snprintf   snprintf
62 #endif
63 
64 #if defined(MBEDTLS_THREADING_C)
65 #include "mbedtls/threading.h"
66 #endif
67 
68 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
69 #include <windows.h>
70 #else
71 #include <time.h>
72 #endif
73 
74 #if defined(MBEDTLS_FS_IO)
75 #include <stdio.h>
76 #if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
77 #include <sys/types.h>
78 #include <sys/stat.h>
79 #include <dirent.h>
80 #endif /* !_WIN32 || EFIX64 || EFI32 */
81 #endif
82 
83 /*
84  * Item in a verification chain: cert and flags for it
85  */
86 typedef struct {
87     mbedtls_x509_crt *crt;
88     uint32_t flags;
89 } x509_crt_verify_chain_item;
90 
91 /*
92  * Max size of verification chain: end-entity + intermediates + trusted root
93  */
94 #define X509_MAX_VERIFY_CHAIN_SIZE    ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
95 
96 /*
97  * Default profile
98  */
99 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
100 {
101 #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
102     /* Allow SHA-1 (weak, but still safe in controlled environments) */
103     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
104 #endif
105     /* Only SHA-2 hashes */
106     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
107     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
108     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
109     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
110     0xFFFFFFF, /* Any PK alg    */
111     0xFFFFFFF, /* Any curve     */
112     2048,
113 };
114 
115 /*
116  * Next-default profile
117  */
118 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
119 {
120     /* Hashes from SHA-256 and above */
121     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
122     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
123     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
124     0xFFFFFFF, /* Any PK alg    */
125 #if defined(MBEDTLS_ECP_C)
126     /* Curves at or above 128-bit security level */
127     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
128     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
129     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
130     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
131     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
132     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
133     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
134 #else
135     0,
136 #endif
137     2048,
138 };
139 
140 /*
141  * NSA Suite B Profile
142  */
143 const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
144 {
145     /* Only SHA-256 and 384 */
146     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
147     MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
148     /* Only ECDSA */
149     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |
150     MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),
151 #if defined(MBEDTLS_ECP_C)
152     /* Only NIST P-256 and P-384 */
153     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
154     MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
155 #else
156     0,
157 #endif
158     0,
159 };
160 
161 /*
162  * Check md_alg against profile
163  * Return 0 if md_alg is acceptable for this profile, -1 otherwise
164  */
x509_profile_check_md_alg(const mbedtls_x509_crt_profile * profile,mbedtls_md_type_t md_alg)165 static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
166                                       mbedtls_md_type_t md_alg )
167 {
168     if( md_alg == MBEDTLS_MD_NONE )
169         return( -1 );
170 
171     if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
172         return( 0 );
173 
174     return( -1 );
175 }
176 
177 /*
178  * Check pk_alg against profile
179  * Return 0 if pk_alg is acceptable for this profile, -1 otherwise
180  */
x509_profile_check_pk_alg(const mbedtls_x509_crt_profile * profile,mbedtls_pk_type_t pk_alg)181 static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
182                                       mbedtls_pk_type_t pk_alg )
183 {
184     if( pk_alg == MBEDTLS_PK_NONE )
185         return( -1 );
186 
187     if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
188         return( 0 );
189 
190     return( -1 );
191 }
192 
193 /*
194  * Check key against profile
195  * Return 0 if pk is acceptable for this profile, -1 otherwise
196  */
x509_profile_check_key(const mbedtls_x509_crt_profile * profile,const mbedtls_pk_context * pk)197 static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
198                                    const mbedtls_pk_context *pk )
199 {
200     const mbedtls_pk_type_t pk_alg = mbedtls_pk_get_type( pk );
201 
202 #if defined(MBEDTLS_RSA_C)
203     if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
204     {
205         if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
206             return( 0 );
207 
208         return( -1 );
209     }
210 #endif
211 
212 #if defined(MBEDTLS_ECP_C)
213     if( pk_alg == MBEDTLS_PK_ECDSA ||
214         pk_alg == MBEDTLS_PK_ECKEY ||
215         pk_alg == MBEDTLS_PK_ECKEY_DH )
216     {
217         const mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
218 
219         if( gid == MBEDTLS_ECP_DP_NONE )
220             return( -1 );
221 
222         if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
223             return( 0 );
224 
225         return( -1 );
226     }
227 #endif
228 
229     return( -1 );
230 }
231 
232 /*
233  * Like memcmp, but case-insensitive and always returns -1 if different
234  */
x509_memcasecmp(const void * s1,const void * s2,size_t len)235 static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
236 {
237     size_t i;
238     unsigned char diff;
239     const unsigned char *n1 = s1, *n2 = s2;
240 
241     for( i = 0; i < len; i++ )
242     {
243         diff = n1[i] ^ n2[i];
244 
245         if( diff == 0 )
246             continue;
247 
248         if( diff == 32 &&
249             ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
250               ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
251         {
252             continue;
253         }
254 
255         return( -1 );
256     }
257 
258     return( 0 );
259 }
260 
261 /*
262  * Return 0 if name matches wildcard, -1 otherwise
263  */
x509_check_wildcard(const char * cn,const mbedtls_x509_buf * name)264 static int x509_check_wildcard( const char *cn, const mbedtls_x509_buf *name )
265 {
266     size_t i;
267     size_t cn_idx = 0, cn_len = strlen( cn );
268 
269     /* We can't have a match if there is no wildcard to match */
270     if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
271         return( -1 );
272 
273     for( i = 0; i < cn_len; ++i )
274     {
275         if( cn[i] == '.' )
276         {
277             cn_idx = i;
278             break;
279         }
280     }
281 
282     if( cn_idx == 0 )
283         return( -1 );
284 
285     if( cn_len - cn_idx == name->len - 1 &&
286         x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
287     {
288         return( 0 );
289     }
290 
291     return( -1 );
292 }
293 
294 /*
295  * Compare two X.509 strings, case-insensitive, and allowing for some encoding
296  * variations (but not all).
297  *
298  * Return 0 if equal, -1 otherwise.
299  */
x509_string_cmp(const mbedtls_x509_buf * a,const mbedtls_x509_buf * b)300 static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
301 {
302     if( a->tag == b->tag &&
303         a->len == b->len &&
304         memcmp( a->p, b->p, b->len ) == 0 )
305     {
306         return( 0 );
307     }
308 
309     if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
310         ( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
311         a->len == b->len &&
312         x509_memcasecmp( a->p, b->p, b->len ) == 0 )
313     {
314         return( 0 );
315     }
316 
317     return( -1 );
318 }
319 
320 /*
321  * Compare two X.509 Names (aka rdnSequence).
322  *
323  * See RFC 5280 section 7.1, though we don't implement the whole algorithm:
324  * we sometimes return unequal when the full algorithm would return equal,
325  * but never the other way. (In particular, we don't do Unicode normalisation
326  * or space folding.)
327  *
328  * Return 0 if equal, -1 otherwise.
329  */
x509_name_cmp(const mbedtls_x509_name * a,const mbedtls_x509_name * b)330 static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
331 {
332     /* Avoid recursion, it might not be optimised by the compiler */
333     while( a != NULL || b != NULL )
334     {
335         if( a == NULL || b == NULL )
336             return( -1 );
337 
338         /* type */
339         if( a->oid.tag != b->oid.tag ||
340             a->oid.len != b->oid.len ||
341             memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
342         {
343             return( -1 );
344         }
345 
346         /* value */
347         if( x509_string_cmp( &a->val, &b->val ) != 0 )
348             return( -1 );
349 
350         /* structure of the list of sets */
351         if( a->next_merged != b->next_merged )
352             return( -1 );
353 
354         a = a->next;
355         b = b->next;
356     }
357 
358     /* a == NULL == b */
359     return( 0 );
360 }
361 
362 /*
363  * Reset (init or clear) a verify_chain
364  */
x509_crt_verify_chain_reset(mbedtls_x509_crt_verify_chain * ver_chain)365 static void x509_crt_verify_chain_reset(
366     mbedtls_x509_crt_verify_chain *ver_chain )
367 {
368     size_t i;
369 
370     for( i = 0; i < MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE; i++ )
371     {
372         ver_chain->items[i].crt = NULL;
373         ver_chain->items[i].flags = -1;
374     }
375 
376     ver_chain->len = 0;
377 }
378 
379 /*
380  *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
381  */
x509_get_version(unsigned char ** p,const unsigned char * end,int * ver)382 static int x509_get_version( unsigned char **p,
383                              const unsigned char *end,
384                              int *ver )
385 {
386     int ret;
387     size_t len;
388 
389     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
390             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
391     {
392         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
393         {
394             *ver = 0;
395             return( 0 );
396         }
397 
398         return( ret );
399     }
400 
401     end = *p + len;
402 
403     if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
404         return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
405 
406     if( *p != end )
407         return( MBEDTLS_ERR_X509_INVALID_VERSION +
408                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
409 
410     return( 0 );
411 }
412 
413 /*
414  *  Validity ::= SEQUENCE {
415  *       notBefore      Time,
416  *       notAfter       Time }
417  */
x509_get_dates(unsigned char ** p,const unsigned char * end,mbedtls_x509_time * from,mbedtls_x509_time * to)418 static int x509_get_dates( unsigned char **p,
419                            const unsigned char *end,
420                            mbedtls_x509_time *from,
421                            mbedtls_x509_time *to )
422 {
423     int ret;
424     size_t len;
425 
426     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
427             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
428         return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
429 
430     end = *p + len;
431 
432     if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
433         return( ret );
434 
435     if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
436         return( ret );
437 
438     if( *p != end )
439         return( MBEDTLS_ERR_X509_INVALID_DATE +
440                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
441 
442     return( 0 );
443 }
444 
445 /*
446  * X.509 v2/v3 unique identifier (not parsed)
447  */
x509_get_uid(unsigned char ** p,const unsigned char * end,mbedtls_x509_buf * uid,int n)448 static int x509_get_uid( unsigned char **p,
449                          const unsigned char *end,
450                          mbedtls_x509_buf *uid, int n )
451 {
452     int ret;
453 
454     if( *p == end )
455         return( 0 );
456 
457     uid->tag = **p;
458 
459     if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
460             MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
461     {
462         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
463             return( 0 );
464 
465         return( ret );
466     }
467 
468     uid->p = *p;
469     *p += uid->len;
470 
471     return( 0 );
472 }
473 
x509_get_basic_constraints(unsigned char ** p,const unsigned char * end,int * ca_istrue,int * max_pathlen)474 static int x509_get_basic_constraints( unsigned char **p,
475                                        const unsigned char *end,
476                                        int *ca_istrue,
477                                        int *max_pathlen )
478 {
479     int ret;
480     size_t len;
481 
482     /*
483      * BasicConstraints ::= SEQUENCE {
484      *      cA                      BOOLEAN DEFAULT FALSE,
485      *      pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
486      */
487     *ca_istrue = 0; /* DEFAULT FALSE */
488     *max_pathlen = 0; /* endless */
489 
490     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
491             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
492         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
493 
494     if( *p == end )
495         return( 0 );
496 
497     if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
498     {
499         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
500             ret = mbedtls_asn1_get_int( p, end, ca_istrue );
501 
502         if( ret != 0 )
503             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
504 
505         if( *ca_istrue != 0 )
506             *ca_istrue = 1;
507     }
508 
509     if( *p == end )
510         return( 0 );
511 
512     if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
513         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
514 
515     if( *p != end )
516         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
517                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
518 
519     (*max_pathlen)++;
520 
521     return( 0 );
522 }
523 
x509_get_ns_cert_type(unsigned char ** p,const unsigned char * end,unsigned char * ns_cert_type)524 static int x509_get_ns_cert_type( unsigned char **p,
525                                        const unsigned char *end,
526                                        unsigned char *ns_cert_type)
527 {
528     int ret;
529     mbedtls_x509_bitstring bs = { 0, 0, NULL };
530 
531     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
532         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
533 
534     if( bs.len != 1 )
535         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
536                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
537 
538     /* Get actual bitstring */
539     *ns_cert_type = *bs.p;
540     return( 0 );
541 }
542 
x509_get_key_usage(unsigned char ** p,const unsigned char * end,unsigned int * key_usage)543 static int x509_get_key_usage( unsigned char **p,
544                                const unsigned char *end,
545                                unsigned int *key_usage)
546 {
547     int ret;
548     size_t i;
549     mbedtls_x509_bitstring bs = { 0, 0, NULL };
550 
551     if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
552         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
553 
554     if( bs.len < 1 )
555         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
556                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
557 
558     /* Get actual bitstring */
559     *key_usage = 0;
560     for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
561     {
562         *key_usage |= (unsigned int) bs.p[i] << (8*i);
563     }
564 
565     return( 0 );
566 }
567 
568 /*
569  * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
570  *
571  * KeyPurposeId ::= OBJECT IDENTIFIER
572  */
x509_get_ext_key_usage(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * ext_key_usage)573 static int x509_get_ext_key_usage( unsigned char **p,
574                                const unsigned char *end,
575                                mbedtls_x509_sequence *ext_key_usage)
576 {
577     int ret;
578 
579     if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
580         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
581 
582     /* Sequence length must be >= 1 */
583     if( ext_key_usage->buf.p == NULL )
584         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
585                 MBEDTLS_ERR_ASN1_INVALID_LENGTH );
586 
587     return( 0 );
588 }
589 
590 /*
591  * SubjectAltName ::= GeneralNames
592  *
593  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
594  *
595  * GeneralName ::= CHOICE {
596  *      otherName                       [0]     OtherName,
597  *      rfc822Name                      [1]     IA5String,
598  *      dNSName                         [2]     IA5String,
599  *      x400Address                     [3]     ORAddress,
600  *      directoryName                   [4]     Name,
601  *      ediPartyName                    [5]     EDIPartyName,
602  *      uniformResourceIdentifier       [6]     IA5String,
603  *      iPAddress                       [7]     OCTET STRING,
604  *      registeredID                    [8]     OBJECT IDENTIFIER }
605  *
606  * OtherName ::= SEQUENCE {
607  *      type-id    OBJECT IDENTIFIER,
608  *      value      [0] EXPLICIT ANY DEFINED BY type-id }
609  *
610  * EDIPartyName ::= SEQUENCE {
611  *      nameAssigner            [0]     DirectoryString OPTIONAL,
612  *      partyName               [1]     DirectoryString }
613  *
614  * NOTE: we only parse and use dNSName at this point.
615  */
x509_get_subject_alt_name(unsigned char ** p,const unsigned char * end,mbedtls_x509_sequence * subject_alt_name)616 static int x509_get_subject_alt_name( unsigned char **p,
617                                       const unsigned char *end,
618                                       mbedtls_x509_sequence *subject_alt_name )
619 {
620     int ret;
621     size_t len, tag_len;
622     mbedtls_asn1_buf *buf;
623     unsigned char tag;
624     mbedtls_asn1_sequence *cur = subject_alt_name;
625 
626     /* Get main sequence tag */
627     if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
628             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
629         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
630 
631     if( *p + len != end )
632         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
633                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
634 
635     while( *p < end )
636     {
637         if( ( end - *p ) < 1 )
638             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
639                     MBEDTLS_ERR_ASN1_OUT_OF_DATA );
640 
641         tag = **p;
642         (*p)++;
643         if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
644             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
645 
646         if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=
647                 MBEDTLS_ASN1_CONTEXT_SPECIFIC )
648         {
649             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
650                     MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
651         }
652 
653         /* Skip everything but DNS name */
654         if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
655         {
656             *p += tag_len;
657             continue;
658         }
659 
660         /* Allocate and assign next pointer */
661         if( cur->buf.p != NULL )
662         {
663             if( cur->next != NULL )
664                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
665 
666             cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
667 
668             if( cur->next == NULL )
669                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
670                         MBEDTLS_ERR_ASN1_ALLOC_FAILED );
671 
672             cur = cur->next;
673         }
674 
675         buf = &(cur->buf);
676         buf->tag = tag;
677         buf->p = *p;
678         buf->len = tag_len;
679         *p += buf->len;
680     }
681 
682     /* Set final sequence entry's next pointer to NULL */
683     cur->next = NULL;
684 
685     if( *p != end )
686         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
687                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
688 
689     return( 0 );
690 }
691 
692 /*
693  * X.509 v3 extensions
694  *
695  */
x509_get_crt_ext(unsigned char ** p,const unsigned char * end,mbedtls_x509_crt * crt)696 static int x509_get_crt_ext( unsigned char **p,
697                              const unsigned char *end,
698                              mbedtls_x509_crt *crt )
699 {
700     int ret;
701     size_t len;
702     unsigned char *end_ext_data, *end_ext_octet;
703 
704     if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
705     {
706         if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
707             return( 0 );
708 
709         return( ret );
710     }
711 
712     while( *p < end )
713     {
714         /*
715          * Extension  ::=  SEQUENCE  {
716          *      extnID      OBJECT IDENTIFIER,
717          *      critical    BOOLEAN DEFAULT FALSE,
718          *      extnValue   OCTET STRING  }
719          */
720         mbedtls_x509_buf extn_oid = {0, 0, NULL};
721         int is_critical = 0; /* DEFAULT FALSE */
722         int ext_type = 0;
723 
724         if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
725                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
726             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
727 
728         end_ext_data = *p + len;
729 
730         /* Get extension ID */
731         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len,
732                                           MBEDTLS_ASN1_OID ) ) != 0 )
733             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
734 
735         extn_oid.tag = MBEDTLS_ASN1_OID;
736         extn_oid.p = *p;
737         *p += extn_oid.len;
738 
739         /* Get optional critical */
740         if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
741             ( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
742             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
743 
744         /* Data should be octet string type */
745         if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
746                 MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
747             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
748 
749         end_ext_octet = *p + len;
750 
751         if( end_ext_octet != end_ext_data )
752             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
753                     MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
754 
755         /*
756          * Detect supported extensions
757          */
758         ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
759 
760         if( ret != 0 )
761         {
762             /* No parser found, skip extension */
763             *p = end_ext_octet;
764 
765 #if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
766             if( is_critical )
767             {
768                 /* Data is marked as critical: fail */
769                 return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
770                         MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
771             }
772 #endif
773             continue;
774         }
775 
776         /* Forbid repeated extensions */
777         if( ( crt->ext_types & ext_type ) != 0 )
778             return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
779 
780         crt->ext_types |= ext_type;
781 
782         switch( ext_type )
783         {
784         case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
785             /* Parse basic constraints */
786             if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
787                     &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
788                 return( ret );
789             break;
790 
791         case MBEDTLS_X509_EXT_KEY_USAGE:
792             /* Parse key usage */
793             if( ( ret = x509_get_key_usage( p, end_ext_octet,
794                     &crt->key_usage ) ) != 0 )
795                 return( ret );
796             break;
797 
798         case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
799             /* Parse extended key usage */
800             if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
801                     &crt->ext_key_usage ) ) != 0 )
802                 return( ret );
803             break;
804 
805         case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
806             /* Parse subject alt name */
807             if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
808                     &crt->subject_alt_names ) ) != 0 )
809                 return( ret );
810             break;
811 
812         case MBEDTLS_X509_EXT_NS_CERT_TYPE:
813             /* Parse netscape certificate type */
814             if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
815                     &crt->ns_cert_type ) ) != 0 )
816                 return( ret );
817             break;
818 
819         default:
820             return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
821         }
822     }
823 
824     if( *p != end )
825         return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
826                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
827 
828     return( 0 );
829 }
830 
831 /*
832  * Parse and fill a single X.509 certificate in DER format
833  */
x509_crt_parse_der_core(mbedtls_x509_crt * crt,const unsigned char * buf,size_t buflen)834 static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
835                                     size_t buflen )
836 {
837     int ret;
838     size_t len;
839     unsigned char *p, *end, *crt_end;
840     mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
841 
842     memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
843     memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
844     memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
845 
846     /*
847      * Check for valid input
848      */
849     if( crt == NULL || buf == NULL )
850         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
851 
852     // Use the original buffer until we figure out actual length
853     p = (unsigned char*) buf;
854     len = buflen;
855     end = p + len;
856 
857     /*
858      * Certificate  ::=  SEQUENCE  {
859      *      tbsCertificate       TBSCertificate,
860      *      signatureAlgorithm   AlgorithmIdentifier,
861      *      signatureValue       BIT STRING  }
862      */
863     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
864             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
865     {
866         mbedtls_x509_crt_free( crt );
867         return( MBEDTLS_ERR_X509_INVALID_FORMAT );
868     }
869 
870     if( len > (size_t) ( end - p ) )
871     {
872         mbedtls_x509_crt_free( crt );
873         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
874                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
875     }
876     crt_end = p + len;
877 
878     // Create and populate a new buffer for the raw field
879     crt->raw.len = crt_end - buf;
880     crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
881     if( p == NULL )
882         return( MBEDTLS_ERR_X509_ALLOC_FAILED );
883 
884     memcpy( p, buf, crt->raw.len );
885 
886     // Direct pointers to the new buffer
887     p += crt->raw.len - len;
888     end = crt_end = p + len;
889 
890     /*
891      * TBSCertificate  ::=  SEQUENCE  {
892      */
893     crt->tbs.p = p;
894 
895     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
896             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
897     {
898         mbedtls_x509_crt_free( crt );
899         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
900     }
901 
902     end = p + len;
903     crt->tbs.len = end - crt->tbs.p;
904 
905     /*
906      * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
907      *
908      * CertificateSerialNumber  ::=  INTEGER
909      *
910      * signature            AlgorithmIdentifier
911      */
912     if( ( ret = x509_get_version(  &p, end, &crt->version  ) ) != 0 ||
913         ( ret = mbedtls_x509_get_serial(   &p, end, &crt->serial   ) ) != 0 ||
914         ( ret = mbedtls_x509_get_alg(      &p, end, &crt->sig_oid,
915                                             &sig_params1 ) ) != 0 )
916     {
917         mbedtls_x509_crt_free( crt );
918         return( ret );
919     }
920 
921     if( crt->version < 0 || crt->version > 2 )
922     {
923         mbedtls_x509_crt_free( crt );
924         return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
925     }
926 
927     crt->version++;
928 
929     if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
930                                   &crt->sig_md, &crt->sig_pk,
931                                   &crt->sig_opts ) ) != 0 )
932     {
933         mbedtls_x509_crt_free( crt );
934         return( ret );
935     }
936 
937     /*
938      * issuer               Name
939      */
940     crt->issuer_raw.p = p;
941 
942     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
943             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
944     {
945         mbedtls_x509_crt_free( crt );
946         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
947     }
948 
949     if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
950     {
951         mbedtls_x509_crt_free( crt );
952         return( ret );
953     }
954 
955     crt->issuer_raw.len = p - crt->issuer_raw.p;
956 
957     /*
958      * Validity ::= SEQUENCE {
959      *      notBefore      Time,
960      *      notAfter       Time }
961      *
962      */
963     if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
964                                          &crt->valid_to ) ) != 0 )
965     {
966         mbedtls_x509_crt_free( crt );
967         return( ret );
968     }
969 
970     /*
971      * subject              Name
972      */
973     crt->subject_raw.p = p;
974 
975     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
976             MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
977     {
978         mbedtls_x509_crt_free( crt );
979         return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
980     }
981 
982     if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
983     {
984         mbedtls_x509_crt_free( crt );
985         return( ret );
986     }
987 
988     crt->subject_raw.len = p - crt->subject_raw.p;
989 
990     /*
991      * SubjectPublicKeyInfo
992      */
993     if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
994     {
995         mbedtls_x509_crt_free( crt );
996         return( ret );
997     }
998 
999     /*
1000      *  issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
1001      *                       -- If present, version shall be v2 or v3
1002      *  subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
1003      *                       -- If present, version shall be v2 or v3
1004      *  extensions      [3]  EXPLICIT Extensions OPTIONAL
1005      *                       -- If present, version shall be v3
1006      */
1007     if( crt->version == 2 || crt->version == 3 )
1008     {
1009         ret = x509_get_uid( &p, end, &crt->issuer_id,  1 );
1010         if( ret != 0 )
1011         {
1012             mbedtls_x509_crt_free( crt );
1013             return( ret );
1014         }
1015     }
1016 
1017     if( crt->version == 2 || crt->version == 3 )
1018     {
1019         ret = x509_get_uid( &p, end, &crt->subject_id,  2 );
1020         if( ret != 0 )
1021         {
1022             mbedtls_x509_crt_free( crt );
1023             return( ret );
1024         }
1025     }
1026 
1027 #if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
1028     if( crt->version == 3 )
1029 #endif
1030     {
1031         ret = x509_get_crt_ext( &p, end, crt );
1032         if( ret != 0 )
1033         {
1034             mbedtls_x509_crt_free( crt );
1035             return( ret );
1036         }
1037     }
1038 
1039     if( p != end )
1040     {
1041         mbedtls_x509_crt_free( crt );
1042         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
1043                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
1044     }
1045 
1046     end = crt_end;
1047 
1048     /*
1049      *  }
1050      *  -- end of TBSCertificate
1051      *
1052      *  signatureAlgorithm   AlgorithmIdentifier,
1053      *  signatureValue       BIT STRING
1054      */
1055     if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
1056     {
1057         mbedtls_x509_crt_free( crt );
1058         return( ret );
1059     }
1060 
1061     if( crt->sig_oid.len != sig_oid2.len ||
1062         memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
1063         sig_params1.len != sig_params2.len ||
1064         ( sig_params1.len != 0 &&
1065           memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
1066     {
1067         mbedtls_x509_crt_free( crt );
1068         return( MBEDTLS_ERR_X509_SIG_MISMATCH );
1069     }
1070 
1071     if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
1072     {
1073         mbedtls_x509_crt_free( crt );
1074         return( ret );
1075     }
1076 
1077     if( p != end )
1078     {
1079         mbedtls_x509_crt_free( crt );
1080         return( MBEDTLS_ERR_X509_INVALID_FORMAT +
1081                 MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
1082     }
1083 
1084     return( 0 );
1085 }
1086 
1087 /*
1088  * Parse one X.509 certificate in DER format from a buffer and add them to a
1089  * chained list
1090  */
mbedtls_x509_crt_parse_der(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen)1091 int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
1092                         size_t buflen )
1093 {
1094     int ret;
1095     mbedtls_x509_crt *crt = chain, *prev = NULL;
1096 
1097     /*
1098      * Check for valid input
1099      */
1100     if( crt == NULL || buf == NULL )
1101         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1102 
1103     while( crt->version != 0 && crt->next != NULL )
1104     {
1105         prev = crt;
1106         crt = crt->next;
1107     }
1108 
1109     /*
1110      * Add new certificate on the end of the chain if needed.
1111      */
1112     if( crt->version != 0 && crt->next == NULL )
1113     {
1114         crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
1115 
1116         if( crt->next == NULL )
1117             return( MBEDTLS_ERR_X509_ALLOC_FAILED );
1118 
1119         prev = crt;
1120         mbedtls_x509_crt_init( crt->next );
1121         crt = crt->next;
1122     }
1123 
1124     if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
1125     {
1126         if( prev )
1127             prev->next = NULL;
1128 
1129         if( crt != chain )
1130             mbedtls_free( crt );
1131 
1132         return( ret );
1133     }
1134 
1135     return( 0 );
1136 }
1137 
1138 /*
1139  * Parse one or more PEM certificates from a buffer and add them to the chained
1140  * list
1141  */
mbedtls_x509_crt_parse(mbedtls_x509_crt * chain,const unsigned char * buf,size_t buflen)1142 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
1143 {
1144 #if defined(MBEDTLS_PEM_PARSE_C)
1145     int success = 0, first_error = 0, total_failed = 0;
1146     int buf_format = MBEDTLS_X509_FORMAT_DER;
1147 #endif
1148 
1149     /*
1150      * Check for valid input
1151      */
1152     if( chain == NULL || buf == NULL )
1153         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1154 
1155     /*
1156      * Determine buffer content. Buffer contains either one DER certificate or
1157      * one or more PEM certificates.
1158      */
1159 #if defined(MBEDTLS_PEM_PARSE_C)
1160     if( buflen != 0 && buf[buflen - 1] == '\0' &&
1161         strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
1162     {
1163         buf_format = MBEDTLS_X509_FORMAT_PEM;
1164     }
1165 
1166     if( buf_format == MBEDTLS_X509_FORMAT_DER )
1167         return mbedtls_x509_crt_parse_der( chain, buf, buflen );
1168 #else
1169     return mbedtls_x509_crt_parse_der( chain, buf, buflen );
1170 #endif
1171 
1172 #if defined(MBEDTLS_PEM_PARSE_C)
1173     if( buf_format == MBEDTLS_X509_FORMAT_PEM )
1174     {
1175         int ret;
1176         mbedtls_pem_context pem;
1177 
1178         /* 1 rather than 0 since the terminating NULL byte is counted in */
1179         while( buflen > 1 )
1180         {
1181             size_t use_len;
1182             mbedtls_pem_init( &pem );
1183 
1184             /* If we get there, we know the string is null-terminated */
1185             ret = mbedtls_pem_read_buffer( &pem,
1186                            "-----BEGIN CERTIFICATE-----",
1187                            "-----END CERTIFICATE-----",
1188                            buf, NULL, 0, &use_len );
1189 
1190             if( ret == 0 )
1191             {
1192                 /*
1193                  * Was PEM encoded
1194                  */
1195                 buflen -= use_len;
1196                 buf += use_len;
1197             }
1198             else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
1199             {
1200                 return( ret );
1201             }
1202             else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
1203             {
1204                 mbedtls_pem_free( &pem );
1205 
1206                 /*
1207                  * PEM header and footer were found
1208                  */
1209                 buflen -= use_len;
1210                 buf += use_len;
1211 
1212                 if( first_error == 0 )
1213                     first_error = ret;
1214 
1215                 total_failed++;
1216                 continue;
1217             }
1218             else
1219                 break;
1220 
1221             ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
1222 
1223             mbedtls_pem_free( &pem );
1224 
1225             if( ret != 0 )
1226             {
1227                 /*
1228                  * Quit parsing on a memory error
1229                  */
1230                 if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
1231                     return( ret );
1232 
1233                 if( first_error == 0 )
1234                     first_error = ret;
1235 
1236                 total_failed++;
1237                 continue;
1238             }
1239 
1240             success = 1;
1241         }
1242     }
1243 
1244     if( success )
1245         return( total_failed );
1246     else if( first_error )
1247         return( first_error );
1248     else
1249         return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
1250 #endif /* MBEDTLS_PEM_PARSE_C */
1251 }
1252 
1253 #if defined(MBEDTLS_FS_IO)
1254 /*
1255  * Load one or more certificates and add them to the chained list
1256  */
mbedtls_x509_crt_parse_file(mbedtls_x509_crt * chain,const char * path)1257 int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
1258 {
1259     int ret;
1260     size_t n;
1261     unsigned char *buf;
1262 
1263     if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
1264         return( ret );
1265 
1266     ret = mbedtls_x509_crt_parse( chain, buf, n );
1267 
1268     mbedtls_platform_zeroize( buf, n );
1269     mbedtls_free( buf );
1270 
1271     return( ret );
1272 }
1273 
mbedtls_x509_crt_parse_path(mbedtls_x509_crt * chain,const char * path)1274 int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
1275 {
1276     int ret = 0;
1277 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
1278     int w_ret;
1279     WCHAR szDir[MAX_PATH];
1280     char filename[MAX_PATH];
1281     char *p;
1282     size_t len = strlen( path );
1283 
1284     WIN32_FIND_DATAW file_data;
1285     HANDLE hFind;
1286 
1287     if( len > MAX_PATH - 3 )
1288         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1289 
1290     memset( szDir, 0, sizeof(szDir) );
1291     memset( filename, 0, MAX_PATH );
1292     memcpy( filename, path, len );
1293     filename[len++] = '\\';
1294     p = filename + len;
1295     filename[len++] = '*';
1296 
1297     w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
1298                                  MAX_PATH - 3 );
1299     if( w_ret == 0 )
1300         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1301 
1302     hFind = FindFirstFileW( szDir, &file_data );
1303     if( hFind == INVALID_HANDLE_VALUE )
1304         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
1305 
1306     len = MAX_PATH - len;
1307     do
1308     {
1309         memset( p, 0, len );
1310 
1311         if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
1312             continue;
1313 
1314         w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
1315                                      lstrlenW( file_data.cFileName ),
1316                                      p, (int) len - 1,
1317                                      NULL, NULL );
1318         if( w_ret == 0 )
1319         {
1320             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1321             goto cleanup;
1322         }
1323 
1324         w_ret = mbedtls_x509_crt_parse_file( chain, filename );
1325         if( w_ret < 0 )
1326             ret++;
1327         else
1328             ret += w_ret;
1329     }
1330     while( FindNextFileW( hFind, &file_data ) != 0 );
1331 
1332     if( GetLastError() != ERROR_NO_MORE_FILES )
1333         ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1334 
1335 cleanup:
1336     FindClose( hFind );
1337 #else /* _WIN32 */
1338     int t_ret;
1339     int snp_ret;
1340     struct stat sb;
1341     struct dirent *entry;
1342     char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
1343     DIR *dir = opendir( path );
1344 
1345     if( dir == NULL )
1346         return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
1347 
1348 #if defined(MBEDTLS_THREADING_C)
1349     if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
1350     {
1351         closedir( dir );
1352         return( ret );
1353     }
1354 #endif /* MBEDTLS_THREADING_C */
1355 
1356     while( ( entry = readdir( dir ) ) != NULL )
1357     {
1358         snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
1359                                     "%s/%s", path, entry->d_name );
1360 
1361         if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
1362         {
1363             ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
1364             goto cleanup;
1365         }
1366         else if( stat( entry_name, &sb ) == -1 )
1367         {
1368             ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
1369             goto cleanup;
1370         }
1371 
1372         if( !S_ISREG( sb.st_mode ) )
1373             continue;
1374 
1375         // Ignore parse errors
1376         //
1377         t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
1378         if( t_ret < 0 )
1379             ret++;
1380         else
1381             ret += t_ret;
1382     }
1383 
1384 cleanup:
1385     closedir( dir );
1386 
1387 #if defined(MBEDTLS_THREADING_C)
1388     if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
1389         ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1390 #endif /* MBEDTLS_THREADING_C */
1391 
1392 #endif /* _WIN32 */
1393 
1394     return( ret );
1395 }
1396 #endif /* MBEDTLS_FS_IO */
1397 
x509_info_subject_alt_name(char ** buf,size_t * size,const mbedtls_x509_sequence * subject_alt_name)1398 static int x509_info_subject_alt_name( char **buf, size_t *size,
1399                                        const mbedtls_x509_sequence *subject_alt_name )
1400 {
1401     size_t i;
1402     size_t n = *size;
1403     char *p = *buf;
1404     const mbedtls_x509_sequence *cur = subject_alt_name;
1405     const char *sep = "";
1406     size_t sep_len = 0;
1407 
1408     while( cur != NULL )
1409     {
1410         if( cur->buf.len + sep_len >= n )
1411         {
1412             *p = '\0';
1413             return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
1414         }
1415 
1416         n -= cur->buf.len + sep_len;
1417         for( i = 0; i < sep_len; i++ )
1418             *p++ = sep[i];
1419         for( i = 0; i < cur->buf.len; i++ )
1420             *p++ = cur->buf.p[i];
1421 
1422         sep = ", ";
1423         sep_len = 2;
1424 
1425         cur = cur->next;
1426     }
1427 
1428     *p = '\0';
1429 
1430     *size = n;
1431     *buf = p;
1432 
1433     return( 0 );
1434 }
1435 
1436 #define PRINT_ITEM(i)                           \
1437     {                                           \
1438         ret = mbedtls_snprintf( p, n, "%s" i, sep );    \
1439         MBEDTLS_X509_SAFE_SNPRINTF;                        \
1440         sep = ", ";                             \
1441     }
1442 
1443 #define CERT_TYPE(type,name)                    \
1444     if( ns_cert_type & type )                   \
1445         PRINT_ITEM( name );
1446 
x509_info_cert_type(char ** buf,size_t * size,unsigned char ns_cert_type)1447 static int x509_info_cert_type( char **buf, size_t *size,
1448                                 unsigned char ns_cert_type )
1449 {
1450     int ret;
1451     size_t n = *size;
1452     char *p = *buf;
1453     const char *sep = "";
1454 
1455     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT,         "SSL Client" );
1456     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER,         "SSL Server" );
1457     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL,              "Email" );
1458     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING,     "Object Signing" );
1459     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED,           "Reserved" );
1460     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA,             "SSL CA" );
1461     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA,           "Email CA" );
1462     CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA,  "Object Signing CA" );
1463 
1464     *size = n;
1465     *buf = p;
1466 
1467     return( 0 );
1468 }
1469 
1470 #define KEY_USAGE(code,name)    \
1471     if( key_usage & code )      \
1472         PRINT_ITEM( name );
1473 
x509_info_key_usage(char ** buf,size_t * size,unsigned int key_usage)1474 static int x509_info_key_usage( char **buf, size_t *size,
1475                                 unsigned int key_usage )
1476 {
1477     int ret;
1478     size_t n = *size;
1479     char *p = *buf;
1480     const char *sep = "";
1481 
1482     KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE,    "Digital Signature" );
1483     KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION,      "Non Repudiation" );
1484     KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT,     "Key Encipherment" );
1485     KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT,    "Data Encipherment" );
1486     KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT,        "Key Agreement" );
1487     KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN,        "Key Cert Sign" );
1488     KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN,             "CRL Sign" );
1489     KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY,        "Encipher Only" );
1490     KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY,        "Decipher Only" );
1491 
1492     *size = n;
1493     *buf = p;
1494 
1495     return( 0 );
1496 }
1497 
x509_info_ext_key_usage(char ** buf,size_t * size,const mbedtls_x509_sequence * extended_key_usage)1498 static int x509_info_ext_key_usage( char **buf, size_t *size,
1499                                     const mbedtls_x509_sequence *extended_key_usage )
1500 {
1501     int ret;
1502     const char *desc;
1503     size_t n = *size;
1504     char *p = *buf;
1505     const mbedtls_x509_sequence *cur = extended_key_usage;
1506     const char *sep = "";
1507 
1508     while( cur != NULL )
1509     {
1510         if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
1511             desc = "???";
1512 
1513         ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
1514         MBEDTLS_X509_SAFE_SNPRINTF;
1515 
1516         sep = ", ";
1517 
1518         cur = cur->next;
1519     }
1520 
1521     *size = n;
1522     *buf = p;
1523 
1524     return( 0 );
1525 }
1526 
1527 /*
1528  * Return an informational string about the certificate.
1529  */
1530 #define BEFORE_COLON    18
1531 #define BC              "18"
mbedtls_x509_crt_info(char * buf,size_t size,const char * prefix,const mbedtls_x509_crt * crt)1532 int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
1533                    const mbedtls_x509_crt *crt )
1534 {
1535     int ret;
1536     size_t n;
1537     char *p;
1538     char key_size_str[BEFORE_COLON];
1539 
1540     p = buf;
1541     n = size;
1542 
1543     if( NULL == crt )
1544     {
1545         ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
1546         MBEDTLS_X509_SAFE_SNPRINTF;
1547 
1548         return( (int) ( size - n ) );
1549     }
1550 
1551     ret = mbedtls_snprintf( p, n, "%scert. version     : %d\n",
1552                                prefix, crt->version );
1553     MBEDTLS_X509_SAFE_SNPRINTF;
1554     ret = mbedtls_snprintf( p, n, "%sserial number     : ",
1555                                prefix );
1556     MBEDTLS_X509_SAFE_SNPRINTF;
1557 
1558     ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
1559     MBEDTLS_X509_SAFE_SNPRINTF;
1560 
1561     ret = mbedtls_snprintf( p, n, "\n%sissuer name       : ", prefix );
1562     MBEDTLS_X509_SAFE_SNPRINTF;
1563     ret = mbedtls_x509_dn_gets( p, n, &crt->issuer  );
1564     MBEDTLS_X509_SAFE_SNPRINTF;
1565 
1566     ret = mbedtls_snprintf( p, n, "\n%ssubject name      : ", prefix );
1567     MBEDTLS_X509_SAFE_SNPRINTF;
1568     ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
1569     MBEDTLS_X509_SAFE_SNPRINTF;
1570 
1571     ret = mbedtls_snprintf( p, n, "\n%sissued  on        : " \
1572                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
1573                    crt->valid_from.year, crt->valid_from.mon,
1574                    crt->valid_from.day,  crt->valid_from.hour,
1575                    crt->valid_from.min,  crt->valid_from.sec );
1576     MBEDTLS_X509_SAFE_SNPRINTF;
1577 
1578     ret = mbedtls_snprintf( p, n, "\n%sexpires on        : " \
1579                    "%04d-%02d-%02d %02d:%02d:%02d", prefix,
1580                    crt->valid_to.year, crt->valid_to.mon,
1581                    crt->valid_to.day,  crt->valid_to.hour,
1582                    crt->valid_to.min,  crt->valid_to.sec );
1583     MBEDTLS_X509_SAFE_SNPRINTF;
1584 
1585     ret = mbedtls_snprintf( p, n, "\n%ssigned using      : ", prefix );
1586     MBEDTLS_X509_SAFE_SNPRINTF;
1587 
1588     ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
1589                              crt->sig_md, crt->sig_opts );
1590     MBEDTLS_X509_SAFE_SNPRINTF;
1591 
1592     /* Key size */
1593     if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
1594                                       mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
1595     {
1596         return( ret );
1597     }
1598 
1599     ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
1600                           (int) mbedtls_pk_get_bitlen( &crt->pk ) );
1601     MBEDTLS_X509_SAFE_SNPRINTF;
1602 
1603     /*
1604      * Optional extensions
1605      */
1606 
1607     if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
1608     {
1609         ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
1610                         crt->ca_istrue ? "true" : "false" );
1611         MBEDTLS_X509_SAFE_SNPRINTF;
1612 
1613         if( crt->max_pathlen > 0 )
1614         {
1615             ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
1616             MBEDTLS_X509_SAFE_SNPRINTF;
1617         }
1618     }
1619 
1620     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
1621     {
1622         ret = mbedtls_snprintf( p, n, "\n%ssubject alt name  : ", prefix );
1623         MBEDTLS_X509_SAFE_SNPRINTF;
1624 
1625         if( ( ret = x509_info_subject_alt_name( &p, &n,
1626                                             &crt->subject_alt_names ) ) != 0 )
1627             return( ret );
1628     }
1629 
1630     if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
1631     {
1632         ret = mbedtls_snprintf( p, n, "\n%scert. type        : ", prefix );
1633         MBEDTLS_X509_SAFE_SNPRINTF;
1634 
1635         if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
1636             return( ret );
1637     }
1638 
1639     if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
1640     {
1641         ret = mbedtls_snprintf( p, n, "\n%skey usage         : ", prefix );
1642         MBEDTLS_X509_SAFE_SNPRINTF;
1643 
1644         if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
1645             return( ret );
1646     }
1647 
1648     if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
1649     {
1650         ret = mbedtls_snprintf( p, n, "\n%sext key usage     : ", prefix );
1651         MBEDTLS_X509_SAFE_SNPRINTF;
1652 
1653         if( ( ret = x509_info_ext_key_usage( &p, &n,
1654                                              &crt->ext_key_usage ) ) != 0 )
1655             return( ret );
1656     }
1657 
1658     ret = mbedtls_snprintf( p, n, "\n" );
1659     MBEDTLS_X509_SAFE_SNPRINTF;
1660 
1661     return( (int) ( size - n ) );
1662 }
1663 
1664 struct x509_crt_verify_string {
1665     int code;
1666     const char *string;
1667 };
1668 
1669 static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
1670     { MBEDTLS_X509_BADCERT_EXPIRED,       "The certificate validity has expired" },
1671     { MBEDTLS_X509_BADCERT_REVOKED,       "The certificate has been revoked (is on a CRL)" },
1672     { MBEDTLS_X509_BADCERT_CN_MISMATCH,   "The certificate Common Name (CN) does not match with the expected CN" },
1673     { MBEDTLS_X509_BADCERT_NOT_TRUSTED,   "The certificate is not correctly signed by the trusted CA" },
1674     { MBEDTLS_X509_BADCRL_NOT_TRUSTED,    "The CRL is not correctly signed by the trusted CA" },
1675     { MBEDTLS_X509_BADCRL_EXPIRED,        "The CRL is expired" },
1676     { MBEDTLS_X509_BADCERT_MISSING,       "Certificate was missing" },
1677     { MBEDTLS_X509_BADCERT_SKIP_VERIFY,   "Certificate verification was skipped" },
1678     { MBEDTLS_X509_BADCERT_OTHER,         "Other reason (can be used by verify callback)" },
1679     { MBEDTLS_X509_BADCERT_FUTURE,        "The certificate validity starts in the future" },
1680     { MBEDTLS_X509_BADCRL_FUTURE,         "The CRL is from the future" },
1681     { MBEDTLS_X509_BADCERT_KEY_USAGE,     "Usage does not match the keyUsage extension" },
1682     { MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
1683     { MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  "Usage does not match the nsCertType extension" },
1684     { MBEDTLS_X509_BADCERT_BAD_MD,        "The certificate is signed with an unacceptable hash." },
1685     { MBEDTLS_X509_BADCERT_BAD_PK,        "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
1686     { MBEDTLS_X509_BADCERT_BAD_KEY,       "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
1687     { MBEDTLS_X509_BADCRL_BAD_MD,         "The CRL is signed with an unacceptable hash." },
1688     { MBEDTLS_X509_BADCRL_BAD_PK,         "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
1689     { MBEDTLS_X509_BADCRL_BAD_KEY,        "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
1690     { 0, NULL }
1691 };
1692 
mbedtls_x509_crt_verify_info(char * buf,size_t size,const char * prefix,uint32_t flags)1693 int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
1694                           uint32_t flags )
1695 {
1696     int ret;
1697     const struct x509_crt_verify_string *cur;
1698     char *p = buf;
1699     size_t n = size;
1700 
1701     for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
1702     {
1703         if( ( flags & cur->code ) == 0 )
1704             continue;
1705 
1706         ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
1707         MBEDTLS_X509_SAFE_SNPRINTF;
1708         flags ^= cur->code;
1709     }
1710 
1711     if( flags != 0 )
1712     {
1713         ret = mbedtls_snprintf( p, n, "%sUnknown reason "
1714                                        "(this should not happen)\n", prefix );
1715         MBEDTLS_X509_SAFE_SNPRINTF;
1716     }
1717 
1718     return( (int) ( size - n ) );
1719 }
1720 
1721 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
mbedtls_x509_crt_check_key_usage(const mbedtls_x509_crt * crt,unsigned int usage)1722 int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
1723                                       unsigned int usage )
1724 {
1725     unsigned int usage_must, usage_may;
1726     unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
1727                           | MBEDTLS_X509_KU_DECIPHER_ONLY;
1728 
1729     if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
1730         return( 0 );
1731 
1732     usage_must = usage & ~may_mask;
1733 
1734     if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
1735         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1736 
1737     usage_may = usage & may_mask;
1738 
1739     if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
1740         return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1741 
1742     return( 0 );
1743 }
1744 #endif
1745 
1746 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
mbedtls_x509_crt_check_extended_key_usage(const mbedtls_x509_crt * crt,const char * usage_oid,size_t usage_len)1747 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
1748                                        const char *usage_oid,
1749                                        size_t usage_len )
1750 {
1751     const mbedtls_x509_sequence *cur;
1752 
1753     /* Extension is not mandatory, absent means no restriction */
1754     if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
1755         return( 0 );
1756 
1757     /*
1758      * Look for the requested usage (or wildcard ANY) in our list
1759      */
1760     for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
1761     {
1762         const mbedtls_x509_buf *cur_oid = &cur->buf;
1763 
1764         if( cur_oid->len == usage_len &&
1765             memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
1766         {
1767             return( 0 );
1768         }
1769 
1770         if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
1771             return( 0 );
1772     }
1773 
1774     return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
1775 }
1776 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
1777 
1778 #if defined(MBEDTLS_X509_CRL_PARSE_C)
1779 /*
1780  * Return 1 if the certificate is revoked, or 0 otherwise.
1781  */
mbedtls_x509_crt_is_revoked(const mbedtls_x509_crt * crt,const mbedtls_x509_crl * crl)1782 int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
1783 {
1784     const mbedtls_x509_crl_entry *cur = &crl->entry;
1785 
1786     while( cur != NULL && cur->serial.len != 0 )
1787     {
1788         if( crt->serial.len == cur->serial.len &&
1789             memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
1790         {
1791             if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
1792                 return( 1 );
1793         }
1794 
1795         cur = cur->next;
1796     }
1797 
1798     return( 0 );
1799 }
1800 
1801 /*
1802  * Check that the given certificate is not revoked according to the CRL.
1803  * Skip validation if no CRL for the given CA is present.
1804  */
x509_crt_verifycrl(mbedtls_x509_crt * crt,mbedtls_x509_crt * ca,mbedtls_x509_crl * crl_list,const mbedtls_x509_crt_profile * profile)1805 static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
1806                                mbedtls_x509_crl *crl_list,
1807                                const mbedtls_x509_crt_profile *profile )
1808 {
1809     int flags = 0;
1810     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
1811     const mbedtls_md_info_t *md_info;
1812 
1813     if( ca == NULL )
1814         return( flags );
1815 
1816     while( crl_list != NULL )
1817     {
1818         if( crl_list->version == 0 ||
1819             x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 )
1820         {
1821             crl_list = crl_list->next;
1822             continue;
1823         }
1824 
1825         /*
1826          * Check if the CA is configured to sign CRLs
1827          */
1828 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
1829         if( mbedtls_x509_crt_check_key_usage( ca,
1830                                               MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
1831         {
1832             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
1833             break;
1834         }
1835 #endif
1836 
1837         /*
1838          * Check if CRL is correctly signed by the trusted CA
1839          */
1840         if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
1841             flags |= MBEDTLS_X509_BADCRL_BAD_MD;
1842 
1843         if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
1844             flags |= MBEDTLS_X509_BADCRL_BAD_PK;
1845 
1846         md_info = mbedtls_md_info_from_type( crl_list->sig_md );
1847         if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )
1848         {
1849             /* Note: this can't happen except after an internal error */
1850             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
1851             break;
1852         }
1853 
1854         if( x509_profile_check_key( profile, &ca->pk ) != 0 )
1855             flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
1856 
1857         if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
1858                            crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
1859                            crl_list->sig.p, crl_list->sig.len ) != 0 )
1860         {
1861             flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
1862             break;
1863         }
1864 
1865         /*
1866          * Check for validity of CRL (Do not drop out)
1867          */
1868         if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
1869             flags |= MBEDTLS_X509_BADCRL_EXPIRED;
1870 
1871         if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
1872             flags |= MBEDTLS_X509_BADCRL_FUTURE;
1873 
1874         /*
1875          * Check if certificate is revoked
1876          */
1877         if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
1878         {
1879             flags |= MBEDTLS_X509_BADCERT_REVOKED;
1880             break;
1881         }
1882 
1883         crl_list = crl_list->next;
1884     }
1885 
1886     return( flags );
1887 }
1888 #endif /* MBEDTLS_X509_CRL_PARSE_C */
1889 
1890 /*
1891  * Check the signature of a certificate by its parent
1892  */
x509_crt_check_signature(const mbedtls_x509_crt * child,mbedtls_x509_crt * parent,mbedtls_x509_crt_restart_ctx * rs_ctx)1893 static int x509_crt_check_signature( const mbedtls_x509_crt *child,
1894                                      mbedtls_x509_crt *parent,
1895                                      mbedtls_x509_crt_restart_ctx *rs_ctx )
1896 {
1897     const mbedtls_md_info_t *md_info;
1898     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
1899 
1900     md_info = mbedtls_md_info_from_type( child->sig_md );
1901     if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
1902     {
1903         /* Note: this can't happen except after an internal error */
1904         return( -1 );
1905     }
1906 
1907     /* Skip expensive computation on obvious mismatch */
1908     if( ! mbedtls_pk_can_do( &parent->pk, child->sig_pk ) )
1909         return( -1 );
1910 
1911 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
1912     if( rs_ctx != NULL && child->sig_pk == MBEDTLS_PK_ECDSA )
1913     {
1914         return( mbedtls_pk_verify_restartable( &parent->pk,
1915                     child->sig_md, hash, mbedtls_md_get_size( md_info ),
1916                     child->sig.p, child->sig.len, &rs_ctx->pk ) );
1917     }
1918 #else
1919     (void) rs_ctx;
1920 #endif
1921 
1922     return( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
1923                 child->sig_md, hash, mbedtls_md_get_size( md_info ),
1924                 child->sig.p, child->sig.len ) );
1925 }
1926 
1927 /*
1928  * Check if 'parent' is a suitable parent (signing CA) for 'child'.
1929  * Return 0 if yes, -1 if not.
1930  *
1931  * top means parent is a locally-trusted certificate
1932  */
x509_crt_check_parent(const mbedtls_x509_crt * child,const mbedtls_x509_crt * parent,int top)1933 static int x509_crt_check_parent( const mbedtls_x509_crt *child,
1934                                   const mbedtls_x509_crt *parent,
1935                                   int top )
1936 {
1937     int need_ca_bit;
1938 
1939     /* Parent must be the issuer */
1940     if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
1941         return( -1 );
1942 
1943     /* Parent must have the basicConstraints CA bit set as a general rule */
1944     need_ca_bit = 1;
1945 
1946     /* Exception: v1/v2 certificates that are locally trusted. */
1947     if( top && parent->version < 3 )
1948         need_ca_bit = 0;
1949 
1950     if( need_ca_bit && ! parent->ca_istrue )
1951         return( -1 );
1952 
1953 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
1954     if( need_ca_bit &&
1955         mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
1956     {
1957         return( -1 );
1958     }
1959 #endif
1960 
1961     return( 0 );
1962 }
1963 
1964 /*
1965  * Find a suitable parent for child in candidates, or return NULL.
1966  *
1967  * Here suitable is defined as:
1968  *  1. subject name matches child's issuer
1969  *  2. if necessary, the CA bit is set and key usage allows signing certs
1970  *  3. for trusted roots, the signature is correct
1971  *     (for intermediates, the signature is checked and the result reported)
1972  *  4. pathlen constraints are satisfied
1973  *
1974  * If there's a suitable candidate which is also time-valid, return the first
1975  * such. Otherwise, return the first suitable candidate (or NULL if there is
1976  * none).
1977  *
1978  * The rationale for this rule is that someone could have a list of trusted
1979  * roots with two versions on the same root with different validity periods.
1980  * (At least one user reported having such a list and wanted it to just work.)
1981  * The reason we don't just require time-validity is that generally there is
1982  * only one version, and if it's expired we want the flags to state that
1983  * rather than NOT_TRUSTED, as would be the case if we required it here.
1984  *
1985  * The rationale for rule 3 (signature for trusted roots) is that users might
1986  * have two versions of the same CA with different keys in their list, and the
1987  * way we select the correct one is by checking the signature (as we don't
1988  * rely on key identifier extensions). (This is one way users might choose to
1989  * handle key rollover, another relies on self-issued certs, see [SIRO].)
1990  *
1991  * Arguments:
1992  *  - [in] child: certificate for which we're looking for a parent
1993  *  - [in] candidates: chained list of potential parents
1994  *  - [out] r_parent: parent found (or NULL)
1995  *  - [out] r_signature_is_good: 1 if child signature by parent is valid, or 0
1996  *  - [in] top: 1 if candidates consists of trusted roots, ie we're at the top
1997  *         of the chain, 0 otherwise
1998  *  - [in] path_cnt: number of intermediates seen so far
1999  *  - [in] self_cnt: number of self-signed intermediates seen so far
2000  *         (will never be greater than path_cnt)
2001  *  - [in-out] rs_ctx: context for restarting operations
2002  *
2003  * Return value:
2004  *  - 0 on success
2005  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
2006  */
x509_crt_find_parent_in(mbedtls_x509_crt * child,mbedtls_x509_crt * candidates,mbedtls_x509_crt ** r_parent,int * r_signature_is_good,int top,unsigned path_cnt,unsigned self_cnt,mbedtls_x509_crt_restart_ctx * rs_ctx)2007 static int x509_crt_find_parent_in(
2008                         mbedtls_x509_crt *child,
2009                         mbedtls_x509_crt *candidates,
2010                         mbedtls_x509_crt **r_parent,
2011                         int *r_signature_is_good,
2012                         int top,
2013                         unsigned path_cnt,
2014                         unsigned self_cnt,
2015                         mbedtls_x509_crt_restart_ctx *rs_ctx )
2016 {
2017     int ret;
2018     mbedtls_x509_crt *parent, *fallback_parent;
2019     int signature_is_good, fallback_signature_is_good;
2020 
2021 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2022     /* did we have something in progress? */
2023     if( rs_ctx != NULL && rs_ctx->parent != NULL )
2024     {
2025         /* restore saved state */
2026         parent = rs_ctx->parent;
2027         fallback_parent = rs_ctx->fallback_parent;
2028         fallback_signature_is_good = rs_ctx->fallback_signature_is_good;
2029 
2030         /* clear saved state */
2031         rs_ctx->parent = NULL;
2032         rs_ctx->fallback_parent = NULL;
2033         rs_ctx->fallback_signature_is_good = 0;
2034 
2035         /* resume where we left */
2036         goto check_signature;
2037     }
2038 #endif
2039 
2040     fallback_parent = NULL;
2041     fallback_signature_is_good = 0;
2042 
2043     for( parent = candidates; parent != NULL; parent = parent->next )
2044     {
2045         /* basic parenting skills (name, CA bit, key usage) */
2046         if( x509_crt_check_parent( child, parent, top ) != 0 )
2047             continue;
2048 
2049         /* +1 because stored max_pathlen is 1 higher that the actual value */
2050         if( parent->max_pathlen > 0 &&
2051             (size_t) parent->max_pathlen < 1 + path_cnt - self_cnt )
2052         {
2053             continue;
2054         }
2055 
2056         /* Signature */
2057 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2058 check_signature:
2059 #endif
2060         ret = x509_crt_check_signature( child, parent, rs_ctx );
2061 
2062 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2063         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2064         {
2065             /* save state */
2066             rs_ctx->parent = parent;
2067             rs_ctx->fallback_parent = fallback_parent;
2068             rs_ctx->fallback_signature_is_good = fallback_signature_is_good;
2069 
2070             return( ret );
2071         }
2072 #else
2073         (void) ret;
2074 #endif
2075 
2076         signature_is_good = ret == 0;
2077         if( top && ! signature_is_good )
2078             continue;
2079 
2080         /* optional time check */
2081         if( mbedtls_x509_time_is_past( &parent->valid_to ) ||
2082             mbedtls_x509_time_is_future( &parent->valid_from ) )
2083         {
2084             if( fallback_parent == NULL )
2085             {
2086                 fallback_parent = parent;
2087                 fallback_signature_is_good = signature_is_good;
2088             }
2089 
2090             continue;
2091         }
2092 
2093         break;
2094     }
2095 
2096     if( parent != NULL )
2097     {
2098         *r_parent = parent;
2099         *r_signature_is_good = signature_is_good;
2100     }
2101     else
2102     {
2103         *r_parent = fallback_parent;
2104         *r_signature_is_good = fallback_signature_is_good;
2105     }
2106 
2107     return( 0 );
2108 }
2109 
2110 /*
2111  * Find a parent in trusted CAs or the provided chain, or return NULL.
2112  *
2113  * Searches in trusted CAs first, and return the first suitable parent found
2114  * (see find_parent_in() for definition of suitable).
2115  *
2116  * Arguments:
2117  *  - [in] child: certificate for which we're looking for a parent, followed
2118  *         by a chain of possible intermediates
2119  *  - [in] trust_ca: list of locally trusted certificates
2120  *  - [out] parent: parent found (or NULL)
2121  *  - [out] parent_is_trusted: 1 if returned `parent` is trusted, or 0
2122  *  - [out] signature_is_good: 1 if child signature by parent is valid, or 0
2123  *  - [in] path_cnt: number of links in the chain so far (EE -> ... -> child)
2124  *  - [in] self_cnt: number of self-signed certs in the chain so far
2125  *         (will always be no greater than path_cnt)
2126  *  - [in-out] rs_ctx: context for restarting operations
2127  *
2128  * Return value:
2129  *  - 0 on success
2130  *  - MBEDTLS_ERR_ECP_IN_PROGRESS otherwise
2131  */
x509_crt_find_parent(mbedtls_x509_crt * child,mbedtls_x509_crt * trust_ca,mbedtls_x509_crt ** parent,int * parent_is_trusted,int * signature_is_good,unsigned path_cnt,unsigned self_cnt,mbedtls_x509_crt_restart_ctx * rs_ctx)2132 static int x509_crt_find_parent(
2133                         mbedtls_x509_crt *child,
2134                         mbedtls_x509_crt *trust_ca,
2135                         mbedtls_x509_crt **parent,
2136                         int *parent_is_trusted,
2137                         int *signature_is_good,
2138                         unsigned path_cnt,
2139                         unsigned self_cnt,
2140                         mbedtls_x509_crt_restart_ctx *rs_ctx )
2141 {
2142     int ret;
2143     mbedtls_x509_crt *search_list;
2144 
2145     *parent_is_trusted = 1;
2146 
2147 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2148     /* restore then clear saved state if we have some stored */
2149     if( rs_ctx != NULL && rs_ctx->parent_is_trusted != -1 )
2150     {
2151         *parent_is_trusted = rs_ctx->parent_is_trusted;
2152         rs_ctx->parent_is_trusted = -1;
2153     }
2154 #endif
2155 
2156     while( 1 ) {
2157         search_list = *parent_is_trusted ? trust_ca : child->next;
2158 
2159         ret = x509_crt_find_parent_in( child, search_list,
2160                                        parent, signature_is_good,
2161                                        *parent_is_trusted,
2162                                        path_cnt, self_cnt, rs_ctx );
2163 
2164 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2165         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2166         {
2167             /* save state */
2168             rs_ctx->parent_is_trusted = *parent_is_trusted;
2169             return( ret );
2170         }
2171 #else
2172         (void) ret;
2173 #endif
2174 
2175         /* stop here if found or already in second iteration */
2176         if( *parent != NULL || *parent_is_trusted == 0 )
2177             break;
2178 
2179         /* prepare second iteration */
2180         *parent_is_trusted = 0;
2181     }
2182 
2183     /* extra precaution against mistakes in the caller */
2184     if( *parent == NULL )
2185     {
2186         *parent_is_trusted = 0;
2187         *signature_is_good = 0;
2188     }
2189 
2190     return( 0 );
2191 }
2192 
2193 /*
2194  * Check if an end-entity certificate is locally trusted
2195  *
2196  * Currently we require such certificates to be self-signed (actually only
2197  * check for self-issued as self-signatures are not checked)
2198  */
x509_crt_check_ee_locally_trusted(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca)2199 static int x509_crt_check_ee_locally_trusted(
2200                     mbedtls_x509_crt *crt,
2201                     mbedtls_x509_crt *trust_ca )
2202 {
2203     mbedtls_x509_crt *cur;
2204 
2205     /* must be self-issued */
2206     if( x509_name_cmp( &crt->issuer, &crt->subject ) != 0 )
2207         return( -1 );
2208 
2209     /* look for an exact match with trusted cert */
2210     for( cur = trust_ca; cur != NULL; cur = cur->next )
2211     {
2212         if( crt->raw.len == cur->raw.len &&
2213             memcmp( crt->raw.p, cur->raw.p, crt->raw.len ) == 0 )
2214         {
2215             return( 0 );
2216         }
2217     }
2218 
2219     /* too bad */
2220     return( -1 );
2221 }
2222 
2223 /*
2224  * Build and verify a certificate chain
2225  *
2226  * Given a peer-provided list of certificates EE, C1, ..., Cn and
2227  * a list of trusted certs R1, ... Rp, try to build and verify a chain
2228  *      EE, Ci1, ... Ciq [, Rj]
2229  * such that every cert in the chain is a child of the next one,
2230  * jumping to a trusted root as early as possible.
2231  *
2232  * Verify that chain and return it with flags for all issues found.
2233  *
2234  * Special cases:
2235  * - EE == Rj -> return a one-element list containing it
2236  * - EE, Ci1, ..., Ciq cannot be continued with a trusted root
2237  *   -> return that chain with NOT_TRUSTED set on Ciq
2238  *
2239  * Tests for (aspects of) this function should include at least:
2240  * - trusted EE
2241  * - EE -> trusted root
2242  * - EE -> intermedate CA -> trusted root
2243  * - if relevant: EE untrusted
2244  * - if relevant: EE -> intermediate, untrusted
2245  * with the aspect under test checked at each relevant level (EE, int, root).
2246  * For some aspects longer chains are required, but usually length 2 is
2247  * enough (but length 1 is not in general).
2248  *
2249  * Arguments:
2250  *  - [in] crt: the cert list EE, C1, ..., Cn
2251  *  - [in] trust_ca: the trusted list R1, ..., Rp
2252  *  - [in] ca_crl, profile: as in verify_with_profile()
2253  *  - [out] ver_chain: the built and verified chain
2254  *      Only valid when return value is 0, may contain garbage otherwise!
2255  *      Restart note: need not be the same when calling again to resume.
2256  *  - [in-out] rs_ctx: context for restarting operations
2257  *
2258  * Return value:
2259  *  - non-zero if the chain could not be fully built and examined
2260  *  - 0 is the chain was successfully built and examined,
2261  *      even if it was found to be invalid
2262  */
x509_crt_verify_chain(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const mbedtls_x509_crt_profile * profile,mbedtls_x509_crt_verify_chain * ver_chain,mbedtls_x509_crt_restart_ctx * rs_ctx)2263 static int x509_crt_verify_chain(
2264                 mbedtls_x509_crt *crt,
2265                 mbedtls_x509_crt *trust_ca,
2266                 mbedtls_x509_crl *ca_crl,
2267                 const mbedtls_x509_crt_profile *profile,
2268                 mbedtls_x509_crt_verify_chain *ver_chain,
2269                 mbedtls_x509_crt_restart_ctx *rs_ctx )
2270 {
2271     /* Don't initialize any of those variables here, so that the compiler can
2272      * catch potential issues with jumping ahead when restarting */
2273     int ret;
2274     uint32_t *flags;
2275     mbedtls_x509_crt_verify_chain_item *cur;
2276     mbedtls_x509_crt *child;
2277     mbedtls_x509_crt *parent;
2278     int parent_is_trusted;
2279     int child_is_trusted;
2280     int signature_is_good;
2281     unsigned self_cnt;
2282 
2283 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2284     /* resume if we had an operation in progress */
2285     if( rs_ctx != NULL && rs_ctx->in_progress == x509_crt_rs_find_parent )
2286     {
2287         /* restore saved state */
2288         *ver_chain = rs_ctx->ver_chain; /* struct copy */
2289         self_cnt = rs_ctx->self_cnt;
2290 
2291         /* restore derived state */
2292         cur = &ver_chain->items[ver_chain->len - 1];
2293         child = cur->crt;
2294         flags = &cur->flags;
2295 
2296         goto find_parent;
2297     }
2298 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
2299 
2300     child = crt;
2301     self_cnt = 0;
2302     parent_is_trusted = 0;
2303     child_is_trusted = 0;
2304 
2305     while( 1 ) {
2306         /* Add certificate to the verification chain */
2307         cur = &ver_chain->items[ver_chain->len];
2308         cur->crt = child;
2309         cur->flags = 0;
2310         ver_chain->len++;
2311         flags = &cur->flags;
2312 
2313         /* Check time-validity (all certificates) */
2314         if( mbedtls_x509_time_is_past( &child->valid_to ) )
2315             *flags |= MBEDTLS_X509_BADCERT_EXPIRED;
2316 
2317         if( mbedtls_x509_time_is_future( &child->valid_from ) )
2318             *flags |= MBEDTLS_X509_BADCERT_FUTURE;
2319 
2320         /* Stop here for trusted roots (but not for trusted EE certs) */
2321         if( child_is_trusted )
2322             return( 0 );
2323 
2324         /* Check signature algorithm: MD & PK algs */
2325         if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
2326             *flags |= MBEDTLS_X509_BADCERT_BAD_MD;
2327 
2328         if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
2329             *flags |= MBEDTLS_X509_BADCERT_BAD_PK;
2330 
2331         /* Special case: EE certs that are locally trusted */
2332         if( ver_chain->len == 1 &&
2333             x509_crt_check_ee_locally_trusted( child, trust_ca ) == 0 )
2334         {
2335             return( 0 );
2336         }
2337 
2338 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2339 find_parent:
2340 #endif
2341         /* Look for a parent in trusted CAs or up the chain */
2342         ret = x509_crt_find_parent( child, trust_ca, &parent,
2343                                        &parent_is_trusted, &signature_is_good,
2344                                        ver_chain->len - 1, self_cnt, rs_ctx );
2345 
2346 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2347         if( rs_ctx != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2348         {
2349             /* save state */
2350             rs_ctx->in_progress = x509_crt_rs_find_parent;
2351             rs_ctx->self_cnt = self_cnt;
2352             rs_ctx->ver_chain = *ver_chain; /* struct copy */
2353 
2354             return( ret );
2355         }
2356 #else
2357         (void) ret;
2358 #endif
2359 
2360         /* No parent? We're done here */
2361         if( parent == NULL )
2362         {
2363             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
2364             return( 0 );
2365         }
2366 
2367         /* Count intermediate self-issued (not necessarily self-signed) certs.
2368          * These can occur with some strategies for key rollover, see [SIRO],
2369          * and should be excluded from max_pathlen checks. */
2370         if( ver_chain->len != 1 &&
2371             x509_name_cmp( &child->issuer, &child->subject ) == 0 )
2372         {
2373             self_cnt++;
2374         }
2375 
2376         /* path_cnt is 0 for the first intermediate CA,
2377          * and if parent is trusted it's not an intermediate CA */
2378         if( ! parent_is_trusted &&
2379             ver_chain->len > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
2380         {
2381             /* return immediately to avoid overflow the chain array */
2382             return( MBEDTLS_ERR_X509_FATAL_ERROR );
2383         }
2384 
2385         /* signature was checked while searching parent */
2386         if( ! signature_is_good )
2387             *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
2388 
2389         /* check size of signing key */
2390         if( x509_profile_check_key( profile, &parent->pk ) != 0 )
2391             *flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
2392 
2393 #if defined(MBEDTLS_X509_CRL_PARSE_C)
2394         /* Check trusted CA's CRL for the given crt */
2395         *flags |= x509_crt_verifycrl( child, parent, ca_crl, profile );
2396 #else
2397         (void) ca_crl;
2398 #endif
2399 
2400         /* prepare for next iteration */
2401         child = parent;
2402         parent = NULL;
2403         child_is_trusted = parent_is_trusted;
2404         signature_is_good = 0;
2405     }
2406 }
2407 
2408 /*
2409  * Check for CN match
2410  */
x509_crt_check_cn(const mbedtls_x509_buf * name,const char * cn,size_t cn_len)2411 static int x509_crt_check_cn( const mbedtls_x509_buf *name,
2412                               const char *cn, size_t cn_len )
2413 {
2414     /* try exact match */
2415     if( name->len == cn_len &&
2416         x509_memcasecmp( cn, name->p, cn_len ) == 0 )
2417     {
2418         return( 0 );
2419     }
2420 
2421     /* try wildcard match */
2422     if( x509_check_wildcard( cn, name ) == 0 )
2423     {
2424         return( 0 );
2425     }
2426 
2427     return( -1 );
2428 }
2429 
2430 /*
2431  * Verify the requested CN - only call this if cn is not NULL!
2432  */
x509_crt_verify_name(const mbedtls_x509_crt * crt,const char * cn,uint32_t * flags)2433 static void x509_crt_verify_name( const mbedtls_x509_crt *crt,
2434                                   const char *cn,
2435                                   uint32_t *flags )
2436 {
2437     const mbedtls_x509_name *name;
2438     const mbedtls_x509_sequence *cur;
2439     size_t cn_len = strlen( cn );
2440 
2441     if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
2442     {
2443         for( cur = &crt->subject_alt_names; cur != NULL; cur = cur->next )
2444         {
2445             if( x509_crt_check_cn( &cur->buf, cn, cn_len ) == 0 )
2446                 break;
2447         }
2448 
2449         if( cur == NULL )
2450             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
2451     }
2452     else
2453     {
2454         for( name = &crt->subject; name != NULL; name = name->next )
2455         {
2456             if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 &&
2457                 x509_crt_check_cn( &name->val, cn, cn_len ) == 0 )
2458             {
2459                 break;
2460             }
2461         }
2462 
2463         if( name == NULL )
2464             *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
2465     }
2466 }
2467 
2468 /*
2469  * Merge the flags for all certs in the chain, after calling callback
2470  */
x509_crt_merge_flags_with_cb(uint32_t * flags,const mbedtls_x509_crt_verify_chain * ver_chain,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)2471 static int x509_crt_merge_flags_with_cb(
2472            uint32_t *flags,
2473            const mbedtls_x509_crt_verify_chain *ver_chain,
2474            int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
2475            void *p_vrfy )
2476 {
2477     int ret;
2478     unsigned i;
2479     uint32_t cur_flags;
2480     const mbedtls_x509_crt_verify_chain_item *cur;
2481 
2482     for( i = ver_chain->len; i != 0; --i )
2483     {
2484         cur = &ver_chain->items[i-1];
2485         cur_flags = cur->flags;
2486 
2487         if( NULL != f_vrfy )
2488             if( ( ret = f_vrfy( p_vrfy, cur->crt, (int) i-1, &cur_flags ) ) != 0 )
2489                 return( ret );
2490 
2491         *flags |= cur_flags;
2492     }
2493 
2494     return( 0 );
2495 }
2496 
2497 /*
2498  * Verify the certificate validity (default profile, not restartable)
2499  */
mbedtls_x509_crt_verify(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)2500 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
2501                      mbedtls_x509_crt *trust_ca,
2502                      mbedtls_x509_crl *ca_crl,
2503                      const char *cn, uint32_t *flags,
2504                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
2505                      void *p_vrfy )
2506 {
2507     return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
2508                 &mbedtls_x509_crt_profile_default, cn, flags,
2509                 f_vrfy, p_vrfy, NULL ) );
2510 }
2511 
2512 /*
2513  * Verify the certificate validity (user-chosen profile, not restartable)
2514  */
mbedtls_x509_crt_verify_with_profile(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy)2515 int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
2516                      mbedtls_x509_crt *trust_ca,
2517                      mbedtls_x509_crl *ca_crl,
2518                      const mbedtls_x509_crt_profile *profile,
2519                      const char *cn, uint32_t *flags,
2520                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
2521                      void *p_vrfy )
2522 {
2523     return( mbedtls_x509_crt_verify_restartable( crt, trust_ca, ca_crl,
2524                 profile, cn, flags, f_vrfy, p_vrfy, NULL ) );
2525 }
2526 
2527 /*
2528  * Verify the certificate validity, with profile, restartable version
2529  *
2530  * This function:
2531  *  - checks the requested CN (if any)
2532  *  - checks the type and size of the EE cert's key,
2533  *    as that isn't done as part of chain building/verification currently
2534  *  - builds and verifies the chain
2535  *  - then calls the callback and merges the flags
2536  */
mbedtls_x509_crt_verify_restartable(mbedtls_x509_crt * crt,mbedtls_x509_crt * trust_ca,mbedtls_x509_crl * ca_crl,const mbedtls_x509_crt_profile * profile,const char * cn,uint32_t * flags,int (* f_vrfy)(void *,mbedtls_x509_crt *,int,uint32_t *),void * p_vrfy,mbedtls_x509_crt_restart_ctx * rs_ctx)2537 int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
2538                      mbedtls_x509_crt *trust_ca,
2539                      mbedtls_x509_crl *ca_crl,
2540                      const mbedtls_x509_crt_profile *profile,
2541                      const char *cn, uint32_t *flags,
2542                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
2543                      void *p_vrfy,
2544                      mbedtls_x509_crt_restart_ctx *rs_ctx )
2545 {
2546     int ret;
2547     mbedtls_pk_type_t pk_type;
2548     mbedtls_x509_crt_verify_chain ver_chain;
2549     uint32_t ee_flags;
2550 
2551     *flags = 0;
2552     ee_flags = 0;
2553     x509_crt_verify_chain_reset( &ver_chain );
2554 
2555     if( profile == NULL )
2556     {
2557         ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
2558         goto exit;
2559     }
2560 
2561     /* check name if requested */
2562     if( cn != NULL )
2563         x509_crt_verify_name( crt, cn, &ee_flags );
2564 
2565     /* Check the type and size of the key */
2566     pk_type = mbedtls_pk_get_type( &crt->pk );
2567 
2568     if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
2569         ee_flags |= MBEDTLS_X509_BADCERT_BAD_PK;
2570 
2571     if( x509_profile_check_key( profile, &crt->pk ) != 0 )
2572         ee_flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
2573 
2574     /* Check the chain */
2575     ret = x509_crt_verify_chain( crt, trust_ca, ca_crl, profile,
2576                                  &ver_chain, rs_ctx );
2577 
2578     if( ret != 0 )
2579         goto exit;
2580 
2581     /* Merge end-entity flags */
2582     ver_chain.items[0].flags |= ee_flags;
2583 
2584     /* Build final flags, calling callback on the way if any */
2585     ret = x509_crt_merge_flags_with_cb( flags, &ver_chain, f_vrfy, p_vrfy );
2586 
2587 exit:
2588 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2589     if( rs_ctx != NULL && ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
2590         mbedtls_x509_crt_restart_free( rs_ctx );
2591 #endif
2592 
2593     /* prevent misuse of the vrfy callback - VERIFY_FAILED would be ignored by
2594      * the SSL module for authmode optional, but non-zero return from the
2595      * callback means a fatal error so it shouldn't be ignored */
2596     if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
2597         ret = MBEDTLS_ERR_X509_FATAL_ERROR;
2598 
2599     if( ret != 0 )
2600     {
2601         *flags = (uint32_t) -1;
2602         return( ret );
2603     }
2604 
2605     if( *flags != 0 )
2606         return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
2607 
2608     return( 0 );
2609 }
2610 
2611 /*
2612  * Initialize a certificate chain
2613  */
mbedtls_x509_crt_init(mbedtls_x509_crt * crt)2614 void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
2615 {
2616     memset( crt, 0, sizeof(mbedtls_x509_crt) );
2617 }
2618 
2619 /*
2620  * Unallocate all certificate data
2621  */
mbedtls_x509_crt_free(mbedtls_x509_crt * crt)2622 void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
2623 {
2624     mbedtls_x509_crt *cert_cur = crt;
2625     mbedtls_x509_crt *cert_prv;
2626     mbedtls_x509_name *name_cur;
2627     mbedtls_x509_name *name_prv;
2628     mbedtls_x509_sequence *seq_cur;
2629     mbedtls_x509_sequence *seq_prv;
2630 
2631     if( crt == NULL )
2632         return;
2633 
2634     do
2635     {
2636         mbedtls_pk_free( &cert_cur->pk );
2637 
2638 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
2639         mbedtls_free( cert_cur->sig_opts );
2640 #endif
2641 
2642         name_cur = cert_cur->issuer.next;
2643         while( name_cur != NULL )
2644         {
2645             name_prv = name_cur;
2646             name_cur = name_cur->next;
2647             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
2648             mbedtls_free( name_prv );
2649         }
2650 
2651         name_cur = cert_cur->subject.next;
2652         while( name_cur != NULL )
2653         {
2654             name_prv = name_cur;
2655             name_cur = name_cur->next;
2656             mbedtls_platform_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
2657             mbedtls_free( name_prv );
2658         }
2659 
2660         seq_cur = cert_cur->ext_key_usage.next;
2661         while( seq_cur != NULL )
2662         {
2663             seq_prv = seq_cur;
2664             seq_cur = seq_cur->next;
2665             mbedtls_platform_zeroize( seq_prv,
2666                                       sizeof( mbedtls_x509_sequence ) );
2667             mbedtls_free( seq_prv );
2668         }
2669 
2670         seq_cur = cert_cur->subject_alt_names.next;
2671         while( seq_cur != NULL )
2672         {
2673             seq_prv = seq_cur;
2674             seq_cur = seq_cur->next;
2675             mbedtls_platform_zeroize( seq_prv,
2676                                       sizeof( mbedtls_x509_sequence ) );
2677             mbedtls_free( seq_prv );
2678         }
2679 
2680         if( cert_cur->raw.p != NULL )
2681         {
2682             mbedtls_platform_zeroize( cert_cur->raw.p, cert_cur->raw.len );
2683             mbedtls_free( cert_cur->raw.p );
2684         }
2685 
2686         cert_cur = cert_cur->next;
2687     }
2688     while( cert_cur != NULL );
2689 
2690     cert_cur = crt;
2691     do
2692     {
2693         cert_prv = cert_cur;
2694         cert_cur = cert_cur->next;
2695 
2696         mbedtls_platform_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
2697         if( cert_prv != crt )
2698             mbedtls_free( cert_prv );
2699     }
2700     while( cert_cur != NULL );
2701 }
2702 
2703 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
2704 /*
2705  * Initialize a restart context
2706  */
mbedtls_x509_crt_restart_init(mbedtls_x509_crt_restart_ctx * ctx)2707 void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx )
2708 {
2709     mbedtls_pk_restart_init( &ctx->pk );
2710 
2711     ctx->parent = NULL;
2712     ctx->fallback_parent = NULL;
2713     ctx->fallback_signature_is_good = 0;
2714 
2715     ctx->parent_is_trusted = -1;
2716 
2717     ctx->in_progress = x509_crt_rs_none;
2718     ctx->self_cnt = 0;
2719     x509_crt_verify_chain_reset( &ctx->ver_chain );
2720 }
2721 
2722 /*
2723  * Free the components of a restart context
2724  */
mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx * ctx)2725 void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx )
2726 {
2727     if( ctx == NULL )
2728         return;
2729 
2730     mbedtls_pk_restart_free( &ctx->pk );
2731     mbedtls_x509_crt_restart_init( ctx );
2732 }
2733 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
2734 
2735 #endif /* MBEDTLS_X509_CRT_PARSE_C */
2736