[travis] Update to current default build environment
[ipxe.git] / src / crypto / x509.c
1 /*
2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301, USA.
18 *
19 * You can also choose to distribute this program under the terms of
20 * the Unmodified Binary Distribution Licence (as given in the file
21 * COPYING.UBDL), provided that you have satisfied its requirements.
22 */
23
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <ipxe/list.h>
31 #include <ipxe/base16.h>
32 #include <ipxe/asn1.h>
33 #include <ipxe/crypto.h>
34 #include <ipxe/md5.h>
35 #include <ipxe/sha1.h>
36 #include <ipxe/sha256.h>
37 #include <ipxe/rsa.h>
38 #include <ipxe/rootcert.h>
39 #include <ipxe/certstore.h>
40 #include <ipxe/socket.h>
41 #include <ipxe/in.h>
42 #include <ipxe/image.h>
43 #include <ipxe/ocsp.h>
44 #include <ipxe/x509.h>
45 #include <config/crypto.h>
46
47 /** @file
48 *
49 * X.509 certificates
50 *
51 * The structure of X.509v3 certificates is documented in RFC 5280
52 * section 4.1.
53 */
54
55 /* Disambiguate the various error causes */
56 #define ENOTSUP_ALGORITHM \
57 __einfo_error ( EINFO_ENOTSUP_ALGORITHM )
58 #define EINFO_ENOTSUP_ALGORITHM \
59 __einfo_uniqify ( EINFO_ENOTSUP, 0x01, "Unsupported algorithm" )
60 #define ENOTSUP_EXTENSION \
61 __einfo_error ( EINFO_ENOTSUP_EXTENSION )
62 #define EINFO_ENOTSUP_EXTENSION \
63 __einfo_uniqify ( EINFO_ENOTSUP, 0x02, "Unsupported extension" )
64 #define EINVAL_ALGORITHM \
65 __einfo_error ( EINFO_EINVAL_ALGORITHM )
66 #define EINFO_EINVAL_ALGORITHM \
67 __einfo_uniqify ( EINFO_EINVAL, 0x01, "Invalid algorithm type" )
68 #define EINVAL_ALGORITHM_MISMATCH \
69 __einfo_error ( EINFO_EINVAL_ALGORITHM_MISMATCH )
70 #define EINFO_EINVAL_ALGORITHM_MISMATCH \
71 __einfo_uniqify ( EINFO_EINVAL, 0x04, "Signature algorithm mismatch" )
72 #define EINVAL_PATH_LEN \
73 __einfo_error ( EINFO_EINVAL_PATH_LEN )
74 #define EINFO_EINVAL_PATH_LEN \
75 __einfo_uniqify ( EINFO_EINVAL, 0x05, "Invalid pathLenConstraint" )
76 #define EINVAL_VERSION \
77 __einfo_error ( EINFO_EINVAL_VERSION )
78 #define EINFO_EINVAL_VERSION \
79 __einfo_uniqify ( EINFO_EINVAL, 0x06, "Invalid version" )
80 #define EACCES_WRONG_ISSUER \
81 __einfo_error ( EINFO_EACCES_WRONG_ISSUER )
82 #define EINFO_EACCES_WRONG_ISSUER \
83 __einfo_uniqify ( EINFO_EACCES, 0x01, "Wrong issuer" )
84 #define EACCES_NOT_CA \
85 __einfo_error ( EINFO_EACCES_NOT_CA )
86 #define EINFO_EACCES_NOT_CA \
87 __einfo_uniqify ( EINFO_EACCES, 0x02, "Not a CA certificate" )
88 #define EACCES_KEY_USAGE \
89 __einfo_error ( EINFO_EACCES_KEY_USAGE )
90 #define EINFO_EACCES_KEY_USAGE \
91 __einfo_uniqify ( EINFO_EACCES, 0x03, "Incorrect key usage" )
92 #define EACCES_EXPIRED \
93 __einfo_error ( EINFO_EACCES_EXPIRED )
94 #define EINFO_EACCES_EXPIRED \
95 __einfo_uniqify ( EINFO_EACCES, 0x04, "Expired (or not yet valid)" )
96 #define EACCES_PATH_LEN \
97 __einfo_error ( EINFO_EACCES_PATH_LEN )
98 #define EINFO_EACCES_PATH_LEN \
99 __einfo_uniqify ( EINFO_EACCES, 0x05, "Maximum path length exceeded" )
100 #define EACCES_UNTRUSTED \
101 __einfo_error ( EINFO_EACCES_UNTRUSTED )
102 #define EINFO_EACCES_UNTRUSTED \
103 __einfo_uniqify ( EINFO_EACCES, 0x06, "Untrusted root certificate" )
104 #define EACCES_OUT_OF_ORDER \
105 __einfo_error ( EINFO_EACCES_OUT_OF_ORDER )
106 #define EINFO_EACCES_OUT_OF_ORDER \
107 __einfo_uniqify ( EINFO_EACCES, 0x07, "Validation out of order" )
108 #define EACCES_EMPTY \
109 __einfo_error ( EINFO_EACCES_EMPTY )
110 #define EINFO_EACCES_EMPTY \
111 __einfo_uniqify ( EINFO_EACCES, 0x08, "Empty certificate chain" )
112 #define EACCES_OCSP_REQUIRED \
113 __einfo_error ( EINFO_EACCES_OCSP_REQUIRED )
114 #define EINFO_EACCES_OCSP_REQUIRED \
115 __einfo_uniqify ( EINFO_EACCES, 0x09, "OCSP check required" )
116 #define EACCES_WRONG_NAME \
117 __einfo_error ( EINFO_EACCES_WRONG_NAME )
118 #define EINFO_EACCES_WRONG_NAME \
119 __einfo_uniqify ( EINFO_EACCES, 0x0a, "Incorrect certificate name" )
120 #define EACCES_USELESS \
121 __einfo_error ( EINFO_EACCES_USELESS )
122 #define EINFO_EACCES_USELESS \
123 __einfo_uniqify ( EINFO_EACCES, 0x0b, "No usable certificates" )
124
125 /**
126 * Free X.509 certificate
127 *
128 * @v refcnt Reference count
129 */
130 static void x509_free ( struct refcnt *refcnt ) {
131 struct x509_certificate *cert =
132 container_of ( refcnt, struct x509_certificate, refcnt );
133
134 x509_root_put ( cert->root );
135 free ( cert );
136 }
137
138 /**
139 * Get X.509 certificate display name
140 *
141 * @v cert X.509 certificate
142 * @ret name Display name
143 */
144 const char * x509_name ( struct x509_certificate *cert ) {
145 struct asn1_cursor *common_name = &cert->subject.common_name;
146 struct digest_algorithm *digest = &sha1_algorithm;
147 static char buf[64];
148 uint8_t fingerprint[ digest->digestsize ];
149 size_t len;
150
151 len = common_name->len;
152 if ( len ) {
153 /* Certificate has a commonName: use that */
154 if ( len > ( sizeof ( buf ) - 1 /* NUL */ ) )
155 len = ( sizeof ( buf ) - 1 /* NUL */ );
156 memcpy ( buf, common_name->data, len );
157 buf[len] = '\0';
158 } else {
159 /* Certificate has no commonName: use SHA-1 fingerprint */
160 x509_fingerprint ( cert, digest, fingerprint );
161 base16_encode ( fingerprint, sizeof ( fingerprint ),
162 buf, sizeof ( buf ) );
163 }
164 return buf;
165 }
166
167 /** "commonName" object identifier */
168 static uint8_t oid_common_name[] = { ASN1_OID_COMMON_NAME };
169
170 /** "commonName" object identifier cursor */
171 static struct asn1_cursor oid_common_name_cursor =
172 ASN1_CURSOR ( oid_common_name );
173
174 /**
175 * Parse X.509 certificate version
176 *
177 * @v cert X.509 certificate
178 * @v raw ASN.1 cursor
179 * @ret rc Return status code
180 */
181 static int x509_parse_version ( struct x509_certificate *cert,
182 const struct asn1_cursor *raw ) {
183 struct asn1_cursor cursor;
184 int version;
185 int rc;
186
187 /* Enter version */
188 memcpy ( &cursor, raw, sizeof ( cursor ) );
189 asn1_enter ( &cursor, ASN1_EXPLICIT_TAG ( 0 ) );
190
191 /* Parse integer */
192 if ( ( rc = asn1_integer ( &cursor, &version ) ) != 0 ) {
193 DBGC ( cert, "X509 %p cannot parse version: %s\n",
194 cert, strerror ( rc ) );
195 DBGC_HDA ( cert, 0, raw->data, raw->len );
196 return rc;
197 }
198
199 /* Sanity check */
200 if ( version < 0 ) {
201 DBGC ( cert, "X509 %p invalid version %d\n", cert, version );
202 DBGC_HDA ( cert, 0, raw->data, raw->len );
203 return -EINVAL_VERSION;
204 }
205
206 /* Record version */
207 cert->version = version;
208 DBGC2 ( cert, "X509 %p is a version %d certificate\n",
209 cert, ( cert->version + 1 ) );
210
211 return 0;
212 }
213
214 /**
215 * Parse X.509 certificate serial number
216 *
217 * @v cert X.509 certificate
218 * @v raw ASN.1 cursor
219 * @ret rc Return status code
220 */
221 static int x509_parse_serial ( struct x509_certificate *cert,
222 const struct asn1_cursor *raw ) {
223 struct x509_serial *serial = &cert->serial;
224 int rc;
225
226 /* Record raw serial number */
227 memcpy ( &serial->raw, raw, sizeof ( serial->raw ) );
228 if ( ( rc = asn1_shrink ( &serial->raw, ASN1_INTEGER ) ) != 0 ) {
229 DBGC ( cert, "X509 %p cannot shrink serialNumber: %s\n",
230 cert, strerror ( rc ) );
231 return rc;
232 }
233 DBGC2 ( cert, "X509 %p issuer is:\n", cert );
234 DBGC2_HDA ( cert, 0, serial->raw.data, serial->raw.len );
235
236 return 0;
237 }
238
239 /**
240 * Parse X.509 certificate issuer
241 *
242 * @v cert X.509 certificate
243 * @v raw ASN.1 cursor
244 * @ret rc Return status code
245 */
246 static int x509_parse_issuer ( struct x509_certificate *cert,
247 const struct asn1_cursor *raw ) {
248 struct x509_issuer *issuer = &cert->issuer;
249 int rc;
250
251 /* Record raw issuer */
252 memcpy ( &issuer->raw, raw, sizeof ( issuer->raw ) );
253 if ( ( rc = asn1_shrink ( &issuer->raw, ASN1_SEQUENCE ) ) != 0 ) {
254 DBGC ( cert, "X509 %p cannot shrink issuer: %s\n",
255 cert, strerror ( rc ) );
256 return rc;
257 }
258 DBGC2 ( cert, "X509 %p issuer is:\n", cert );
259 DBGC2_HDA ( cert, 0, issuer->raw.data, issuer->raw.len );
260
261 return 0;
262 }
263
264 /**
265 * Parse X.509 certificate validity
266 *
267 * @v cert X.509 certificate
268 * @v raw ASN.1 cursor
269 * @ret rc Return status code
270 */
271 static int x509_parse_validity ( struct x509_certificate *cert,
272 const struct asn1_cursor *raw ) {
273 struct x509_validity *validity = &cert->validity;
274 struct x509_time *not_before = &validity->not_before;
275 struct x509_time *not_after = &validity->not_after;
276 struct asn1_cursor cursor;
277 int rc;
278
279 /* Enter validity */
280 memcpy ( &cursor, raw, sizeof ( cursor ) );
281 asn1_enter ( &cursor, ASN1_SEQUENCE );
282
283 /* Parse notBefore */
284 if ( ( rc = asn1_generalized_time ( &cursor,
285 &not_before->time ) ) != 0 ) {
286 DBGC ( cert, "X509 %p cannot parse notBefore: %s\n",
287 cert, strerror ( rc ) );
288 return rc;
289 }
290 DBGC2 ( cert, "X509 %p valid from time %lld\n",
291 cert, not_before->time );
292 asn1_skip_any ( &cursor );
293
294 /* Parse notAfter */
295 if ( ( rc = asn1_generalized_time ( &cursor,
296 &not_after->time ) ) != 0 ) {
297 DBGC ( cert, "X509 %p cannot parse notAfter: %s\n",
298 cert, strerror ( rc ) );
299 return rc;
300 }
301 DBGC2 ( cert, "X509 %p valid until time %lld\n",
302 cert, not_after->time );
303
304 return 0;
305 }
306
307 /**
308 * Parse X.509 certificate common name
309 *
310 * @v cert X.509 certificate
311 * @v raw ASN.1 cursor
312 * @ret rc Return status code
313 */
314 static int x509_parse_common_name ( struct x509_certificate *cert,
315 const struct asn1_cursor *raw ) {
316 struct asn1_cursor cursor;
317 struct asn1_cursor oid_cursor;
318 struct asn1_cursor name_cursor;
319 int rc;
320
321 /* Enter name */
322 memcpy ( &cursor, raw, sizeof ( cursor ) );
323 asn1_enter ( &cursor, ASN1_SEQUENCE );
324
325 /* Scan through name list */
326 for ( ; cursor.len ; asn1_skip_any ( &cursor ) ) {
327
328 /* Check for "commonName" OID */
329 memcpy ( &oid_cursor, &cursor, sizeof ( oid_cursor ) );
330 asn1_enter ( &oid_cursor, ASN1_SET );
331 asn1_enter ( &oid_cursor, ASN1_SEQUENCE );
332 memcpy ( &name_cursor, &oid_cursor, sizeof ( name_cursor ) );
333 asn1_enter ( &oid_cursor, ASN1_OID );
334 if ( asn1_compare ( &oid_common_name_cursor, &oid_cursor ) != 0)
335 continue;
336 asn1_skip_any ( &name_cursor );
337 if ( ( rc = asn1_enter_any ( &name_cursor ) ) != 0 ) {
338 DBGC ( cert, "X509 %p cannot locate name:\n", cert );
339 DBGC_HDA ( cert, 0, raw->data, raw->len );
340 return rc;
341 }
342
343 /* Record common name */
344 memcpy ( &cert->subject.common_name, &name_cursor,
345 sizeof ( cert->subject.common_name ) );
346
347 return 0;
348 }
349
350 /* Certificates may not have a commonName */
351 DBGC2 ( cert, "X509 %p no commonName found:\n", cert );
352 return 0;
353 }
354
355 /**
356 * Parse X.509 certificate subject
357 *
358 * @v cert X.509 certificate
359 * @v raw ASN.1 cursor
360 * @ret rc Return status code
361 */
362 static int x509_parse_subject ( struct x509_certificate *cert,
363 const struct asn1_cursor *raw ) {
364 struct x509_subject *subject = &cert->subject;
365 int rc;
366
367 /* Record raw subject */
368 memcpy ( &subject->raw, raw, sizeof ( subject->raw ) );
369 asn1_shrink_any ( &subject->raw );
370 DBGC2 ( cert, "X509 %p subject is:\n", cert );
371 DBGC2_HDA ( cert, 0, subject->raw.data, subject->raw.len );
372
373 /* Parse common name */
374 if ( ( rc = x509_parse_common_name ( cert, raw ) ) != 0 )
375 return rc;
376 DBGC2 ( cert, "X509 %p common name is \"%s\":\n", cert,
377 x509_name ( cert ) );
378
379 return 0;
380 }
381
382 /**
383 * Parse X.509 certificate public key information
384 *
385 * @v cert X.509 certificate
386 * @v raw ASN.1 cursor
387 * @ret rc Return status code
388 */
389 static int x509_parse_public_key ( struct x509_certificate *cert,
390 const struct asn1_cursor *raw ) {
391 struct x509_public_key *public_key = &cert->subject.public_key;
392 struct asn1_algorithm **algorithm = &public_key->algorithm;
393 struct asn1_bit_string *raw_bits = &public_key->raw_bits;
394 struct asn1_cursor cursor;
395 int rc;
396
397 /* Record raw subjectPublicKeyInfo */
398 memcpy ( &cursor, raw, sizeof ( cursor ) );
399 asn1_shrink_any ( &cursor );
400 memcpy ( &public_key->raw, &cursor, sizeof ( public_key->raw ) );
401 DBGC2 ( cert, "X509 %p public key is:\n", cert );
402 DBGC2_HDA ( cert, 0, public_key->raw.data, public_key->raw.len );
403
404 /* Enter subjectPublicKeyInfo */
405 asn1_enter ( &cursor, ASN1_SEQUENCE );
406
407 /* Parse algorithm */
408 if ( ( rc = asn1_pubkey_algorithm ( &cursor, algorithm ) ) != 0 ) {
409 DBGC ( cert, "X509 %p could not parse public key algorithm: "
410 "%s\n", cert, strerror ( rc ) );
411 return rc;
412 }
413 DBGC2 ( cert, "X509 %p public key algorithm is %s\n",
414 cert, (*algorithm)->name );
415 asn1_skip_any ( &cursor );
416
417 /* Parse bit string */
418 if ( ( rc = asn1_bit_string ( &cursor, raw_bits ) ) != 0 ) {
419 DBGC ( cert, "X509 %p could not parse public key bits: %s\n",
420 cert, strerror ( rc ) );
421 return rc;
422 }
423
424 return 0;
425 }
426
427 /**
428 * Parse X.509 certificate basic constraints
429 *
430 * @v cert X.509 certificate
431 * @v raw ASN.1 cursor
432 * @ret rc Return status code
433 */
434 static int x509_parse_basic_constraints ( struct x509_certificate *cert,
435 const struct asn1_cursor *raw ) {
436 struct x509_basic_constraints *basic = &cert->extensions.basic;
437 struct asn1_cursor cursor;
438 int ca = 0;
439 int path_len;
440 int rc;
441
442 /* Enter basicConstraints */
443 memcpy ( &cursor, raw, sizeof ( cursor ) );
444 asn1_enter ( &cursor, ASN1_SEQUENCE );
445
446 /* Parse "cA", if present */
447 if ( asn1_type ( &cursor ) == ASN1_BOOLEAN ) {
448 ca = asn1_boolean ( &cursor );
449 if ( ca < 0 ) {
450 rc = ca;
451 DBGC ( cert, "X509 %p cannot parse cA: %s\n",
452 cert, strerror ( rc ) );
453 DBGC_HDA ( cert, 0, raw->data, raw->len );
454 return rc;
455 }
456 asn1_skip_any ( &cursor );
457 }
458 basic->ca = ca;
459 DBGC2 ( cert, "X509 %p is %sa CA certificate\n",
460 cert, ( basic->ca ? "" : "not " ) );
461
462 /* Ignore everything else unless "cA" is true */
463 if ( ! ca )
464 return 0;
465
466 /* Parse "pathLenConstraint", if present and applicable */
467 basic->path_len = X509_PATH_LEN_UNLIMITED;
468 if ( asn1_type ( &cursor ) == ASN1_INTEGER ) {
469 if ( ( rc = asn1_integer ( &cursor, &path_len ) ) != 0 ) {
470 DBGC ( cert, "X509 %p cannot parse pathLenConstraint: "
471 "%s\n", cert, strerror ( rc ) );
472 DBGC_HDA ( cert, 0, raw->data, raw->len );
473 return rc;
474 }
475 if ( path_len < 0 ) {
476 DBGC ( cert, "X509 %p invalid pathLenConstraint %d\n",
477 cert, path_len );
478 DBGC_HDA ( cert, 0, raw->data, raw->len );
479 return -EINVAL;
480 }
481 basic->path_len = path_len;
482 DBGC2 ( cert, "X509 %p path length constraint is %d\n",
483 cert, basic->path_len );
484 }
485
486 return 0;
487 }
488
489 /**
490 * Parse X.509 certificate key usage
491 *
492 * @v cert X.509 certificate
493 * @v raw ASN.1 cursor
494 * @ret rc Return status code
495 */
496 static int x509_parse_key_usage ( struct x509_certificate *cert,
497 const struct asn1_cursor *raw ) {
498 struct x509_key_usage *usage = &cert->extensions.usage;
499 struct asn1_bit_string bit_string;
500 const uint8_t *bytes;
501 size_t len;
502 unsigned int i;
503 int rc;
504
505 /* Mark extension as present */
506 usage->present = 1;
507
508 /* Parse bit string */
509 if ( ( rc = asn1_bit_string ( raw, &bit_string ) ) != 0 ) {
510 DBGC ( cert, "X509 %p could not parse key usage: %s\n",
511 cert, strerror ( rc ) );
512 return rc;
513 }
514
515 /* Parse key usage bits */
516 bytes = bit_string.data;
517 len = bit_string.len;
518 if ( len > sizeof ( usage->bits ) )
519 len = sizeof ( usage->bits );
520 for ( i = 0 ; i < len ; i++ ) {
521 usage->bits |= ( *(bytes++) << ( 8 * i ) );
522 }
523 DBGC2 ( cert, "X509 %p key usage is %08x\n", cert, usage->bits );
524
525 return 0;
526 }
527
528 /** "id-kp-codeSigning" object identifier */
529 static uint8_t oid_code_signing[] = { ASN1_OID_CODESIGNING };
530
531 /** "id-kp-OCSPSigning" object identifier */
532 static uint8_t oid_ocsp_signing[] = { ASN1_OID_OCSPSIGNING };
533
534 /** Supported key purposes */
535 static struct x509_key_purpose x509_key_purposes[] = {
536 {
537 .name = "codeSigning",
538 .bits = X509_CODE_SIGNING,
539 .oid = ASN1_CURSOR ( oid_code_signing ),
540 },
541 {
542 .name = "ocspSigning",
543 .bits = X509_OCSP_SIGNING,
544 .oid = ASN1_CURSOR ( oid_ocsp_signing ),
545 },
546 };
547
548 /**
549 * Parse X.509 certificate key purpose identifier
550 *
551 * @v cert X.509 certificate
552 * @v raw ASN.1 cursor
553 * @ret rc Return status code
554 */
555 static int x509_parse_key_purpose ( struct x509_certificate *cert,
556 const struct asn1_cursor *raw ) {
557 struct x509_extended_key_usage *ext_usage = &cert->extensions.ext_usage;
558 struct x509_key_purpose *purpose;
559 struct asn1_cursor cursor;
560 unsigned int i;
561 int rc;
562
563 /* Enter keyPurposeId */
564 memcpy ( &cursor, raw, sizeof ( cursor ) );
565 if ( ( rc = asn1_enter ( &cursor, ASN1_OID ) ) != 0 ) {
566 DBGC ( cert, "X509 %p invalid keyPurposeId:\n", cert );
567 DBGC_HDA ( cert, 0, raw->data, raw->len );
568 return rc;
569 }
570
571 /* Identify key purpose */
572 for ( i = 0 ; i < ( sizeof ( x509_key_purposes ) /
573 sizeof ( x509_key_purposes[0] ) ) ; i++ ) {
574 purpose = &x509_key_purposes[i];
575 if ( asn1_compare ( &cursor, &purpose->oid ) == 0 ) {
576 DBGC2 ( cert, "X509 %p has key purpose %s\n",
577 cert, purpose->name );
578 ext_usage->bits |= purpose->bits;
579 return 0;
580 }
581 }
582
583 /* Ignore unrecognised key purposes */
584 return 0;
585 }
586
587 /**
588 * Parse X.509 certificate extended key usage
589 *
590 * @v cert X.509 certificate
591 * @v raw ASN.1 cursor
592 * @ret rc Return status code
593 */
594 static int x509_parse_extended_key_usage ( struct x509_certificate *cert,
595 const struct asn1_cursor *raw ) {
596 struct asn1_cursor cursor;
597 int rc;
598
599 /* Enter extKeyUsage */
600 memcpy ( &cursor, raw, sizeof ( cursor ) );
601 asn1_enter ( &cursor, ASN1_SEQUENCE );
602
603 /* Parse each extended key usage in turn */
604 while ( cursor.len ) {
605 if ( ( rc = x509_parse_key_purpose ( cert, &cursor ) ) != 0 )
606 return rc;
607 asn1_skip_any ( &cursor );
608 }
609
610 return 0;
611 }
612
613 /**
614 * Parse X.509 certificate OCSP access method
615 *
616 * @v cert X.509 certificate
617 * @v raw ASN.1 cursor
618 * @ret rc Return status code
619 */
620 static int x509_parse_ocsp ( struct x509_certificate *cert,
621 const struct asn1_cursor *raw ) {
622 struct x509_ocsp_responder *ocsp = &cert->extensions.auth_info.ocsp;
623 struct asn1_cursor *uri = &ocsp->uri;
624 int rc;
625
626 /* Enter accessLocation */
627 memcpy ( uri, raw, sizeof ( *uri ) );
628 if ( ( rc = asn1_enter ( uri, X509_GENERAL_NAME_URI ) ) != 0 ) {
629 DBGC ( cert, "X509 %p OCSP does not contain "
630 "uniformResourceIdentifier:\n", cert );
631 DBGC_HDA ( cert, 0, raw->data, raw->len );
632 return rc;
633 }
634 DBGC2 ( cert, "X509 %p OCSP URI is:\n", cert );
635 DBGC2_HDA ( cert, 0, uri->data, uri->len );
636
637 return 0;
638 }
639
640 /** "id-ad-ocsp" object identifier */
641 static uint8_t oid_ad_ocsp[] = { ASN1_OID_OCSP };
642
643 /** Supported access methods */
644 static struct x509_access_method x509_access_methods[] = {
645 {
646 .name = "OCSP",
647 .oid = ASN1_CURSOR ( oid_ad_ocsp ),
648 .parse = x509_parse_ocsp,
649 },
650 };
651
652 /**
653 * Identify X.509 access method by OID
654 *
655 * @v oid OID
656 * @ret method Access method, or NULL
657 */
658 static struct x509_access_method *
659 x509_find_access_method ( const struct asn1_cursor *oid ) {
660 struct x509_access_method *method;
661 unsigned int i;
662
663 for ( i = 0 ; i < ( sizeof ( x509_access_methods ) /
664 sizeof ( x509_access_methods[0] ) ) ; i++ ) {
665 method = &x509_access_methods[i];
666 if ( asn1_compare ( &method->oid, oid ) == 0 )
667 return method;
668 }
669
670 return NULL;
671 }
672
673 /**
674 * Parse X.509 certificate access description
675 *
676 * @v cert X.509 certificate
677 * @v raw ASN.1 cursor
678 * @ret rc Return status code
679 */
680 static int x509_parse_access_description ( struct x509_certificate *cert,
681 const struct asn1_cursor *raw ) {
682 struct asn1_cursor cursor;
683 struct asn1_cursor subcursor;
684 struct x509_access_method *method;
685 int rc;
686
687 /* Enter keyPurposeId */
688 memcpy ( &cursor, raw, sizeof ( cursor ) );
689 asn1_enter ( &cursor, ASN1_SEQUENCE );
690
691 /* Try to identify access method */
692 memcpy ( &subcursor, &cursor, sizeof ( subcursor ) );
693 asn1_enter ( &subcursor, ASN1_OID );
694 method = x509_find_access_method ( &subcursor );
695 asn1_skip_any ( &cursor );
696 DBGC2 ( cert, "X509 %p found access method %s\n",
697 cert, ( method ? method->name : "<unknown>" ) );
698
699 /* Parse access location, if applicable */
700 if ( method && ( ( rc = method->parse ( cert, &cursor ) ) != 0 ) )
701 return rc;
702
703 return 0;
704 }
705
706 /**
707 * Parse X.509 certificate authority information access
708 *
709 * @v cert X.509 certificate
710 * @v raw ASN.1 cursor
711 * @ret rc Return status code
712 */
713 static int x509_parse_authority_info_access ( struct x509_certificate *cert,
714 const struct asn1_cursor *raw ) {
715 struct asn1_cursor cursor;
716 int rc;
717
718 /* Enter authorityInfoAccess */
719 memcpy ( &cursor, raw, sizeof ( cursor ) );
720 asn1_enter ( &cursor, ASN1_SEQUENCE );
721
722 /* Parse each access description in turn */
723 while ( cursor.len ) {
724 if ( ( rc = x509_parse_access_description ( cert,
725 &cursor ) ) != 0 )
726 return rc;
727 asn1_skip_any ( &cursor );
728 }
729
730 return 0;
731 }
732
733 /**
734 * Parse X.509 certificate subject alternative name
735 *
736 * @v cert X.509 certificate
737 * @v raw ASN.1 cursor
738 * @ret rc Return status code
739 */
740 static int x509_parse_subject_alt_name ( struct x509_certificate *cert,
741 const struct asn1_cursor *raw ) {
742 struct x509_subject_alt_name *alt_name = &cert->extensions.alt_name;
743 struct asn1_cursor *names = &alt_name->names;
744 int rc;
745
746 /* Enter subjectAltName */
747 memcpy ( names, raw, sizeof ( *names ) );
748 if ( ( rc = asn1_enter ( names, ASN1_SEQUENCE ) ) != 0 ) {
749 DBGC ( cert, "X509 %p invalid subjectAltName: %s\n",
750 cert, strerror ( rc ) );
751 DBGC_HDA ( cert, 0, raw->data, raw->len );
752 return rc;
753 }
754 DBGC2 ( cert, "X509 %p has subjectAltName:\n", cert );
755 DBGC2_HDA ( cert, 0, names->data, names->len );
756
757 return 0;
758 }
759
760 /** "id-ce-basicConstraints" object identifier */
761 static uint8_t oid_ce_basic_constraints[] =
762 { ASN1_OID_BASICCONSTRAINTS };
763
764 /** "id-ce-keyUsage" object identifier */
765 static uint8_t oid_ce_key_usage[] =
766 { ASN1_OID_KEYUSAGE };
767
768 /** "id-ce-extKeyUsage" object identifier */
769 static uint8_t oid_ce_ext_key_usage[] =
770 { ASN1_OID_EXTKEYUSAGE };
771
772 /** "id-pe-authorityInfoAccess" object identifier */
773 static uint8_t oid_pe_authority_info_access[] =
774 { ASN1_OID_AUTHORITYINFOACCESS };
775
776 /** "id-ce-subjectAltName" object identifier */
777 static uint8_t oid_ce_subject_alt_name[] =
778 { ASN1_OID_SUBJECTALTNAME };
779
780 /** Supported certificate extensions */
781 static struct x509_extension x509_extensions[] = {
782 {
783 .name = "basicConstraints",
784 .oid = ASN1_CURSOR ( oid_ce_basic_constraints ),
785 .parse = x509_parse_basic_constraints,
786 },
787 {
788 .name = "keyUsage",
789 .oid = ASN1_CURSOR ( oid_ce_key_usage ),
790 .parse = x509_parse_key_usage,
791 },
792 {
793 .name = "extKeyUsage",
794 .oid = ASN1_CURSOR ( oid_ce_ext_key_usage ),
795 .parse = x509_parse_extended_key_usage,
796 },
797 {
798 .name = "authorityInfoAccess",
799 .oid = ASN1_CURSOR ( oid_pe_authority_info_access ),
800 .parse = x509_parse_authority_info_access,
801 },
802 {
803 .name = "subjectAltName",
804 .oid = ASN1_CURSOR ( oid_ce_subject_alt_name ),
805 .parse = x509_parse_subject_alt_name,
806 },
807 };
808
809 /**
810 * Identify X.509 extension by OID
811 *
812 * @v oid OID
813 * @ret extension Extension, or NULL
814 */
815 static struct x509_extension *
816 x509_find_extension ( const struct asn1_cursor *oid ) {
817 struct x509_extension *extension;
818 unsigned int i;
819
820 for ( i = 0 ; i < ( sizeof ( x509_extensions ) /
821 sizeof ( x509_extensions[0] ) ) ; i++ ) {
822 extension = &x509_extensions[i];
823 if ( asn1_compare ( &extension->oid, oid ) == 0 )
824 return extension;
825 }
826
827 return NULL;
828 }
829
830 /**
831 * Parse X.509 certificate extension
832 *
833 * @v cert X.509 certificate
834 * @v raw ASN.1 cursor
835 * @ret rc Return status code
836 */
837 static int x509_parse_extension ( struct x509_certificate *cert,
838 const struct asn1_cursor *raw ) {
839 struct asn1_cursor cursor;
840 struct asn1_cursor subcursor;
841 struct x509_extension *extension;
842 int is_critical = 0;
843 int rc;
844
845 /* Enter extension */
846 memcpy ( &cursor, raw, sizeof ( cursor ) );
847 asn1_enter ( &cursor, ASN1_SEQUENCE );
848
849 /* Try to identify extension */
850 memcpy ( &subcursor, &cursor, sizeof ( subcursor ) );
851 asn1_enter ( &subcursor, ASN1_OID );
852 extension = x509_find_extension ( &subcursor );
853 asn1_skip_any ( &cursor );
854 DBGC2 ( cert, "X509 %p found extension %s\n",
855 cert, ( extension ? extension->name : "<unknown>" ) );
856
857 /* Identify criticality */
858 if ( asn1_type ( &cursor ) == ASN1_BOOLEAN ) {
859 is_critical = asn1_boolean ( &cursor );
860 if ( is_critical < 0 ) {
861 rc = is_critical;
862 DBGC ( cert, "X509 %p cannot parse extension "
863 "criticality: %s\n", cert, strerror ( rc ) );
864 DBGC_HDA ( cert, 0, raw->data, raw->len );
865 return rc;
866 }
867 asn1_skip_any ( &cursor );
868 }
869
870 /* Handle unknown extensions */
871 if ( ! extension ) {
872 if ( is_critical ) {
873 /* Fail if we cannot handle a critical extension */
874 DBGC ( cert, "X509 %p cannot handle critical "
875 "extension:\n", cert );
876 DBGC_HDA ( cert, 0, raw->data, raw->len );
877 return -ENOTSUP_EXTENSION;
878 } else {
879 /* Ignore unknown non-critical extensions */
880 return 0;
881 }
882 };
883
884 /* Extract extnValue */
885 if ( ( rc = asn1_enter ( &cursor, ASN1_OCTET_STRING ) ) != 0 ) {
886 DBGC ( cert, "X509 %p extension missing extnValue:\n", cert );
887 DBGC_HDA ( cert, 0, raw->data, raw->len );
888 return rc;
889 }
890
891 /* Parse extension */
892 if ( ( rc = extension->parse ( cert, &cursor ) ) != 0 )
893 return rc;
894
895 return 0;
896 }
897
898 /**
899 * Parse X.509 certificate extensions, if present
900 *
901 * @v cert X.509 certificate
902 * @v raw ASN.1 cursor
903 * @ret rc Return status code
904 */
905 static int x509_parse_extensions ( struct x509_certificate *cert,
906 const struct asn1_cursor *raw ) {
907 struct asn1_cursor cursor;
908 int rc;
909
910 /* Enter extensions, if present */
911 memcpy ( &cursor, raw, sizeof ( cursor ) );
912 asn1_enter ( &cursor, ASN1_EXPLICIT_TAG ( 3 ) );
913 asn1_enter ( &cursor, ASN1_SEQUENCE );
914
915 /* Parse each extension in turn */
916 while ( cursor.len ) {
917 if ( ( rc = x509_parse_extension ( cert, &cursor ) ) != 0 )
918 return rc;
919 asn1_skip_any ( &cursor );
920 }
921
922 return 0;
923 }
924
925 /**
926 * Parse X.509 certificate tbsCertificate
927 *
928 * @v cert X.509 certificate
929 * @v raw ASN.1 cursor
930 * @ret rc Return status code
931 */
932 static int x509_parse_tbscertificate ( struct x509_certificate *cert,
933 const struct asn1_cursor *raw ) {
934 struct asn1_algorithm **algorithm = &cert->signature_algorithm;
935 struct asn1_cursor cursor;
936 int rc;
937
938 /* Record raw tbsCertificate */
939 memcpy ( &cursor, raw, sizeof ( cursor ) );
940 asn1_shrink_any ( &cursor );
941 memcpy ( &cert->tbs, &cursor, sizeof ( cert->tbs ) );
942
943 /* Enter tbsCertificate */
944 asn1_enter ( &cursor, ASN1_SEQUENCE );
945
946 /* Parse version, if present */
947 if ( asn1_type ( &cursor ) == ASN1_EXPLICIT_TAG ( 0 ) ) {
948 if ( ( rc = x509_parse_version ( cert, &cursor ) ) != 0 )
949 return rc;
950 asn1_skip_any ( &cursor );
951 }
952
953 /* Parse serialNumber */
954 if ( ( rc = x509_parse_serial ( cert, &cursor ) ) != 0 )
955 return rc;
956 asn1_skip_any ( &cursor );
957
958 /* Parse signature */
959 if ( ( rc = asn1_signature_algorithm ( &cursor, algorithm ) ) != 0 ) {
960 DBGC ( cert, "X509 %p could not parse signature algorithm: "
961 "%s\n", cert, strerror ( rc ) );
962 return rc;
963 }
964 DBGC2 ( cert, "X509 %p tbsCertificate signature algorithm is %s\n",
965 cert, (*algorithm)->name );
966 asn1_skip_any ( &cursor );
967
968 /* Parse issuer */
969 if ( ( rc = x509_parse_issuer ( cert, &cursor ) ) != 0 )
970 return rc;
971 asn1_skip_any ( &cursor );
972
973 /* Parse validity */
974 if ( ( rc = x509_parse_validity ( cert, &cursor ) ) != 0 )
975 return rc;
976 asn1_skip_any ( &cursor );
977
978 /* Parse subject */
979 if ( ( rc = x509_parse_subject ( cert, &cursor ) ) != 0 )
980 return rc;
981 asn1_skip_any ( &cursor );
982
983 /* Parse subjectPublicKeyInfo */
984 if ( ( rc = x509_parse_public_key ( cert, &cursor ) ) != 0 )
985 return rc;
986 asn1_skip_any ( &cursor );
987
988 /* Parse extensions, if present */
989 if ( ( rc = x509_parse_extensions ( cert, &cursor ) ) != 0 )
990 return rc;
991
992 return 0;
993 }
994
995 /**
996 * Parse X.509 certificate from ASN.1 data
997 *
998 * @v cert X.509 certificate
999 * @v raw ASN.1 cursor
1000 * @ret rc Return status code
1001 */
1002 int x509_parse ( struct x509_certificate *cert,
1003 const struct asn1_cursor *raw ) {
1004 struct x509_signature *signature = &cert->signature;
1005 struct asn1_algorithm **signature_algorithm = &signature->algorithm;
1006 struct asn1_bit_string *signature_value = &signature->value;
1007 struct asn1_cursor cursor;
1008 int rc;
1009
1010 /* Record raw certificate */
1011 memcpy ( &cursor, raw, sizeof ( cursor ) );
1012 memcpy ( &cert->raw, &cursor, sizeof ( cert->raw ) );
1013
1014 /* Enter certificate */
1015 asn1_enter ( &cursor, ASN1_SEQUENCE );
1016
1017 /* Parse tbsCertificate */
1018 if ( ( rc = x509_parse_tbscertificate ( cert, &cursor ) ) != 0 )
1019 return rc;
1020 asn1_skip_any ( &cursor );
1021
1022 /* Parse signatureAlgorithm */
1023 if ( ( rc = asn1_signature_algorithm ( &cursor,
1024 signature_algorithm ) ) != 0 ) {
1025 DBGC ( cert, "X509 %p could not parse signature algorithm: "
1026 "%s\n", cert, strerror ( rc ) );
1027 return rc;
1028 }
1029 DBGC2 ( cert, "X509 %p signatureAlgorithm is %s\n",
1030 cert, (*signature_algorithm)->name );
1031 asn1_skip_any ( &cursor );
1032
1033 /* Parse signatureValue */
1034 if ( ( rc = asn1_integral_bit_string ( &cursor,
1035 signature_value ) ) != 0 ) {
1036 DBGC ( cert, "X509 %p could not parse signature value: %s\n",
1037 cert, strerror ( rc ) );
1038 return rc;
1039 }
1040 DBGC2 ( cert, "X509 %p signatureValue is:\n", cert );
1041 DBGC2_HDA ( cert, 0, signature_value->data, signature_value->len );
1042
1043 /* Check that algorithm in tbsCertificate matches algorithm in
1044 * signature
1045 */
1046 if ( signature->algorithm != (*signature_algorithm) ) {
1047 DBGC ( cert, "X509 %p signature algorithm %s does not match "
1048 "signatureAlgorithm %s\n",
1049 cert, signature->algorithm->name,
1050 (*signature_algorithm)->name );
1051 return -EINVAL_ALGORITHM_MISMATCH;
1052 }
1053
1054 return 0;
1055 }
1056
1057 /**
1058 * Create X.509 certificate
1059 *
1060 * @v data Raw certificate data
1061 * @v len Length of raw data
1062 * @ret cert X.509 certificate
1063 * @ret rc Return status code
1064 *
1065 * On success, the caller holds a reference to the X.509 certificate,
1066 * and is responsible for ultimately calling x509_put().
1067 */
1068 int x509_certificate ( const void *data, size_t len,
1069 struct x509_certificate **cert ) {
1070 struct asn1_cursor cursor;
1071 void *raw;
1072 int rc;
1073
1074 /* Initialise cursor */
1075 cursor.data = data;
1076 cursor.len = len;
1077 asn1_shrink_any ( &cursor );
1078
1079 /* Return stored certificate, if present */
1080 if ( ( *cert = certstore_find ( &cursor ) ) != NULL ) {
1081
1082 /* Add caller's reference */
1083 x509_get ( *cert );
1084 return 0;
1085 }
1086
1087 /* Allocate and initialise certificate */
1088 *cert = zalloc ( sizeof ( **cert ) + cursor.len );
1089 if ( ! *cert )
1090 return -ENOMEM;
1091 ref_init ( &(*cert)->refcnt, x509_free );
1092 raw = ( *cert + 1 );
1093
1094 /* Copy raw data */
1095 memcpy ( raw, cursor.data, cursor.len );
1096 cursor.data = raw;
1097
1098 /* Parse certificate */
1099 if ( ( rc = x509_parse ( *cert, &cursor ) ) != 0 ) {
1100 x509_put ( *cert );
1101 *cert = NULL;
1102 return rc;
1103 }
1104
1105 /* Add certificate to store */
1106 certstore_add ( *cert );
1107
1108 return 0;
1109 }
1110
1111 /**
1112 * Check X.509 certificate signature
1113 *
1114 * @v cert X.509 certificate
1115 * @v public_key X.509 public key
1116 * @ret rc Return status code
1117 */
1118 static int x509_check_signature ( struct x509_certificate *cert,
1119 struct x509_public_key *public_key ) {
1120 struct x509_signature *signature = &cert->signature;
1121 struct asn1_algorithm *algorithm = signature->algorithm;
1122 struct digest_algorithm *digest = algorithm->digest;
1123 struct pubkey_algorithm *pubkey = algorithm->pubkey;
1124 uint8_t digest_ctx[ digest->ctxsize ];
1125 uint8_t digest_out[ digest->digestsize ];
1126 uint8_t pubkey_ctx[ pubkey->ctxsize ];
1127 int rc;
1128
1129 /* Sanity check */
1130 assert ( cert->signature_algorithm == cert->signature.algorithm );
1131
1132 /* Calculate certificate digest */
1133 digest_init ( digest, digest_ctx );
1134 digest_update ( digest, digest_ctx, cert->tbs.data, cert->tbs.len );
1135 digest_final ( digest, digest_ctx, digest_out );
1136 DBGC2 ( cert, "X509 %p \"%s\" digest:\n", cert, x509_name ( cert ) );
1137 DBGC2_HDA ( cert, 0, digest_out, sizeof ( digest_out ) );
1138
1139 /* Check that signature public key algorithm matches signer */
1140 if ( public_key->algorithm->pubkey != pubkey ) {
1141 DBGC ( cert, "X509 %p \"%s\" signature algorithm %s does not "
1142 "match signer's algorithm %s\n",
1143 cert, x509_name ( cert ), algorithm->name,
1144 public_key->algorithm->name );
1145 rc = -EINVAL_ALGORITHM_MISMATCH;
1146 goto err_mismatch;
1147 }
1148
1149 /* Verify signature using signer's public key */
1150 if ( ( rc = pubkey_init ( pubkey, pubkey_ctx, public_key->raw.data,
1151 public_key->raw.len ) ) != 0 ) {
1152 DBGC ( cert, "X509 %p \"%s\" cannot initialise public key: "
1153 "%s\n", cert, x509_name ( cert ), strerror ( rc ) );
1154 goto err_pubkey_init;
1155 }
1156 if ( ( rc = pubkey_verify ( pubkey, pubkey_ctx, digest, digest_out,
1157 signature->value.data,
1158 signature->value.len ) ) != 0 ) {
1159 DBGC ( cert, "X509 %p \"%s\" signature verification failed: "
1160 "%s\n", cert, x509_name ( cert ), strerror ( rc ) );
1161 goto err_pubkey_verify;
1162 }
1163
1164 /* Success */
1165 rc = 0;
1166
1167 err_pubkey_verify:
1168 pubkey_final ( pubkey, pubkey_ctx );
1169 err_pubkey_init:
1170 err_mismatch:
1171 return rc;
1172 }
1173
1174 /**
1175 * Check X.509 certificate against issuer certificate
1176 *
1177 * @v cert X.509 certificate
1178 * @v issuer X.509 issuer certificate
1179 * @ret rc Return status code
1180 */
1181 int x509_check_issuer ( struct x509_certificate *cert,
1182 struct x509_certificate *issuer ) {
1183 struct x509_public_key *public_key = &issuer->subject.public_key;
1184 int rc;
1185
1186 /* Check issuer. In theory, this should be a full X.500 DN
1187 * comparison, which would require support for a plethora of
1188 * abominations such as TeletexString (which allows the
1189 * character set to be changed mid-string using escape codes).
1190 * In practice, we assume that anyone who deliberately changes
1191 * the encoding of the issuer DN is probably a masochist who
1192 * will rather enjoy the process of figuring out exactly why
1193 * their certificate doesn't work.
1194 *
1195 * See http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt
1196 * for some enjoyable ranting on this subject.
1197 */
1198 if ( asn1_compare ( &cert->issuer.raw, &issuer->subject.raw ) != 0 ) {
1199 DBGC ( cert, "X509 %p \"%s\" issuer does not match ",
1200 cert, x509_name ( cert ) );
1201 DBGC ( cert, "X509 %p \"%s\" subject\n",
1202 issuer, x509_name ( issuer ) );
1203 DBGC_HDA ( cert, 0, cert->issuer.raw.data,
1204 cert->issuer.raw.len );
1205 DBGC_HDA ( issuer, 0, issuer->subject.raw.data,
1206 issuer->subject.raw.len );
1207 return -EACCES_WRONG_ISSUER;
1208 }
1209
1210 /* Check that issuer is allowed to sign certificates */
1211 if ( ! issuer->extensions.basic.ca ) {
1212 DBGC ( issuer, "X509 %p \"%s\" cannot sign ",
1213 issuer, x509_name ( issuer ) );
1214 DBGC ( issuer, "X509 %p \"%s\": not a CA certificate\n",
1215 cert, x509_name ( cert ) );
1216 return -EACCES_NOT_CA;
1217 }
1218 if ( issuer->extensions.usage.present &&
1219 ( ! ( issuer->extensions.usage.bits & X509_KEY_CERT_SIGN ) ) ) {
1220 DBGC ( issuer, "X509 %p \"%s\" cannot sign ",
1221 issuer, x509_name ( issuer ) );
1222 DBGC ( issuer, "X509 %p \"%s\": no keyCertSign usage\n",
1223 cert, x509_name ( cert ) );
1224 return -EACCES_KEY_USAGE;
1225 }
1226
1227 /* Check signature */
1228 if ( ( rc = x509_check_signature ( cert, public_key ) ) != 0 )
1229 return rc;
1230
1231 return 0;
1232 }
1233
1234 /**
1235 * Calculate X.509 certificate fingerprint
1236 *
1237 * @v cert X.509 certificate
1238 * @v digest Digest algorithm
1239 * @v fingerprint Fingerprint buffer
1240 */
1241 void x509_fingerprint ( struct x509_certificate *cert,
1242 struct digest_algorithm *digest,
1243 void *fingerprint ) {
1244 uint8_t ctx[ digest->ctxsize ];
1245
1246 /* Calculate fingerprint */
1247 digest_init ( digest, ctx );
1248 digest_update ( digest, ctx, cert->raw.data, cert->raw.len );
1249 digest_final ( digest, ctx, fingerprint );
1250 }
1251
1252 /**
1253 * Check X.509 root certificate
1254 *
1255 * @v cert X.509 certificate
1256 * @v root X.509 root certificate list
1257 * @ret rc Return status code
1258 */
1259 int x509_check_root ( struct x509_certificate *cert, struct x509_root *root ) {
1260 struct digest_algorithm *digest = root->digest;
1261 uint8_t fingerprint[ digest->digestsize ];
1262 const uint8_t *root_fingerprint = root->fingerprints;
1263 unsigned int i;
1264
1265 /* Calculate certificate fingerprint */
1266 x509_fingerprint ( cert, digest, fingerprint );
1267
1268 /* Check fingerprint against all root certificates */
1269 for ( i = 0 ; i < root->count ; i++ ) {
1270 if ( memcmp ( fingerprint, root_fingerprint,
1271 sizeof ( fingerprint ) ) == 0 ) {
1272 DBGC ( cert, "X509 %p \"%s\" is a root certificate\n",
1273 cert, x509_name ( cert ) );
1274 return 0;
1275 }
1276 root_fingerprint += sizeof ( fingerprint );
1277 }
1278
1279 DBGC2 ( cert, "X509 %p \"%s\" is not a root certificate\n",
1280 cert, x509_name ( cert ) );
1281 return -ENOENT;
1282 }
1283
1284 /**
1285 * Check X.509 certificate validity period
1286 *
1287 * @v cert X.509 certificate
1288 * @v time Time at which to check certificate
1289 * @ret rc Return status code
1290 */
1291 int x509_check_time ( struct x509_certificate *cert, time_t time ) {
1292 struct x509_validity *validity = &cert->validity;
1293
1294 /* Check validity period */
1295 if ( validity->not_before.time > ( time + TIMESTAMP_ERROR_MARGIN ) ) {
1296 DBGC ( cert, "X509 %p \"%s\" is not yet valid (at time %lld)\n",
1297 cert, x509_name ( cert ), time );
1298 return -EACCES_EXPIRED;
1299 }
1300 if ( validity->not_after.time < ( time - TIMESTAMP_ERROR_MARGIN ) ) {
1301 DBGC ( cert, "X509 %p \"%s\" has expired (at time %lld)\n",
1302 cert, x509_name ( cert ), time );
1303 return -EACCES_EXPIRED;
1304 }
1305
1306 DBGC2 ( cert, "X509 %p \"%s\" is valid (at time %lld)\n",
1307 cert, x509_name ( cert ), time );
1308 return 0;
1309 }
1310
1311 /**
1312 * Check if X.509 certificate is valid
1313 *
1314 * @v cert X.509 certificate
1315 * @v root Root certificate list, or NULL to use default
1316 */
1317 int x509_is_valid ( struct x509_certificate *cert, struct x509_root *root ) {
1318
1319 /* Use default root certificate store if none specified */
1320 if ( ! root )
1321 root = &root_certificates;
1322
1323 return ( cert->root == root );
1324 }
1325
1326 /**
1327 * Set X.509 certificate as validated
1328 *
1329 * @v cert X.509 certificate
1330 * @v issuer Issuing X.509 certificate (or NULL)
1331 * @v root Root certificate list
1332 */
1333 static void x509_set_valid ( struct x509_certificate *cert,
1334 struct x509_certificate *issuer,
1335 struct x509_root *root ) {
1336 unsigned int max_path_remaining;
1337
1338 /* Sanity checks */
1339 assert ( root != NULL );
1340 assert ( ( issuer == NULL ) || ( issuer->path_remaining >= 1 ) );
1341
1342 /* Record validation root */
1343 x509_root_put ( cert->root );
1344 cert->root = x509_root_get ( root );
1345
1346 /* Calculate effective path length */
1347 cert->path_remaining = ( cert->extensions.basic.path_len + 1 );
1348 if ( issuer ) {
1349 max_path_remaining = ( issuer->path_remaining - 1 );
1350 if ( cert->path_remaining > max_path_remaining )
1351 cert->path_remaining = max_path_remaining;
1352 }
1353 }
1354
1355 /**
1356 * Validate X.509 certificate
1357 *
1358 * @v cert X.509 certificate
1359 * @v issuer Issuing X.509 certificate (or NULL)
1360 * @v time Time at which to validate certificate
1361 * @v root Root certificate list, or NULL to use default
1362 * @ret rc Return status code
1363 *
1364 * The issuing certificate must have already been validated.
1365 *
1366 * Validation results are cached: if a certificate has already been
1367 * successfully validated then @c issuer, @c time, and @c root will be
1368 * ignored.
1369 */
1370 int x509_validate ( struct x509_certificate *cert,
1371 struct x509_certificate *issuer,
1372 time_t time, struct x509_root *root ) {
1373 int rc;
1374
1375 /* Use default root certificate store if none specified */
1376 if ( ! root )
1377 root = &root_certificates;
1378
1379 /* Return success if certificate has already been validated */
1380 if ( x509_is_valid ( cert, root ) )
1381 return 0;
1382
1383 /* Fail if certificate is invalid at specified time */
1384 if ( ( rc = x509_check_time ( cert, time ) ) != 0 )
1385 return rc;
1386
1387 /* Succeed if certificate is a trusted root certificate */
1388 if ( x509_check_root ( cert, root ) == 0 ) {
1389 x509_set_valid ( cert, NULL, root );
1390 return 0;
1391 }
1392
1393 /* Fail unless we have an issuer */
1394 if ( ! issuer ) {
1395 DBGC2 ( cert, "X509 %p \"%s\" has no trusted issuer\n",
1396 cert, x509_name ( cert ) );
1397 return -EACCES_UNTRUSTED;
1398 }
1399
1400 /* Fail unless issuer has already been validated */
1401 if ( ! x509_is_valid ( issuer, root ) ) {
1402 DBGC ( cert, "X509 %p \"%s\" ", cert, x509_name ( cert ) );
1403 DBGC ( cert, "issuer %p \"%s\" has not yet been validated\n",
1404 issuer, x509_name ( issuer ) );
1405 return -EACCES_OUT_OF_ORDER;
1406 }
1407
1408 /* Fail if issuing certificate cannot validate this certificate */
1409 if ( ( rc = x509_check_issuer ( cert, issuer ) ) != 0 )
1410 return rc;
1411
1412 /* Fail if path length constraint is violated */
1413 if ( issuer->path_remaining == 0 ) {
1414 DBGC ( cert, "X509 %p \"%s\" ", cert, x509_name ( cert ) );
1415 DBGC ( cert, "issuer %p \"%s\" path length exceeded\n",
1416 issuer, x509_name ( issuer ) );
1417 return -EACCES_PATH_LEN;
1418 }
1419
1420 /* Fail if OCSP is required */
1421 if ( ocsp_required ( cert ) ) {
1422 DBGC ( cert, "X509 %p \"%s\" requires an OCSP check\n",
1423 cert, x509_name ( cert ) );
1424 return -EACCES_OCSP_REQUIRED;
1425 }
1426
1427 /* Mark certificate as valid */
1428 x509_set_valid ( cert, issuer, root );
1429
1430 DBGC ( cert, "X509 %p \"%s\" successfully validated using ",
1431 cert, x509_name ( cert ) );
1432 DBGC ( cert, "issuer %p \"%s\"\n", issuer, x509_name ( issuer ) );
1433 return 0;
1434 }
1435
1436 /**
1437 * Check X.509 certificate alternative dNSName
1438 *
1439 * @v cert X.509 certificate
1440 * @v raw ASN.1 cursor
1441 * @v name Name
1442 * @ret rc Return status code
1443 */
1444 static int x509_check_dnsname ( struct x509_certificate *cert,
1445 const struct asn1_cursor *raw,
1446 const char *name ) {
1447 const char *fullname = name;
1448 const char *dnsname = raw->data;
1449 size_t len = raw->len;
1450
1451 /* Check for wildcards */
1452 if ( ( len >= 2 ) && ( dnsname[0] == '*' ) && ( dnsname[1] == '.' ) ) {
1453
1454 /* Skip initial "*." */
1455 dnsname += 2;
1456 len -= 2;
1457
1458 /* Skip initial portion of name to be tested */
1459 name = strchr ( name, '.' );
1460 if ( ! name )
1461 return -ENOENT;
1462 name++;
1463 }
1464
1465 /* Compare names */
1466 if ( ! ( ( strlen ( name ) == len ) &&
1467 ( memcmp ( name, dnsname, len ) == 0 ) ) )
1468 return -ENOENT;
1469
1470 if ( name != fullname ) {
1471 DBGC2 ( cert, "X509 %p \"%s\" found wildcard match for "
1472 "\"*.%s\"\n", cert, x509_name ( cert ), name );
1473 }
1474 return 0;
1475 }
1476
1477 /**
1478 * Check X.509 certificate alternative iPAddress
1479 *
1480 * @v cert X.509 certificate
1481 * @v raw ASN.1 cursor
1482 * @v name Name
1483 * @ret rc Return status code
1484 */
1485 static int x509_check_ipaddress ( struct x509_certificate *cert,
1486 const struct asn1_cursor *raw,
1487 const char *name ) {
1488 struct sockaddr sa;
1489 sa_family_t family;
1490 const void *address;
1491 int rc;
1492
1493 /* Determine address family */
1494 if ( raw->len == sizeof ( struct in_addr ) ) {
1495 struct sockaddr_in *sin = ( ( struct sockaddr_in * ) &sa );
1496 family = AF_INET;
1497 address = &sin->sin_addr;
1498 } else if ( raw->len == sizeof ( struct in6_addr ) ) {
1499 struct sockaddr_in6 *sin6 = ( ( struct sockaddr_in6 * ) &sa );
1500 family = AF_INET6;
1501 address = &sin6->sin6_addr;
1502 } else {
1503 DBGC ( cert, "X509 %p \"%s\" has iPAddress with unexpected "
1504 "length %zd\n", cert, x509_name ( cert ), raw->len );
1505 DBGC_HDA ( cert, 0, raw->data, raw->len );
1506 return -EINVAL;
1507 }
1508
1509 /* Attempt to convert name to a socket address */
1510 if ( ( rc = sock_aton ( name, &sa ) ) != 0 ) {
1511 DBGC2 ( cert, "X509 %p \"%s\" cannot parse \"%s\" as "
1512 "iPAddress: %s\n", cert, x509_name ( cert ), name,
1513 strerror ( rc ) );
1514 return rc;
1515 }
1516 if ( sa.sa_family != family )
1517 return -ENOENT;
1518
1519 /* Compare addresses */
1520 if ( memcmp ( address, raw->data, raw->len ) != 0 )
1521 return -ENOENT;
1522
1523 DBGC2 ( cert, "X509 %p \"%s\" found iPAddress match for \"%s\"\n",
1524 cert, x509_name ( cert ), sock_ntoa ( &sa ) );
1525 return 0;
1526 }
1527
1528 /**
1529 * Check X.509 certificate alternative name
1530 *
1531 * @v cert X.509 certificate
1532 * @v raw ASN.1 cursor
1533 * @v name Name
1534 * @ret rc Return status code
1535 */
1536 static int x509_check_alt_name ( struct x509_certificate *cert,
1537 const struct asn1_cursor *raw,
1538 const char *name ) {
1539 struct asn1_cursor alt_name;
1540 unsigned int type;
1541
1542 /* Enter generalName */
1543 memcpy ( &alt_name, raw, sizeof ( alt_name ) );
1544 type = asn1_type ( &alt_name );
1545 asn1_enter_any ( &alt_name );
1546
1547 /* Check this name */
1548 switch ( type ) {
1549 case X509_GENERAL_NAME_DNS :
1550 return x509_check_dnsname ( cert, &alt_name, name );
1551 case X509_GENERAL_NAME_IP :
1552 return x509_check_ipaddress ( cert, &alt_name, name );
1553 default:
1554 DBGC2 ( cert, "X509 %p \"%s\" unknown name of type %#02x:\n",
1555 cert, x509_name ( cert ), type );
1556 DBGC2_HDA ( cert, 0, alt_name.data, alt_name.len );
1557 return -ENOTSUP;
1558 }
1559 }
1560
1561 /**
1562 * Check X.509 certificate name
1563 *
1564 * @v cert X.509 certificate
1565 * @v name Name
1566 * @ret rc Return status code
1567 */
1568 int x509_check_name ( struct x509_certificate *cert, const char *name ) {
1569 struct asn1_cursor *common_name = &cert->subject.common_name;
1570 struct asn1_cursor alt_name;
1571 int rc;
1572
1573 /* Check commonName */
1574 if ( x509_check_dnsname ( cert, common_name, name ) == 0 ) {
1575 DBGC2 ( cert, "X509 %p \"%s\" commonName matches \"%s\"\n",
1576 cert, x509_name ( cert ), name );
1577 return 0;
1578 }
1579
1580 /* Check any subjectAlternativeNames */
1581 memcpy ( &alt_name, &cert->extensions.alt_name.names,
1582 sizeof ( alt_name ) );
1583 for ( ; alt_name.len ; asn1_skip_any ( &alt_name ) ) {
1584 if ( ( rc = x509_check_alt_name ( cert, &alt_name,
1585 name ) ) == 0 ) {
1586 DBGC2 ( cert, "X509 %p \"%s\" subjectAltName matches "
1587 "\"%s\"\n", cert, x509_name ( cert ), name );
1588 return 0;
1589 }
1590 }
1591
1592 DBGC ( cert, "X509 %p \"%s\" does not match name \"%s\"\n",
1593 cert, x509_name ( cert ), name );
1594 return -EACCES_WRONG_NAME;
1595 }
1596
1597 /**
1598 * Free X.509 certificate chain
1599 *
1600 * @v refcnt Reference count
1601 */
1602 static void x509_free_chain ( struct refcnt *refcnt ) {
1603 struct x509_chain *chain =
1604 container_of ( refcnt, struct x509_chain, refcnt );
1605 struct x509_link *link;
1606 struct x509_link *tmp;
1607
1608 DBGC2 ( chain, "X509 chain %p freed\n", chain );
1609
1610 /* Free each link in the chain */
1611 list_for_each_entry_safe ( link, tmp, &chain->links, list ) {
1612 x509_put ( link->cert );
1613 list_del ( &link->list );
1614 free ( link );
1615 }
1616
1617 /* Free chain */
1618 free ( chain );
1619 }
1620
1621 /**
1622 * Allocate X.509 certificate chain
1623 *
1624 * @ret chain X.509 certificate chain, or NULL
1625 */
1626 struct x509_chain * x509_alloc_chain ( void ) {
1627 struct x509_chain *chain;
1628
1629 /* Allocate chain */
1630 chain = zalloc ( sizeof ( *chain ) );
1631 if ( ! chain )
1632 return NULL;
1633
1634 /* Initialise chain */
1635 ref_init ( &chain->refcnt, x509_free_chain );
1636 INIT_LIST_HEAD ( &chain->links );
1637
1638 DBGC2 ( chain, "X509 chain %p allocated\n", chain );
1639 return chain;
1640 }
1641
1642 /**
1643 * Append X.509 certificate to X.509 certificate chain
1644 *
1645 * @v chain X.509 certificate chain
1646 * @v cert X.509 certificate
1647 * @ret rc Return status code
1648 */
1649 int x509_append ( struct x509_chain *chain, struct x509_certificate *cert ) {
1650 struct x509_link *link;
1651
1652 /* Allocate link */
1653 link = zalloc ( sizeof ( *link ) );
1654 if ( ! link )
1655 return -ENOMEM;
1656
1657 /* Add link to chain */
1658 link->cert = x509_get ( cert );
1659 list_add_tail ( &link->list, &chain->links );
1660 DBGC ( chain, "X509 chain %p added X509 %p \"%s\"\n",
1661 chain, cert, x509_name ( cert ) );
1662
1663 return 0;
1664 }
1665
1666 /**
1667 * Append X.509 certificate to X.509 certificate chain
1668 *
1669 * @v chain X.509 certificate chain
1670 * @v data Raw certificate data
1671 * @v len Length of raw data
1672 * @ret rc Return status code
1673 */
1674 int x509_append_raw ( struct x509_chain *chain, const void *data,
1675 size_t len ) {
1676 struct x509_certificate *cert;
1677 int rc;
1678
1679 /* Parse certificate */
1680 if ( ( rc = x509_certificate ( data, len, &cert ) ) != 0 )
1681 goto err_parse;
1682
1683 /* Append certificate to chain */
1684 if ( ( rc = x509_append ( chain, cert ) ) != 0 )
1685 goto err_append;
1686
1687 /* Drop reference to certificate */
1688 x509_put ( cert );
1689
1690 return 0;
1691
1692 err_append:
1693 x509_put ( cert );
1694 err_parse:
1695 return rc;
1696 }
1697
1698 /**
1699 * Identify X.509 certificate by subject
1700 *
1701 * @v certs X.509 certificate list
1702 * @v subject Subject
1703 * @ret cert X.509 certificate, or NULL if not found
1704 */
1705 static struct x509_certificate *
1706 x509_find_subject ( struct x509_chain *certs,
1707 const struct asn1_cursor *subject ) {
1708 struct x509_link *link;
1709 struct x509_certificate *cert;
1710
1711 /* Scan through certificate list */
1712 list_for_each_entry ( link, &certs->links, list ) {
1713
1714 /* Check subject */
1715 cert = link->cert;
1716 if ( asn1_compare ( subject, &cert->subject.raw ) == 0 )
1717 return cert;
1718 }
1719
1720 return NULL;
1721 }
1722
1723 /**
1724 * Append X.509 certificates to X.509 certificate chain
1725 *
1726 * @v chain X.509 certificate chain
1727 * @v certs X.509 certificate list
1728 * @ret rc Return status code
1729 *
1730 * Certificates will be automatically appended to the chain based upon
1731 * the subject and issuer names.
1732 */
1733 int x509_auto_append ( struct x509_chain *chain, struct x509_chain *certs ) {
1734 struct x509_certificate *cert;
1735 struct x509_certificate *previous;
1736 int rc;
1737
1738 /* Get current certificate */
1739 cert = x509_last ( chain );
1740 if ( ! cert ) {
1741 DBGC ( chain, "X509 chain %p has no certificates\n", chain );
1742 return -EACCES_EMPTY;
1743 }
1744
1745 /* Append certificates, in order */
1746 while ( 1 ) {
1747
1748 /* Find issuing certificate */
1749 previous = cert;
1750 cert = x509_find_subject ( certs, &cert->issuer.raw );
1751 if ( ! cert )
1752 break;
1753 if ( cert == previous )
1754 break;
1755
1756 /* Append certificate to chain */
1757 if ( ( rc = x509_append ( chain, cert ) ) != 0 )
1758 return rc;
1759 }
1760
1761 return 0;
1762 }
1763
1764 /**
1765 * Validate X.509 certificate chain
1766 *
1767 * @v chain X.509 certificate chain
1768 * @v time Time at which to validate certificates
1769 * @v store Certificate store, or NULL to use default
1770 * @v root Root certificate list, or NULL to use default
1771 * @ret rc Return status code
1772 */
1773 int x509_validate_chain ( struct x509_chain *chain, time_t time,
1774 struct x509_chain *store, struct x509_root *root ) {
1775 struct x509_certificate *issuer = NULL;
1776 struct x509_link *link;
1777 int rc;
1778
1779 /* Use default certificate store if none specified */
1780 if ( ! store )
1781 store = &certstore;
1782
1783 /* Append any applicable certificates from the certificate store */
1784 if ( ( rc = x509_auto_append ( chain, store ) ) != 0 )
1785 return rc;
1786
1787 /* Find first certificate that can be validated as a
1788 * standalone (i.e. is already valid, or can be validated as
1789 * a trusted root certificate).
1790 */
1791 list_for_each_entry ( link, &chain->links, list ) {
1792
1793 /* Try validating this certificate as a standalone */
1794 if ( ( rc = x509_validate ( link->cert, NULL, time,
1795 root ) ) != 0 )
1796 continue;
1797
1798 /* Work back up to start of chain, performing pairwise
1799 * validation.
1800 */
1801 issuer = link->cert;
1802 list_for_each_entry_continue_reverse ( link, &chain->links,
1803 list ) {
1804
1805 /* Validate this certificate against its issuer */
1806 if ( ( rc = x509_validate ( link->cert, issuer, time,
1807 root ) ) != 0 )
1808 return rc;
1809 issuer = link->cert;
1810 }
1811
1812 return 0;
1813 }
1814
1815 DBGC ( chain, "X509 chain %p found no usable certificates\n", chain );
1816 return -EACCES_USELESS;
1817 }
1818
1819 /**
1820 * Extract X.509 certificate object from image
1821 *
1822 * @v image Image
1823 * @v offset Offset within image
1824 * @ret cert X.509 certificate
1825 * @ret next Offset to next image, or negative error
1826 *
1827 * On success, the caller holds a reference to the X.509 certificate,
1828 * and is responsible for ultimately calling x509_put().
1829 */
1830 int image_x509 ( struct image *image, size_t offset,
1831 struct x509_certificate **cert ) {
1832 struct asn1_cursor *cursor;
1833 int next;
1834 int rc;
1835
1836 /* Get ASN.1 object */
1837 next = image_asn1 ( image, offset, &cursor );
1838 if ( next < 0 ) {
1839 rc = next;
1840 goto err_asn1;
1841 }
1842
1843 /* Parse certificate */
1844 if ( ( rc = x509_certificate ( cursor->data, cursor->len,
1845 cert ) ) != 0 )
1846 goto err_certificate;
1847
1848 /* Free ASN.1 object */
1849 free ( cursor );
1850
1851 return next;
1852
1853 x509_put ( *cert );
1854 err_certificate:
1855 free ( cursor );
1856 err_asn1:
1857 return rc;
1858 }
1859
1860 /* Drag in objects via x509_validate() */
1861 REQUIRING_SYMBOL ( x509_validate );
1862
1863 /* Drag in certificate store */
1864 REQUIRE_OBJECT ( certstore );
1865
1866 /* Drag in crypto configuration */
1867 REQUIRE_OBJECT ( config_crypto );