PolarSSL v1.3.3
x509_crt.c
Go to the documentation of this file.
1 /*
2  * X.509 certificate and private key decoding
3  *
4  * Copyright (C) 2006-2013, Brainspark B.V.
5  *
6  * This file is part of PolarSSL (http://www.polarssl.org)
7  * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
8  *
9  * All rights reserved.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25 /*
26  * The ITU-T X.509 standard defines a certificate format for PKI.
27  *
28  * http://www.ietf.org/rfc/rfc3279.txt
29  * http://www.ietf.org/rfc/rfc3280.txt
30  *
31  * ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-1v2.asc
32  *
33  * http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
34  * http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
35  */
36 
37 #include "polarssl/config.h"
38 
39 #if defined(POLARSSL_X509_CRT_PARSE_C)
40 
41 #include "polarssl/x509_crt.h"
42 #include "polarssl/oid.h"
43 #if defined(POLARSSL_PEM_PARSE_C)
44 #include "polarssl/pem.h"
45 #endif
46 
47 #if defined(POLARSSL_MEMORY_C)
48 #include "polarssl/memory.h"
49 #else
50 #define polarssl_malloc malloc
51 #define polarssl_free free
52 #endif
53 
54 #if defined(POLARSSL_THREADING_C)
55 #include "polarssl/threading.h"
56 #endif
57 
58 #include <string.h>
59 #include <stdlib.h>
60 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
61 #include <windows.h>
62 #else
63 #include <time.h>
64 #endif
65 
66 #if defined(EFIX64) || defined(EFI32)
67 #include <stdio.h>
68 #endif
69 
70 #if defined(POLARSSL_FS_IO)
71 #include <stdio.h>
72 #if !defined(_WIN32)
73 #include <sys/types.h>
74 #include <sys/stat.h>
75 #include <dirent.h>
76 #endif
77 #endif
78 
79 /*
80  * Version ::= INTEGER { v1(0), v2(1), v3(2) }
81  */
82 static int x509_get_version( unsigned char **p,
83  const unsigned char *end,
84  int *ver )
85 {
86  int ret;
87  size_t len;
88 
89  if( ( ret = asn1_get_tag( p, end, &len,
91  {
93  {
94  *ver = 0;
95  return( 0 );
96  }
97 
98  return( ret );
99  }
100 
101  end = *p + len;
102 
103  if( ( ret = asn1_get_int( p, end, ver ) ) != 0 )
104  return( POLARSSL_ERR_X509_INVALID_VERSION + ret );
105 
106  if( *p != end )
109 
110  return( 0 );
111 }
112 
113 /*
114  * Validity ::= SEQUENCE {
115  * notBefore Time,
116  * notAfter Time }
117  */
118 static int x509_get_dates( unsigned char **p,
119  const unsigned char *end,
120  x509_time *from,
121  x509_time *to )
122 {
123  int ret;
124  size_t len;
125 
126  if( ( ret = asn1_get_tag( p, end, &len,
127  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
128  return( POLARSSL_ERR_X509_INVALID_DATE + ret );
129 
130  end = *p + len;
131 
132  if( ( ret = x509_get_time( p, end, from ) ) != 0 )
133  return( ret );
134 
135  if( ( ret = x509_get_time( p, end, to ) ) != 0 )
136  return( ret );
137 
138  if( *p != end )
141 
142  return( 0 );
143 }
144 
145 /*
146  * X.509 v2/v3 unique identifier (not parsed)
147  */
148 static int x509_get_uid( unsigned char **p,
149  const unsigned char *end,
150  x509_buf *uid, int n )
151 {
152  int ret;
153 
154  if( *p == end )
155  return( 0 );
156 
157  uid->tag = **p;
158 
159  if( ( ret = asn1_get_tag( p, end, &uid->len,
160  ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | n ) ) != 0 )
161  {
163  return( 0 );
164 
165  return( ret );
166  }
167 
168  uid->p = *p;
169  *p += uid->len;
170 
171  return( 0 );
172 }
173 
174 static int x509_get_basic_constraints( unsigned char **p,
175  const unsigned char *end,
176  int *ca_istrue,
177  int *max_pathlen )
178 {
179  int ret;
180  size_t len;
181 
182  /*
183  * BasicConstraints ::= SEQUENCE {
184  * cA BOOLEAN DEFAULT FALSE,
185  * pathLenConstraint INTEGER (0..MAX) OPTIONAL }
186  */
187  *ca_istrue = 0; /* DEFAULT FALSE */
188  *max_pathlen = 0; /* endless */
189 
190  if( ( ret = asn1_get_tag( p, end, &len,
191  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
192  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
193 
194  if( *p == end )
195  return 0;
196 
197  if( ( ret = asn1_get_bool( p, end, ca_istrue ) ) != 0 )
198  {
200  ret = asn1_get_int( p, end, ca_istrue );
201 
202  if( ret != 0 )
203  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
204 
205  if( *ca_istrue != 0 )
206  *ca_istrue = 1;
207  }
208 
209  if( *p == end )
210  return 0;
211 
212  if( ( ret = asn1_get_int( p, end, max_pathlen ) ) != 0 )
213  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
214 
215  if( *p != end )
218 
219  (*max_pathlen)++;
220 
221  return 0;
222 }
223 
224 static int x509_get_ns_cert_type( unsigned char **p,
225  const unsigned char *end,
226  unsigned char *ns_cert_type)
227 {
228  int ret;
229  x509_bitstring bs = { 0, 0, NULL };
230 
231  if( ( ret = asn1_get_bitstring( p, end, &bs ) ) != 0 )
232  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
233 
234  if( bs.len != 1 )
237 
238  /* Get actual bitstring */
239  *ns_cert_type = *bs.p;
240  return 0;
241 }
242 
243 static int x509_get_key_usage( unsigned char **p,
244  const unsigned char *end,
245  unsigned char *key_usage)
246 {
247  int ret;
248  x509_bitstring bs = { 0, 0, NULL };
249 
250  if( ( ret = asn1_get_bitstring( p, end, &bs ) ) != 0 )
251  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
252 
253  if( bs.len < 1 )
256 
257  /* Get actual bitstring */
258  *key_usage = *bs.p;
259  return 0;
260 }
261 
262 /*
263  * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
264  *
265  * KeyPurposeId ::= OBJECT IDENTIFIER
266  */
267 static int x509_get_ext_key_usage( unsigned char **p,
268  const unsigned char *end,
269  x509_sequence *ext_key_usage)
270 {
271  int ret;
272 
273  if( ( ret = asn1_get_sequence_of( p, end, ext_key_usage, ASN1_OID ) ) != 0 )
274  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
275 
276  /* Sequence length must be >= 1 */
277  if( ext_key_usage->buf.p == NULL )
280 
281  return 0;
282 }
283 
284 /*
285  * SubjectAltName ::= GeneralNames
286  *
287  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
288  *
289  * GeneralName ::= CHOICE {
290  * otherName [0] OtherName,
291  * rfc822Name [1] IA5String,
292  * dNSName [2] IA5String,
293  * x400Address [3] ORAddress,
294  * directoryName [4] Name,
295  * ediPartyName [5] EDIPartyName,
296  * uniformResourceIdentifier [6] IA5String,
297  * iPAddress [7] OCTET STRING,
298  * registeredID [8] OBJECT IDENTIFIER }
299  *
300  * OtherName ::= SEQUENCE {
301  * type-id OBJECT IDENTIFIER,
302  * value [0] EXPLICIT ANY DEFINED BY type-id }
303  *
304  * EDIPartyName ::= SEQUENCE {
305  * nameAssigner [0] DirectoryString OPTIONAL,
306  * partyName [1] DirectoryString }
307  *
308  * NOTE: PolarSSL only parses and uses dNSName at this point.
309  */
310 static int x509_get_subject_alt_name( unsigned char **p,
311  const unsigned char *end,
312  x509_sequence *subject_alt_name )
313 {
314  int ret;
315  size_t len, tag_len;
316  asn1_buf *buf;
317  unsigned char tag;
318  asn1_sequence *cur = subject_alt_name;
319 
320  /* Get main sequence tag */
321  if( ( ret = asn1_get_tag( p, end, &len,
322  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
323  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
324 
325  if( *p + len != end )
328 
329  while( *p < end )
330  {
331  if( ( end - *p ) < 1 )
334 
335  tag = **p;
336  (*p)++;
337  if( ( ret = asn1_get_len( p, end, &tag_len ) ) != 0 )
338  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
339 
340  if( ( tag & ASN1_CONTEXT_SPECIFIC ) != ASN1_CONTEXT_SPECIFIC )
343 
344  if( tag != ( ASN1_CONTEXT_SPECIFIC | 2 ) )
345  {
346  *p += tag_len;
347  continue;
348  }
349 
350  buf = &(cur->buf);
351  buf->tag = tag;
352  buf->p = *p;
353  buf->len = tag_len;
354  *p += buf->len;
355 
356  /* Allocate and assign next pointer */
357  if (*p < end)
358  {
360  sizeof( asn1_sequence ) );
361 
362  if( cur->next == NULL )
365 
366  memset( cur->next, 0, sizeof( asn1_sequence ) );
367  cur = cur->next;
368  }
369  }
370 
371  /* Set final sequence entry's next pointer to NULL */
372  cur->next = NULL;
373 
374  if( *p != end )
377 
378  return( 0 );
379 }
380 
381 /*
382  * X.509 v3 extensions
383  *
384  * TODO: Perform all of the basic constraints tests required by the RFC
385  * TODO: Set values for undetected extensions to a sane default?
386  *
387  */
388 static int x509_get_crt_ext( unsigned char **p,
389  const unsigned char *end,
390  x509_crt *crt )
391 {
392  int ret;
393  size_t len;
394  unsigned char *end_ext_data, *end_ext_octet;
395 
396  if( ( ret = x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
397  {
399  return( 0 );
400 
401  return( ret );
402  }
403 
404  while( *p < end )
405  {
406  /*
407  * Extension ::= SEQUENCE {
408  * extnID OBJECT IDENTIFIER,
409  * critical BOOLEAN DEFAULT FALSE,
410  * extnValue OCTET STRING }
411  */
412  x509_buf extn_oid = {0, 0, NULL};
413  int is_critical = 0; /* DEFAULT FALSE */
414  int ext_type = 0;
415 
416  if( ( ret = asn1_get_tag( p, end, &len,
417  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
418  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
419 
420  end_ext_data = *p + len;
421 
422  /* Get extension ID */
423  extn_oid.tag = **p;
424 
425  if( ( ret = asn1_get_tag( p, end, &extn_oid.len, ASN1_OID ) ) != 0 )
426  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
427 
428  extn_oid.p = *p;
429  *p += extn_oid.len;
430 
431  if( ( end - *p ) < 1 )
434 
435  /* Get optional critical */
436  if( ( ret = asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
438  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
439 
440  /* Data should be octet string type */
441  if( ( ret = asn1_get_tag( p, end_ext_data, &len,
442  ASN1_OCTET_STRING ) ) != 0 )
443  return( POLARSSL_ERR_X509_INVALID_EXTENSIONS + ret );
444 
445  end_ext_octet = *p + len;
446 
447  if( end_ext_octet != end_ext_data )
450 
451  /*
452  * Detect supported extensions
453  */
454  ret = oid_get_x509_ext_type( &extn_oid, &ext_type );
455 
456  if( ret != 0 )
457  {
458  /* No parser found, skip extension */
459  *p = end_ext_octet;
460 
461 #if !defined(POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
462  if( is_critical )
463  {
464  /* Data is marked as critical: fail */
467  }
468 #endif
469  continue;
470  }
471 
472  crt->ext_types |= ext_type;
473 
474  switch( ext_type )
475  {
477  /* Parse basic constraints */
478  if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
479  &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
480  return ( ret );
481  break;
482 
483  case EXT_KEY_USAGE:
484  /* Parse key usage */
485  if( ( ret = x509_get_key_usage( p, end_ext_octet,
486  &crt->key_usage ) ) != 0 )
487  return ( ret );
488  break;
489 
491  /* Parse extended key usage */
492  if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
493  &crt->ext_key_usage ) ) != 0 )
494  return ( ret );
495  break;
496 
498  /* Parse subject alt name */
499  if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
500  &crt->subject_alt_names ) ) != 0 )
501  return ( ret );
502  break;
503 
504  case EXT_NS_CERT_TYPE:
505  /* Parse netscape certificate type */
506  if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
507  &crt->ns_cert_type ) ) != 0 )
508  return ( ret );
509  break;
510 
511  default:
513  }
514  }
515 
516  if( *p != end )
519 
520  return( 0 );
521 }
522 
523 /*
524  * Parse and fill a single X.509 certificate in DER format
525  */
526 static int x509_crt_parse_der_core( x509_crt *crt, const unsigned char *buf,
527  size_t buflen )
528 {
529  int ret;
530  size_t len;
531  unsigned char *p, *end, *crt_end;
532 
533  /*
534  * Check for valid input
535  */
536  if( crt == NULL || buf == NULL )
538 
539  p = (unsigned char *) polarssl_malloc( len = buflen );
540 
541  if( p == NULL )
543 
544  memcpy( p, buf, buflen );
545 
546  buflen = 0;
547 
548  crt->raw.p = p;
549  crt->raw.len = len;
550  end = p + len;
551 
552  /*
553  * Certificate ::= SEQUENCE {
554  * tbsCertificate TBSCertificate,
555  * signatureAlgorithm AlgorithmIdentifier,
556  * signatureValue BIT STRING }
557  */
558  if( ( ret = asn1_get_tag( &p, end, &len,
559  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
560  {
561  x509_crt_free( crt );
563  }
564 
565  if( len > (size_t) ( end - p ) )
566  {
567  x509_crt_free( crt );
570  }
571  crt_end = p + len;
572 
573  /*
574  * TBSCertificate ::= SEQUENCE {
575  */
576  crt->tbs.p = p;
577 
578  if( ( ret = asn1_get_tag( &p, end, &len,
579  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
580  {
581  x509_crt_free( crt );
582  return( POLARSSL_ERR_X509_INVALID_FORMAT + ret );
583  }
584 
585  end = p + len;
586  crt->tbs.len = end - crt->tbs.p;
587 
588  /*
589  * Version ::= INTEGER { v1(0), v2(1), v3(2) }
590  *
591  * CertificateSerialNumber ::= INTEGER
592  *
593  * signature AlgorithmIdentifier
594  */
595  if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
596  ( ret = x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
597  ( ret = x509_get_alg_null( &p, end, &crt->sig_oid1 ) ) != 0 )
598  {
599  x509_crt_free( crt );
600  return( ret );
601  }
602 
603  crt->version++;
604 
605  if( crt->version > 3 )
606  {
607  x509_crt_free( crt );
609  }
610 
611  if( ( ret = x509_get_sig_alg( &crt->sig_oid1, &crt->sig_md,
612  &crt->sig_pk ) ) != 0 )
613  {
614  x509_crt_free( crt );
615  return( ret );
616  }
617 
618  /*
619  * issuer Name
620  */
621  crt->issuer_raw.p = p;
622 
623  if( ( ret = asn1_get_tag( &p, end, &len,
624  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
625  {
626  x509_crt_free( crt );
627  return( POLARSSL_ERR_X509_INVALID_FORMAT + ret );
628  }
629 
630  if( ( ret = x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
631  {
632  x509_crt_free( crt );
633  return( ret );
634  }
635 
636  crt->issuer_raw.len = p - crt->issuer_raw.p;
637 
638  /*
639  * Validity ::= SEQUENCE {
640  * notBefore Time,
641  * notAfter Time }
642  *
643  */
644  if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
645  &crt->valid_to ) ) != 0 )
646  {
647  x509_crt_free( crt );
648  return( ret );
649  }
650 
651  /*
652  * subject Name
653  */
654  crt->subject_raw.p = p;
655 
656  if( ( ret = asn1_get_tag( &p, end, &len,
657  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
658  {
659  x509_crt_free( crt );
660  return( POLARSSL_ERR_X509_INVALID_FORMAT + ret );
661  }
662 
663  if( len && ( ret = x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
664  {
665  x509_crt_free( crt );
666  return( ret );
667  }
668 
669  crt->subject_raw.len = p - crt->subject_raw.p;
670 
671  /*
672  * SubjectPublicKeyInfo
673  */
674  if( ( ret = pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
675  {
676  x509_crt_free( crt );
677  return( ret );
678  }
679 
680  /*
681  * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
682  * -- If present, version shall be v2 or v3
683  * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
684  * -- If present, version shall be v2 or v3
685  * extensions [3] EXPLICIT Extensions OPTIONAL
686  * -- If present, version shall be v3
687  */
688  if( crt->version == 2 || crt->version == 3 )
689  {
690  ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
691  if( ret != 0 )
692  {
693  x509_crt_free( crt );
694  return( ret );
695  }
696  }
697 
698  if( crt->version == 2 || crt->version == 3 )
699  {
700  ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
701  if( ret != 0 )
702  {
703  x509_crt_free( crt );
704  return( ret );
705  }
706  }
707 
708 #if !defined(POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3)
709  if( crt->version == 3 )
710  {
711 #endif
712  ret = x509_get_crt_ext( &p, end, crt);
713  if( ret != 0 )
714  {
715  x509_crt_free( crt );
716  return( ret );
717  }
718 #if !defined(POLARSSL_X509_ALLOW_EXTENSIONS_NON_V3)
719  }
720 #endif
721 
722  if( p != end )
723  {
724  x509_crt_free( crt );
727  }
728 
729  end = crt_end;
730 
731  /*
732  * }
733  * -- end of TBSCertificate
734  *
735  * signatureAlgorithm AlgorithmIdentifier,
736  * signatureValue BIT STRING
737  */
738  if( ( ret = x509_get_alg_null( &p, end, &crt->sig_oid2 ) ) != 0 )
739  {
740  x509_crt_free( crt );
741  return( ret );
742  }
743 
744  if( crt->sig_oid1.len != crt->sig_oid2.len ||
745  memcmp( crt->sig_oid1.p, crt->sig_oid2.p, crt->sig_oid1.len ) != 0 )
746  {
747  x509_crt_free( crt );
749  }
750 
751  if( ( ret = x509_get_sig( &p, end, &crt->sig ) ) != 0 )
752  {
753  x509_crt_free( crt );
754  return( ret );
755  }
756 
757  if( p != end )
758  {
759  x509_crt_free( crt );
762  }
763 
764  return( 0 );
765 }
766 
767 /*
768  * Parse one X.509 certificate in DER format from a buffer and add them to a
769  * chained list
770  */
771 int x509_crt_parse_der( x509_crt *chain, const unsigned char *buf,
772  size_t buflen )
773 {
774  int ret;
775  x509_crt *crt = chain, *prev = NULL;
776 
777  /*
778  * Check for valid input
779  */
780  if( crt == NULL || buf == NULL )
782 
783  while( crt->version != 0 && crt->next != NULL )
784  {
785  prev = crt;
786  crt = crt->next;
787  }
788 
789  /*
790  * Add new certificate on the end of the chain if needed.
791  */
792  if ( crt->version != 0 && crt->next == NULL)
793  {
794  crt->next = (x509_crt *) polarssl_malloc( sizeof( x509_crt ) );
795 
796  if( crt->next == NULL )
798 
799  prev = crt;
800  crt = crt->next;
801  x509_crt_init( crt );
802  }
803 
804  if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
805  {
806  if( prev )
807  prev->next = NULL;
808 
809  if( crt != chain )
810  polarssl_free( crt );
811 
812  return( ret );
813  }
814 
815  return( 0 );
816 }
817 
818 /*
819  * Parse one or more PEM certificates from a buffer and add them to the chained list
820  */
821 int x509_crt_parse( x509_crt *chain, const unsigned char *buf, size_t buflen )
822 {
823  int success = 0, first_error = 0, total_failed = 0;
824  int buf_format = X509_FORMAT_DER;
825 
826  /*
827  * Check for valid input
828  */
829  if( chain == NULL || buf == NULL )
831 
832  /*
833  * Determine buffer content. Buffer contains either one DER certificate or
834  * one or more PEM certificates.
835  */
836 #if defined(POLARSSL_PEM_PARSE_C)
837  if( strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
838  buf_format = X509_FORMAT_PEM;
839 #endif
840 
841  if( buf_format == X509_FORMAT_DER )
842  return x509_crt_parse_der( chain, buf, buflen );
843 
844 #if defined(POLARSSL_PEM_PARSE_C)
845  if( buf_format == X509_FORMAT_PEM )
846  {
847  int ret;
848  pem_context pem;
849 
850  while( buflen > 0 )
851  {
852  size_t use_len;
853  pem_init( &pem );
854 
855  ret = pem_read_buffer( &pem,
856  "-----BEGIN CERTIFICATE-----",
857  "-----END CERTIFICATE-----",
858  buf, NULL, 0, &use_len );
859 
860  if( ret == 0 )
861  {
862  /*
863  * Was PEM encoded
864  */
865  buflen -= use_len;
866  buf += use_len;
867  }
868  else if( ret == POLARSSL_ERR_PEM_BAD_INPUT_DATA )
869  {
870  return( ret );
871  }
873  {
874  pem_free( &pem );
875 
876  /*
877  * PEM header and footer were found
878  */
879  buflen -= use_len;
880  buf += use_len;
881 
882  if( first_error == 0 )
883  first_error = ret;
884 
885  continue;
886  }
887  else
888  break;
889 
890  ret = x509_crt_parse_der( chain, pem.buf, pem.buflen );
891 
892  pem_free( &pem );
893 
894  if( ret != 0 )
895  {
896  /*
897  * Quit parsing on a memory error
898  */
900  return( ret );
901 
902  if( first_error == 0 )
903  first_error = ret;
904 
905  total_failed++;
906  continue;
907  }
908 
909  success = 1;
910  }
911  }
912 #endif
913 
914  if( success )
915  return( total_failed );
916  else if( first_error )
917  return( first_error );
918  else
920 }
921 
922 #if defined(POLARSSL_FS_IO)
923 /*
924  * Load one or more certificates and add them to the chained list
925  */
926 int x509_crt_parse_file( x509_crt *chain, const char *path )
927 {
928  int ret;
929  size_t n;
930  unsigned char *buf;
931 
932  if ( ( ret = x509_load_file( path, &buf, &n ) ) != 0 )
933  return( ret );
934 
935  ret = x509_crt_parse( chain, buf, n );
936 
937  memset( buf, 0, n + 1 );
938  polarssl_free( buf );
939 
940  return( ret );
941 }
942 
943 #if defined(POLARSSL_THREADING_PTHREAD)
944 static threading_mutex_t readdir_mutex = PTHREAD_MUTEX_INITIALIZER;
945 #endif
946 
947 int x509_crt_parse_path( x509_crt *chain, const char *path )
948 {
949  int ret = 0;
950 #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
951  int w_ret;
952  WCHAR szDir[MAX_PATH];
953  char filename[MAX_PATH];
954  char *p;
955  int len = (int) strlen( path );
956 
957  WIN32_FIND_DATAW file_data;
958  HANDLE hFind;
959 
960  if( len > MAX_PATH - 3 )
962 
963  memset( szDir, 0, sizeof(szDir) );
964  memset( filename, 0, MAX_PATH );
965  memcpy( filename, path, len );
966  filename[len++] = '\\';
967  p = filename + len;
968  filename[len++] = '*';
969 
970  w_ret = MultiByteToWideChar( CP_ACP, 0, filename, len, szDir, MAX_PATH - 3 );
971 
972  hFind = FindFirstFileW( szDir, &file_data );
973  if (hFind == INVALID_HANDLE_VALUE)
975 
976  len = MAX_PATH - len;
977  do
978  {
979  memset( p, 0, len );
980 
981  if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
982  continue;
983 
984  w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
985  lstrlenW(file_data.cFileName),
986  p, len - 1,
987  NULL, NULL );
988 
989  w_ret = x509_crt_parse_file( chain, filename );
990  if( w_ret < 0 )
991  ret++;
992  else
993  ret += w_ret;
994  }
995  while( FindNextFileW( hFind, &file_data ) != 0 );
996 
997  if (GetLastError() != ERROR_NO_MORE_FILES)
999 
1000  FindClose( hFind );
1001 #else /* _WIN32 */
1002  int t_ret;
1003  struct stat sb;
1004  struct dirent *entry;
1005  char entry_name[255];
1006  DIR *dir = opendir( path );
1007 
1008  if( dir == NULL)
1010 
1011 #if defined(POLARSSL_THREADING_PTHREAD)
1012  if( ( ret = polarssl_mutex_lock( &readdir_mutex ) ) != 0 )
1013  return( ret );
1014 #endif
1015 
1016  while( ( entry = readdir( dir ) ) != NULL )
1017  {
1018  snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name );
1019 
1020  if( stat( entry_name, &sb ) == -1 )
1021  {
1022  closedir( dir );
1024  goto cleanup;
1025  }
1026 
1027  if( !S_ISREG( sb.st_mode ) )
1028  continue;
1029 
1030  // Ignore parse errors
1031  //
1032  t_ret = x509_crt_parse_file( chain, entry_name );
1033  if( t_ret < 0 )
1034  ret++;
1035  else
1036  ret += t_ret;
1037  }
1038  closedir( dir );
1039 
1040 cleanup:
1041 #if defined(POLARSSL_THREADING_PTHREAD)
1042  if( polarssl_mutex_unlock( &readdir_mutex ) != 0 )
1044 #endif
1045 
1046 #endif /* _WIN32 */
1047 
1048  return( ret );
1049 }
1050 #endif /* POLARSSL_FS_IO */
1051 
1052 #if defined(_MSC_VER) && !defined snprintf && !defined(EFIX64) && \
1053  !defined(EFI32)
1054 #include <stdarg.h>
1055 
1056 #if !defined vsnprintf
1057 #define vsnprintf _vsnprintf
1058 #endif // vsnprintf
1059 
1060 /*
1061  * Windows _snprintf and _vsnprintf are not compatible to linux versions.
1062  * Result value is not size of buffer needed, but -1 if no fit is possible.
1063  *
1064  * This fuction tries to 'fix' this by at least suggesting enlarging the
1065  * size by 20.
1066  */
1067 static int compat_snprintf(char *str, size_t size, const char *format, ...)
1068 {
1069  va_list ap;
1070  int res = -1;
1071 
1072  va_start( ap, format );
1073 
1074  res = vsnprintf( str, size, format, ap );
1075 
1076  va_end( ap );
1077 
1078  // No quick fix possible
1079  if ( res < 0 )
1080  return( (int) size + 20 );
1081 
1082  return res;
1083 }
1084 
1085 #define snprintf compat_snprintf
1086 #endif
1087 
1088 #define POLARSSL_ERR_DEBUG_BUF_TOO_SMALL -2
1089 
1090 #define SAFE_SNPRINTF() \
1091 { \
1092  if( ret == -1 ) \
1093  return( -1 ); \
1094  \
1095  if ( (unsigned int) ret > n ) { \
1096  p[n - 1] = '\0'; \
1097  return POLARSSL_ERR_DEBUG_BUF_TOO_SMALL;\
1098  } \
1099  \
1100  n -= (unsigned int) ret; \
1101  p += (unsigned int) ret; \
1102 }
1103 
1104 /*
1105  * Return an informational string about the certificate.
1106  */
1107 #define BEFORE_COLON 14
1108 #define BC "14"
1109 int x509_crt_info( char *buf, size_t size, const char *prefix,
1110  const x509_crt *crt )
1111 {
1112  int ret;
1113  size_t n;
1114  char *p;
1115  const char *desc = NULL;
1116  char key_size_str[BEFORE_COLON];
1117 
1118  p = buf;
1119  n = size;
1120 
1121  ret = snprintf( p, n, "%scert. version : %d\n",
1122  prefix, crt->version );
1123  SAFE_SNPRINTF();
1124  ret = snprintf( p, n, "%sserial number : ",
1125  prefix );
1126  SAFE_SNPRINTF();
1127 
1128  ret = x509_serial_gets( p, n, &crt->serial);
1129  SAFE_SNPRINTF();
1130 
1131  ret = snprintf( p, n, "\n%sissuer name : ", prefix );
1132  SAFE_SNPRINTF();
1133  ret = x509_dn_gets( p, n, &crt->issuer );
1134  SAFE_SNPRINTF();
1135 
1136  ret = snprintf( p, n, "\n%ssubject name : ", prefix );
1137  SAFE_SNPRINTF();
1138  ret = x509_dn_gets( p, n, &crt->subject );
1139  SAFE_SNPRINTF();
1140 
1141  ret = snprintf( p, n, "\n%sissued on : " \
1142  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
1143  crt->valid_from.year, crt->valid_from.mon,
1144  crt->valid_from.day, crt->valid_from.hour,
1145  crt->valid_from.min, crt->valid_from.sec );
1146  SAFE_SNPRINTF();
1147 
1148  ret = snprintf( p, n, "\n%sexpires on : " \
1149  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
1150  crt->valid_to.year, crt->valid_to.mon,
1151  crt->valid_to.day, crt->valid_to.hour,
1152  crt->valid_to.min, crt->valid_to.sec );
1153  SAFE_SNPRINTF();
1154 
1155  ret = snprintf( p, n, "\n%ssigned using : ", prefix );
1156  SAFE_SNPRINTF();
1157 
1158  ret = oid_get_sig_alg_desc( &crt->sig_oid1, &desc );
1159  if( ret != 0 )
1160  ret = snprintf( p, n, "???" );
1161  else
1162  ret = snprintf( p, n, "%s", desc );
1163  SAFE_SNPRINTF();
1164 
1165  if( ( ret = x509_key_size_helper( key_size_str, BEFORE_COLON,
1166  pk_get_name( &crt->pk ) ) ) != 0 )
1167  {
1168  return( ret );
1169  }
1170 
1171  ret = snprintf( p, n, "\n%s%-" BC "s: %d bits\n", prefix, key_size_str,
1172  (int) pk_get_size( &crt->pk ) );
1173  SAFE_SNPRINTF();
1174 
1175  return( (int) ( size - n ) );
1176 }
1177 
1178 #if defined(POLARSSL_X509_CRL_PARSE_C)
1179 /*
1180  * Return 1 if the certificate is revoked, or 0 otherwise.
1181  */
1182 int x509_crt_revoked( const x509_crt *crt, const x509_crl *crl )
1183 {
1184  const x509_crl_entry *cur = &crl->entry;
1185 
1186  while( cur != NULL && cur->serial.len != 0 )
1187  {
1188  if( crt->serial.len == cur->serial.len &&
1189  memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
1190  {
1191  if( x509_time_expired( &cur->revocation_date ) )
1192  return( 1 );
1193  }
1194 
1195  cur = cur->next;
1196  }
1197 
1198  return( 0 );
1199 }
1200 
1201 /*
1202  * Check that the given certificate is valid according to the CRL.
1203  */
1204 static int x509_crt_verifycrl( x509_crt *crt, x509_crt *ca,
1205  x509_crl *crl_list)
1206 {
1207  int flags = 0;
1208  unsigned char hash[POLARSSL_MD_MAX_SIZE];
1209  const md_info_t *md_info;
1210 
1211  if( ca == NULL )
1212  return( flags );
1213 
1214  /*
1215  * TODO: What happens if no CRL is present?
1216  * Suggestion: Revocation state should be unknown if no CRL is present.
1217  * For backwards compatibility this is not yet implemented.
1218  */
1219 
1220  while( crl_list != NULL )
1221  {
1222  if( crl_list->version == 0 ||
1223  crl_list->issuer_raw.len != ca->subject_raw.len ||
1224  memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
1225  crl_list->issuer_raw.len ) != 0 )
1226  {
1227  crl_list = crl_list->next;
1228  continue;
1229  }
1230 
1231  /*
1232  * Check if CRL is correctly signed by the trusted CA
1233  */
1234  md_info = md_info_from_type( crl_list->sig_md );
1235  if( md_info == NULL )
1236  {
1237  /*
1238  * Cannot check 'unknown' hash
1239  */
1240  flags |= BADCRL_NOT_TRUSTED;
1241  break;
1242  }
1243 
1244  md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
1245 
1246  if( pk_can_do( &ca->pk, crl_list->sig_pk ) == 0 ||
1247  pk_verify( &ca->pk, crl_list->sig_md, hash, md_info->size,
1248  crl_list->sig.p, crl_list->sig.len ) != 0 )
1249  {
1250  flags |= BADCRL_NOT_TRUSTED;
1251  break;
1252  }
1253 
1254  /*
1255  * Check for validity of CRL (Do not drop out)
1256  */
1257  if( x509_time_expired( &crl_list->next_update ) )
1258  flags |= BADCRL_EXPIRED;
1259 
1260  /*
1261  * Check if certificate is revoked
1262  */
1263  if( x509_crt_revoked(crt, crl_list) )
1264  {
1265  flags |= BADCERT_REVOKED;
1266  break;
1267  }
1268 
1269  crl_list = crl_list->next;
1270  }
1271  return flags;
1272 }
1273 #endif /* POLARSSL_X509_CRL_PARSE_C */
1274 
1275 // Equal == 0, inequal == 1
1276 static int x509_name_cmp( const void *s1, const void *s2, size_t len )
1277 {
1278  size_t i;
1279  unsigned char diff;
1280  const unsigned char *n1 = s1, *n2 = s2;
1281 
1282  for( i = 0; i < len; i++ )
1283  {
1284  diff = n1[i] ^ n2[i];
1285 
1286  if( diff == 0 )
1287  continue;
1288 
1289  if( diff == 32 &&
1290  ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
1291  ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
1292  {
1293  continue;
1294  }
1295 
1296  return( 1 );
1297  }
1298 
1299  return( 0 );
1300 }
1301 
1302 static int x509_wildcard_verify( const char *cn, x509_buf *name )
1303 {
1304  size_t i;
1305  size_t cn_idx = 0;
1306 
1307  if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
1308  return( 0 );
1309 
1310  for( i = 0; i < strlen( cn ); ++i )
1311  {
1312  if( cn[i] == '.' )
1313  {
1314  cn_idx = i;
1315  break;
1316  }
1317  }
1318 
1319  if( cn_idx == 0 )
1320  return( 0 );
1321 
1322  if( strlen( cn ) - cn_idx == name->len - 1 &&
1323  x509_name_cmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
1324  {
1325  return( 1 );
1326  }
1327 
1328  return( 0 );
1329 }
1330 
1331 static int x509_crt_verify_top(
1332  x509_crt *child, x509_crt *trust_ca,
1333  x509_crl *ca_crl, int path_cnt, int *flags,
1334  int (*f_vrfy)(void *, x509_crt *, int, int *),
1335  void *p_vrfy )
1336 {
1337  int ret;
1338  int ca_flags = 0, check_path_cnt = path_cnt + 1;
1339  unsigned char hash[POLARSSL_MD_MAX_SIZE];
1340  const md_info_t *md_info;
1341 
1342  if( x509_time_expired( &child->valid_to ) )
1343  *flags |= BADCERT_EXPIRED;
1344 
1345  /*
1346  * Child is the top of the chain. Check against the trust_ca list.
1347  */
1348  *flags |= BADCERT_NOT_TRUSTED;
1349 
1350  md_info = md_info_from_type( child->sig_md );
1351  if( md_info == NULL )
1352  {
1353  /*
1354  * Cannot check 'unknown', no need to try any CA
1355  */
1356  trust_ca = NULL;
1357  }
1358  else
1359  md( md_info, child->tbs.p, child->tbs.len, hash );
1360 
1361  while( trust_ca != NULL )
1362  {
1363  if( trust_ca->version == 0 ||
1364  child->issuer_raw.len != trust_ca->subject_raw.len ||
1365  memcmp( child->issuer_raw.p, trust_ca->subject_raw.p,
1366  child->issuer_raw.len ) != 0 )
1367  {
1368  trust_ca = trust_ca->next;
1369  continue;
1370  }
1371 
1372  /*
1373  * Reduce path_len to check against if top of the chain is
1374  * the same as the trusted CA
1375  */
1376  if( child->subject_raw.len == trust_ca->subject_raw.len &&
1377  memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
1378  child->issuer_raw.len ) == 0 )
1379  {
1380  check_path_cnt--;
1381  }
1382 
1383  if( trust_ca->max_pathlen > 0 &&
1384  trust_ca->max_pathlen < check_path_cnt )
1385  {
1386  trust_ca = trust_ca->next;
1387  continue;
1388  }
1389 
1390  if( pk_can_do( &trust_ca->pk, child->sig_pk ) == 0 ||
1391  pk_verify( &trust_ca->pk, child->sig_md, hash, md_info->size,
1392  child->sig.p, child->sig.len ) != 0 )
1393  {
1394  trust_ca = trust_ca->next;
1395  continue;
1396  }
1397 
1398  /*
1399  * Top of chain is signed by a trusted CA
1400  */
1401  *flags &= ~BADCERT_NOT_TRUSTED;
1402  break;
1403  }
1404 
1405  /*
1406  * If top of chain is not the same as the trusted CA send a verify request
1407  * to the callback for any issues with validity and CRL presence for the
1408  * trusted CA certificate.
1409  */
1410  if( trust_ca != NULL &&
1411  ( child->subject_raw.len != trust_ca->subject_raw.len ||
1412  memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
1413  child->issuer_raw.len ) != 0 ) )
1414  {
1415 #if defined(POLARSSL_X509_CRL_PARSE_C)
1416  /* Check trusted CA's CRL for the chain's top crt */
1417  *flags |= x509_crt_verifycrl( child, trust_ca, ca_crl );
1418 #else
1419  ((void) ca_crl);
1420 #endif
1421 
1422  if( x509_time_expired( &trust_ca->valid_to ) )
1423  ca_flags |= BADCERT_EXPIRED;
1424 
1425  if( NULL != f_vrfy )
1426  {
1427  if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1, &ca_flags ) ) != 0 )
1428  return( ret );
1429  }
1430  }
1431 
1432  /* Call callback on top cert */
1433  if( NULL != f_vrfy )
1434  {
1435  if( ( ret = f_vrfy(p_vrfy, child, path_cnt, flags ) ) != 0 )
1436  return( ret );
1437  }
1438 
1439  *flags |= ca_flags;
1440 
1441  return( 0 );
1442 }
1443 
1444 static int x509_crt_verify_child(
1445  x509_crt *child, x509_crt *parent, x509_crt *trust_ca,
1446  x509_crl *ca_crl, int path_cnt, int *flags,
1447  int (*f_vrfy)(void *, x509_crt *, int, int *),
1448  void *p_vrfy )
1449 {
1450  int ret;
1451  int parent_flags = 0;
1452  unsigned char hash[POLARSSL_MD_MAX_SIZE];
1453  x509_crt *grandparent;
1454  const md_info_t *md_info;
1455 
1456  if( x509_time_expired( &child->valid_to ) )
1457  *flags |= BADCERT_EXPIRED;
1458 
1459  md_info = md_info_from_type( child->sig_md );
1460  if( md_info == NULL )
1461  {
1462  /*
1463  * Cannot check 'unknown' hash
1464  */
1465  *flags |= BADCERT_NOT_TRUSTED;
1466  }
1467  else
1468  {
1469  md( md_info, child->tbs.p, child->tbs.len, hash );
1470 
1471  if( pk_can_do( &parent->pk, child->sig_pk ) == 0 ||
1472  pk_verify( &parent->pk, child->sig_md, hash, md_info->size,
1473  child->sig.p, child->sig.len ) != 0 )
1474  {
1475  *flags |= BADCERT_NOT_TRUSTED;
1476  }
1477  }
1478 
1479 #if defined(POLARSSL_X509_CRL_PARSE_C)
1480  /* Check trusted CA's CRL for the given crt */
1481  *flags |= x509_crt_verifycrl(child, parent, ca_crl);
1482 #endif
1483 
1484  grandparent = parent->next;
1485 
1486  while( grandparent != NULL )
1487  {
1488  if( grandparent->version == 0 ||
1489  grandparent->ca_istrue == 0 ||
1490  parent->issuer_raw.len != grandparent->subject_raw.len ||
1491  memcmp( parent->issuer_raw.p, grandparent->subject_raw.p,
1492  parent->issuer_raw.len ) != 0 )
1493  {
1494  grandparent = grandparent->next;
1495  continue;
1496  }
1497  break;
1498  }
1499 
1500  if( grandparent != NULL )
1501  {
1502  /*
1503  * Part of the chain
1504  */
1505  ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy );
1506  if( ret != 0 )
1507  return( ret );
1508  }
1509  else
1510  {
1511  ret = x509_crt_verify_top( parent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy );
1512  if( ret != 0 )
1513  return( ret );
1514  }
1515 
1516  /* child is verified to be a child of the parent, call verify callback */
1517  if( NULL != f_vrfy )
1518  if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
1519  return( ret );
1520 
1521  *flags |= parent_flags;
1522 
1523  return( 0 );
1524 }
1525 
1526 /*
1527  * Verify the certificate validity
1528  */
1529 int x509_crt_verify( x509_crt *crt,
1530  x509_crt *trust_ca,
1531  x509_crl *ca_crl,
1532  const char *cn, int *flags,
1533  int (*f_vrfy)(void *, x509_crt *, int, int *),
1534  void *p_vrfy )
1535 {
1536  size_t cn_len;
1537  int ret;
1538  int pathlen = 0;
1539  x509_crt *parent;
1540  x509_name *name;
1541  x509_sequence *cur = NULL;
1542 
1543  *flags = 0;
1544 
1545  if( cn != NULL )
1546  {
1547  name = &crt->subject;
1548  cn_len = strlen( cn );
1549 
1550  if( crt->ext_types & EXT_SUBJECT_ALT_NAME )
1551  {
1552  cur = &crt->subject_alt_names;
1553 
1554  while( cur != NULL )
1555  {
1556  if( cur->buf.len == cn_len &&
1557  x509_name_cmp( cn, cur->buf.p, cn_len ) == 0 )
1558  break;
1559 
1560  if( cur->buf.len > 2 &&
1561  memcmp( cur->buf.p, "*.", 2 ) == 0 &&
1562  x509_wildcard_verify( cn, &cur->buf ) )
1563  break;
1564 
1565  cur = cur->next;
1566  }
1567 
1568  if( cur == NULL )
1569  *flags |= BADCERT_CN_MISMATCH;
1570  }
1571  else
1572  {
1573  while( name != NULL )
1574  {
1575  if( OID_CMP( OID_AT_CN, &name->oid ) )
1576  {
1577  if( name->val.len == cn_len &&
1578  x509_name_cmp( name->val.p, cn, cn_len ) == 0 )
1579  break;
1580 
1581  if( name->val.len > 2 &&
1582  memcmp( name->val.p, "*.", 2 ) == 0 &&
1583  x509_wildcard_verify( cn, &name->val ) )
1584  break;
1585  }
1586 
1587  name = name->next;
1588  }
1589 
1590  if( name == NULL )
1591  *flags |= BADCERT_CN_MISMATCH;
1592  }
1593  }
1594 
1595  /*
1596  * Iterate upwards in the given cert chain, to find our crt parent.
1597  * Ignore any upper cert with CA != TRUE.
1598  */
1599  parent = crt->next;
1600 
1601  while( parent != NULL && parent->version != 0 )
1602  {
1603  if( parent->ca_istrue == 0 ||
1604  crt->issuer_raw.len != parent->subject_raw.len ||
1605  memcmp( crt->issuer_raw.p, parent->subject_raw.p,
1606  crt->issuer_raw.len ) != 0 )
1607  {
1608  parent = parent->next;
1609  continue;
1610  }
1611  break;
1612  }
1613 
1614  if( parent != NULL )
1615  {
1616  /*
1617  * Part of the chain
1618  */
1619  ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, pathlen, flags, f_vrfy, p_vrfy );
1620  if( ret != 0 )
1621  return( ret );
1622  }
1623  else
1624  {
1625  ret = x509_crt_verify_top( crt, trust_ca, ca_crl, pathlen, flags, f_vrfy, p_vrfy );
1626  if( ret != 0 )
1627  return( ret );
1628  }
1629 
1630  if( *flags != 0 )
1632 
1633  return( 0 );
1634 }
1635 
1636 /*
1637  * Initialize a certificate chain
1638  */
1639 void x509_crt_init( x509_crt *crt )
1640 {
1641  memset( crt, 0, sizeof(x509_crt) );
1642 }
1643 
1644 /*
1645  * Unallocate all certificate data
1646  */
1647 void x509_crt_free( x509_crt *crt )
1648 {
1649  x509_crt *cert_cur = crt;
1650  x509_crt *cert_prv;
1651  x509_name *name_cur;
1652  x509_name *name_prv;
1653  x509_sequence *seq_cur;
1654  x509_sequence *seq_prv;
1655 
1656  if( crt == NULL )
1657  return;
1658 
1659  do
1660  {
1661  pk_free( &cert_cur->pk );
1662 
1663  name_cur = cert_cur->issuer.next;
1664  while( name_cur != NULL )
1665  {
1666  name_prv = name_cur;
1667  name_cur = name_cur->next;
1668  memset( name_prv, 0, sizeof( x509_name ) );
1669  polarssl_free( name_prv );
1670  }
1671 
1672  name_cur = cert_cur->subject.next;
1673  while( name_cur != NULL )
1674  {
1675  name_prv = name_cur;
1676  name_cur = name_cur->next;
1677  memset( name_prv, 0, sizeof( x509_name ) );
1678  polarssl_free( name_prv );
1679  }
1680 
1681  seq_cur = cert_cur->ext_key_usage.next;
1682  while( seq_cur != NULL )
1683  {
1684  seq_prv = seq_cur;
1685  seq_cur = seq_cur->next;
1686  memset( seq_prv, 0, sizeof( x509_sequence ) );
1687  polarssl_free( seq_prv );
1688  }
1689 
1690  seq_cur = cert_cur->subject_alt_names.next;
1691  while( seq_cur != NULL )
1692  {
1693  seq_prv = seq_cur;
1694  seq_cur = seq_cur->next;
1695  memset( seq_prv, 0, sizeof( x509_sequence ) );
1696  polarssl_free( seq_prv );
1697  }
1698 
1699  if( cert_cur->raw.p != NULL )
1700  {
1701  memset( cert_cur->raw.p, 0, cert_cur->raw.len );
1702  polarssl_free( cert_cur->raw.p );
1703  }
1704 
1705  cert_cur = cert_cur->next;
1706  }
1707  while( cert_cur != NULL );
1708 
1709  cert_cur = crt;
1710  do
1711  {
1712  cert_prv = cert_cur;
1713  cert_cur = cert_cur->next;
1714 
1715  memset( cert_prv, 0, sizeof( x509_crt ) );
1716  if( cert_prv != crt )
1717  polarssl_free( cert_prv );
1718  }
1719  while( cert_cur != NULL );
1720 }
1721 
1722 #endif
int md(const md_info_t *md_info, const unsigned char *input, size_t ilen, unsigned char *output)
Output = message_digest( input buffer )
x509_buf sig
Definition: x509_crl.h:89
int x509_time_expired(const x509_time *time)
Check a given x509_time against the system time and check if it is valid.
int asn1_get_sequence_of(unsigned char **p, const unsigned char *end, asn1_sequence *cur, int tag)
Parses and splits an ASN.1 &quot;SEQUENCE OF &lt;tag&gt;&quot; Updated the pointer to immediately behind the full seq...
x509_sequence subject_alt_names
Optional list of Subject Alternative Names (Only dNSName supported).
Definition: x509_crt.h:76
#define X509_FORMAT_DER
Definition: x509.h:134
Memory allocation layer.
#define ASN1_OID
Definition: asn1.h:76
#define EXT_KEY_USAGE
Definition: x509.h:114
int(* polarssl_mutex_lock)(threading_mutex_t *mutex)
void *(* polarssl_malloc)(size_t len)
int sec
Time.
Definition: x509.h:175
int x509_get_name(unsigned char **p, const unsigned char *end, x509_name *cur)
#define POLARSSL_ERR_X509_INVALID_DATE
The date tag or value is invalid.
Definition: x509.h:55
int version
Definition: x509_crl.h:74
asn1_buf buf
Buffer containing the given ASN.1 item.
Definition: asn1.h:140
int x509_get_serial(unsigned char **p, const unsigned char *end, x509_buf *serial)
x509_buf raw
The raw certificate data (DER).
Definition: x509_crt.h:55
x509_time next_update
Definition: x509_crl.h:82
#define POLARSSL_ERR_ASN1_LENGTH_MISMATCH
Actual length differs from expected length.
Definition: asn1.h:53
int ext_types
Bit string containing detected and parsed extensions.
Definition: x509_crt.h:78
Certificate revocation list entry.
Definition: x509_crl.h:51
size_t pk_get_size(const pk_context *ctx)
Get the size in bits of the underlying key.
#define POLARSSL_ERR_X509_CERT_UNKNOWN_FORMAT
Format not recognized as DER or PEM.
Definition: x509.h:62
#define EXT_BASIC_CONSTRAINTS
Definition: x509.h:120
unsigned char ns_cert_type
Optional Netscape certificate type extension value: See the values below.
Definition: x509_crt.h:86
x509_buf issuer_raw
The raw issuer data (DER).
Definition: x509_crt.h:62
#define POLARSSL_ERR_X509_INVALID_FORMAT
The CRT/CRL/CSR format is invalid, e.g.
Definition: x509.h:50
int x509_key_size_helper(char *buf, size_t size, const char *name)
struct _x509_crl * next
Definition: x509_crl.h:93
int asn1_get_int(unsigned char **p, const unsigned char *end, int *val)
Retrieve an integer ASN.1 tag and its value.
size_t len
ASN1 length, e.g.
Definition: asn1.h:129
int x509_get_alg_null(unsigned char **p, const unsigned char *end, x509_buf *alg)
Container for date and time (precision in seconds).
Definition: x509.h:172
int x509_crt_parse(x509_crt *chain, const unsigned char *buf, size_t buflen)
Parse one or more certificates and add them to the chained list.
#define ASN1_SEQUENCE
Definition: asn1.h:78
x509_buf sig_oid2
Signature algorithm.
Definition: x509_crt.h:88
int oid_get_x509_ext_type(const asn1_buf *oid, int *ext_type)
Translate an X.509 extension OID into local values.
void x509_crt_free(x509_crt *crt)
Unallocate all certificate data.
Configuration options (set of defines)
#define OID_CMP(oid_str, oid_buf)
Compares two asn1_buf structures for the same OID.
Definition: asn1.h:100
x509_buf tbs
The raw certificate body (DER).
Definition: x509_crt.h:56
x509_buf serial
Unique id for certificate issued by a specific CA.
Definition: x509_crt.h:59
md_type_t sig_md
Internal representation of the MD algorithm of the signature algorithm, e.g.
Definition: x509_crt.h:90
int ca_istrue
Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise...
Definition: x509_crt.h:79
#define ASN1_CONSTRUCTED
Definition: asn1.h:88
int x509_crt_parse_der(x509_crt *chain, const unsigned char *buf, size_t buflen)
Parse a single DER formatted certificate and add it to the chained list.
int max_pathlen
Optional Basic Constraint extension value: The maximum path length to the root certificate.
Definition: x509_crt.h:80
int x509_get_sig(unsigned char **p, const unsigned char *end, x509_buf *sig)
const char * pk_get_name(const pk_context *ctx)
Access the type name.
#define BADCRL_NOT_TRUSTED
CRL is not correctly signed by the trusted CA.
Definition: x509.h:76
#define POLARSSL_ERR_ASN1_INVALID_LENGTH
Error when trying to determine the length or invalid length.
Definition: asn1.h:52
Container for ASN1 bit strings.
Definition: asn1.h:127
#define POLARSSL_ERR_X509_UNKNOWN_VERSION
CRT/CRL/CSR has an unsupported version number.
Definition: x509.h:58
Object Identifier (OID) database.
x509_buf serial
Definition: x509_crl.h:55
#define OID_AT_CN
id-at-commonName AttributeType:= {id-at 3}
Definition: oid.h:106
struct _x509_crt * next
Next certificate in the CA-chain.
Definition: x509_crt.h:93
x509_crl_entry entry
The CRL entries containing the certificate revocation times for this CA.
Definition: x509_crl.h:84
asn1_buf val
The named value.
Definition: asn1.h:151
int hour
Definition: x509.h:175
int mon
Definition: x509.h:174
Container for a sequence of ASN.1 items.
Definition: asn1.h:138
const md_info_t * md_info_from_type(md_type_t md_type)
Returns the message digest information associated with the given digest type.
int x509_get_time(unsigned char **p, const unsigned char *end, x509_time *time)
#define BADCERT_EXPIRED
The certificate validity has expired.
Definition: x509.h:72
unsigned char * p
Raw ASN1 data for the bit string.
Definition: asn1.h:131
Threading abstraction layer.
#define POLARSSL_ERR_X509_CERT_VERIFY_FAILED
Certificate verification failed, e.g.
Definition: x509.h:61
Container for an X.509 certificate.
Definition: x509_crt.h:53
Privacy Enhanced Mail (PEM) decoding.
x509_time valid_from
Start time of certificate validity.
Definition: x509_crt.h:68
int x509_dn_gets(char *buf, size_t size, const x509_name *dn)
Store the certificate DN in printable form into buf; no more than size characters will be written...
asn1_buf oid
The object identifier.
Definition: asn1.h:150
int pk_verify(pk_context *ctx, md_type_t md_alg, const unsigned char *hash, size_t hash_len, const unsigned char *sig, size_t sig_len)
Verify signature.
x509_sequence ext_key_usage
Optional list of extended key usage OIDs.
Definition: x509_crt.h:84
void x509_crt_init(x509_crt *crt)
Initialize a certificate (chain)
void(* polarssl_free)(void *ptr)
unsigned char * p
ASN1 data, e.g.
Definition: asn1.h:120
int oid_get_sig_alg_desc(const asn1_buf *oid, const char **desc)
Translate SignatureAlgorithm OID into description.
x509_name subject
The parsed subject data (named information object).
Definition: x509_crt.h:66
#define EXT_NS_CERT_TYPE
Definition: x509.h:128
int x509_crt_verify(x509_crt *crt, x509_crt *trust_ca, x509_crl *ca_crl, const char *cn, int *flags, int(*f_vrfy)(void *, x509_crt *, int, int *), void *p_vrfy)
Verify the certificate signature.
int pk_can_do(pk_context *ctx, pk_type_t type)
Tell if a context can do the operation given by type.
x509_buf tbs
The raw certificate body (DER).
Definition: x509_crl.h:72
int asn1_get_bool(unsigned char **p, const unsigned char *end, int *val)
Retrieve a boolean ASN.1 tag and its value.
x509_time valid_to
End time of certificate validity.
Definition: x509_crt.h:69
struct _x509_crl_entry * next
Definition: x509_crl.h:61
md_type_t sig_md
Internal representation of the MD algorithm of the signature algorithm, e.g.
Definition: x509_crl.h:90
X.509 certificate parsing and writing.
int day
Date.
Definition: x509.h:174
int x509_get_sig_alg(const x509_buf *sig_oid, md_type_t *md_alg, pk_type_t *pk_alg)
x509_buf sig_oid1
Signature algorithm, e.g.
Definition: x509_crt.h:60
int tag
ASN1 type, e.g.
Definition: asn1.h:118
#define POLARSSL_ERR_ASN1_OUT_OF_DATA
Out of data when parsing an ASN1 data structure.
Definition: asn1.h:50
#define EXT_EXTENDED_KEY_USAGE
Definition: x509.h:123
int pk_parse_subpubkey(unsigned char **p, const unsigned char *end, pk_context *pk)
Parse a SubjectPublicKeyInfo DER structure.
int x509_load_file(const char *path, unsigned char **buf, size_t *n)
#define POLARSSL_ERR_ASN1_MALLOC_FAILED
Memory allocation failed.
Definition: asn1.h:55
#define ASN1_CONTEXT_SPECIFIC
Definition: asn1.h:89
#define BADCERT_NOT_TRUSTED
The certificate is not correctly signed by the trusted CA.
Definition: x509.h:75
#define POLARSSL_ERR_X509_FILE_IO_ERROR
Read/write of file failed.
Definition: x509.h:65
int x509_crt_revoked(const x509_crt *crt, const x509_crl *crl)
Verify the certificate revocation status.
Container for a sequence or list of &#39;named&#39; ASN.1 data items.
Definition: asn1.h:148
Type-length-value structure that allows for ASN1 using DER.
Definition: asn1.h:116
pk_type_t sig_pk
&lt; Internal representation of the Public Key algorithm of the signature algorithm, e...
Definition: x509_crl.h:91
size_t len
ASN1 length, e.g.
Definition: asn1.h:119
x509_name issuer
The parsed issuer data (named information object).
Definition: x509_crt.h:65
#define X509_FORMAT_PEM
Definition: x509.h:135
void pk_free(pk_context *ctx)
Free a pk_context.
#define POLARSSL_MD_MAX_SIZE
Definition: md.h:66
int(* polarssl_mutex_unlock)(threading_mutex_t *mutex)
int year
Definition: x509.h:174
#define BADCERT_REVOKED
The certificate has been revoked (is on a CRL).
Definition: x509.h:73
#define BADCRL_EXPIRED
CRL is expired.
Definition: x509.h:77
int asn1_get_len(unsigned char **p, const unsigned char *end, size_t *len)
Get the length of an ASN.1 element.
#define POLARSSL_ERR_X509_FEATURE_UNAVAILABLE
Unavailable feature, e.g.
Definition: x509.h:48
int asn1_get_tag(unsigned char **p, const unsigned char *end, size_t *len, int tag)
Get the tag and length of the tag.
int x509_get_ext(unsigned char **p, const unsigned char *end, x509_buf *ext, int tag)
#define POLARSSL_ERR_X509_INVALID_VERSION
The CRT/CRL/CSR version element is invalid.
Definition: x509.h:51
Certificate revocation list structure.
Definition: x509_crl.h:69
int asn1_get_bitstring(unsigned char **p, const unsigned char *end, asn1_bitstring *bs)
Retrieve a bitstring ASN.1 tag and its value.
pk_context pk
Container for the public key context.
Definition: x509_crt.h:71
#define POLARSSL_ERR_THREADING_MUTEX_ERROR
Locking / unlocking / free failed with error code.
Definition: threading.h:40
int min
Definition: x509.h:175
struct _asn1_named_data * next
The next entry in the sequence.
Definition: asn1.h:152
int size
Output length of the digest function.
Definition: md.h:81
x509_buf issuer_id
Optional X.509 v2/v3 issuer unique identifier.
Definition: x509_crt.h:73
#define POLARSSL_ERR_X509_INVALID_EXTENSIONS
The extension tag or value is invalid.
Definition: x509.h:57
#define ASN1_OCTET_STRING
Definition: asn1.h:74
int x509_crt_parse_path(x509_crt *chain, const char *path)
Load one or more certificate files from a path and add them to the chained list.
x509_buf v3_ext
Optional X.509 v3 extensions.
Definition: x509_crt.h:75
#define POLARSSL_ERR_X509_BAD_INPUT_DATA
Input invalid.
Definition: x509.h:63
x509_buf subject_id
Optional X.509 v2/v3 subject unique identifier.
Definition: x509_crt.h:74
#define BADCERT_CN_MISMATCH
The certificate Common Name (CN) does not match with the expected CN.
Definition: x509.h:74
int version
The X.509 version.
Definition: x509_crt.h:58
#define POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT
No PEM header or footer found.
Definition: pem.h:38
pk_type_t sig_pk
&lt; Internal representation of the Public Key algorithm of the signature algorithm, e...
Definition: x509_crt.h:91
x509_time revocation_date
Definition: x509_crl.h:57
x509_buf issuer_raw
The raw issuer data (DER).
Definition: x509_crl.h:77
int x509_crt_info(char *buf, size_t size, const char *prefix, const x509_crt *crt)
Returns an informational string about the certificate.
#define POLARSSL_ERR_X509_MALLOC_FAILED
Allocation of memory failed.
Definition: x509.h:64
#define POLARSSL_ERR_PEM_BAD_INPUT_DATA
Bad input parameters to function.
Definition: pem.h:46
unsigned char key_usage
Optional key usage extension value: See the values below.
Definition: x509_crt.h:82
x509_buf subject_raw
The raw subject data (DER).
Definition: x509_crt.h:63
Message digest information.
Definition: md.h:73
#define POLARSSL_ERR_ASN1_UNEXPECTED_TAG
ASN1 tag was of an unexpected value.
Definition: asn1.h:51
int x509_serial_gets(char *buf, size_t size, const x509_buf *serial)
Store the certificate serial in printable form into buf; no more than size characters will be written...
#define POLARSSL_ERR_X509_SIG_MISMATCH
Signature algorithms do not match.
Definition: x509.h:60
struct _asn1_sequence * next
The next entry in the sequence.
Definition: asn1.h:141
int x509_crt_parse_file(x509_crt *chain, const char *path)
Load one or more certificates and add them to the chained list.
x509_buf sig
Signature: hash of the tbs part signed with the private key.
Definition: x509_crt.h:89
#define EXT_SUBJECT_ALT_NAME
Definition: x509.h:117