PolarSSL v1.2.12
x509parse.c
Go to the documentation of this file.
1 /*
2  * X.509 certificate and private key decoding
3  *
4  * Copyright (C) 2006-2011, 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_PARSE_C)
40 
41 #include "polarssl/x509.h"
42 #include "polarssl/asn1.h"
43 #include "polarssl/pem.h"
44 #include "polarssl/des.h"
45 #if defined(POLARSSL_MD2_C)
46 #include "polarssl/md2.h"
47 #endif
48 #if defined(POLARSSL_MD4_C)
49 #include "polarssl/md4.h"
50 #endif
51 #if defined(POLARSSL_MD5_C)
52 #include "polarssl/md5.h"
53 #endif
54 #if defined(POLARSSL_SHA1_C)
55 #include "polarssl/sha1.h"
56 #endif
57 #if defined(POLARSSL_SHA2_C)
58 #include "polarssl/sha2.h"
59 #endif
60 #if defined(POLARSSL_SHA4_C)
61 #include "polarssl/sha4.h"
62 #endif
63 #include "polarssl/dhm.h"
64 #if defined(POLARSSL_PKCS5_C)
65 #include "polarssl/pkcs5.h"
66 #endif
67 #if defined(POLARSSL_PKCS12_C)
68 #include "polarssl/pkcs12.h"
69 #endif
70 
71 #include <string.h>
72 #include <stdlib.h>
73 #if defined(_WIN32)
74 #include <windows.h>
75 #else
76 #include <time.h>
77 #endif
78 
79 #if defined(POLARSSL_FS_IO)
80 #include <stdio.h>
81 #if !defined(_WIN32)
82 #include <sys/types.h>
83 #include <sys/stat.h>
84 #include <dirent.h>
85 #endif
86 #endif
87 
88 /* Compare a given OID string with an OID x509_buf * */
89 #define OID_CMP(oid_str, oid_buf) \
90  ( ( OID_SIZE(oid_str) == (oid_buf)->len ) && \
91  memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) == 0)
92 
93 /*
94  * Version ::= INTEGER { v1(0), v2(1), v3(2) }
95  */
96 static int x509_get_version( unsigned char **p,
97  const unsigned char *end,
98  int *ver )
99 {
100  int ret;
101  size_t len;
102 
103  if( ( ret = asn1_get_tag( p, end, &len,
104  ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0 ) ) != 0 )
105  {
107  {
108  *ver = 0;
109  return( 0 );
110  }
111 
112  return( ret );
113  }
114 
115  end = *p + len;
116 
117  if( ( ret = asn1_get_int( p, end, ver ) ) != 0 )
119 
120  if( *p != end )
123 
124  return( 0 );
125 }
126 
127 /*
128  * Version ::= INTEGER { v1(0), v2(1) }
129  */
130 static int x509_crl_get_version( unsigned char **p,
131  const unsigned char *end,
132  int *ver )
133 {
134  int ret;
135 
136  if( ( ret = asn1_get_int( p, end, ver ) ) != 0 )
137  {
139  {
140  *ver = 0;
141  return( 0 );
142  }
143 
145  }
146 
147  return( 0 );
148 }
149 
150 /*
151  * CertificateSerialNumber ::= INTEGER
152  */
153 static int x509_get_serial( unsigned char **p,
154  const unsigned char *end,
155  x509_buf *serial )
156 {
157  int ret;
158 
159  if( ( end - *p ) < 1 )
162 
163  if( **p != ( ASN1_CONTEXT_SPECIFIC | ASN1_PRIMITIVE | 2 ) &&
164  **p != ASN1_INTEGER )
167 
168  serial->tag = *(*p)++;
169 
170  if( ( ret = asn1_get_len( p, end, &serial->len ) ) != 0 )
172 
173  serial->p = *p;
174  *p += serial->len;
175 
176  return( 0 );
177 }
178 
179 /*
180  * AlgorithmIdentifier ::= SEQUENCE {
181  * algorithm OBJECT IDENTIFIER,
182  * parameters ANY DEFINED BY algorithm OPTIONAL }
183  */
184 static int x509_get_alg( unsigned char **p,
185  const unsigned char *end,
186  x509_buf *alg )
187 {
188  int ret;
189  size_t len;
190 
191  if( ( ret = asn1_get_tag( p, end, &len,
192  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
193  return( POLARSSL_ERR_X509_CERT_INVALID_ALG + ret );
194 
195  end = *p + len;
196  alg->tag = **p;
197 
198  if( ( ret = asn1_get_tag( p, end, &alg->len, ASN1_OID ) ) != 0 )
199  return( POLARSSL_ERR_X509_CERT_INVALID_ALG + ret );
200 
201  alg->p = *p;
202  *p += alg->len;
203 
204  if( *p == end )
205  return( 0 );
206 
207  /*
208  * assume the algorithm parameters must be NULL
209  */
210  if( ( ret = asn1_get_tag( p, end, &len, ASN1_NULL ) ) != 0 )
211  return( POLARSSL_ERR_X509_CERT_INVALID_ALG + ret );
212 
213  if( *p != end )
216 
217  return( 0 );
218 }
219 
220 /*
221  * AttributeTypeAndValue ::= SEQUENCE {
222  * type AttributeType,
223  * value AttributeValue }
224  *
225  * AttributeType ::= OBJECT IDENTIFIER
226  *
227  * AttributeValue ::= ANY DEFINED BY AttributeType
228  */
229 static int x509_get_attr_type_value( unsigned char **p,
230  const unsigned char *end,
231  x509_name *cur )
232 {
233  int ret;
234  size_t len;
235  x509_buf *oid;
236  x509_buf *val;
237 
238  if( ( ret = asn1_get_tag( p, end, &len,
239  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
240  return( POLARSSL_ERR_X509_CERT_INVALID_NAME + ret );
241 
242  oid = &cur->oid;
243  oid->tag = **p;
244 
245  if( ( ret = asn1_get_tag( p, end, &oid->len, ASN1_OID ) ) != 0 )
246  return( POLARSSL_ERR_X509_CERT_INVALID_NAME + ret );
247 
248  oid->p = *p;
249  *p += oid->len;
250 
251  if( ( end - *p ) < 1 )
254 
255  if( **p != ASN1_BMP_STRING && **p != ASN1_UTF8_STRING &&
256  **p != ASN1_T61_STRING && **p != ASN1_PRINTABLE_STRING &&
257  **p != ASN1_IA5_STRING && **p != ASN1_UNIVERSAL_STRING )
260 
261  val = &cur->val;
262  val->tag = *(*p)++;
263 
264  if( ( ret = asn1_get_len( p, end, &val->len ) ) != 0 )
265  return( POLARSSL_ERR_X509_CERT_INVALID_NAME + ret );
266 
267  val->p = *p;
268  *p += val->len;
269 
270  cur->next = NULL;
271 
272  return( 0 );
273 }
274 
275 /*
276  * RelativeDistinguishedName ::=
277  * SET OF AttributeTypeAndValue
278  *
279  * AttributeTypeAndValue ::= SEQUENCE {
280  * type AttributeType,
281  * value AttributeValue }
282  *
283  * AttributeType ::= OBJECT IDENTIFIER
284  *
285  * AttributeValue ::= ANY DEFINED BY AttributeType
286  *
287  * We restrict RelativeDistinguishedName to be a set of 1 element. This is
288  * the most common case, and our x509_name structure currently can't handle
289  * more than that.
290  */
291 static int x509_get_name( unsigned char **p,
292  const unsigned char *end,
293  x509_name *cur )
294 {
295  int ret;
296  size_t set_len;
297  const unsigned char *end_set;
298 
299  /*
300  * parse first SET, restricted to 1 element
301  */
302  if( ( ret = asn1_get_tag( p, end, &set_len,
303  ASN1_CONSTRUCTED | ASN1_SET ) ) != 0 )
304  return( POLARSSL_ERR_X509_CERT_INVALID_NAME + ret );
305 
306  end_set = *p + set_len;
307 
308  if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )
309  return( ret );
310 
311  if( *p != end_set )
313 
314  /*
315  * recurse until end of SEQUENCE is reached
316  */
317  if( *p == end )
318  return( 0 );
319 
320  cur->next = (x509_name *) malloc(
321  sizeof( x509_name ) );
322 
323  if( cur->next == NULL )
325 
326  memset( cur->next, 0, sizeof( x509_name ) );
327 
328  return( x509_get_name( p, end, cur->next ) );
329 }
330 
331 /*
332  * Time ::= CHOICE {
333  * utcTime UTCTime,
334  * generalTime GeneralizedTime }
335  */
336 static int x509_get_time( unsigned char **p,
337  const unsigned char *end,
338  x509_time *time )
339 {
340  int ret;
341  size_t len;
342  char date[64];
343  unsigned char tag;
344 
345  if( ( end - *p ) < 1 )
348 
349  tag = **p;
350 
351  if ( tag == ASN1_UTC_TIME )
352  {
353  (*p)++;
354  ret = asn1_get_len( p, end, &len );
355 
356  if( ret != 0 )
357  return( POLARSSL_ERR_X509_CERT_INVALID_DATE + ret );
358 
359  memset( date, 0, sizeof( date ) );
360  memcpy( date, *p, ( len < sizeof( date ) - 1 ) ?
361  len : sizeof( date ) - 1 );
362 
363  if( sscanf( date, "%2d%2d%2d%2d%2d%2dZ",
364  &time->year, &time->mon, &time->day,
365  &time->hour, &time->min, &time->sec ) < 5 )
367 
368  time->year += 100 * ( time->year < 50 );
369  time->year += 1900;
370 
371  *p += len;
372 
373  return( 0 );
374  }
375  else if ( tag == ASN1_GENERALIZED_TIME )
376  {
377  (*p)++;
378  ret = asn1_get_len( p, end, &len );
379 
380  if( ret != 0 )
381  return( POLARSSL_ERR_X509_CERT_INVALID_DATE + ret );
382 
383  memset( date, 0, sizeof( date ) );
384  memcpy( date, *p, ( len < sizeof( date ) - 1 ) ?
385  len : sizeof( date ) - 1 );
386 
387  if( sscanf( date, "%4d%2d%2d%2d%2d%2dZ",
388  &time->year, &time->mon, &time->day,
389  &time->hour, &time->min, &time->sec ) < 5 )
391 
392  *p += len;
393 
394  return( 0 );
395  }
396  else
398 }
399 
400 
401 /*
402  * Validity ::= SEQUENCE {
403  * notBefore Time,
404  * notAfter Time }
405  */
406 static int x509_get_dates( unsigned char **p,
407  const unsigned char *end,
408  x509_time *from,
409  x509_time *to )
410 {
411  int ret;
412  size_t len;
413 
414  if( ( ret = asn1_get_tag( p, end, &len,
415  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
416  return( POLARSSL_ERR_X509_CERT_INVALID_DATE + ret );
417 
418  end = *p + len;
419 
420  if( ( ret = x509_get_time( p, end, from ) ) != 0 )
421  return( ret );
422 
423  if( ( ret = x509_get_time( p, end, to ) ) != 0 )
424  return( ret );
425 
426  if( *p != end )
429 
430  return( 0 );
431 }
432 
433 /*
434  * SubjectPublicKeyInfo ::= SEQUENCE {
435  * algorithm AlgorithmIdentifier,
436  * subjectPublicKey BIT STRING }
437  */
438 static int x509_get_pubkey( unsigned char **p,
439  const unsigned char *end,
440  x509_buf *pk_alg_oid,
441  mpi *N, mpi *E )
442 {
443  int ret;
444  size_t len;
445  unsigned char *end2;
446 
447  if( ( ret = x509_get_alg( p, end, pk_alg_oid ) ) != 0 )
448  return( ret );
449 
450  /*
451  * only RSA public keys handled at this time
452  */
453  if( pk_alg_oid->len != 9 ||
454  memcmp( pk_alg_oid->p, OID_PKCS1_RSA, 9 ) != 0 )
455  {
457  }
458 
459  if( ( ret = asn1_get_tag( p, end, &len, ASN1_BIT_STRING ) ) != 0 )
461 
462  if( ( end - *p ) < 1 )
465 
466  end2 = *p + len;
467 
468  if( *(*p)++ != 0 )
470 
471  /*
472  * RSAPublicKey ::= SEQUENCE {
473  * modulus INTEGER, -- n
474  * publicExponent INTEGER -- e
475  * }
476  */
477  if( ( ret = asn1_get_tag( p, end2, &len,
478  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
480 
481  if( *p + len != end2 )
484 
485  if( ( ret = asn1_get_mpi( p, end2, N ) ) != 0 ||
486  ( ret = asn1_get_mpi( p, end2, E ) ) != 0 )
488 
489  if( *p != end )
492 
493  return( 0 );
494 }
495 
496 static int x509_get_sig( unsigned char **p,
497  const unsigned char *end,
498  x509_buf *sig )
499 {
500  int ret;
501  size_t len;
502 
503  if( ( end - *p ) < 1 )
506 
507  sig->tag = **p;
508 
509  if( ( ret = asn1_get_tag( p, end, &len, ASN1_BIT_STRING ) ) != 0 )
511 
512 
513  if( --len < 1 || *(*p)++ != 0 )
515 
516  sig->len = len;
517  sig->p = *p;
518 
519  *p += len;
520 
521  return( 0 );
522 }
523 
524 /*
525  * X.509 v2/v3 unique identifier (not parsed)
526  */
527 static int x509_get_uid( unsigned char **p,
528  const unsigned char *end,
529  x509_buf *uid, int n )
530 {
531  int ret;
532 
533  if( *p == end )
534  return( 0 );
535 
536  uid->tag = **p;
537 
538  if( ( ret = asn1_get_tag( p, end, &uid->len,
539  ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | n ) ) != 0 )
540  {
542  return( 0 );
543 
544  return( ret );
545  }
546 
547  uid->p = *p;
548  *p += uid->len;
549 
550  return( 0 );
551 }
552 
553 /*
554  * X.509 Extensions (No parsing of extensions, pointer should
555  * be either manually updated or extensions should be parsed!
556  */
557 static int x509_get_ext( unsigned char **p,
558  const unsigned char *end,
559  x509_buf *ext, int tag )
560 {
561  int ret;
562  size_t len;
563 
564  if( *p == end )
565  return( 0 );
566 
567  ext->tag = **p;
568 
569  if( ( ret = asn1_get_tag( p, end, &ext->len,
570  ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | tag ) ) != 0 )
571  return( ret );
572 
573  ext->p = *p;
574  end = *p + ext->len;
575 
576  /*
577  * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
578  *
579  * Extension ::= SEQUENCE {
580  * extnID OBJECT IDENTIFIER,
581  * critical BOOLEAN DEFAULT FALSE,
582  * extnValue OCTET STRING }
583  */
584  if( ( ret = asn1_get_tag( p, end, &len,
585  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
587 
588  if( end != *p + len )
591 
592  return( 0 );
593 }
594 
595 /*
596  * X.509 CRL v2 extensions (no extensions parsed yet.)
597  */
598 static int x509_get_crl_ext( unsigned char **p,
599  const unsigned char *end,
600  x509_buf *ext )
601 {
602  int ret;
603  size_t len = 0;
604 
605  /* Get explicit tag */
606  if( ( ret = x509_get_ext( p, end, ext, 0) ) != 0 )
607  {
609  return( 0 );
610 
611  return( ret );
612  }
613 
614  while( *p < end )
615  {
616  if( ( ret = asn1_get_tag( p, end, &len,
617  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
619 
620  *p += len;
621  }
622 
623  if( *p != end )
626 
627  return( 0 );
628 }
629 
630 /*
631  * X.509 CRL v2 entry extensions (no extensions parsed yet.)
632  */
633 static int x509_get_crl_entry_ext( unsigned char **p,
634  const unsigned char *end,
635  x509_buf *ext )
636 {
637  int ret;
638  size_t len = 0;
639 
640  /* OPTIONAL */
641  if (end <= *p)
642  return( 0 );
643 
644  ext->tag = **p;
645  ext->p = *p;
646 
647  /*
648  * Get CRL-entry extension sequence header
649  * crlEntryExtensions Extensions OPTIONAL -- if present, MUST be v2
650  */
651  if( ( ret = asn1_get_tag( p, end, &ext->len,
652  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
653  {
655  {
656  ext->p = NULL;
657  return( 0 );
658  }
660  }
661 
662  end = *p + ext->len;
663 
664  if( end != *p + ext->len )
667 
668  while( *p < end )
669  {
670  if( ( ret = asn1_get_tag( p, end, &len,
671  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
673 
674  *p += len;
675  }
676 
677  if( *p != end )
680 
681  return( 0 );
682 }
683 
684 static int x509_get_basic_constraints( unsigned char **p,
685  const unsigned char *end,
686  int *ca_istrue,
687  int *max_pathlen )
688 {
689  int ret;
690  size_t len;
691 
692  /*
693  * BasicConstraints ::= SEQUENCE {
694  * cA BOOLEAN DEFAULT FALSE,
695  * pathLenConstraint INTEGER (0..MAX) OPTIONAL }
696  */
697  *ca_istrue = 0; /* DEFAULT FALSE */
698  *max_pathlen = 0; /* endless */
699 
700  if( ( ret = asn1_get_tag( p, end, &len,
701  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
703 
704  if( *p == end )
705  return 0;
706 
707  if( ( ret = asn1_get_bool( p, end, ca_istrue ) ) != 0 )
708  {
710  ret = asn1_get_int( p, end, ca_istrue );
711 
712  if( ret != 0 )
714 
715  if( *ca_istrue != 0 )
716  *ca_istrue = 1;
717  }
718 
719  if( *p == end )
720  return 0;
721 
722  if( ( ret = asn1_get_int( p, end, max_pathlen ) ) != 0 )
724 
725  if( *p != end )
728 
729  (*max_pathlen)++;
730 
731  return 0;
732 }
733 
734 static int x509_get_ns_cert_type( unsigned char **p,
735  const unsigned char *end,
736  unsigned char *ns_cert_type)
737 {
738  int ret;
739  x509_bitstring bs = { 0, 0, NULL };
740 
741  if( ( ret = asn1_get_bitstring( p, end, &bs ) ) != 0 )
743 
744  if( bs.len != 1 )
747 
748  /* Get actual bitstring */
749  *ns_cert_type = *bs.p;
750  return 0;
751 }
752 
753 static int x509_get_key_usage( unsigned char **p,
754  const unsigned char *end,
755  unsigned char *key_usage)
756 {
757  int ret;
758  x509_bitstring bs = { 0, 0, NULL };
759 
760  if( ( ret = asn1_get_bitstring( p, end, &bs ) ) != 0 )
762 
763  if( bs.len < 1 )
766 
767  /* Get actual bitstring */
768  *key_usage = *bs.p;
769  return 0;
770 }
771 
772 /*
773  * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
774  *
775  * KeyPurposeId ::= OBJECT IDENTIFIER
776  */
777 static int x509_get_ext_key_usage( unsigned char **p,
778  const unsigned char *end,
779  x509_sequence *ext_key_usage)
780 {
781  int ret;
782 
783  if( ( ret = asn1_get_sequence_of( p, end, ext_key_usage, ASN1_OID ) ) != 0 )
785 
786  /* Sequence length must be >= 1 */
787  if( ext_key_usage->buf.p == NULL )
790 
791  return 0;
792 }
793 
794 /*
795  * SubjectAltName ::= GeneralNames
796  *
797  * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
798  *
799  * GeneralName ::= CHOICE {
800  * otherName [0] OtherName,
801  * rfc822Name [1] IA5String,
802  * dNSName [2] IA5String,
803  * x400Address [3] ORAddress,
804  * directoryName [4] Name,
805  * ediPartyName [5] EDIPartyName,
806  * uniformResourceIdentifier [6] IA5String,
807  * iPAddress [7] OCTET STRING,
808  * registeredID [8] OBJECT IDENTIFIER }
809  *
810  * OtherName ::= SEQUENCE {
811  * type-id OBJECT IDENTIFIER,
812  * value [0] EXPLICIT ANY DEFINED BY type-id }
813  *
814  * EDIPartyName ::= SEQUENCE {
815  * nameAssigner [0] DirectoryString OPTIONAL,
816  * partyName [1] DirectoryString }
817  *
818  * NOTE: PolarSSL only parses and uses dNSName at this point.
819  */
820 static int x509_get_subject_alt_name( unsigned char **p,
821  const unsigned char *end,
822  x509_sequence *subject_alt_name )
823 {
824  int ret;
825  size_t len, tag_len;
826  asn1_buf *buf;
827  unsigned char tag;
828  asn1_sequence *cur = subject_alt_name;
829 
830  /* Get main sequence tag */
831  if( ( ret = asn1_get_tag( p, end, &len,
832  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
834 
835  if( *p + len != end )
838 
839  while( *p < end )
840  {
841  if( ( end - *p ) < 1 )
844 
845  tag = **p;
846  (*p)++;
847  if( ( ret = asn1_get_len( p, end, &tag_len ) ) != 0 )
849 
850  if( ( tag & ASN1_CONTEXT_SPECIFIC ) != ASN1_CONTEXT_SPECIFIC )
853 
854  if( tag != ( ASN1_CONTEXT_SPECIFIC | 2 ) )
855  {
856  *p += tag_len;
857  continue;
858  }
859 
860  buf = &(cur->buf);
861  buf->tag = tag;
862  buf->p = *p;
863  buf->len = tag_len;
864  *p += buf->len;
865 
866  /* Allocate and assign next pointer */
867  if (*p < end)
868  {
869  cur->next = (asn1_sequence *) malloc(
870  sizeof( asn1_sequence ) );
871 
872  if( cur->next == NULL )
875 
876  memset( cur->next, 0, sizeof( asn1_sequence ) );
877  cur = cur->next;
878  }
879  }
880 
881  /* Set final sequence entry's next pointer to NULL */
882  cur->next = NULL;
883 
884  if( *p != end )
887 
888  return( 0 );
889 }
890 
891 /*
892  * X.509 v3 extensions
893  *
894  * TODO: Perform all of the basic constraints tests required by the RFC
895  * TODO: Set values for undetected extensions to a sane default?
896  *
897  */
898 static int x509_get_crt_ext( unsigned char **p,
899  const unsigned char *end,
900  x509_cert *crt )
901 {
902  int ret;
903  size_t len;
904  unsigned char *end_ext_data, *end_ext_octet;
905 
906  if( ( ret = x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
907  {
909  return( 0 );
910 
911  return( ret );
912  }
913 
914  while( *p < end )
915  {
916  /*
917  * Extension ::= SEQUENCE {
918  * extnID OBJECT IDENTIFIER,
919  * critical BOOLEAN DEFAULT FALSE,
920  * extnValue OCTET STRING }
921  */
922  x509_buf extn_oid = {0, 0, NULL};
923  int is_critical = 0; /* DEFAULT FALSE */
924 
925  if( ( ret = asn1_get_tag( p, end, &len,
926  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
928 
929  end_ext_data = *p + len;
930 
931  /* Get extension ID */
932  extn_oid.tag = **p;
933 
934  if( ( ret = asn1_get_tag( p, end, &extn_oid.len, ASN1_OID ) ) != 0 )
936 
937  extn_oid.p = *p;
938  *p += extn_oid.len;
939 
940  if( ( end - *p ) < 1 )
943 
944  /* Get optional critical */
945  if( ( ret = asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
948 
949  /* Data should be octet string type */
950  if( ( ret = asn1_get_tag( p, end_ext_data, &len,
951  ASN1_OCTET_STRING ) ) != 0 )
953 
954  end_ext_octet = *p + len;
955 
956  if( end_ext_octet != end_ext_data )
959 
960  /*
961  * Detect supported extensions
962  */
963  if( ( OID_SIZE( OID_BASIC_CONSTRAINTS ) == extn_oid.len ) &&
964  memcmp( extn_oid.p, OID_BASIC_CONSTRAINTS, extn_oid.len ) == 0 )
965  {
966  /* Parse basic constraints */
967  if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
968  &crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
969  return ( ret );
971  }
972  else if( ( OID_SIZE( OID_NS_CERT_TYPE ) == extn_oid.len ) &&
973  memcmp( extn_oid.p, OID_NS_CERT_TYPE, extn_oid.len ) == 0 )
974  {
975  /* Parse netscape certificate type */
976  if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
977  &crt->ns_cert_type ) ) != 0 )
978  return ( ret );
979  crt->ext_types |= EXT_NS_CERT_TYPE;
980  }
981  else if( ( OID_SIZE( OID_KEY_USAGE ) == extn_oid.len ) &&
982  memcmp( extn_oid.p, OID_KEY_USAGE, extn_oid.len ) == 0 )
983  {
984  /* Parse key usage */
985  if( ( ret = x509_get_key_usage( p, end_ext_octet,
986  &crt->key_usage ) ) != 0 )
987  return ( ret );
988  crt->ext_types |= EXT_KEY_USAGE;
989  }
990  else if( ( OID_SIZE( OID_EXTENDED_KEY_USAGE ) == extn_oid.len ) &&
991  memcmp( extn_oid.p, OID_EXTENDED_KEY_USAGE, extn_oid.len ) == 0 )
992  {
993  /* Parse extended key usage */
994  if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
995  &crt->ext_key_usage ) ) != 0 )
996  return ( ret );
998  }
999  else if( ( OID_SIZE( OID_SUBJECT_ALT_NAME ) == extn_oid.len ) &&
1000  memcmp( extn_oid.p, OID_SUBJECT_ALT_NAME, extn_oid.len ) == 0 )
1001  {
1002  /* Parse extended key usage */
1003  if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
1004  &crt->subject_alt_names ) ) != 0 )
1005  return ( ret );
1007  }
1008  else
1009  {
1010  /* No parser found, skip extension */
1011  *p = end_ext_octet;
1012 
1013 #if !defined(POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
1014  if( is_critical )
1015  {
1016  /* Data is marked as critical: fail */
1019  }
1020 #endif
1021  }
1022  }
1023 
1024  if( *p != end )
1027 
1028  return( 0 );
1029 }
1030 
1031 /*
1032  * X.509 CRL Entries
1033  */
1034 static int x509_get_entries( unsigned char **p,
1035  const unsigned char *end,
1037 {
1038  int ret;
1039  size_t entry_len;
1040  x509_crl_entry *cur_entry = entry;
1041 
1042  if( *p == end )
1043  return( 0 );
1044 
1045  if( ( ret = asn1_get_tag( p, end, &entry_len,
1046  ASN1_SEQUENCE | ASN1_CONSTRUCTED ) ) != 0 )
1047  {
1049  return( 0 );
1050 
1051  return( ret );
1052  }
1053 
1054  end = *p + entry_len;
1055 
1056  while( *p < end )
1057  {
1058  size_t len2;
1059  const unsigned char *end2;
1060 
1061  if( ( ret = asn1_get_tag( p, end, &len2,
1062  ASN1_SEQUENCE | ASN1_CONSTRUCTED ) ) != 0 )
1063  {
1064  return( ret );
1065  }
1066 
1067  cur_entry->raw.tag = **p;
1068  cur_entry->raw.p = *p;
1069  cur_entry->raw.len = len2;
1070  end2 = *p + len2;
1071 
1072  if( ( ret = x509_get_serial( p, end2, &cur_entry->serial ) ) != 0 )
1073  return( ret );
1074 
1075  if( ( ret = x509_get_time( p, end2, &cur_entry->revocation_date ) ) != 0 )
1076  return( ret );
1077 
1078  if( ( ret = x509_get_crl_entry_ext( p, end2, &cur_entry->entry_ext ) ) != 0 )
1079  return( ret );
1080 
1081  if ( *p < end )
1082  {
1083  cur_entry->next = malloc( sizeof( x509_crl_entry ) );
1084 
1085  if( cur_entry->next == NULL )
1087 
1088  cur_entry = cur_entry->next;
1089  memset( cur_entry, 0, sizeof( x509_crl_entry ) );
1090  }
1091  }
1092 
1093  return( 0 );
1094 }
1095 
1096 static int x509_get_sig_alg( const x509_buf *sig_oid, int *sig_alg )
1097 {
1098  if( sig_oid->len == 9 &&
1099  memcmp( sig_oid->p, OID_PKCS1, 8 ) == 0 )
1100  {
1101  if( sig_oid->p[8] >= 2 && sig_oid->p[8] <= 5 )
1102  {
1103  *sig_alg = sig_oid->p[8];
1104  return( 0 );
1105  }
1106 
1107  if ( sig_oid->p[8] >= 11 && sig_oid->p[8] <= 14 )
1108  {
1109  *sig_alg = sig_oid->p[8];
1110  return( 0 );
1111  }
1112 
1114  }
1115  if( sig_oid->len == 5 &&
1116  memcmp( sig_oid->p, OID_RSA_SHA_OBS, 5 ) == 0 )
1117  {
1118  *sig_alg = SIG_RSA_SHA1;
1119  return( 0 );
1120  }
1121 
1123 }
1124 
1125 /*
1126  * Parse and fill a single X.509 certificate in DER format
1127  */
1128 static int x509parse_crt_der_core( x509_cert *crt, const unsigned char *buf,
1129  size_t buflen )
1130 {
1131  int ret;
1132  size_t len;
1133  unsigned char *p, *end, *crt_end;
1134 
1135  /*
1136  * Check for valid input
1137  */
1138  if( crt == NULL || buf == NULL )
1140 
1141  p = (unsigned char *) malloc( len = buflen );
1142 
1143  if( p == NULL )
1145 
1146  memcpy( p, buf, buflen );
1147 
1148  crt->raw.p = p;
1149  crt->raw.len = len;
1150  end = p + len;
1151 
1152  /*
1153  * Certificate ::= SEQUENCE {
1154  * tbsCertificate TBSCertificate,
1155  * signatureAlgorithm AlgorithmIdentifier,
1156  * signatureValue BIT STRING }
1157  */
1158  if( ( ret = asn1_get_tag( &p, end, &len,
1159  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1160  {
1161  x509_free( crt );
1163  }
1164 
1165  if( len > (size_t) ( end - p ) )
1166  {
1167  x509_free( crt );
1170  }
1171  crt_end = p + len;
1172 
1173  /*
1174  * TBSCertificate ::= SEQUENCE {
1175  */
1176  crt->tbs.p = p;
1177 
1178  if( ( ret = asn1_get_tag( &p, end, &len,
1179  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1180  {
1181  x509_free( crt );
1182  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1183  }
1184 
1185  end = p + len;
1186  crt->tbs.len = end - crt->tbs.p;
1187 
1188  /*
1189  * Version ::= INTEGER { v1(0), v2(1), v3(2) }
1190  *
1191  * CertificateSerialNumber ::= INTEGER
1192  *
1193  * signature AlgorithmIdentifier
1194  */
1195  if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
1196  ( ret = x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
1197  ( ret = x509_get_alg( &p, end, &crt->sig_oid1 ) ) != 0 )
1198  {
1199  x509_free( crt );
1200  return( ret );
1201  }
1202 
1203  crt->version++;
1204 
1205  if( crt->version > 3 )
1206  {
1207  x509_free( crt );
1209  }
1210 
1211  if( ( ret = x509_get_sig_alg( &crt->sig_oid1, &crt->sig_alg ) ) != 0 )
1212  {
1213  x509_free( crt );
1214  return( ret );
1215  }
1216 
1217  /*
1218  * issuer Name
1219  */
1220  crt->issuer_raw.p = p;
1221 
1222  if( ( ret = asn1_get_tag( &p, end, &len,
1223  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1224  {
1225  x509_free( crt );
1226  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1227  }
1228 
1229  if( ( ret = x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
1230  {
1231  x509_free( crt );
1232  return( ret );
1233  }
1234 
1235  crt->issuer_raw.len = p - crt->issuer_raw.p;
1236 
1237  /*
1238  * Validity ::= SEQUENCE {
1239  * notBefore Time,
1240  * notAfter Time }
1241  *
1242  */
1243  if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
1244  &crt->valid_to ) ) != 0 )
1245  {
1246  x509_free( crt );
1247  return( ret );
1248  }
1249 
1250  /*
1251  * subject Name
1252  */
1253  crt->subject_raw.p = p;
1254 
1255  if( ( ret = asn1_get_tag( &p, end, &len,
1256  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1257  {
1258  x509_free( crt );
1259  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1260  }
1261 
1262  if( len && ( ret = x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
1263  {
1264  x509_free( crt );
1265  return( ret );
1266  }
1267 
1268  crt->subject_raw.len = p - crt->subject_raw.p;
1269 
1270  /*
1271  * SubjectPublicKeyInfo ::= SEQUENCE
1272  * algorithm AlgorithmIdentifier,
1273  * subjectPublicKey BIT STRING }
1274  */
1275  if( ( ret = asn1_get_tag( &p, end, &len,
1276  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1277  {
1278  x509_free( crt );
1279  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1280  }
1281 
1282  if( ( ret = x509_get_pubkey( &p, p + len, &crt->pk_oid,
1283  &crt->rsa.N, &crt->rsa.E ) ) != 0 )
1284  {
1285  x509_free( crt );
1286  return( ret );
1287  }
1288 
1289  if( ( ret = rsa_check_pubkey( &crt->rsa ) ) != 0 )
1290  {
1291  x509_free( crt );
1292  return( ret );
1293  }
1294 
1295  crt->rsa.len = mpi_size( &crt->rsa.N );
1296 
1297  /*
1298  * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
1299  * -- If present, version shall be v2 or v3
1300  * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
1301  * -- If present, version shall be v2 or v3
1302  * extensions [3] EXPLICIT Extensions OPTIONAL
1303  * -- If present, version shall be v3
1304  */
1305  if( crt->version == 2 || crt->version == 3 )
1306  {
1307  ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
1308  if( ret != 0 )
1309  {
1310  x509_free( crt );
1311  return( ret );
1312  }
1313  }
1314 
1315  if( crt->version == 2 || crt->version == 3 )
1316  {
1317  ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
1318  if( ret != 0 )
1319  {
1320  x509_free( crt );
1321  return( ret );
1322  }
1323  }
1324 
1325  if( crt->version == 3 )
1326  {
1327  ret = x509_get_crt_ext( &p, end, crt);
1328  if( ret != 0 )
1329  {
1330  x509_free( crt );
1331  return( ret );
1332  }
1333  }
1334 
1335  if( p != end )
1336  {
1337  x509_free( crt );
1340  }
1341 
1342  end = crt_end;
1343 
1344  /*
1345  * signatureAlgorithm AlgorithmIdentifier,
1346  * signatureValue BIT STRING
1347  */
1348  if( ( ret = x509_get_alg( &p, end, &crt->sig_oid2 ) ) != 0 )
1349  {
1350  x509_free( crt );
1351  return( ret );
1352  }
1353 
1354  if( crt->sig_oid1.len != crt->sig_oid2.len ||
1355  memcmp( crt->sig_oid1.p, crt->sig_oid2.p, crt->sig_oid1.len ) != 0 )
1356  {
1357  x509_free( crt );
1359  }
1360 
1361  if( ( ret = x509_get_sig( &p, end, &crt->sig ) ) != 0 )
1362  {
1363  x509_free( crt );
1364  return( ret );
1365  }
1366 
1367  if( p != end )
1368  {
1369  x509_free( crt );
1372  }
1373 
1374  return( 0 );
1375 }
1376 
1377 /*
1378  * Parse one X.509 certificate in DER format from a buffer and add them to a
1379  * chained list
1380  */
1381 int x509parse_crt_der( x509_cert *chain, const unsigned char *buf, size_t buflen )
1382 {
1383  int ret;
1384  x509_cert *crt = chain, *prev = NULL;
1385 
1386  /*
1387  * Check for valid input
1388  */
1389  if( crt == NULL || buf == NULL )
1391 
1392  while( crt->version != 0 && crt->next != NULL )
1393  {
1394  prev = crt;
1395  crt = crt->next;
1396  }
1397 
1398  /*
1399  * Add new certificate on the end of the chain if needed.
1400  */
1401  if ( crt->version != 0 && crt->next == NULL)
1402  {
1403  crt->next = (x509_cert *) malloc( sizeof( x509_cert ) );
1404 
1405  if( crt->next == NULL )
1407 
1408  prev = crt;
1409  crt = crt->next;
1410  memset( crt, 0, sizeof( x509_cert ) );
1411  }
1412 
1413  if( ( ret = x509parse_crt_der_core( crt, buf, buflen ) ) != 0 )
1414  {
1415  if( prev )
1416  prev->next = NULL;
1417 
1418  if( crt != chain )
1419  free( crt );
1420 
1421  return( ret );
1422  }
1423 
1424  return( 0 );
1425 }
1426 
1427 /*
1428  * Parse one or more PEM certificates from a buffer and add them to the chained list
1429  */
1430 int x509parse_crt( x509_cert *chain, const unsigned char *buf, size_t buflen )
1431 {
1432  int ret, success = 0, first_error = 0, total_failed = 0;
1433  int buf_format = X509_FORMAT_DER;
1434 
1435  /*
1436  * Check for valid input
1437  */
1438  if( chain == NULL || buf == NULL )
1440 
1441  /*
1442  * Determine buffer content. Buffer contains either one DER certificate or
1443  * one or more PEM certificates.
1444  */
1445 #if defined(POLARSSL_PEM_C)
1446  if( strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
1447  buf_format = X509_FORMAT_PEM;
1448 #endif
1449 
1450  if( buf_format == X509_FORMAT_DER )
1451  return x509parse_crt_der( chain, buf, buflen );
1452 
1453 #if defined(POLARSSL_PEM_C)
1454  if( buf_format == X509_FORMAT_PEM )
1455  {
1456  pem_context pem;
1457 
1458  while( buflen > 0 )
1459  {
1460  size_t use_len;
1461  pem_init( &pem );
1462 
1463  ret = pem_read_buffer( &pem,
1464  (char *) "-----BEGIN CERTIFICATE-----",
1465  (char *) "-----END CERTIFICATE-----",
1466  buf, NULL, 0, &use_len );
1467 
1468  if( ret == 0 )
1469  {
1470  /*
1471  * Was PEM encoded
1472  */
1473  buflen -= use_len;
1474  buf += use_len;
1475  }
1476  else if( ret == POLARSSL_ERR_PEM_BAD_INPUT_DATA )
1477  {
1478  return( ret );
1479  }
1481  {
1482  pem_free( &pem );
1483 
1484  /*
1485  * PEM header and footer were found
1486  */
1487  buflen -= use_len;
1488  buf += use_len;
1489 
1490  if( first_error == 0 )
1491  first_error = ret;
1492 
1493  total_failed++;
1494  continue;
1495  }
1496  else
1497  break;
1498 
1499  ret = x509parse_crt_der( chain, pem.buf, pem.buflen );
1500 
1501  pem_free( &pem );
1502 
1503  if( ret != 0 )
1504  {
1505  /*
1506  * Quit parsing on a memory error
1507  */
1508  if( ret == POLARSSL_ERR_X509_MALLOC_FAILED )
1509  return( ret );
1510 
1511  if( first_error == 0 )
1512  first_error = ret;
1513 
1514  total_failed++;
1515  continue;
1516  }
1517 
1518  success = 1;
1519  }
1520  }
1521 #endif
1522 
1523  if( success )
1524  return( total_failed );
1525  else if( first_error )
1526  return( first_error );
1527  else
1529 }
1530 
1531 /*
1532  * Parse one or more CRLs and add them to the chained list
1533  */
1534 int x509parse_crl( x509_crl *chain, const unsigned char *buf, size_t buflen )
1535 {
1536  int ret;
1537  size_t len;
1538  unsigned char *p, *end;
1539  x509_crl *crl;
1540 #if defined(POLARSSL_PEM_C)
1541  size_t use_len;
1542  pem_context pem;
1543 #endif
1544 
1545  crl = chain;
1546 
1547  /*
1548  * Check for valid input
1549  */
1550  if( crl == NULL || buf == NULL )
1552 
1553  while( crl->version != 0 && crl->next != NULL )
1554  crl = crl->next;
1555 
1556  /*
1557  * Add new CRL on the end of the chain if needed.
1558  */
1559  if ( crl->version != 0 && crl->next == NULL)
1560  {
1561  crl->next = (x509_crl *) malloc( sizeof( x509_crl ) );
1562 
1563  if( crl->next == NULL )
1564  {
1565  x509_crl_free( crl );
1567  }
1568 
1569  crl = crl->next;
1570  memset( crl, 0, sizeof( x509_crl ) );
1571  }
1572 
1573 #if defined(POLARSSL_PEM_C)
1574  pem_init( &pem );
1575  ret = pem_read_buffer( &pem,
1576  (char *) "-----BEGIN X509 CRL-----",
1577  (char *) "-----END X509 CRL-----",
1578  buf, NULL, 0, &use_len );
1579 
1580  if( ret == 0 )
1581  {
1582  /*
1583  * Was PEM encoded
1584  */
1585  buflen -= use_len;
1586  buf += use_len;
1587 
1588  /*
1589  * Steal PEM buffer
1590  */
1591  p = pem.buf;
1592  pem.buf = NULL;
1593  len = pem.buflen;
1594  pem_free( &pem );
1595  }
1597  {
1598  pem_free( &pem );
1599  return( ret );
1600  }
1601  else
1602  {
1603  /*
1604  * nope, copy the raw DER data
1605  */
1606  p = (unsigned char *) malloc( len = buflen );
1607 
1608  if( p == NULL )
1610 
1611  memcpy( p, buf, buflen );
1612 
1613  buflen = 0;
1614  }
1615 #else
1616  p = (unsigned char *) malloc( len = buflen );
1617 
1618  if( p == NULL )
1620 
1621  memcpy( p, buf, buflen );
1622 
1623  buflen = 0;
1624 #endif
1625 
1626  crl->raw.p = p;
1627  crl->raw.len = len;
1628  end = p + len;
1629 
1630  /*
1631  * CertificateList ::= SEQUENCE {
1632  * tbsCertList TBSCertList,
1633  * signatureAlgorithm AlgorithmIdentifier,
1634  * signatureValue BIT STRING }
1635  */
1636  if( ( ret = asn1_get_tag( &p, end, &len,
1637  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1638  {
1639  x509_crl_free( crl );
1641  }
1642 
1643  if( len != (size_t) ( end - p ) )
1644  {
1645  x509_crl_free( crl );
1648  }
1649 
1650  /*
1651  * TBSCertList ::= SEQUENCE {
1652  */
1653  crl->tbs.p = p;
1654 
1655  if( ( ret = asn1_get_tag( &p, end, &len,
1656  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1657  {
1658  x509_crl_free( crl );
1659  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1660  }
1661 
1662  end = p + len;
1663  crl->tbs.len = end - crl->tbs.p;
1664 
1665  /*
1666  * Version ::= INTEGER OPTIONAL { v1(0), v2(1) }
1667  * -- if present, MUST be v2
1668  *
1669  * signature AlgorithmIdentifier
1670  */
1671  if( ( ret = x509_crl_get_version( &p, end, &crl->version ) ) != 0 ||
1672  ( ret = x509_get_alg( &p, end, &crl->sig_oid1 ) ) != 0 )
1673  {
1674  x509_crl_free( crl );
1675  return( ret );
1676  }
1677 
1678  crl->version++;
1679 
1680  if( crl->version > 2 )
1681  {
1682  x509_crl_free( crl );
1684  }
1685 
1686  if( ( ret = x509_get_sig_alg( &crl->sig_oid1, &crl->sig_alg ) ) != 0 )
1687  {
1688  x509_crl_free( crl );
1690  }
1691 
1692  /*
1693  * issuer Name
1694  */
1695  crl->issuer_raw.p = p;
1696 
1697  if( ( ret = asn1_get_tag( &p, end, &len,
1698  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
1699  {
1700  x509_crl_free( crl );
1701  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
1702  }
1703 
1704  if( ( ret = x509_get_name( &p, p + len, &crl->issuer ) ) != 0 )
1705  {
1706  x509_crl_free( crl );
1707  return( ret );
1708  }
1709 
1710  crl->issuer_raw.len = p - crl->issuer_raw.p;
1711 
1712  /*
1713  * thisUpdate Time
1714  * nextUpdate Time OPTIONAL
1715  */
1716  if( ( ret = x509_get_time( &p, end, &crl->this_update ) ) != 0 )
1717  {
1718  x509_crl_free( crl );
1719  return( ret );
1720  }
1721 
1722  if( ( ret = x509_get_time( &p, end, &crl->next_update ) ) != 0 )
1723  {
1724  if ( ret != ( POLARSSL_ERR_X509_CERT_INVALID_DATE +
1728  {
1729  x509_crl_free( crl );
1730  return( ret );
1731  }
1732  }
1733 
1734  /*
1735  * revokedCertificates SEQUENCE OF SEQUENCE {
1736  * userCertificate CertificateSerialNumber,
1737  * revocationDate Time,
1738  * crlEntryExtensions Extensions OPTIONAL
1739  * -- if present, MUST be v2
1740  * } OPTIONAL
1741  */
1742  if( ( ret = x509_get_entries( &p, end, &crl->entry ) ) != 0 )
1743  {
1744  x509_crl_free( crl );
1745  return( ret );
1746  }
1747 
1748  /*
1749  * crlExtensions EXPLICIT Extensions OPTIONAL
1750  * -- if present, MUST be v2
1751  */
1752  if( crl->version == 2 )
1753  {
1754  ret = x509_get_crl_ext( &p, end, &crl->crl_ext );
1755 
1756  if( ret != 0 )
1757  {
1758  x509_crl_free( crl );
1759  return( ret );
1760  }
1761  }
1762 
1763  if( p != end )
1764  {
1765  x509_crl_free( crl );
1768  }
1769 
1770  end = crl->raw.p + crl->raw.len;
1771 
1772  /*
1773  * signatureAlgorithm AlgorithmIdentifier,
1774  * signatureValue BIT STRING
1775  */
1776  if( ( ret = x509_get_alg( &p, end, &crl->sig_oid2 ) ) != 0 )
1777  {
1778  x509_crl_free( crl );
1779  return( ret );
1780  }
1781 
1782  if( crl->sig_oid1.len != crl->sig_oid2.len ||
1783  memcmp( crl->sig_oid1.p, crl->sig_oid2.p, crl->sig_oid1.len ) != 0 )
1784  {
1785  x509_crl_free( crl );
1787  }
1788 
1789  if( ( ret = x509_get_sig( &p, end, &crl->sig ) ) != 0 )
1790  {
1791  x509_crl_free( crl );
1792  return( ret );
1793  }
1794 
1795  if( p != end )
1796  {
1797  x509_crl_free( crl );
1800  }
1801 
1802  if( buflen > 0 )
1803  {
1804  crl->next = (x509_crl *) malloc( sizeof( x509_crl ) );
1805 
1806  if( crl->next == NULL )
1807  {
1808  x509_crl_free( crl );
1810  }
1811 
1812  crl = crl->next;
1813  memset( crl, 0, sizeof( x509_crl ) );
1814 
1815  return( x509parse_crl( crl, buf, buflen ) );
1816  }
1817 
1818  return( 0 );
1819 }
1820 
1821 #if defined(POLARSSL_FS_IO)
1822 /*
1823  * Load all data from a file into a given buffer.
1824  */
1825 static int load_file( const char *path, unsigned char **buf, size_t *n )
1826 {
1827  FILE *f;
1828  long size;
1829 
1830  if( ( f = fopen( path, "rb" ) ) == NULL )
1832 
1833  fseek( f, 0, SEEK_END );
1834  if( ( size = ftell( f ) ) == -1 )
1835  {
1836  fclose( f );
1838  }
1839  fseek( f, 0, SEEK_SET );
1840 
1841  *n = (size_t) size;
1842 
1843  if( *n + 1 == 0 ||
1844  ( *buf = (unsigned char *) malloc( *n + 1 ) ) == NULL )
1845  {
1846  fclose( f );
1848  }
1849 
1850  if( fread( *buf, 1, *n, f ) != *n )
1851  {
1852  fclose( f );
1853  free( *buf );
1855  }
1856 
1857  fclose( f );
1858 
1859  (*buf)[*n] = '\0';
1860 
1861  return( 0 );
1862 }
1863 
1864 /*
1865  * Load one or more certificates and add them to the chained list
1866  */
1867 int x509parse_crtfile( x509_cert *chain, const char *path )
1868 {
1869  int ret;
1870  size_t n;
1871  unsigned char *buf;
1872 
1873  if ( (ret = load_file( path, &buf, &n ) ) != 0 )
1874  return( ret );
1875 
1876  ret = x509parse_crt( chain, buf, n );
1877 
1878  memset( buf, 0, n + 1 );
1879  free( buf );
1880 
1881  return( ret );
1882 }
1883 
1884 int x509parse_crtpath( x509_cert *chain, const char *path )
1885 {
1886  int ret = 0;
1887 #if defined(_WIN32)
1888  int w_ret;
1889  WCHAR szDir[MAX_PATH];
1890  char filename[MAX_PATH];
1891  char *p;
1892  int len = strlen( path );
1893 
1894  WIN32_FIND_DATAW file_data;
1895  HANDLE hFind;
1896 
1897  if( len > MAX_PATH - 3 )
1899 
1900  memset( szDir, 0, sizeof(szDir) );
1901  memset( filename, 0, MAX_PATH );
1902  memcpy( filename, path, len );
1903  filename[len++] = '\\';
1904  p = filename + len;
1905  filename[len++] = '*';
1906 
1907  w_ret = MultiByteToWideChar( CP_ACP, 0, filename, len, szDir, MAX_PATH - 3 );
1908 
1909  hFind = FindFirstFileW( szDir, &file_data );
1910  if (hFind == INVALID_HANDLE_VALUE)
1912 
1913  len = MAX_PATH - len;
1914  do
1915  {
1916  memset( p, 0, len );
1917 
1918  if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
1919  continue;
1920 
1921  w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
1922  lstrlenW(file_data.cFileName),
1923  p, len - 1,
1924  NULL, NULL );
1925 
1926  w_ret = x509parse_crtfile( chain, filename );
1927  if( w_ret < 0 )
1928  ret++;
1929  else
1930  ret += w_ret;
1931  }
1932  while( FindNextFileW( hFind, &file_data ) != 0 );
1933 
1934  if (GetLastError() != ERROR_NO_MORE_FILES)
1936 
1937  FindClose( hFind );
1938 #else
1939 #if defined(POLARSSL_HAVE_READDIR_R)
1940  int t_ret, i;
1941  struct stat sb;
1942  struct dirent entry, *result = NULL;
1943  char entry_name[255];
1944  DIR *dir = opendir( path );
1945 
1946  if( dir == NULL)
1948 
1949  while( ( t_ret = readdir_r( dir, &entry, &result ) ) == 0 )
1950  {
1951  if( result == NULL )
1952  break;
1953 
1954  snprintf( entry_name, sizeof(entry_name), "%s/%s", path, entry.d_name );
1955 
1956  i = stat( entry_name, &sb );
1957 
1958  if( i == -1 )
1959  {
1960  closedir( dir );
1962  }
1963 
1964  if( !S_ISREG( sb.st_mode ) )
1965  continue;
1966 
1967  // Ignore parse errors
1968  //
1969  t_ret = x509parse_crtfile( chain, entry_name );
1970  if( t_ret < 0 )
1971  ret++;
1972  else
1973  ret += t_ret;
1974  }
1975  closedir( dir );
1976 #else /* POLARSSL_HAVE_READDIR_R */
1977  ((void) chain);
1978  ((void) path);
1980 #endif /* POLARSSL_HAVE_READDIR_R */
1981 #endif /* _WIN32 */
1982 
1983  return( ret );
1984 }
1985 
1986 /*
1987  * Load one or more CRLs and add them to the chained list
1988  */
1989 int x509parse_crlfile( x509_crl *chain, const char *path )
1990 {
1991  int ret;
1992  size_t n;
1993  unsigned char *buf;
1994 
1995  if ( (ret = load_file( path, &buf, &n ) ) != 0 )
1996  return( ret );
1997 
1998  ret = x509parse_crl( chain, buf, n );
1999 
2000  memset( buf, 0, n + 1 );
2001  free( buf );
2002 
2003  return( ret );
2004 }
2005 
2006 /*
2007  * Load and parse a private RSA key
2008  */
2009 int x509parse_keyfile( rsa_context *rsa, const char *path, const char *pwd )
2010 {
2011  int ret;
2012  size_t n;
2013  unsigned char *buf;
2014 
2015  if ( (ret = load_file( path, &buf, &n ) ) != 0 )
2016  return( ret );
2017 
2018  if( pwd == NULL )
2019  ret = x509parse_key( rsa, buf, n, NULL, 0 );
2020  else
2021  ret = x509parse_key( rsa, buf, n,
2022  (unsigned char *) pwd, strlen( pwd ) );
2023 
2024  memset( buf, 0, n + 1 );
2025  free( buf );
2026 
2027  return( ret );
2028 }
2029 
2030 /*
2031  * Load and parse a public RSA key
2032  */
2033 int x509parse_public_keyfile( rsa_context *rsa, const char *path )
2034 {
2035  int ret;
2036  size_t n;
2037  unsigned char *buf;
2038 
2039  if ( (ret = load_file( path, &buf, &n ) ) != 0 )
2040  return( ret );
2041 
2042  ret = x509parse_public_key( rsa, buf, n );
2043 
2044  memset( buf, 0, n + 1 );
2045  free( buf );
2046 
2047  return( ret );
2048 }
2049 #endif /* POLARSSL_FS_IO */
2050 
2051 /*
2052  * Parse a PKCS#1 encoded private RSA key
2053  */
2054 static int x509parse_key_pkcs1_der( rsa_context *rsa,
2055  const unsigned char *key,
2056  size_t keylen )
2057 {
2058  int ret;
2059  size_t len;
2060  unsigned char *p, *end;
2061 
2062  p = (unsigned char *) key;
2063  end = p + keylen;
2064 
2065  /*
2066  * This function parses the RSAPrivateKey (PKCS#1)
2067  *
2068  * RSAPrivateKey ::= SEQUENCE {
2069  * version Version,
2070  * modulus INTEGER, -- n
2071  * publicExponent INTEGER, -- e
2072  * privateExponent INTEGER, -- d
2073  * prime1 INTEGER, -- p
2074  * prime2 INTEGER, -- q
2075  * exponent1 INTEGER, -- d mod (p-1)
2076  * exponent2 INTEGER, -- d mod (q-1)
2077  * coefficient INTEGER, -- (inverse of q) mod p
2078  * otherPrimeInfos OtherPrimeInfos OPTIONAL
2079  * }
2080  */
2081  if( ( ret = asn1_get_tag( &p, end, &len,
2082  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2083  {
2084  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2085  }
2086 
2087  end = p + len;
2088 
2089  if( ( ret = asn1_get_int( &p, end, &rsa->ver ) ) != 0 )
2090  {
2091  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2092  }
2093 
2094  if( rsa->ver != 0 )
2095  {
2096  return( POLARSSL_ERR_X509_KEY_INVALID_VERSION + ret );
2097  }
2098 
2099  if( ( ret = asn1_get_mpi( &p, end, &rsa->N ) ) != 0 ||
2100  ( ret = asn1_get_mpi( &p, end, &rsa->E ) ) != 0 ||
2101  ( ret = asn1_get_mpi( &p, end, &rsa->D ) ) != 0 ||
2102  ( ret = asn1_get_mpi( &p, end, &rsa->P ) ) != 0 ||
2103  ( ret = asn1_get_mpi( &p, end, &rsa->Q ) ) != 0 ||
2104  ( ret = asn1_get_mpi( &p, end, &rsa->DP ) ) != 0 ||
2105  ( ret = asn1_get_mpi( &p, end, &rsa->DQ ) ) != 0 ||
2106  ( ret = asn1_get_mpi( &p, end, &rsa->QP ) ) != 0 )
2107  {
2108  rsa_free( rsa );
2109  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2110  }
2111 
2112  rsa->len = mpi_size( &rsa->N );
2113 
2114  if( p != end )
2115  {
2116  rsa_free( rsa );
2119  }
2120 
2121  if( ( ret = rsa_check_privkey( rsa ) ) != 0 )
2122  {
2123  rsa_free( rsa );
2124  return( ret );
2125  }
2126 
2127  return( 0 );
2128 }
2129 
2130 /*
2131  * Parse an unencrypted PKCS#8 encoded private RSA key
2132  */
2133 static int x509parse_key_pkcs8_unencrypted_der(
2134  rsa_context *rsa,
2135  const unsigned char *key,
2136  size_t keylen )
2137 {
2138  int ret;
2139  size_t len;
2140  unsigned char *p, *end;
2141  x509_buf pk_alg_oid;
2142 
2143  p = (unsigned char *) key;
2144  end = p + keylen;
2145 
2146  /*
2147  * This function parses the PrivatKeyInfo object (PKCS#8)
2148  *
2149  * PrivateKeyInfo ::= SEQUENCE {
2150  * version Version,
2151  * algorithm AlgorithmIdentifier,
2152  * PrivateKey BIT STRING
2153  * }
2154  *
2155  * AlgorithmIdentifier ::= SEQUENCE {
2156  * algorithm OBJECT IDENTIFIER,
2157  * parameters ANY DEFINED BY algorithm OPTIONAL
2158  * }
2159  *
2160  * The PrivateKey BIT STRING is a PKCS#1 RSAPrivateKey
2161  */
2162  if( ( ret = asn1_get_tag( &p, end, &len,
2163  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2164  {
2165  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2166  }
2167 
2168  end = p + len;
2169 
2170  if( ( ret = asn1_get_int( &p, end, &rsa->ver ) ) != 0 )
2171  {
2172  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2173  }
2174 
2175  if( rsa->ver != 0 )
2176  {
2177  return( POLARSSL_ERR_X509_KEY_INVALID_VERSION + ret );
2178  }
2179 
2180  if( ( ret = x509_get_alg( &p, end, &pk_alg_oid ) ) != 0 )
2181  {
2182  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2183  }
2184 
2185  /*
2186  * only RSA keys handled at this time
2187  */
2188  if( pk_alg_oid.len != 9 ||
2189  memcmp( pk_alg_oid.p, OID_PKCS1_RSA, 9 ) != 0 )
2190  {
2192  }
2193 
2194  /*
2195  * Get the OCTET STRING and parse the PKCS#1 format inside
2196  */
2197  if( ( ret = asn1_get_tag( &p, end, &len, ASN1_OCTET_STRING ) ) != 0 )
2198  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2199 
2200  if( ( end - p ) < 1 )
2201  {
2204  }
2205 
2206  end = p + len;
2207 
2208  if( ( ret = x509parse_key_pkcs1_der( rsa, p, end - p ) ) != 0 )
2209  return( ret );
2210 
2211  return( 0 );
2212 }
2213 
2214 /*
2215  * Parse an encrypted PKCS#8 encoded private RSA key
2216  */
2217 static int x509parse_key_pkcs8_encrypted_der(
2218  rsa_context *rsa,
2219  const unsigned char *key,
2220  size_t keylen,
2221  const unsigned char *pwd,
2222  size_t pwdlen )
2223 {
2224  int ret;
2225  size_t len;
2226  unsigned char *p, *end, *end2;
2227  x509_buf pbe_alg_oid, pbe_params;
2228  unsigned char buf[2048];
2229 
2230  memset(buf, 0, 2048);
2231 
2232  p = (unsigned char *) key;
2233  end = p + keylen;
2234 
2235  if( pwdlen == 0 )
2237 
2238  /*
2239  * This function parses the EncryptedPrivatKeyInfo object (PKCS#8)
2240  *
2241  * EncryptedPrivateKeyInfo ::= SEQUENCE {
2242  * encryptionAlgorithm EncryptionAlgorithmIdentifier,
2243  * encryptedData EncryptedData
2244  * }
2245  *
2246  * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
2247  *
2248  * EncryptedData ::= OCTET STRING
2249  *
2250  * The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
2251  */
2252  if( ( ret = asn1_get_tag( &p, end, &len,
2253  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2254  {
2255  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2256  }
2257 
2258  end = p + len;
2259 
2260  if( ( ret = asn1_get_tag( &p, end, &len,
2261  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2262  {
2263  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2264  }
2265 
2266  end2 = p + len;
2267 
2268  if( ( ret = asn1_get_tag( &p, end, &pbe_alg_oid.len, ASN1_OID ) ) != 0 )
2269  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2270 
2271  pbe_alg_oid.p = p;
2272  p += pbe_alg_oid.len;
2273 
2274  /*
2275  * Store the algorithm parameters
2276  */
2277  pbe_params.p = p;
2278  pbe_params.len = end2 - p;
2279  p += pbe_params.len;
2280 
2281  if( ( ret = asn1_get_tag( &p, end, &len, ASN1_OCTET_STRING ) ) != 0 )
2282  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2283 
2284  // buf has been sized to 2048 bytes
2285  if( len > 2048 )
2287 
2288  /*
2289  * Decrypt EncryptedData with appropriate PDE
2290  */
2291 #if defined(POLARSSL_PKCS12_C)
2292  if( OID_CMP( OID_PKCS12_PBE_SHA1_DES3_EDE_CBC, &pbe_alg_oid ) )
2293  {
2294  if( ( ret = pkcs12_pbe( &pbe_params, PKCS12_PBE_DECRYPT,
2296  pwd, pwdlen, p, len, buf ) ) != 0 )
2297  {
2300 
2301  return( ret );
2302  }
2303  }
2304  else if( OID_CMP( OID_PKCS12_PBE_SHA1_DES2_EDE_CBC, &pbe_alg_oid ) )
2305  {
2306  if( ( ret = pkcs12_pbe( &pbe_params, PKCS12_PBE_DECRYPT,
2308  pwd, pwdlen, p, len, buf ) ) != 0 )
2309  {
2312 
2313  return( ret );
2314  }
2315  }
2316  else if( OID_CMP( OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) )
2317  {
2318  if( ( ret = pkcs12_pbe_sha1_rc4_128( &pbe_params,
2320  pwd, pwdlen,
2321  p, len, buf ) ) != 0 )
2322  {
2323  return( ret );
2324  }
2325 
2326  // Best guess for password mismatch when using RC4. If first tag is
2327  // not ASN1_CONSTRUCTED | ASN1_SEQUENCE
2328  //
2329  if( *buf != ( ASN1_CONSTRUCTED | ASN1_SEQUENCE ) )
2331  }
2332  else
2333 #endif /* POLARSSL_PKCS12_C */
2334 #if defined(POLARSSL_PKCS5_C)
2335  if( OID_CMP( OID_PKCS5_PBES2, &pbe_alg_oid ) )
2336  {
2337  if( ( ret = pkcs5_pbes2( &pbe_params, PKCS5_DECRYPT, pwd, pwdlen,
2338  p, len, buf ) ) != 0 )
2339  {
2342 
2343  return( ret );
2344  }
2345  }
2346  else
2347 #endif /* POLARSSL_PKCS5_C */
2349 
2350  return x509parse_key_pkcs8_unencrypted_der( rsa, buf, len );
2351 }
2352 
2353 /*
2354  * Parse a private RSA key
2355  */
2356 int x509parse_key( rsa_context *rsa, const unsigned char *key, size_t keylen,
2357  const unsigned char *pwd, size_t pwdlen )
2358 {
2359  int ret;
2360 
2361 #if defined(POLARSSL_PEM_C)
2362  size_t len;
2363  pem_context pem;
2364 
2365  pem_init( &pem );
2366  ret = pem_read_buffer( &pem,
2367  (char *) "-----BEGIN RSA PRIVATE KEY-----",
2368  (char *) "-----END RSA PRIVATE KEY-----",
2369  key, pwd, pwdlen, &len );
2370  if( ret == 0 )
2371  {
2372  if( ( ret = x509parse_key_pkcs1_der( rsa, pem.buf, pem.buflen ) ) != 0 )
2373  {
2374  rsa_free( rsa );
2375  }
2376 
2377  pem_free( &pem );
2378  return( ret );
2379  }
2380  else if( ret == POLARSSL_ERR_PEM_PASSWORD_MISMATCH )
2382  else if( ret == POLARSSL_ERR_PEM_PASSWORD_REQUIRED )
2385  return( ret );
2386 
2387  ret = pem_read_buffer( &pem,
2388  (char *) "-----BEGIN PRIVATE KEY-----",
2389  (char *) "-----END PRIVATE KEY-----",
2390  key, NULL, 0, &len );
2391  if( ret == 0 )
2392  {
2393  if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa,
2394  pem.buf, pem.buflen ) ) != 0 )
2395  {
2396  rsa_free( rsa );
2397  }
2398 
2399  pem_free( &pem );
2400  return( ret );
2401  }
2403  return( ret );
2404 
2405  ret = pem_read_buffer( &pem,
2406  (char *) "-----BEGIN ENCRYPTED PRIVATE KEY-----",
2407  (char *) "-----END ENCRYPTED PRIVATE KEY-----",
2408  key, NULL, 0, &len );
2409  if( ret == 0 )
2410  {
2411  if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa,
2412  pem.buf, pem.buflen,
2413  pwd, pwdlen ) ) != 0 )
2414  {
2415  rsa_free( rsa );
2416  }
2417 
2418  pem_free( &pem );
2419  return( ret );
2420  }
2422  return( ret );
2423 #else
2424  ((void) pwd);
2425  ((void) pwdlen);
2426 #endif /* POLARSSL_PEM_C */
2427 
2428  // At this point we only know it's not a PEM formatted key. Could be any
2429  // of the known DER encoded private key formats
2430  //
2431  // We try the different DER format parsers to see if one passes without
2432  // error
2433  //
2434  if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa, key, keylen,
2435  pwd, pwdlen ) ) == 0 )
2436  {
2437  return( 0 );
2438  }
2439 
2440  rsa_free( rsa );
2441 
2443  {
2444  return( ret );
2445  }
2446 
2447  if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa, key, keylen ) ) == 0 )
2448  return( 0 );
2449 
2450  rsa_free( rsa );
2451 
2452  if( ( ret = x509parse_key_pkcs1_der( rsa, key, keylen ) ) == 0 )
2453  return( 0 );
2454 
2455  rsa_free( rsa );
2456 
2458 }
2459 
2460 /*
2461  * Parse a public RSA key
2462  */
2463 int x509parse_public_key( rsa_context *rsa, const unsigned char *key, size_t keylen )
2464 {
2465  int ret;
2466  size_t len;
2467  unsigned char *p, *end;
2468  x509_buf alg_oid;
2469 #if defined(POLARSSL_PEM_C)
2470  pem_context pem;
2471 
2472  pem_init( &pem );
2473  ret = pem_read_buffer( &pem,
2474  (char *) "-----BEGIN PUBLIC KEY-----",
2475  (char *) "-----END PUBLIC KEY-----",
2476  key, NULL, 0, &len );
2477 
2478  if( ret == 0 )
2479  {
2480  /*
2481  * Was PEM encoded
2482  */
2483  keylen = pem.buflen;
2484  }
2486  {
2487  pem_free( &pem );
2488  return( ret );
2489  }
2490 
2491  p = ( ret == 0 ) ? pem.buf : (unsigned char *) key;
2492 #else
2493  p = (unsigned char *) key;
2494 #endif
2495  end = p + keylen;
2496 
2497  /*
2498  * PublicKeyInfo ::= SEQUENCE {
2499  * algorithm AlgorithmIdentifier,
2500  * PublicKey BIT STRING
2501  * }
2502  *
2503  * AlgorithmIdentifier ::= SEQUENCE {
2504  * algorithm OBJECT IDENTIFIER,
2505  * parameters ANY DEFINED BY algorithm OPTIONAL
2506  * }
2507  *
2508  * RSAPublicKey ::= SEQUENCE {
2509  * modulus INTEGER, -- n
2510  * publicExponent INTEGER -- e
2511  * }
2512  */
2513 
2514  if( ( ret = asn1_get_tag( &p, end, &len,
2515  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2516  {
2517 #if defined(POLARSSL_PEM_C)
2518  pem_free( &pem );
2519 #endif
2520  rsa_free( rsa );
2521  return( POLARSSL_ERR_X509_CERT_INVALID_FORMAT + ret );
2522  }
2523 
2524  if( ( ret = x509_get_pubkey( &p, end, &alg_oid, &rsa->N, &rsa->E ) ) != 0 )
2525  {
2526 #if defined(POLARSSL_PEM_C)
2527  pem_free( &pem );
2528 #endif
2529  rsa_free( rsa );
2530  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2531  }
2532 
2533  if( ( ret = rsa_check_pubkey( rsa ) ) != 0 )
2534  {
2535 #if defined(POLARSSL_PEM_C)
2536  pem_free( &pem );
2537 #endif
2538  rsa_free( rsa );
2539  return( ret );
2540  }
2541 
2542  rsa->len = mpi_size( &rsa->N );
2543 
2544 #if defined(POLARSSL_PEM_C)
2545  pem_free( &pem );
2546 #endif
2547 
2548  return( 0 );
2549 }
2550 
2551 #if defined(POLARSSL_DHM_C)
2552 /*
2553  * Parse DHM parameters
2554  */
2555 int x509parse_dhm( dhm_context *dhm, const unsigned char *dhmin, size_t dhminlen )
2556 {
2557  int ret;
2558  size_t len;
2559  unsigned char *p, *end;
2560 #if defined(POLARSSL_PEM_C)
2561  pem_context pem;
2562 
2563  pem_init( &pem );
2564 
2565  ret = pem_read_buffer( &pem,
2566  (char *) "-----BEGIN DH PARAMETERS-----",
2567  (char *) "-----END DH PARAMETERS-----",
2568  dhmin, NULL, 0, &dhminlen );
2569 
2570  if( ret == 0 )
2571  {
2572  /*
2573  * Was PEM encoded
2574  */
2575  dhminlen = pem.buflen;
2576  }
2578  {
2579  pem_free( &pem );
2580  return( ret );
2581  }
2582 
2583  p = ( ret == 0 ) ? pem.buf : (unsigned char *) dhmin;
2584 #else
2585  p = (unsigned char *) dhmin;
2586 #endif
2587  end = p + dhminlen;
2588 
2589  memset( dhm, 0, sizeof( dhm_context ) );
2590 
2591  /*
2592  * DHParams ::= SEQUENCE {
2593  * prime INTEGER, -- P
2594  * generator INTEGER, -- g
2595  * }
2596  */
2597  if( ( ret = asn1_get_tag( &p, end, &len,
2598  ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
2599  {
2600 #if defined(POLARSSL_PEM_C)
2601  pem_free( &pem );
2602 #endif
2603  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2604  }
2605 
2606  end = p + len;
2607 
2608  if( ( ret = asn1_get_mpi( &p, end, &dhm->P ) ) != 0 ||
2609  ( ret = asn1_get_mpi( &p, end, &dhm->G ) ) != 0 )
2610  {
2611 #if defined(POLARSSL_PEM_C)
2612  pem_free( &pem );
2613 #endif
2614  dhm_free( dhm );
2615  return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
2616  }
2617 
2618  if( p != end )
2619  {
2620 #if defined(POLARSSL_PEM_C)
2621  pem_free( &pem );
2622 #endif
2623  dhm_free( dhm );
2626  }
2627 
2628 #if defined(POLARSSL_PEM_C)
2629  pem_free( &pem );
2630 #endif
2631 
2632  return( 0 );
2633 }
2634 
2635 #if defined(POLARSSL_FS_IO)
2636 /*
2637  * Load and parse a private RSA key
2638  */
2639 int x509parse_dhmfile( dhm_context *dhm, const char *path )
2640 {
2641  int ret;
2642  size_t n;
2643  unsigned char *buf;
2644 
2645  if ( ( ret = load_file( path, &buf, &n ) ) != 0 )
2646  return( ret );
2647 
2648  ret = x509parse_dhm( dhm, buf, n );
2649 
2650  memset( buf, 0, n + 1 );
2651  free( buf );
2652 
2653  return( ret );
2654 }
2655 #endif /* POLARSSL_FS_IO */
2656 #endif /* POLARSSL_DHM_C */
2657 
2658 #if defined _MSC_VER && !defined snprintf
2659 #include <stdarg.h>
2660 
2661 #if !defined vsnprintf
2662 #define vsnprintf _vsnprintf
2663 #endif // vsnprintf
2664 
2665 /*
2666  * Windows _snprintf and _vsnprintf are not compatible to linux versions.
2667  * Result value is not size of buffer needed, but -1 if no fit is possible.
2668  *
2669  * This fuction tries to 'fix' this by at least suggesting enlarging the
2670  * size by 20.
2671  */
2672 int compat_snprintf(char *str, size_t size, const char *format, ...)
2673 {
2674  va_list ap;
2675  int res = -1;
2676 
2677  va_start( ap, format );
2678 
2679  res = vsnprintf( str, size, format, ap );
2680 
2681  va_end( ap );
2682 
2683  // No quick fix possible
2684  if ( res < 0 )
2685  return( (int) size + 20 );
2686 
2687  return res;
2688 }
2689 
2690 #define snprintf compat_snprintf
2691 #endif
2692 
2693 #define POLARSSL_ERR_DEBUG_BUF_TOO_SMALL -2
2694 
2695 #define SAFE_SNPRINTF() \
2696 { \
2697  if( ret == -1 ) \
2698  return( -1 ); \
2699  \
2700  if ( (unsigned int) ret > n ) { \
2701  p[n - 1] = '\0'; \
2702  return POLARSSL_ERR_DEBUG_BUF_TOO_SMALL;\
2703  } \
2704  \
2705  n -= (unsigned int) ret; \
2706  p += (unsigned int) ret; \
2707 }
2708 
2709 /*
2710  * Store the name in printable form into buf; no more
2711  * than size characters will be written
2712  */
2713 int x509parse_dn_gets( char *buf, size_t size, const x509_name *dn )
2714 {
2715  int ret;
2716  size_t i, n;
2717  unsigned char c;
2718  const x509_name *name;
2719  char s[128], *p;
2720 
2721  memset( s, 0, sizeof( s ) );
2722 
2723  name = dn;
2724  p = buf;
2725  n = size;
2726 
2727  while( name != NULL )
2728  {
2729  if( !name->oid.p )
2730  {
2731  name = name->next;
2732  continue;
2733  }
2734 
2735  if( name != dn )
2736  {
2737  ret = snprintf( p, n, ", " );
2738  SAFE_SNPRINTF();
2739  }
2740 
2741  if( name->oid.len == 3 &&
2742  memcmp( name->oid.p, OID_X520, 2 ) == 0 )
2743  {
2744  switch( name->oid.p[2] )
2745  {
2746  case X520_COMMON_NAME:
2747  ret = snprintf( p, n, "CN=" ); break;
2748 
2749  case X520_COUNTRY:
2750  ret = snprintf( p, n, "C=" ); break;
2751 
2752  case X520_LOCALITY:
2753  ret = snprintf( p, n, "L=" ); break;
2754 
2755  case X520_STATE:
2756  ret = snprintf( p, n, "ST=" ); break;
2757 
2758  case X520_ORGANIZATION:
2759  ret = snprintf( p, n, "O=" ); break;
2760 
2761  case X520_ORG_UNIT:
2762  ret = snprintf( p, n, "OU=" ); break;
2763 
2764  default:
2765  ret = snprintf( p, n, "0x%02X=",
2766  name->oid.p[2] );
2767  break;
2768  }
2769  SAFE_SNPRINTF();
2770  }
2771  else if( name->oid.len == 9 &&
2772  memcmp( name->oid.p, OID_PKCS9, 8 ) == 0 )
2773  {
2774  switch( name->oid.p[8] )
2775  {
2776  case PKCS9_EMAIL:
2777  ret = snprintf( p, n, "emailAddress=" ); break;
2778 
2779  default:
2780  ret = snprintf( p, n, "0x%02X=",
2781  name->oid.p[8] );
2782  break;
2783  }
2784  SAFE_SNPRINTF();
2785  }
2786  else
2787  {
2788  ret = snprintf( p, n, "\?\?=" );
2789  SAFE_SNPRINTF();
2790  }
2791 
2792  for( i = 0; i < name->val.len; i++ )
2793  {
2794  if( i >= sizeof( s ) - 1 )
2795  break;
2796 
2797  c = name->val.p[i];
2798  if( c < 32 || c == 127 || ( c > 128 && c < 160 ) )
2799  s[i] = '?';
2800  else s[i] = c;
2801  }
2802  s[i] = '\0';
2803  ret = snprintf( p, n, "%s", s );
2804  SAFE_SNPRINTF();
2805  name = name->next;
2806  }
2807 
2808  return( (int) ( size - n ) );
2809 }
2810 
2811 /*
2812  * Store the serial in printable form into buf; no more
2813  * than size characters will be written
2814  */
2815 int x509parse_serial_gets( char *buf, size_t size, const x509_buf *serial )
2816 {
2817  int ret;
2818  size_t i, n, nr;
2819  char *p;
2820 
2821  p = buf;
2822  n = size;
2823 
2824  nr = ( serial->len <= 32 )
2825  ? serial->len : 28;
2826 
2827  for( i = 0; i < nr; i++ )
2828  {
2829  if( i == 0 && nr > 1 && serial->p[i] == 0x0 )
2830  continue;
2831 
2832  ret = snprintf( p, n, "%02X%s",
2833  serial->p[i], ( i < nr - 1 ) ? ":" : "" );
2834  SAFE_SNPRINTF();
2835  }
2836 
2837  if( nr != serial->len )
2838  {
2839  ret = snprintf( p, n, "...." );
2840  SAFE_SNPRINTF();
2841  }
2842 
2843  return( (int) ( size - n ) );
2844 }
2845 
2846 /*
2847  * Return an informational string about the certificate.
2848  */
2849 int x509parse_cert_info( char *buf, size_t size, const char *prefix,
2850  const x509_cert *crt )
2851 {
2852  int ret;
2853  size_t n;
2854  char *p;
2855 
2856  p = buf;
2857  n = size;
2858 
2859  ret = snprintf( p, n, "%scert. version : %d\n",
2860  prefix, crt->version );
2861  SAFE_SNPRINTF();
2862  ret = snprintf( p, n, "%sserial number : ",
2863  prefix );
2864  SAFE_SNPRINTF();
2865 
2866  ret = x509parse_serial_gets( p, n, &crt->serial);
2867  SAFE_SNPRINTF();
2868 
2869  ret = snprintf( p, n, "\n%sissuer name : ", prefix );
2870  SAFE_SNPRINTF();
2871  ret = x509parse_dn_gets( p, n, &crt->issuer );
2872  SAFE_SNPRINTF();
2873 
2874  ret = snprintf( p, n, "\n%ssubject name : ", prefix );
2875  SAFE_SNPRINTF();
2876  ret = x509parse_dn_gets( p, n, &crt->subject );
2877  SAFE_SNPRINTF();
2878 
2879  ret = snprintf( p, n, "\n%sissued on : " \
2880  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
2881  crt->valid_from.year, crt->valid_from.mon,
2882  crt->valid_from.day, crt->valid_from.hour,
2883  crt->valid_from.min, crt->valid_from.sec );
2884  SAFE_SNPRINTF();
2885 
2886  ret = snprintf( p, n, "\n%sexpires on : " \
2887  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
2888  crt->valid_to.year, crt->valid_to.mon,
2889  crt->valid_to.day, crt->valid_to.hour,
2890  crt->valid_to.min, crt->valid_to.sec );
2891  SAFE_SNPRINTF();
2892 
2893  ret = snprintf( p, n, "\n%ssigned using : RSA+", prefix );
2894  SAFE_SNPRINTF();
2895 
2896  switch( crt->sig_alg )
2897  {
2898  case SIG_RSA_MD2 : ret = snprintf( p, n, "MD2" ); break;
2899  case SIG_RSA_MD4 : ret = snprintf( p, n, "MD4" ); break;
2900  case SIG_RSA_MD5 : ret = snprintf( p, n, "MD5" ); break;
2901  case SIG_RSA_SHA1 : ret = snprintf( p, n, "SHA1" ); break;
2902  case SIG_RSA_SHA224 : ret = snprintf( p, n, "SHA224" ); break;
2903  case SIG_RSA_SHA256 : ret = snprintf( p, n, "SHA256" ); break;
2904  case SIG_RSA_SHA384 : ret = snprintf( p, n, "SHA384" ); break;
2905  case SIG_RSA_SHA512 : ret = snprintf( p, n, "SHA512" ); break;
2906  default: ret = snprintf( p, n, "???" ); break;
2907  }
2908  SAFE_SNPRINTF();
2909 
2910  ret = snprintf( p, n, "\n%sRSA key size : %d bits\n", prefix,
2911  (int) crt->rsa.N.n * (int) sizeof( t_uint ) * 8 );
2912  SAFE_SNPRINTF();
2913 
2914  return( (int) ( size - n ) );
2915 }
2916 
2917 /*
2918  * Return an informational string describing the given OID
2919  */
2920 const char *x509_oid_get_description( x509_buf *oid )
2921 {
2922  if ( oid == NULL )
2923  return ( NULL );
2924 
2925  else if( OID_CMP( OID_SERVER_AUTH, oid ) )
2926  return( STRING_SERVER_AUTH );
2927 
2928  else if( OID_CMP( OID_CLIENT_AUTH, oid ) )
2929  return( STRING_CLIENT_AUTH );
2930 
2931  else if( OID_CMP( OID_CODE_SIGNING, oid ) )
2932  return( STRING_CODE_SIGNING );
2933 
2934  else if( OID_CMP( OID_EMAIL_PROTECTION, oid ) )
2935  return( STRING_EMAIL_PROTECTION );
2936 
2937  else if( OID_CMP( OID_TIME_STAMPING, oid ) )
2938  return( STRING_TIME_STAMPING );
2939 
2940  else if( OID_CMP( OID_OCSP_SIGNING, oid ) )
2941  return( STRING_OCSP_SIGNING );
2942 
2943  return( NULL );
2944 }
2945 
2946 /* Return the x.y.z.... style numeric string for the given OID */
2947 int x509_oid_get_numeric_string( char *buf, size_t size, x509_buf *oid )
2948 {
2949  int ret;
2950  size_t i, n;
2951  unsigned int value;
2952  char *p;
2953 
2954  p = buf;
2955  n = size;
2956 
2957  /* First byte contains first two dots */
2958  if( oid->len > 0 )
2959  {
2960  ret = snprintf( p, n, "%d.%d", oid->p[0]/40, oid->p[0]%40 );
2961  SAFE_SNPRINTF();
2962  }
2963 
2964  /* TODO: value can overflow in value. */
2965  value = 0;
2966  for( i = 1; i < oid->len; i++ )
2967  {
2968  value <<= 7;
2969  value += oid->p[i] & 0x7F;
2970 
2971  if( !( oid->p[i] & 0x80 ) )
2972  {
2973  /* Last byte */
2974  ret = snprintf( p, n, ".%d", value );
2975  SAFE_SNPRINTF();
2976  value = 0;
2977  }
2978  }
2979 
2980  return( (int) ( size - n ) );
2981 }
2982 
2983 /*
2984  * Return an informational string about the CRL.
2985  */
2986 int x509parse_crl_info( char *buf, size_t size, const char *prefix,
2987  const x509_crl *crl )
2988 {
2989  int ret;
2990  size_t n;
2991  char *p;
2992  const x509_crl_entry *entry;
2993 
2994  p = buf;
2995  n = size;
2996 
2997  ret = snprintf( p, n, "%sCRL version : %d",
2998  prefix, crl->version );
2999  SAFE_SNPRINTF();
3000 
3001  ret = snprintf( p, n, "\n%sissuer name : ", prefix );
3002  SAFE_SNPRINTF();
3003  ret = x509parse_dn_gets( p, n, &crl->issuer );
3004  SAFE_SNPRINTF();
3005 
3006  ret = snprintf( p, n, "\n%sthis update : " \
3007  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
3008  crl->this_update.year, crl->this_update.mon,
3009  crl->this_update.day, crl->this_update.hour,
3010  crl->this_update.min, crl->this_update.sec );
3011  SAFE_SNPRINTF();
3012 
3013  ret = snprintf( p, n, "\n%snext update : " \
3014  "%04d-%02d-%02d %02d:%02d:%02d", prefix,
3015  crl->next_update.year, crl->next_update.mon,
3016  crl->next_update.day, crl->next_update.hour,
3017  crl->next_update.min, crl->next_update.sec );
3018  SAFE_SNPRINTF();
3019 
3020  entry = &crl->entry;
3021 
3022  ret = snprintf( p, n, "\n%sRevoked certificates:",
3023  prefix );
3024  SAFE_SNPRINTF();
3025 
3026  while( entry != NULL && entry->raw.len != 0 )
3027  {
3028  ret = snprintf( p, n, "\n%sserial number: ",
3029  prefix );
3030  SAFE_SNPRINTF();
3031 
3032  ret = x509parse_serial_gets( p, n, &entry->serial);
3033  SAFE_SNPRINTF();
3034 
3035  ret = snprintf( p, n, " revocation date: " \
3036  "%04d-%02d-%02d %02d:%02d:%02d",
3037  entry->revocation_date.year, entry->revocation_date.mon,
3038  entry->revocation_date.day, entry->revocation_date.hour,
3039  entry->revocation_date.min, entry->revocation_date.sec );
3040  SAFE_SNPRINTF();
3041 
3042  entry = entry->next;
3043  }
3044 
3045  ret = snprintf( p, n, "\n%ssigned using : RSA+", prefix );
3046  SAFE_SNPRINTF();
3047 
3048  switch( crl->sig_alg )
3049  {
3050  case SIG_RSA_MD2 : ret = snprintf( p, n, "MD2" ); break;
3051  case SIG_RSA_MD4 : ret = snprintf( p, n, "MD4" ); break;
3052  case SIG_RSA_MD5 : ret = snprintf( p, n, "MD5" ); break;
3053  case SIG_RSA_SHA1 : ret = snprintf( p, n, "SHA1" ); break;
3054  case SIG_RSA_SHA224 : ret = snprintf( p, n, "SHA224" ); break;
3055  case SIG_RSA_SHA256 : ret = snprintf( p, n, "SHA256" ); break;
3056  case SIG_RSA_SHA384 : ret = snprintf( p, n, "SHA384" ); break;
3057  case SIG_RSA_SHA512 : ret = snprintf( p, n, "SHA512" ); break;
3058  default: ret = snprintf( p, n, "???" ); break;
3059  }
3060  SAFE_SNPRINTF();
3061 
3062  ret = snprintf( p, n, "\n" );
3063  SAFE_SNPRINTF();
3064 
3065  return( (int) ( size - n ) );
3066 }
3067 
3068 /*
3069  * Return 0 if the x509_time is still valid, or 1 otherwise.
3070  */
3071 static void x509_get_current_time( x509_time *now )
3072 {
3073 #if defined(_WIN32)
3074  SYSTEMTIME st;
3075 
3076  GetSystemTime(&st);
3077 
3078  now->year = st.wYear;
3079  now->mon = st.wMonth;
3080  now->day = st.wDay;
3081  now->hour = st.wHour;
3082  now->min = st.wMinute;
3083  now->sec = st.wSecond;
3084 #else
3085  struct tm lt;
3086  time_t tt;
3087 
3088  tt = time( NULL );
3089  gmtime_r( &tt, &lt );
3090 
3091  now->year = lt.tm_year + 1900;
3092  now->mon = lt.tm_mon + 1;
3093  now->day = lt.tm_mday;
3094  now->hour = lt.tm_hour;
3095  now->min = lt.tm_min;
3096  now->sec = lt.tm_sec;
3097 #endif
3098 }
3099 
3100 /*
3101  * Return 0 if before <= after, 1 otherwise
3102  */
3103 static int x509_check_time( const x509_time *before, const x509_time *after )
3104 {
3105  if( before->year > after->year )
3106  return( 1 );
3107 
3108  if( before->year == after->year &&
3109  before->mon > after->mon )
3110  return( 1 );
3111 
3112  if( before->year == after->year &&
3113  before->mon == after->mon &&
3114  before->day > after->day )
3115  return( 1 );
3116 
3117  if( before->year == after->year &&
3118  before->mon == after->mon &&
3119  before->day == after->day &&
3120  before->hour > after->hour )
3121  return( 1 );
3122 
3123  if( before->year == after->year &&
3124  before->mon == after->mon &&
3125  before->day == after->day &&
3126  before->hour == after->hour &&
3127  before->min > after->min )
3128  return( 1 );
3129 
3130  if( before->year == after->year &&
3131  before->mon == after->mon &&
3132  before->day == after->day &&
3133  before->hour == after->hour &&
3134  before->min == after->min &&
3135  before->sec > after->sec )
3136  return( 1 );
3137 
3138  return( 0 );
3139 }
3140 
3141 int x509parse_time_expired( const x509_time *to )
3142 {
3143  x509_time now;
3144 
3145  x509_get_current_time( &now );
3146 
3147  return( x509_check_time( &now, to ) );
3148 }
3149 
3150 int x509parse_time_future( const x509_time *from )
3151 {
3152  x509_time now;
3153 
3154  x509_get_current_time( &now );
3155 
3156  return( x509_check_time( from, &now ) );
3157 }
3158 
3159 /*
3160  * Return 1 if the certificate is revoked, or 0 otherwise.
3161  */
3162 int x509parse_revoked( const x509_cert *crt, const x509_crl *crl )
3163 {
3164  const x509_crl_entry *cur = &crl->entry;
3165 
3166  while( cur != NULL && cur->serial.len != 0 )
3167  {
3168  if( crt->serial.len == cur->serial.len &&
3169  memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
3170  {
3172  return( 1 );
3173  }
3174 
3175  cur = cur->next;
3176  }
3177 
3178  return( 0 );
3179 }
3180 
3181 /*
3182  * Wrapper for x509 hashes.
3183  */
3184 static void x509_hash( const unsigned char *in, size_t len, int alg,
3185  unsigned char *out )
3186 {
3187  switch( alg )
3188  {
3189 #if defined(POLARSSL_MD2_C)
3190  case SIG_RSA_MD2 : md2( in, len, out ); break;
3191 #endif
3192 #if defined(POLARSSL_MD4_C)
3193  case SIG_RSA_MD4 : md4( in, len, out ); break;
3194 #endif
3195 #if defined(POLARSSL_MD5_C)
3196  case SIG_RSA_MD5 : md5( in, len, out ); break;
3197 #endif
3198 #if defined(POLARSSL_SHA1_C)
3199  case SIG_RSA_SHA1 : sha1( in, len, out ); break;
3200 #endif
3201 #if defined(POLARSSL_SHA2_C)
3202  case SIG_RSA_SHA224 : sha2( in, len, out, 1 ); break;
3203  case SIG_RSA_SHA256 : sha2( in, len, out, 0 ); break;
3204 #endif
3205 #if defined(POLARSSL_SHA4_C)
3206  case SIG_RSA_SHA384 : sha4( in, len, out, 1 ); break;
3207  case SIG_RSA_SHA512 : sha4( in, len, out, 0 ); break;
3208 #endif
3209  default:
3210  memset( out, '\xFF', 64 );
3211  break;
3212  }
3213 }
3214 
3215 /*
3216  * Check that the given certificate is valid accoring to the CRL.
3217  */
3218 static int x509parse_verifycrl(x509_cert *crt, x509_cert *ca,
3219  x509_crl *crl_list)
3220 {
3221  int flags = 0;
3222  int hash_id;
3223  unsigned char hash[64];
3224 
3225  if( ca == NULL )
3226  return( flags );
3227 
3228  /*
3229  * TODO: What happens if no CRL is present?
3230  * Suggestion: Revocation state should be unknown if no CRL is present.
3231  * For backwards compatibility this is not yet implemented.
3232  */
3233 
3234  while( crl_list != NULL )
3235  {
3236  if( crl_list->version == 0 ||
3237  crl_list->issuer_raw.len != ca->subject_raw.len ||
3238  memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
3239  crl_list->issuer_raw.len ) != 0 )
3240  {
3241  crl_list = crl_list->next;
3242  continue;
3243  }
3244 
3245  /*
3246  * Check if CRL is correctly signed by the trusted CA
3247  */
3248  hash_id = crl_list->sig_alg;
3249 
3250  x509_hash( crl_list->tbs.p, crl_list->tbs.len, hash_id, hash );
3251 
3252  if( !rsa_pkcs1_verify( &ca->rsa, NULL, NULL, RSA_PUBLIC, hash_id,
3253  0, hash, crl_list->sig.p ) == 0 )
3254  {
3255  /*
3256  * CRL is not trusted
3257  */
3258  flags |= BADCRL_NOT_TRUSTED;
3259  break;
3260  }
3261 
3262  /*
3263  * Check for validity of CRL (Do not drop out)
3264  */
3265  if( x509parse_time_expired( &crl_list->next_update ) )
3266  flags |= BADCRL_EXPIRED;
3267 
3268  if( x509parse_time_future( &crl_list->this_update ) )
3269  flags |= BADCRL_FUTURE;
3270 
3271  /*
3272  * Check if certificate is revoked
3273  */
3274  if( x509parse_revoked(crt, crl_list) )
3275  {
3276  flags |= BADCERT_REVOKED;
3277  break;
3278  }
3279 
3280  crl_list = crl_list->next;
3281  }
3282  return flags;
3283 }
3284 
3285 // Equal == 0, inequal == 1
3286 static int x509_name_cmp( const void *s1, const void *s2, size_t len )
3287 {
3288  size_t i;
3289  unsigned char diff;
3290  const unsigned char *n1 = s1, *n2 = s2;
3291 
3292  for( i = 0; i < len; i++ )
3293  {
3294  diff = n1[i] ^ n2[i];
3295 
3296  if( diff == 0 )
3297  continue;
3298 
3299  if( diff == 32 &&
3300  ( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
3301  ( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
3302  {
3303  continue;
3304  }
3305 
3306  return( 1 );
3307  }
3308 
3309  return( 0 );
3310 }
3311 
3312 static int x509_wildcard_verify( const char *cn, x509_buf *name )
3313 {
3314  size_t i;
3315  size_t cn_idx = 0;
3316 
3317  if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
3318  return( 0 );
3319 
3320  for( i = 0; i < strlen( cn ); ++i )
3321  {
3322  if( cn[i] == '.' )
3323  {
3324  cn_idx = i;
3325  break;
3326  }
3327  }
3328 
3329  if( cn_idx == 0 )
3330  return( 0 );
3331 
3332  if( strlen( cn ) - cn_idx == name->len - 1 &&
3333  x509_name_cmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
3334  {
3335  return( 1 );
3336  }
3337 
3338  return( 0 );
3339 }
3340 
3341 static int x509parse_verify_top(
3342  x509_cert *child, x509_cert *trust_ca,
3343  x509_crl *ca_crl, int path_cnt, int *flags,
3344  int (*f_vrfy)(void *, x509_cert *, int, int *),
3345  void *p_vrfy )
3346 {
3347  int hash_id, ret;
3348  int ca_flags = 0, check_path_cnt = path_cnt + 1;
3349  unsigned char hash[64];
3350 
3351  if( x509parse_time_expired( &child->valid_to ) )
3352  *flags |= BADCERT_EXPIRED;
3353 
3354  if( x509parse_time_future( &child->valid_from ) )
3355  *flags |= BADCERT_FUTURE;
3356 
3357  /*
3358  * Child is the top of the chain. Check against the trust_ca list.
3359  */
3360  *flags |= BADCERT_NOT_TRUSTED;
3361 
3362  while( trust_ca != NULL )
3363  {
3364  if( trust_ca->version == 0 ||
3365  child->issuer_raw.len != trust_ca->subject_raw.len ||
3366  memcmp( child->issuer_raw.p, trust_ca->subject_raw.p,
3367  child->issuer_raw.len ) != 0 )
3368  {
3369  trust_ca = trust_ca->next;
3370  continue;
3371  }
3372 
3373  /*
3374  * Reduce path_len to check against if top of the chain is
3375  * the same as the trusted CA
3376  */
3377  if( child->subject_raw.len == trust_ca->subject_raw.len &&
3378  memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
3379  child->issuer_raw.len ) == 0 )
3380  {
3381  check_path_cnt--;
3382  }
3383 
3384  if( trust_ca->max_pathlen > 0 &&
3385  trust_ca->max_pathlen < check_path_cnt )
3386  {
3387  trust_ca = trust_ca->next;
3388  continue;
3389  }
3390 
3391  hash_id = child->sig_alg;
3392 
3393  x509_hash( child->tbs.p, child->tbs.len, hash_id, hash );
3394 
3395  if( rsa_pkcs1_verify( &trust_ca->rsa, NULL, NULL, RSA_PUBLIC, hash_id,
3396  0, hash, child->sig.p ) != 0 )
3397  {
3398  trust_ca = trust_ca->next;
3399  continue;
3400  }
3401 
3402  /*
3403  * Top of chain is signed by a trusted CA
3404  */
3405  *flags &= ~BADCERT_NOT_TRUSTED;
3406  break;
3407  }
3408 
3409  /*
3410  * If top of chain is not the same as the trusted CA send a verify request
3411  * to the callback for any issues with validity and CRL presence for the
3412  * trusted CA certificate.
3413  */
3414  if( trust_ca != NULL &&
3415  ( child->subject_raw.len != trust_ca->subject_raw.len ||
3416  memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
3417  child->issuer_raw.len ) != 0 ) )
3418  {
3419  /* Check trusted CA's CRL for then chain's top crt */
3420  *flags |= x509parse_verifycrl( child, trust_ca, ca_crl );
3421 
3422  if( x509parse_time_expired( &trust_ca->valid_to ) )
3423  ca_flags |= BADCERT_EXPIRED;
3424 
3425  if( x509parse_time_future( &trust_ca->valid_from ) )
3426  ca_flags |= BADCERT_FUTURE;
3427 
3428  if( NULL != f_vrfy )
3429  {
3430  if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1, &ca_flags ) ) != 0 )
3431  return( ret );
3432  }
3433  }
3434 
3435  /* Call callback on top cert */
3436  if( NULL != f_vrfy )
3437  {
3438  if( ( ret = f_vrfy(p_vrfy, child, path_cnt, flags ) ) != 0 )
3439  return( ret );
3440  }
3441 
3442  *flags |= ca_flags;
3443 
3444  return( 0 );
3445 }
3446 
3447 static int x509parse_verify_child(
3448  x509_cert *child, x509_cert *parent, x509_cert *trust_ca,
3449  x509_crl *ca_crl, int path_cnt, int *flags,
3450  int (*f_vrfy)(void *, x509_cert *, int, int *),
3451  void *p_vrfy )
3452 {
3453  int hash_id, ret;
3454  int parent_flags = 0;
3455  unsigned char hash[64];
3456  x509_cert *grandparent;
3457 
3458  if( x509parse_time_expired( &child->valid_to ) )
3459  *flags |= BADCERT_EXPIRED;
3460 
3461  if( x509parse_time_future( &child->valid_from ) )
3462  *flags |= BADCERT_FUTURE;
3463 
3464  hash_id = child->sig_alg;
3465 
3466  x509_hash( child->tbs.p, child->tbs.len, hash_id, hash );
3467 
3468  if( rsa_pkcs1_verify( &parent->rsa, NULL, NULL, RSA_PUBLIC, hash_id, 0,
3469  hash, child->sig.p ) != 0 )
3470  *flags |= BADCERT_NOT_TRUSTED;
3471 
3472  /* Check trusted CA's CRL for the given crt */
3473  *flags |= x509parse_verifycrl(child, parent, ca_crl);
3474 
3475  grandparent = parent->next;
3476 
3477  while( grandparent != NULL )
3478  {
3479  if( grandparent->version == 0 ||
3480  grandparent->ca_istrue == 0 ||
3481  parent->issuer_raw.len != grandparent->subject_raw.len ||
3482  memcmp( parent->issuer_raw.p, grandparent->subject_raw.p,
3483  parent->issuer_raw.len ) != 0 )
3484  {
3485  grandparent = grandparent->next;
3486  continue;
3487  }
3488  break;
3489  }
3490 
3491  if( grandparent != NULL )
3492  {
3493  /*
3494  * Part of the chain
3495  */
3496  ret = x509parse_verify_child( parent, grandparent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy );
3497  if( ret != 0 )
3498  return( ret );
3499  }
3500  else
3501  {
3502  ret = x509parse_verify_top( parent, trust_ca, ca_crl, path_cnt + 1, &parent_flags, f_vrfy, p_vrfy );
3503  if( ret != 0 )
3504  return( ret );
3505  }
3506 
3507  /* child is verified to be a child of the parent, call verify callback */
3508  if( NULL != f_vrfy )
3509  if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
3510  return( ret );
3511 
3512  *flags |= parent_flags;
3513 
3514  return( 0 );
3515 }
3516 
3517 /*
3518  * Verify the certificate validity
3519  */
3520 int x509parse_verify( x509_cert *crt,
3521  x509_cert *trust_ca,
3522  x509_crl *ca_crl,
3523  const char *cn, int *flags,
3524  int (*f_vrfy)(void *, x509_cert *, int, int *),
3525  void *p_vrfy )
3526 {
3527  size_t cn_len;
3528  int ret;
3529  int pathlen = 0;
3530  x509_cert *parent;
3531  x509_name *name;
3532  x509_sequence *cur = NULL;
3533 
3534  *flags = 0;
3535 
3536  if( cn != NULL )
3537  {
3538  name = &crt->subject;
3539  cn_len = strlen( cn );
3540 
3541  if( crt->ext_types & EXT_SUBJECT_ALT_NAME )
3542  {
3543  cur = &crt->subject_alt_names;
3544 
3545  while( cur != NULL )
3546  {
3547  if( cur->buf.len == cn_len &&
3548  x509_name_cmp( cn, cur->buf.p, cn_len ) == 0 )
3549  break;
3550 
3551  if( cur->buf.len > 2 &&
3552  memcmp( cur->buf.p, "*.", 2 ) == 0 &&
3553  x509_wildcard_verify( cn, &cur->buf ) )
3554  break;
3555 
3556  cur = cur->next;
3557  }
3558 
3559  if( cur == NULL )
3560  *flags |= BADCERT_CN_MISMATCH;
3561  }
3562  else
3563  {
3564  while( name != NULL )
3565  {
3566  if( name->oid.len == 3 &&
3567  memcmp( name->oid.p, OID_CN, 3 ) == 0 )
3568  {
3569  if( name->val.len == cn_len &&
3570  x509_name_cmp( name->val.p, cn, cn_len ) == 0 )
3571  break;
3572 
3573  if( name->val.len > 2 &&
3574  memcmp( name->val.p, "*.", 2 ) == 0 &&
3575  x509_wildcard_verify( cn, &name->val ) )
3576  break;
3577  }
3578 
3579  name = name->next;
3580  }
3581 
3582  if( name == NULL )
3583  *flags |= BADCERT_CN_MISMATCH;
3584  }
3585  }
3586 
3587  /*
3588  * Iterate upwards in the given cert chain, to find our crt parent.
3589  * Ignore any upper cert with CA != TRUE.
3590  */
3591  parent = crt->next;
3592 
3593  while( parent != NULL && parent->version != 0 )
3594  {
3595  if( parent->ca_istrue == 0 ||
3596  crt->issuer_raw.len != parent->subject_raw.len ||
3597  memcmp( crt->issuer_raw.p, parent->subject_raw.p,
3598  crt->issuer_raw.len ) != 0 )
3599  {
3600  parent = parent->next;
3601  continue;
3602  }
3603  break;
3604  }
3605 
3606  if( parent != NULL )
3607  {
3608  /*
3609  * Part of the chain
3610  */
3611  ret = x509parse_verify_child( crt, parent, trust_ca, ca_crl, pathlen, flags, f_vrfy, p_vrfy );
3612  if( ret != 0 )
3613  return( ret );
3614  }
3615  else
3616  {
3617  ret = x509parse_verify_top( crt, trust_ca, ca_crl, pathlen, flags, f_vrfy, p_vrfy );
3618  if( ret != 0 )
3619  return( ret );
3620  }
3621 
3622  if( *flags != 0 )
3624 
3625  return( 0 );
3626 }
3627 
3628 /*
3629  * Unallocate all certificate data
3630  */
3631 void x509_free( x509_cert *crt )
3632 {
3633  x509_cert *cert_cur = crt;
3634  x509_cert *cert_prv;
3635  x509_name *name_cur;
3636  x509_name *name_prv;
3637  x509_sequence *seq_cur;
3638  x509_sequence *seq_prv;
3639 
3640  if( crt == NULL )
3641  return;
3642 
3643  do
3644  {
3645  rsa_free( &cert_cur->rsa );
3646 
3647  name_cur = cert_cur->issuer.next;
3648  while( name_cur != NULL )
3649  {
3650  name_prv = name_cur;
3651  name_cur = name_cur->next;
3652  memset( name_prv, 0, sizeof( x509_name ) );
3653  free( name_prv );
3654  }
3655 
3656  name_cur = cert_cur->subject.next;
3657  while( name_cur != NULL )
3658  {
3659  name_prv = name_cur;
3660  name_cur = name_cur->next;
3661  memset( name_prv, 0, sizeof( x509_name ) );
3662  free( name_prv );
3663  }
3664 
3665  seq_cur = cert_cur->ext_key_usage.next;
3666  while( seq_cur != NULL )
3667  {
3668  seq_prv = seq_cur;
3669  seq_cur = seq_cur->next;
3670  memset( seq_prv, 0, sizeof( x509_sequence ) );
3671  free( seq_prv );
3672  }
3673 
3674  seq_cur = cert_cur->subject_alt_names.next;
3675  while( seq_cur != NULL )
3676  {
3677  seq_prv = seq_cur;
3678  seq_cur = seq_cur->next;
3679  memset( seq_prv, 0, sizeof( x509_sequence ) );
3680  free( seq_prv );
3681  }
3682 
3683  if( cert_cur->raw.p != NULL )
3684  {
3685  memset( cert_cur->raw.p, 0, cert_cur->raw.len );
3686  free( cert_cur->raw.p );
3687  }
3688 
3689  cert_cur = cert_cur->next;
3690  }
3691  while( cert_cur != NULL );
3692 
3693  cert_cur = crt;
3694  do
3695  {
3696  cert_prv = cert_cur;
3697  cert_cur = cert_cur->next;
3698 
3699  memset( cert_prv, 0, sizeof( x509_cert ) );
3700  if( cert_prv != crt )
3701  free( cert_prv );
3702  }
3703  while( cert_cur != NULL );
3704 }
3705 
3706 /*
3707  * Unallocate all CRL data
3708  */
3709 void x509_crl_free( x509_crl *crl )
3710 {
3711  x509_crl *crl_cur = crl;
3712  x509_crl *crl_prv;
3713  x509_name *name_cur;
3714  x509_name *name_prv;
3715  x509_crl_entry *entry_cur;
3716  x509_crl_entry *entry_prv;
3717 
3718  if( crl == NULL )
3719  return;
3720 
3721  do
3722  {
3723  name_cur = crl_cur->issuer.next;
3724  while( name_cur != NULL )
3725  {
3726  name_prv = name_cur;
3727  name_cur = name_cur->next;
3728  memset( name_prv, 0, sizeof( x509_name ) );
3729  free( name_prv );
3730  }
3731 
3732  entry_cur = crl_cur->entry.next;
3733  while( entry_cur != NULL )
3734  {
3735  entry_prv = entry_cur;
3736  entry_cur = entry_cur->next;
3737  memset( entry_prv, 0, sizeof( x509_crl_entry ) );
3738  free( entry_prv );
3739  }
3740 
3741  if( crl_cur->raw.p != NULL )
3742  {
3743  memset( crl_cur->raw.p, 0, crl_cur->raw.len );
3744  free( crl_cur->raw.p );
3745  }
3746 
3747  crl_cur = crl_cur->next;
3748  }
3749  while( crl_cur != NULL );
3750 
3751  crl_cur = crl;
3752  do
3753  {
3754  crl_prv = crl_cur;
3755  crl_cur = crl_cur->next;
3756 
3757  memset( crl_prv, 0, sizeof( x509_crl ) );
3758  if( crl_prv != crl )
3759  free( crl_prv );
3760  }
3761  while( crl_cur != NULL );
3762 }
3763 
3764 #if defined(POLARSSL_SELF_TEST)
3765 
3766 #include "polarssl/certs.h"
3767 
3768 /*
3769  * Checkup routine
3770  */
3771 int x509_self_test( int verbose )
3772 {
3773 #if defined(POLARSSL_CERTS_C) && defined(POLARSSL_MD5_C)
3774  int ret;
3775  int flags;
3776  size_t i, j;
3777  x509_cert cacert;
3778  x509_cert clicert;
3779  rsa_context rsa;
3780 #if defined(POLARSSL_DHM_C)
3781  dhm_context dhm;
3782 #endif
3783 
3784  if( verbose != 0 )
3785  printf( " X.509 certificate load: " );
3786 
3787  memset( &clicert, 0, sizeof( x509_cert ) );
3788 
3789  ret = x509parse_crt( &clicert, (const unsigned char *) test_cli_crt,
3790  strlen( test_cli_crt ) );
3791  if( ret != 0 )
3792  {
3793  if( verbose != 0 )
3794  printf( "failed\n" );
3795 
3796  return( ret );
3797  }
3798 
3799  memset( &cacert, 0, sizeof( x509_cert ) );
3800 
3801  ret = x509parse_crt( &cacert, (const unsigned char *) test_ca_crt,
3802  strlen( test_ca_crt ) );
3803  if( ret != 0 )
3804  {
3805  if( verbose != 0 )
3806  printf( "failed\n" );
3807 
3808  return( ret );
3809  }
3810 
3811  if( verbose != 0 )
3812  printf( "passed\n X.509 private key load: " );
3813 
3814  i = strlen( test_ca_key );
3815  j = strlen( test_ca_pwd );
3816 
3817  rsa_init( &rsa, RSA_PKCS_V15, 0 );
3818 
3819  if( ( ret = x509parse_key( &rsa,
3820  (const unsigned char *) test_ca_key, i,
3821  (const unsigned char *) test_ca_pwd, j ) ) != 0 )
3822  {
3823  if( verbose != 0 )
3824  printf( "failed\n" );
3825 
3826  return( ret );
3827  }
3828 
3829  if( verbose != 0 )
3830  printf( "passed\n X.509 signature verify: ");
3831 
3832  ret = x509parse_verify( &clicert, &cacert, NULL, "PolarSSL Client 2", &flags, NULL, NULL );
3833  if( ret != 0 )
3834  {
3835  if( verbose != 0 )
3836  printf( "failed\n" );
3837 
3838  return( ret );
3839  }
3840 
3841 #if defined(POLARSSL_DHM_C)
3842  if( verbose != 0 )
3843  printf( "passed\n X.509 DHM parameter load: " );
3844 
3845  i = strlen( test_dhm_params );
3846  j = strlen( test_ca_pwd );
3847 
3848  if( ( ret = x509parse_dhm( &dhm, (const unsigned char *) test_dhm_params, i ) ) != 0 )
3849  {
3850  if( verbose != 0 )
3851  printf( "failed\n" );
3852 
3853  return( ret );
3854  }
3855 
3856  if( verbose != 0 )
3857  printf( "passed\n\n" );
3858 #endif
3859 
3860  x509_free( &cacert );
3861  x509_free( &clicert );
3862  rsa_free( &rsa );
3863 #if defined(POLARSSL_DHM_C)
3864  dhm_free( &dhm );
3865 #endif
3866 
3867  return( 0 );
3868 #else
3869  ((void) verbose);
3871 #endif
3872 }
3873 
3874 #endif
3875 
3876 #endif