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