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