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