Add qemu 2.4.0
[kvmfornfv.git] / qemu / roms / ipxe / src / net / validator.c
1 /*
2  * Copyright (C) 2012 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 (at your option) 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
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 #include <string.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <ipxe/refcnt.h>
26 #include <ipxe/malloc.h>
27 #include <ipxe/interface.h>
28 #include <ipxe/xfer.h>
29 #include <ipxe/open.h>
30 #include <ipxe/iobuf.h>
31 #include <ipxe/xferbuf.h>
32 #include <ipxe/process.h>
33 #include <ipxe/x509.h>
34 #include <ipxe/settings.h>
35 #include <ipxe/dhcp.h>
36 #include <ipxe/base64.h>
37 #include <ipxe/crc32.h>
38 #include <ipxe/ocsp.h>
39 #include <ipxe/validator.h>
40
41 /** @file
42  *
43  * Certificate validator
44  *
45  */
46
47 /** A certificate validator */
48 struct validator {
49         /** Reference count */
50         struct refcnt refcnt;
51         /** Job control interface */
52         struct interface job;
53         /** Data transfer interface */
54         struct interface xfer;
55
56         /** Process */
57         struct process process;
58
59         /** X.509 certificate chain */
60         struct x509_chain *chain;
61         /** OCSP check */
62         struct ocsp_check *ocsp;
63         /** Data buffer */
64         struct xfer_buffer buffer;
65         /** Action to take upon completed transfer */
66         int ( * done ) ( struct validator *validator, const void *data,
67                          size_t len );
68 };
69
70 /**
71  * Free certificate validator
72  *
73  * @v refcnt            Reference count
74  */
75 static void validator_free ( struct refcnt *refcnt ) {
76         struct validator *validator =
77                 container_of ( refcnt, struct validator, refcnt );
78
79         DBGC2 ( validator, "VALIDATOR %p freed\n", validator );
80         x509_chain_put ( validator->chain );
81         ocsp_put ( validator->ocsp );
82         xferbuf_done ( &validator->buffer );
83         free ( validator );
84 }
85
86 /**
87  * Mark certificate validation as finished
88  *
89  * @v validator         Certificate validator
90  * @v rc                Reason for finishing
91  */
92 static void validator_finished ( struct validator *validator, int rc ) {
93
94         /* Remove process */
95         process_del ( &validator->process );
96
97         /* Close all interfaces */
98         intf_shutdown ( &validator->xfer, rc );
99         intf_shutdown ( &validator->job, rc );
100 }
101
102 /****************************************************************************
103  *
104  * Job control interface
105  *
106  */
107
108 /** Certificate validator job control interface operations */
109 static struct interface_operation validator_job_operations[] = {
110         INTF_OP ( intf_close, struct validator *, validator_finished ),
111 };
112
113 /** Certificate validator job control interface descriptor */
114 static struct interface_descriptor validator_job_desc =
115         INTF_DESC ( struct validator, job, validator_job_operations );
116
117 /****************************************************************************
118  *
119  * Cross-signing certificates
120  *
121  */
122
123 /** Cross-signed certificate source setting */
124 const struct setting crosscert_setting __setting ( SETTING_CRYPTO, crosscert )={
125         .name = "crosscert",
126         .description = "Cross-signed certificate source",
127         .tag = DHCP_EB_CROSS_CERT,
128         .type = &setting_type_string,
129 };
130
131 /** Default cross-signed certificate source */
132 static const char crosscert_default[] = "http://ca.ipxe.org/auto";
133
134 /**
135  * Append cross-signing certificates to certificate chain
136  *
137  * @v validator         Certificate validator
138  * @v data              Raw cross-signing certificate data
139  * @v len               Length of raw data
140  * @ret rc              Return status code
141  */
142 static int validator_append ( struct validator *validator,
143                               const void *data, size_t len ) {
144         struct asn1_cursor cursor;
145         struct x509_chain *certs;
146         struct x509_certificate *cert;
147         struct x509_certificate *last;
148         int rc;
149
150         /* Allocate certificate list */
151         certs = x509_alloc_chain();
152         if ( ! certs ) {
153                 rc = -ENOMEM;
154                 goto err_alloc_certs;
155         }
156
157         /* Initialise cursor */
158         cursor.data = data;
159         cursor.len = len;
160
161         /* Enter certificateSet */
162         if ( ( rc = asn1_enter ( &cursor, ASN1_SET ) ) != 0 ) {
163                 DBGC ( validator, "VALIDATOR %p could not enter "
164                        "certificateSet: %s\n", validator, strerror ( rc ) );
165                 goto err_certificateset;
166         }
167
168         /* Add each certificate to list */
169         while ( cursor.len ) {
170
171                 /* Add certificate to chain */
172                 if ( ( rc = x509_append_raw ( certs, cursor.data,
173                                               cursor.len ) ) != 0 ) {
174                         DBGC ( validator, "VALIDATOR %p could not append "
175                                "certificate: %s\n",
176                                validator, strerror ( rc) );
177                         DBGC_HDA ( validator, 0, cursor.data, cursor.len );
178                         return rc;
179                 }
180                 cert = x509_last ( certs );
181                 DBGC ( validator, "VALIDATOR %p found certificate %s\n",
182                        validator, x509_name ( cert ) );
183
184                 /* Move to next certificate */
185                 asn1_skip_any ( &cursor );
186         }
187
188         /* Append certificates to chain */
189         last = x509_last ( validator->chain );
190         if ( ( rc = x509_auto_append ( validator->chain, certs ) ) != 0 ) {
191                 DBGC ( validator, "VALIDATOR %p could not append "
192                        "certificates: %s\n", validator, strerror ( rc ) );
193                 goto err_auto_append;
194         }
195
196         /* Check that at least one certificate has been added */
197         if ( last == x509_last ( validator->chain ) ) {
198                 DBGC ( validator, "VALIDATOR %p failed to append any "
199                        "applicable certificates\n", validator );
200                 rc = -EACCES;
201                 goto err_no_progress;
202         }
203
204         /* Drop reference to certificate list */
205         x509_chain_put ( certs );
206
207         return 0;
208
209  err_no_progress:
210  err_auto_append:
211  err_certificateset:
212         x509_chain_put ( certs );
213  err_alloc_certs:
214         return rc;
215 }
216
217 /**
218  * Start download of cross-signing certificate
219  *
220  * @v validator         Certificate validator
221  * @v issuer            Required issuer
222  * @ret rc              Return status code
223  */
224 static int validator_start_download ( struct validator *validator,
225                                       const struct asn1_cursor *issuer ) {
226         const char *crosscert;
227         char *crosscert_copy;
228         char *uri_string;
229         size_t uri_string_len;
230         uint32_t crc;
231         int len;
232         int rc;
233
234         /* Determine cross-signed certificate source */
235         fetch_string_setting_copy ( NULL, &crosscert_setting, &crosscert_copy );
236         crosscert = ( crosscert_copy ? crosscert_copy : crosscert_default );
237
238         /* Allocate URI string */
239         uri_string_len = ( strlen ( crosscert ) + 22 /* "/%08x.der?subject=" */
240                            + base64_encoded_len ( issuer->len ) + 1 /* NUL */ );
241         uri_string = zalloc ( uri_string_len );
242         if ( ! uri_string ) {
243                 rc = -ENOMEM;
244                 goto err_alloc_uri_string;
245         }
246
247         /* Generate CRC32 */
248         crc = crc32_le ( 0xffffffffUL, issuer->data, issuer->len );
249
250         /* Generate URI string */
251         len = snprintf ( uri_string, uri_string_len, "%s/%08x.der?subject=",
252                          crosscert, crc );
253         base64_encode ( issuer->data, issuer->len, ( uri_string + len ) );
254         DBGC ( validator, "VALIDATOR %p downloading cross-signed certificate "
255                "from %s\n", validator, uri_string );
256
257         /* Set completion handler */
258         validator->done = validator_append;
259
260         /* Open URI */
261         if ( ( rc = xfer_open_uri_string ( &validator->xfer,
262                                            uri_string ) ) != 0 ) {
263                 DBGC ( validator, "VALIDATOR %p could not open %s: %s\n",
264                        validator, uri_string, strerror ( rc ) );
265                 goto err_open_uri_string;
266         }
267
268         /* Success */
269         rc = 0;
270
271  err_open_uri_string:
272         free ( uri_string );
273  err_alloc_uri_string:
274         free ( crosscert_copy );
275         return rc;
276 }
277
278 /****************************************************************************
279  *
280  * OCSP checks
281  *
282  */
283
284 /**
285  * Validate OCSP response
286  *
287  * @v validator         Certificate validator
288  * @v data              Raw OCSP response
289  * @v len               Length of raw data
290  * @ret rc              Return status code
291  */
292 static int validator_ocsp_validate ( struct validator *validator,
293                                      const void *data, size_t len ) {
294         time_t now;
295         int rc;
296
297         /* Record OCSP response */
298         if ( ( rc = ocsp_response ( validator->ocsp, data, len ) ) != 0 ) {
299                 DBGC ( validator, "VALIDATOR %p could not record OCSP "
300                        "response: %s\n", validator, strerror ( rc ) );
301                 return rc;
302         }
303
304         /* Validate OCSP response */
305         now = time ( NULL );
306         if ( ( rc = ocsp_validate ( validator->ocsp, now ) ) != 0 ) {
307                 DBGC ( validator, "VALIDATOR %p could not validate OCSP "
308                        "response: %s\n", validator, strerror ( rc ) );
309                 return rc;
310         }
311
312         /* Drop reference to OCSP check */
313         ocsp_put ( validator->ocsp );
314         validator->ocsp = NULL;
315
316         return 0;
317 }
318
319 /**
320  * Start OCSP check
321  *
322  * @v validator         Certificate validator
323  * @v cert              Certificate to check
324  * @v issuer            Issuing certificate
325  * @ret rc              Return status code
326  */
327 static int validator_start_ocsp ( struct validator *validator,
328                                   struct x509_certificate *cert,
329                                   struct x509_certificate *issuer ) {
330         const char *uri_string;
331         int rc;
332
333         /* Create OCSP check */
334         assert ( validator->ocsp == NULL );
335         if ( ( rc = ocsp_check ( cert, issuer, &validator->ocsp ) ) != 0 ) {
336                 DBGC ( validator, "VALIDATOR %p could not create OCSP check: "
337                        "%s\n", validator, strerror ( rc ) );
338                 return rc;
339         }
340
341         /* Set completion handler */
342         validator->done = validator_ocsp_validate;
343
344         /* Open URI */
345         uri_string = validator->ocsp->uri_string;
346         DBGC ( validator, "VALIDATOR %p performing OCSP check at %s\n",
347                validator, uri_string );
348         if ( ( rc = xfer_open_uri_string ( &validator->xfer,
349                                            uri_string ) ) != 0 ) {
350                 DBGC ( validator, "VALIDATOR %p could not open %s: %s\n",
351                        validator, uri_string, strerror ( rc ) );
352                 return rc;
353         }
354
355         return 0;
356 }
357
358 /****************************************************************************
359  *
360  * Data transfer interface
361  *
362  */
363
364 /**
365  * Close data transfer interface
366  *
367  * @v validator         Certificate validator
368  * @v rc                Reason for close
369  */
370 static void validator_xfer_close ( struct validator *validator, int rc ) {
371
372         /* Close data transfer interface */
373         intf_restart ( &validator->xfer, rc );
374
375         /* Check for errors */
376         if ( rc != 0 ) {
377                 DBGC ( validator, "VALIDATOR %p transfer failed: %s\n",
378                        validator, strerror ( rc ) );
379                 goto err_transfer;
380         }
381         DBGC2 ( validator, "VALIDATOR %p transfer complete\n", validator );
382
383         /* Process completed download */
384         assert ( validator->done != NULL );
385         if ( ( rc = validator->done ( validator, validator->buffer.data,
386                                        validator->buffer.len ) ) != 0 )
387                 goto err_append;
388
389         /* Free downloaded data */
390         xferbuf_done ( &validator->buffer );
391
392         /* Resume validation process */
393         process_add ( &validator->process );
394
395         return;
396
397  err_append:
398  err_transfer:
399         validator_finished ( validator, rc );
400 }
401
402 /**
403  * Receive data
404  *
405  * @v validator         Certificate validator
406  * @v iobuf             I/O buffer
407  * @v meta              Data transfer metadata
408  * @ret rc              Return status code
409  */
410 static int validator_xfer_deliver ( struct validator *validator,
411                                     struct io_buffer *iobuf,
412                                     struct xfer_metadata *meta ) {
413         int rc;
414
415         /* Add data to buffer */
416         if ( ( rc = xferbuf_deliver ( &validator->buffer, iob_disown ( iobuf ),
417                                       meta ) ) != 0 ) {
418                 DBGC ( validator, "VALIDATOR %p could not receive data: %s\n",
419                        validator, strerror ( rc ) );
420                 validator_finished ( validator, rc );
421                 return rc;
422         }
423
424         return 0;
425 }
426
427 /** Certificate validator data transfer interface operations */
428 static struct interface_operation validator_xfer_operations[] = {
429         INTF_OP ( xfer_deliver, struct validator *, validator_xfer_deliver ),
430         INTF_OP ( intf_close, struct validator *, validator_xfer_close ),
431 };
432
433 /** Certificate validator data transfer interface descriptor */
434 static struct interface_descriptor validator_xfer_desc =
435         INTF_DESC ( struct validator, xfer, validator_xfer_operations );
436
437 /****************************************************************************
438  *
439  * Validation process
440  *
441  */
442
443 /**
444  * Certificate validation process
445  *
446  * @v validator         Certificate validator
447  */
448 static void validator_step ( struct validator *validator ) {
449         struct x509_link *link;
450         struct x509_certificate *cert;
451         struct x509_certificate *issuer = NULL;
452         struct x509_certificate *last;
453         time_t now;
454         int rc;
455
456         /* Try validating chain.  Try even if the chain is incomplete,
457          * since certificates may already have been validated
458          * previously.
459          */
460         now = time ( NULL );
461         if ( ( rc = x509_validate_chain ( validator->chain, now, NULL,
462                                           NULL ) ) == 0 ) {
463                 validator_finished ( validator, 0 );
464                 return;
465         }
466
467         /* If there is a certificate that could be validated using
468          * OCSP, try it.
469          */
470         list_for_each_entry ( link, &validator->chain->links, list ) {
471                 cert = issuer;
472                 issuer = link->cert;
473                 if ( ! cert )
474                         continue;
475                 if ( ! issuer->valid )
476                         continue;
477                 /* The issuer is valid, but this certificate is not
478                  * yet valid.  If OCSP is applicable, start it.
479                  */
480                 if ( cert->extensions.auth_info.ocsp.uri.len &&
481                      ( ! cert->extensions.auth_info.ocsp.good ) ) {
482                         /* Start OCSP */
483                         if ( ( rc = validator_start_ocsp ( validator, cert,
484                                                            issuer ) ) != 0 ) {
485                                 validator_finished ( validator, rc );
486                                 return;
487                         }
488                         return;
489                 }
490                 /* Otherwise, this is a permanent failure */
491                 validator_finished ( validator, rc );
492                 return;
493         }
494
495         /* If chain ends with a self-issued certificate, then there is
496          * nothing more to do.
497          */
498         last = x509_last ( validator->chain );
499         if ( asn1_compare ( &last->issuer.raw, &last->subject.raw ) == 0 ) {
500                 validator_finished ( validator, rc );
501                 return;
502         }
503
504         /* Otherwise, try to download a suitable cross-signing
505          * certificate.
506          */
507         if ( ( rc = validator_start_download ( validator,
508                                                &last->issuer.raw ) ) != 0 ) {
509                 validator_finished ( validator, rc );
510                 return;
511         }
512 }
513
514 /** Certificate validator process descriptor */
515 static struct process_descriptor validator_process_desc =
516         PROC_DESC_ONCE ( struct validator, process, validator_step );
517
518 /****************************************************************************
519  *
520  * Instantiator
521  *
522  */
523
524 /**
525  * Instantiate a certificate validator
526  *
527  * @v job               Job control interface
528  * @v chain             X.509 certificate chain
529  * @ret rc              Return status code
530  */
531 int create_validator ( struct interface *job, struct x509_chain *chain ) {
532         struct validator *validator;
533         int rc;
534
535         /* Sanity check */
536         if ( ! chain ) {
537                 rc = -EINVAL;
538                 goto err_sanity;
539         }
540
541         /* Allocate and initialise structure */
542         validator = zalloc ( sizeof ( *validator ) );
543         if ( ! validator ) {
544                 rc = -ENOMEM;
545                 goto err_alloc;
546         }
547         ref_init ( &validator->refcnt, validator_free );
548         intf_init ( &validator->job, &validator_job_desc,
549                     &validator->refcnt );
550         intf_init ( &validator->xfer, &validator_xfer_desc,
551                     &validator->refcnt );
552         process_init ( &validator->process, &validator_process_desc,
553                        &validator->refcnt );
554         validator->chain = x509_chain_get ( chain );
555
556         /* Attach parent interface, mortalise self, and return */
557         intf_plug_plug ( &validator->job, job );
558         ref_put ( &validator->refcnt );
559         DBGC2 ( validator, "VALIDATOR %p validating X509 chain %p\n",
560                 validator, validator->chain );
561         return 0;
562
563         validator_finished ( validator, rc );
564         ref_put ( &validator->refcnt );
565  err_alloc:
566  err_sanity:
567         return rc;
568 }