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