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