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