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