[tls] Display cross-certificate and OCSP status messages
[ipxe.git] / src / net / tls.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
20 FILE_LICENCE ( GPL2_OR_LATER );
21
22 /**
23 * @file
24 *
25 * Transport Layer Security Protocol
26 */
27
28 #include <stdint.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <time.h>
33 #include <errno.h>
34 #include <byteswap.h>
35 #include <ipxe/pending.h>
36 #include <ipxe/hmac.h>
37 #include <ipxe/md5.h>
38 #include <ipxe/sha1.h>
39 #include <ipxe/sha256.h>
40 #include <ipxe/aes.h>
41 #include <ipxe/rsa.h>
42 #include <ipxe/iobuf.h>
43 #include <ipxe/xfer.h>
44 #include <ipxe/open.h>
45 #include <ipxe/x509.h>
46 #include <ipxe/privkey.h>
47 #include <ipxe/certstore.h>
48 #include <ipxe/rbg.h>
49 #include <ipxe/validator.h>
50 #include <ipxe/job.h>
51 #include <ipxe/tls.h>
52
53 /* Disambiguate the various error causes */
54 #define EINVAL_CHANGE_CIPHER __einfo_error ( EINFO_EINVAL_CHANGE_CIPHER )
55 #define EINFO_EINVAL_CHANGE_CIPHER \
56 __einfo_uniqify ( EINFO_EINVAL, 0x01, \
57 "Invalid Change Cipher record" )
58 #define EINVAL_ALERT __einfo_error ( EINFO_EINVAL_ALERT )
59 #define EINFO_EINVAL_ALERT \
60 __einfo_uniqify ( EINFO_EINVAL, 0x02, \
61 "Invalid Alert record" )
62 #define EINVAL_HELLO __einfo_error ( EINFO_EINVAL_HELLO )
63 #define EINFO_EINVAL_HELLO \
64 __einfo_uniqify ( EINFO_EINVAL, 0x03, \
65 "Invalid Server Hello record" )
66 #define EINVAL_CERTIFICATE __einfo_error ( EINFO_EINVAL_CERTIFICATE )
67 #define EINFO_EINVAL_CERTIFICATE \
68 __einfo_uniqify ( EINFO_EINVAL, 0x04, \
69 "Invalid Certificate" )
70 #define EINVAL_CERTIFICATES __einfo_error ( EINFO_EINVAL_CERTIFICATES )
71 #define EINFO_EINVAL_CERTIFICATES \
72 __einfo_uniqify ( EINFO_EINVAL, 0x05, \
73 "Invalid Server Certificate record" )
74 #define EINVAL_HELLO_DONE __einfo_error ( EINFO_EINVAL_HELLO_DONE )
75 #define EINFO_EINVAL_HELLO_DONE \
76 __einfo_uniqify ( EINFO_EINVAL, 0x06, \
77 "Invalid Server Hello Done record" )
78 #define EINVAL_FINISHED __einfo_error ( EINFO_EINVAL_FINISHED )
79 #define EINFO_EINVAL_FINISHED \
80 __einfo_uniqify ( EINFO_EINVAL, 0x07, \
81 "Invalid Server Finished record" )
82 #define EINVAL_HANDSHAKE __einfo_error ( EINFO_EINVAL_HANDSHAKE )
83 #define EINFO_EINVAL_HANDSHAKE \
84 __einfo_uniqify ( EINFO_EINVAL, 0x08, \
85 "Invalid Handshake record" )
86 #define EINVAL_STREAM __einfo_error ( EINFO_EINVAL_STREAM )
87 #define EINFO_EINVAL_STREAM \
88 __einfo_uniqify ( EINFO_EINVAL, 0x09, \
89 "Invalid stream-ciphered record" )
90 #define EINVAL_BLOCK __einfo_error ( EINFO_EINVAL_BLOCK )
91 #define EINFO_EINVAL_BLOCK \
92 __einfo_uniqify ( EINFO_EINVAL, 0x0a, \
93 "Invalid block-ciphered record" )
94 #define EINVAL_PADDING __einfo_error ( EINFO_EINVAL_PADDING )
95 #define EINFO_EINVAL_PADDING \
96 __einfo_uniqify ( EINFO_EINVAL, 0x0b, \
97 "Invalid block padding" )
98 #define EINVAL_RX_STATE __einfo_error ( EINFO_EINVAL_RX_STATE )
99 #define EINFO_EINVAL_RX_STATE \
100 __einfo_uniqify ( EINFO_EINVAL, 0x0c, \
101 "Invalid receive state" )
102 #define EINVAL_MAC __einfo_error ( EINFO_EINVAL_MAC )
103 #define EINFO_EINVAL_MAC \
104 __einfo_uniqify ( EINFO_EINVAL, 0x0d, \
105 "Invalid MAC" )
106 #define EINVAL_TICKET __einfo_error ( EINFO_EINVAL_TICKET )
107 #define EINFO_EINVAL_TICKET \
108 __einfo_uniqify ( EINFO_EINVAL, 0x0e, \
109 "Invalid New Session Ticket record")
110 #define EIO_ALERT __einfo_error ( EINFO_EIO_ALERT )
111 #define EINFO_EIO_ALERT \
112 __einfo_uniqify ( EINFO_EIO, 0x01, \
113 "Unknown alert level" )
114 #define ENOMEM_CONTEXT __einfo_error ( EINFO_ENOMEM_CONTEXT )
115 #define EINFO_ENOMEM_CONTEXT \
116 __einfo_uniqify ( EINFO_ENOMEM, 0x01, \
117 "Not enough space for crypto context" )
118 #define ENOMEM_CERTIFICATE __einfo_error ( EINFO_ENOMEM_CERTIFICATE )
119 #define EINFO_ENOMEM_CERTIFICATE \
120 __einfo_uniqify ( EINFO_ENOMEM, 0x02, \
121 "Not enough space for certificate" )
122 #define ENOMEM_CHAIN __einfo_error ( EINFO_ENOMEM_CHAIN )
123 #define EINFO_ENOMEM_CHAIN \
124 __einfo_uniqify ( EINFO_ENOMEM, 0x03, \
125 "Not enough space for certificate chain" )
126 #define ENOMEM_TX_PLAINTEXT __einfo_error ( EINFO_ENOMEM_TX_PLAINTEXT )
127 #define EINFO_ENOMEM_TX_PLAINTEXT \
128 __einfo_uniqify ( EINFO_ENOMEM, 0x04, \
129 "Not enough space for transmitted plaintext" )
130 #define ENOMEM_TX_CIPHERTEXT __einfo_error ( EINFO_ENOMEM_TX_CIPHERTEXT )
131 #define EINFO_ENOMEM_TX_CIPHERTEXT \
132 __einfo_uniqify ( EINFO_ENOMEM, 0x05, \
133 "Not enough space for transmitted ciphertext" )
134 #define ENOMEM_RX_DATA __einfo_error ( EINFO_ENOMEM_RX_DATA )
135 #define EINFO_ENOMEM_RX_DATA \
136 __einfo_uniqify ( EINFO_ENOMEM, 0x07, \
137 "Not enough space for received data" )
138 #define ENOMEM_RX_CONCAT __einfo_error ( EINFO_ENOMEM_RX_CONCAT )
139 #define EINFO_ENOMEM_RX_CONCAT \
140 __einfo_uniqify ( EINFO_ENOMEM, 0x08, \
141 "Not enough space to concatenate received data" )
142 #define ENOTSUP_CIPHER __einfo_error ( EINFO_ENOTSUP_CIPHER )
143 #define EINFO_ENOTSUP_CIPHER \
144 __einfo_uniqify ( EINFO_ENOTSUP, 0x01, \
145 "Unsupported cipher" )
146 #define ENOTSUP_NULL __einfo_error ( EINFO_ENOTSUP_NULL )
147 #define EINFO_ENOTSUP_NULL \
148 __einfo_uniqify ( EINFO_ENOTSUP, 0x02, \
149 "Refusing to use null cipher" )
150 #define ENOTSUP_SIG_HASH __einfo_error ( EINFO_ENOTSUP_SIG_HASH )
151 #define EINFO_ENOTSUP_SIG_HASH \
152 __einfo_uniqify ( EINFO_ENOTSUP, 0x03, \
153 "Unsupported signature and hash algorithm" )
154 #define ENOTSUP_VERSION __einfo_error ( EINFO_ENOTSUP_VERSION )
155 #define EINFO_ENOTSUP_VERSION \
156 __einfo_uniqify ( EINFO_ENOTSUP, 0x04, \
157 "Unsupported protocol version" )
158 #define EPERM_ALERT __einfo_error ( EINFO_EPERM_ALERT )
159 #define EINFO_EPERM_ALERT \
160 __einfo_uniqify ( EINFO_EPERM, 0x01, \
161 "Received fatal alert" )
162 #define EPERM_VERIFY __einfo_error ( EINFO_EPERM_VERIFY )
163 #define EINFO_EPERM_VERIFY \
164 __einfo_uniqify ( EINFO_EPERM, 0x02, \
165 "Handshake verification failed" )
166 #define EPERM_CLIENT_CERT __einfo_error ( EINFO_EPERM_CLIENT_CERT )
167 #define EINFO_EPERM_CLIENT_CERT \
168 __einfo_uniqify ( EINFO_EPERM, 0x03, \
169 "No suitable client certificate available" )
170 #define EPERM_RENEG_INSECURE __einfo_error ( EINFO_EPERM_RENEG_INSECURE )
171 #define EINFO_EPERM_RENEG_INSECURE \
172 __einfo_uniqify ( EINFO_EPERM, 0x04, \
173 "Secure renegotiation not supported" )
174 #define EPERM_RENEG_VERIFY __einfo_error ( EINFO_EPERM_RENEG_VERIFY )
175 #define EINFO_EPERM_RENEG_VERIFY \
176 __einfo_uniqify ( EINFO_EPERM, 0x05, \
177 "Secure renegotiation verification failed" )
178 #define EPROTO_VERSION __einfo_error ( EINFO_EPROTO_VERSION )
179 #define EINFO_EPROTO_VERSION \
180 __einfo_uniqify ( EINFO_EPROTO, 0x01, \
181 "Illegal protocol version upgrade" )
182
183 /** List of TLS session */
184 static LIST_HEAD ( tls_sessions );
185
186 static void tls_tx_resume_all ( struct tls_session *session );
187 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
188 const void *data, size_t len );
189 static void tls_clear_cipher ( struct tls_connection *tls,
190 struct tls_cipherspec *cipherspec );
191
192 /******************************************************************************
193 *
194 * Utility functions
195 *
196 ******************************************************************************
197 */
198
199 /** A TLS 24-bit integer
200 *
201 * TLS uses 24-bit integers in several places, which are awkward to
202 * parse in C.
203 */
204 typedef struct {
205 /** High byte */
206 uint8_t high;
207 /** Low word */
208 uint16_t low;
209 } __attribute__ (( packed )) tls24_t;
210
211 /**
212 * Extract 24-bit field value
213 *
214 * @v field24 24-bit field
215 * @ret value Field value
216 *
217 */
218 static inline __attribute__ (( always_inline )) unsigned long
219 tls_uint24 ( const tls24_t *field24 ) {
220
221 return ( ( field24->high << 16 ) | be16_to_cpu ( field24->low ) );
222 }
223
224 /**
225 * Set 24-bit field value
226 *
227 * @v field24 24-bit field
228 * @v value Field value
229 */
230 static void tls_set_uint24 ( tls24_t *field24, unsigned long value ) {
231
232 field24->high = ( value >> 16 );
233 field24->low = cpu_to_be16 ( value );
234 }
235
236 /**
237 * Determine if TLS connection is ready for application data
238 *
239 * @v tls TLS connection
240 * @ret is_ready TLS connection is ready
241 */
242 static int tls_ready ( struct tls_connection *tls ) {
243 return ( ( ! is_pending ( &tls->client_negotiation ) ) &&
244 ( ! is_pending ( &tls->server_negotiation ) ) );
245 }
246
247 /******************************************************************************
248 *
249 * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
250 *
251 ******************************************************************************
252 */
253
254 /**
255 * Initialise MD5+SHA1 algorithm
256 *
257 * @v ctx MD5+SHA1 context
258 */
259 static void md5_sha1_init ( void *ctx ) {
260 struct md5_sha1_context *context = ctx;
261
262 digest_init ( &md5_algorithm, context->md5 );
263 digest_init ( &sha1_algorithm, context->sha1 );
264 }
265
266 /**
267 * Accumulate data with MD5+SHA1 algorithm
268 *
269 * @v ctx MD5+SHA1 context
270 * @v data Data
271 * @v len Length of data
272 */
273 static void md5_sha1_update ( void *ctx, const void *data, size_t len ) {
274 struct md5_sha1_context *context = ctx;
275
276 digest_update ( &md5_algorithm, context->md5, data, len );
277 digest_update ( &sha1_algorithm, context->sha1, data, len );
278 }
279
280 /**
281 * Generate MD5+SHA1 digest
282 *
283 * @v ctx MD5+SHA1 context
284 * @v out Output buffer
285 */
286 static void md5_sha1_final ( void *ctx, void *out ) {
287 struct md5_sha1_context *context = ctx;
288 struct md5_sha1_digest *digest = out;
289
290 digest_final ( &md5_algorithm, context->md5, digest->md5 );
291 digest_final ( &sha1_algorithm, context->sha1, digest->sha1 );
292 }
293
294 /** Hybrid MD5+SHA1 digest algorithm */
295 static struct digest_algorithm md5_sha1_algorithm = {
296 .name = "md5+sha1",
297 .ctxsize = sizeof ( struct md5_sha1_context ),
298 .blocksize = 0, /* Not applicable */
299 .digestsize = sizeof ( struct md5_sha1_digest ),
300 .init = md5_sha1_init,
301 .update = md5_sha1_update,
302 .final = md5_sha1_final,
303 };
304
305 /** RSA digestInfo prefix for MD5+SHA1 algorithm */
306 struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix = {
307 .digest = &md5_sha1_algorithm,
308 .data = NULL, /* MD5+SHA1 signatures have no digestInfo */
309 .len = 0,
310 };
311
312 /******************************************************************************
313 *
314 * Cleanup functions
315 *
316 ******************************************************************************
317 */
318
319 /**
320 * Free TLS session
321 *
322 * @v refcnt Reference counter
323 */
324 static void free_tls_session ( struct refcnt *refcnt ) {
325 struct tls_session *session =
326 container_of ( refcnt, struct tls_session, refcnt );
327
328 /* Sanity check */
329 assert ( list_empty ( &session->conn ) );
330
331 /* Remove from list of sessions */
332 list_del ( &session->list );
333
334 /* Free session ticket */
335 free ( session->ticket );
336
337 /* Free session */
338 free ( session );
339 }
340
341 /**
342 * Free TLS connection
343 *
344 * @v refcnt Reference counter
345 */
346 static void free_tls ( struct refcnt *refcnt ) {
347 struct tls_connection *tls =
348 container_of ( refcnt, struct tls_connection, refcnt );
349 struct tls_session *session = tls->session;
350 struct io_buffer *iobuf;
351 struct io_buffer *tmp;
352
353 /* Free dynamically-allocated resources */
354 free ( tls->new_session_ticket );
355 tls_clear_cipher ( tls, &tls->tx_cipherspec );
356 tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
357 tls_clear_cipher ( tls, &tls->rx_cipherspec );
358 tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
359 list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
360 list_del ( &iobuf->list );
361 free_iob ( iobuf );
362 }
363 x509_put ( tls->cert );
364 x509_chain_put ( tls->chain );
365
366 /* Drop reference to session */
367 assert ( list_empty ( &tls->list ) );
368 ref_put ( &session->refcnt );
369
370 /* Free TLS structure itself */
371 free ( tls );
372 }
373
374 /**
375 * Finish with TLS connection
376 *
377 * @v tls TLS connection
378 * @v rc Status code
379 */
380 static void tls_close ( struct tls_connection *tls, int rc ) {
381
382 /* Remove pending operations, if applicable */
383 pending_put ( &tls->client_negotiation );
384 pending_put ( &tls->server_negotiation );
385
386 /* Remove process */
387 process_del ( &tls->process );
388
389 /* Close all interfaces */
390 intf_shutdown ( &tls->cipherstream, rc );
391 intf_shutdown ( &tls->plainstream, rc );
392 intf_shutdown ( &tls->validator, rc );
393
394 /* Remove from session */
395 list_del ( &tls->list );
396 INIT_LIST_HEAD ( &tls->list );
397
398 /* Resume all other connections, in case we were the lead connection */
399 tls_tx_resume_all ( tls->session );
400 }
401
402 /******************************************************************************
403 *
404 * Random number generation
405 *
406 ******************************************************************************
407 */
408
409 /**
410 * Generate random data
411 *
412 * @v tls TLS connection
413 * @v data Buffer to fill
414 * @v len Length of buffer
415 * @ret rc Return status code
416 */
417 static int tls_generate_random ( struct tls_connection *tls,
418 void *data, size_t len ) {
419 int rc;
420
421 /* Generate random bits with no additional input and without
422 * prediction resistance
423 */
424 if ( ( rc = rbg_generate ( NULL, 0, 0, data, len ) ) != 0 ) {
425 DBGC ( tls, "TLS %p could not generate random data: %s\n",
426 tls, strerror ( rc ) );
427 return rc;
428 }
429
430 return 0;
431 }
432
433 /**
434 * Update HMAC with a list of ( data, len ) pairs
435 *
436 * @v digest Hash function to use
437 * @v digest_ctx Digest context
438 * @v args ( data, len ) pairs of data, terminated by NULL
439 */
440 static void tls_hmac_update_va ( struct digest_algorithm *digest,
441 void *digest_ctx, va_list args ) {
442 void *data;
443 size_t len;
444
445 while ( ( data = va_arg ( args, void * ) ) ) {
446 len = va_arg ( args, size_t );
447 hmac_update ( digest, digest_ctx, data, len );
448 }
449 }
450
451 /**
452 * Generate secure pseudo-random data using a single hash function
453 *
454 * @v tls TLS connection
455 * @v digest Hash function to use
456 * @v secret Secret
457 * @v secret_len Length of secret
458 * @v out Output buffer
459 * @v out_len Length of output buffer
460 * @v seeds ( data, len ) pairs of seed data, terminated by NULL
461 */
462 static void tls_p_hash_va ( struct tls_connection *tls,
463 struct digest_algorithm *digest,
464 void *secret, size_t secret_len,
465 void *out, size_t out_len,
466 va_list seeds ) {
467 uint8_t secret_copy[secret_len];
468 uint8_t digest_ctx[digest->ctxsize];
469 uint8_t digest_ctx_partial[digest->ctxsize];
470 uint8_t a[digest->digestsize];
471 uint8_t out_tmp[digest->digestsize];
472 size_t frag_len = digest->digestsize;
473 va_list tmp;
474
475 /* Copy the secret, in case HMAC modifies it */
476 memcpy ( secret_copy, secret, secret_len );
477 secret = secret_copy;
478 DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
479 DBGC2_HD ( tls, secret, secret_len );
480
481 /* Calculate A(1) */
482 hmac_init ( digest, digest_ctx, secret, &secret_len );
483 va_copy ( tmp, seeds );
484 tls_hmac_update_va ( digest, digest_ctx, tmp );
485 va_end ( tmp );
486 hmac_final ( digest, digest_ctx, secret, &secret_len, a );
487 DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
488 DBGC2_HD ( tls, &a, sizeof ( a ) );
489
490 /* Generate as much data as required */
491 while ( out_len ) {
492 /* Calculate output portion */
493 hmac_init ( digest, digest_ctx, secret, &secret_len );
494 hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
495 memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
496 va_copy ( tmp, seeds );
497 tls_hmac_update_va ( digest, digest_ctx, tmp );
498 va_end ( tmp );
499 hmac_final ( digest, digest_ctx,
500 secret, &secret_len, out_tmp );
501
502 /* Copy output */
503 if ( frag_len > out_len )
504 frag_len = out_len;
505 memcpy ( out, out_tmp, frag_len );
506 DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
507 DBGC2_HD ( tls, out, frag_len );
508
509 /* Calculate A(i) */
510 hmac_final ( digest, digest_ctx_partial,
511 secret, &secret_len, a );
512 DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
513 DBGC2_HD ( tls, &a, sizeof ( a ) );
514
515 out += frag_len;
516 out_len -= frag_len;
517 }
518 }
519
520 /**
521 * Generate secure pseudo-random data
522 *
523 * @v tls TLS connection
524 * @v secret Secret
525 * @v secret_len Length of secret
526 * @v out Output buffer
527 * @v out_len Length of output buffer
528 * @v ... ( data, len ) pairs of seed data, terminated by NULL
529 */
530 static void tls_prf ( struct tls_connection *tls, void *secret,
531 size_t secret_len, void *out, size_t out_len, ... ) {
532 va_list seeds;
533 va_list tmp;
534 size_t subsecret_len;
535 void *md5_secret;
536 void *sha1_secret;
537 uint8_t buf[out_len];
538 unsigned int i;
539
540 va_start ( seeds, out_len );
541
542 if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
543 /* Use P_SHA256 for TLSv1.2 and later */
544 tls_p_hash_va ( tls, &sha256_algorithm, secret, secret_len,
545 out, out_len, seeds );
546 } else {
547 /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
548 * and earlier
549 */
550
551 /* Split secret into two, with an overlap of up to one byte */
552 subsecret_len = ( ( secret_len + 1 ) / 2 );
553 md5_secret = secret;
554 sha1_secret = ( secret + secret_len - subsecret_len );
555
556 /* Calculate MD5 portion */
557 va_copy ( tmp, seeds );
558 tls_p_hash_va ( tls, &md5_algorithm, md5_secret,
559 subsecret_len, out, out_len, seeds );
560 va_end ( tmp );
561
562 /* Calculate SHA1 portion */
563 va_copy ( tmp, seeds );
564 tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret,
565 subsecret_len, buf, out_len, seeds );
566 va_end ( tmp );
567
568 /* XOR the two portions together into the final output buffer */
569 for ( i = 0 ; i < out_len ; i++ )
570 *( ( uint8_t * ) out + i ) ^= buf[i];
571 }
572
573 va_end ( seeds );
574 }
575
576 /**
577 * Generate secure pseudo-random data
578 *
579 * @v secret Secret
580 * @v secret_len Length of secret
581 * @v out Output buffer
582 * @v out_len Length of output buffer
583 * @v label String literal label
584 * @v ... ( data, len ) pairs of seed data
585 */
586 #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
587 tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
588 label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
589
590 /******************************************************************************
591 *
592 * Secret management
593 *
594 ******************************************************************************
595 */
596
597 /**
598 * Generate master secret
599 *
600 * @v tls TLS connection
601 *
602 * The pre-master secret and the client and server random values must
603 * already be known.
604 */
605 static void tls_generate_master_secret ( struct tls_connection *tls ) {
606 DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
607 DBGC_HD ( tls, &tls->pre_master_secret,
608 sizeof ( tls->pre_master_secret ) );
609 DBGC ( tls, "TLS %p client random bytes:\n", tls );
610 DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
611 DBGC ( tls, "TLS %p server random bytes:\n", tls );
612 DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
613
614 tls_prf_label ( tls, &tls->pre_master_secret,
615 sizeof ( tls->pre_master_secret ),
616 &tls->master_secret, sizeof ( tls->master_secret ),
617 "master secret",
618 &tls->client_random, sizeof ( tls->client_random ),
619 &tls->server_random, sizeof ( tls->server_random ) );
620
621 DBGC ( tls, "TLS %p generated master secret:\n", tls );
622 DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
623 }
624
625 /**
626 * Generate key material
627 *
628 * @v tls TLS connection
629 *
630 * The master secret must already be known.
631 */
632 static int tls_generate_keys ( struct tls_connection *tls ) {
633 struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
634 struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
635 size_t hash_size = tx_cipherspec->suite->digest->digestsize;
636 size_t key_size = tx_cipherspec->suite->key_len;
637 size_t iv_size = tx_cipherspec->suite->cipher->blocksize;
638 size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
639 uint8_t key_block[total];
640 uint8_t *key;
641 int rc;
642
643 /* Generate key block */
644 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
645 key_block, sizeof ( key_block ), "key expansion",
646 &tls->server_random, sizeof ( tls->server_random ),
647 &tls->client_random, sizeof ( tls->client_random ) );
648
649 /* Split key block into portions */
650 key = key_block;
651
652 /* TX MAC secret */
653 memcpy ( tx_cipherspec->mac_secret, key, hash_size );
654 DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
655 DBGC_HD ( tls, key, hash_size );
656 key += hash_size;
657
658 /* RX MAC secret */
659 memcpy ( rx_cipherspec->mac_secret, key, hash_size );
660 DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
661 DBGC_HD ( tls, key, hash_size );
662 key += hash_size;
663
664 /* TX key */
665 if ( ( rc = cipher_setkey ( tx_cipherspec->suite->cipher,
666 tx_cipherspec->cipher_ctx,
667 key, key_size ) ) != 0 ) {
668 DBGC ( tls, "TLS %p could not set TX key: %s\n",
669 tls, strerror ( rc ) );
670 return rc;
671 }
672 DBGC ( tls, "TLS %p TX key:\n", tls );
673 DBGC_HD ( tls, key, key_size );
674 key += key_size;
675
676 /* RX key */
677 if ( ( rc = cipher_setkey ( rx_cipherspec->suite->cipher,
678 rx_cipherspec->cipher_ctx,
679 key, key_size ) ) != 0 ) {
680 DBGC ( tls, "TLS %p could not set TX key: %s\n",
681 tls, strerror ( rc ) );
682 return rc;
683 }
684 DBGC ( tls, "TLS %p RX key:\n", tls );
685 DBGC_HD ( tls, key, key_size );
686 key += key_size;
687
688 /* TX initialisation vector */
689 cipher_setiv ( tx_cipherspec->suite->cipher,
690 tx_cipherspec->cipher_ctx, key );
691 DBGC ( tls, "TLS %p TX IV:\n", tls );
692 DBGC_HD ( tls, key, iv_size );
693 key += iv_size;
694
695 /* RX initialisation vector */
696 cipher_setiv ( rx_cipherspec->suite->cipher,
697 rx_cipherspec->cipher_ctx, key );
698 DBGC ( tls, "TLS %p RX IV:\n", tls );
699 DBGC_HD ( tls, key, iv_size );
700 key += iv_size;
701
702 assert ( ( key_block + total ) == key );
703
704 return 0;
705 }
706
707 /******************************************************************************
708 *
709 * Cipher suite management
710 *
711 ******************************************************************************
712 */
713
714 /** Null cipher suite */
715 struct tls_cipher_suite tls_cipher_suite_null = {
716 .pubkey = &pubkey_null,
717 .cipher = &cipher_null,
718 .digest = &digest_null,
719 };
720
721 /** Number of supported cipher suites */
722 #define TLS_NUM_CIPHER_SUITES table_num_entries ( TLS_CIPHER_SUITES )
723
724 /**
725 * Identify cipher suite
726 *
727 * @v cipher_suite Cipher suite specification
728 * @ret suite Cipher suite, or NULL
729 */
730 static struct tls_cipher_suite *
731 tls_find_cipher_suite ( unsigned int cipher_suite ) {
732 struct tls_cipher_suite *suite;
733
734 /* Identify cipher suite */
735 for_each_table_entry ( suite, TLS_CIPHER_SUITES ) {
736 if ( suite->code == cipher_suite )
737 return suite;
738 }
739
740 return NULL;
741 }
742
743 /**
744 * Clear cipher suite
745 *
746 * @v cipherspec TLS cipher specification
747 */
748 static void tls_clear_cipher ( struct tls_connection *tls __unused,
749 struct tls_cipherspec *cipherspec ) {
750
751 if ( cipherspec->suite ) {
752 pubkey_final ( cipherspec->suite->pubkey,
753 cipherspec->pubkey_ctx );
754 }
755 free ( cipherspec->dynamic );
756 memset ( cipherspec, 0, sizeof ( *cipherspec ) );
757 cipherspec->suite = &tls_cipher_suite_null;
758 }
759
760 /**
761 * Set cipher suite
762 *
763 * @v tls TLS connection
764 * @v cipherspec TLS cipher specification
765 * @v suite Cipher suite
766 * @ret rc Return status code
767 */
768 static int tls_set_cipher ( struct tls_connection *tls,
769 struct tls_cipherspec *cipherspec,
770 struct tls_cipher_suite *suite ) {
771 struct pubkey_algorithm *pubkey = suite->pubkey;
772 struct cipher_algorithm *cipher = suite->cipher;
773 struct digest_algorithm *digest = suite->digest;
774 size_t total;
775 void *dynamic;
776
777 /* Clear out old cipher contents, if any */
778 tls_clear_cipher ( tls, cipherspec );
779
780 /* Allocate dynamic storage */
781 total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
782 dynamic = zalloc ( total );
783 if ( ! dynamic ) {
784 DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
785 "context\n", tls, total );
786 return -ENOMEM_CONTEXT;
787 }
788
789 /* Assign storage */
790 cipherspec->dynamic = dynamic;
791 cipherspec->pubkey_ctx = dynamic; dynamic += pubkey->ctxsize;
792 cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
793 cipherspec->cipher_next_ctx = dynamic; dynamic += cipher->ctxsize;
794 cipherspec->mac_secret = dynamic; dynamic += digest->digestsize;
795 assert ( ( cipherspec->dynamic + total ) == dynamic );
796
797 /* Store parameters */
798 cipherspec->suite = suite;
799
800 return 0;
801 }
802
803 /**
804 * Select next cipher suite
805 *
806 * @v tls TLS connection
807 * @v cipher_suite Cipher suite specification
808 * @ret rc Return status code
809 */
810 static int tls_select_cipher ( struct tls_connection *tls,
811 unsigned int cipher_suite ) {
812 struct tls_cipher_suite *suite;
813 int rc;
814
815 /* Identify cipher suite */
816 suite = tls_find_cipher_suite ( cipher_suite );
817 if ( ! suite ) {
818 DBGC ( tls, "TLS %p does not support cipher %04x\n",
819 tls, ntohs ( cipher_suite ) );
820 return -ENOTSUP_CIPHER;
821 }
822
823 /* Set ciphers */
824 if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending,
825 suite ) ) != 0 )
826 return rc;
827 if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending,
828 suite ) ) != 0 )
829 return rc;
830
831 DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls, suite->pubkey->name,
832 suite->cipher->name, ( suite->key_len * 8 ),
833 suite->digest->name );
834
835 return 0;
836 }
837
838 /**
839 * Activate next cipher suite
840 *
841 * @v tls TLS connection
842 * @v pending Pending cipher specification
843 * @v active Active cipher specification to replace
844 * @ret rc Return status code
845 */
846 static int tls_change_cipher ( struct tls_connection *tls,
847 struct tls_cipherspec *pending,
848 struct tls_cipherspec *active ) {
849
850 /* Sanity check */
851 if ( pending->suite == &tls_cipher_suite_null ) {
852 DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
853 return -ENOTSUP_NULL;
854 }
855
856 tls_clear_cipher ( tls, active );
857 memswap ( active, pending, sizeof ( *active ) );
858 return 0;
859 }
860
861 /******************************************************************************
862 *
863 * Signature and hash algorithms
864 *
865 ******************************************************************************
866 */
867
868 /** Number of supported signature and hash algorithms */
869 #define TLS_NUM_SIG_HASH_ALGORITHMS \
870 table_num_entries ( TLS_SIG_HASH_ALGORITHMS )
871
872 /**
873 * Find TLS signature and hash algorithm
874 *
875 * @v pubkey Public-key algorithm
876 * @v digest Digest algorithm
877 * @ret sig_hash Signature and hash algorithm, or NULL
878 */
879 static struct tls_signature_hash_algorithm *
880 tls_signature_hash_algorithm ( struct pubkey_algorithm *pubkey,
881 struct digest_algorithm *digest ) {
882 struct tls_signature_hash_algorithm *sig_hash;
883
884 /* Identify signature and hash algorithm */
885 for_each_table_entry ( sig_hash, TLS_SIG_HASH_ALGORITHMS ) {
886 if ( ( sig_hash->pubkey == pubkey ) &&
887 ( sig_hash->digest == digest ) ) {
888 return sig_hash;
889 }
890 }
891
892 return NULL;
893 }
894
895 /******************************************************************************
896 *
897 * Handshake verification
898 *
899 ******************************************************************************
900 */
901
902 /**
903 * Add handshake record to verification hash
904 *
905 * @v tls TLS connection
906 * @v data Handshake record
907 * @v len Length of handshake record
908 */
909 static void tls_add_handshake ( struct tls_connection *tls,
910 const void *data, size_t len ) {
911
912 digest_update ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx,
913 data, len );
914 digest_update ( &sha256_algorithm, tls->handshake_sha256_ctx,
915 data, len );
916 }
917
918 /**
919 * Calculate handshake verification hash
920 *
921 * @v tls TLS connection
922 * @v out Output buffer
923 *
924 * Calculates the MD5+SHA1 or SHA256 digest over all handshake
925 * messages seen so far.
926 */
927 static void tls_verify_handshake ( struct tls_connection *tls, void *out ) {
928 struct digest_algorithm *digest = tls->handshake_digest;
929 uint8_t ctx[ digest->ctxsize ];
930
931 memcpy ( ctx, tls->handshake_ctx, sizeof ( ctx ) );
932 digest_final ( digest, ctx, out );
933 }
934
935 /******************************************************************************
936 *
937 * Record handling
938 *
939 ******************************************************************************
940 */
941
942 /**
943 * Restart negotiation
944 *
945 * @v tls TLS connection
946 */
947 static void tls_restart ( struct tls_connection *tls ) {
948
949 /* Sanity check */
950 assert ( ! tls->tx_pending );
951 assert ( ! is_pending ( &tls->client_negotiation ) );
952 assert ( ! is_pending ( &tls->server_negotiation ) );
953
954 /* (Re)initialise handshake context */
955 digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
956 digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
957 tls->handshake_digest = &sha256_algorithm;
958 tls->handshake_ctx = tls->handshake_sha256_ctx;
959
960 /* (Re)start negotiation */
961 tls->tx_pending = TLS_TX_CLIENT_HELLO;
962 pending_get ( &tls->client_negotiation );
963 pending_get ( &tls->server_negotiation );
964 }
965
966 /**
967 * Resume TX state machine
968 *
969 * @v tls TLS connection
970 */
971 static void tls_tx_resume ( struct tls_connection *tls ) {
972 process_add ( &tls->process );
973 }
974
975 /**
976 * Resume TX state machine for all connections within a session
977 *
978 * @v session TLS session
979 */
980 static void tls_tx_resume_all ( struct tls_session *session ) {
981 struct tls_connection *tls;
982
983 list_for_each_entry ( tls, &session->conn, list )
984 tls_tx_resume ( tls );
985 }
986
987 /**
988 * Transmit Handshake record
989 *
990 * @v tls TLS connection
991 * @v data Plaintext record
992 * @v len Length of plaintext record
993 * @ret rc Return status code
994 */
995 static int tls_send_handshake ( struct tls_connection *tls,
996 void *data, size_t len ) {
997
998 /* Add to handshake digest */
999 tls_add_handshake ( tls, data, len );
1000
1001 /* Send record */
1002 return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
1003 }
1004
1005 /**
1006 * Transmit Client Hello record
1007 *
1008 * @v tls TLS connection
1009 * @ret rc Return status code
1010 */
1011 static int tls_send_client_hello ( struct tls_connection *tls ) {
1012 struct tls_session *session = tls->session;
1013 size_t name_len = strlen ( session->name );
1014 struct {
1015 uint32_t type_length;
1016 uint16_t version;
1017 uint8_t random[32];
1018 uint8_t session_id_len;
1019 uint8_t session_id[tls->session_id_len];
1020 uint16_t cipher_suite_len;
1021 uint16_t cipher_suites[TLS_NUM_CIPHER_SUITES];
1022 uint8_t compression_methods_len;
1023 uint8_t compression_methods[1];
1024 uint16_t extensions_len;
1025 struct {
1026 uint16_t server_name_type;
1027 uint16_t server_name_len;
1028 struct {
1029 uint16_t len;
1030 struct {
1031 uint8_t type;
1032 uint16_t len;
1033 uint8_t name[name_len];
1034 } __attribute__ (( packed )) list[1];
1035 } __attribute__ (( packed )) server_name;
1036 uint16_t max_fragment_length_type;
1037 uint16_t max_fragment_length_len;
1038 struct {
1039 uint8_t max;
1040 } __attribute__ (( packed )) max_fragment_length;
1041 uint16_t signature_algorithms_type;
1042 uint16_t signature_algorithms_len;
1043 struct {
1044 uint16_t len;
1045 struct tls_signature_hash_id
1046 code[TLS_NUM_SIG_HASH_ALGORITHMS];
1047 } __attribute__ (( packed )) signature_algorithms;
1048 uint16_t renegotiation_info_type;
1049 uint16_t renegotiation_info_len;
1050 struct {
1051 uint8_t len;
1052 uint8_t data[ tls->secure_renegotiation ?
1053 sizeof ( tls->verify.client ) :0];
1054 } __attribute__ (( packed )) renegotiation_info;
1055 uint16_t session_ticket_type;
1056 uint16_t session_ticket_len;
1057 struct {
1058 uint8_t data[session->ticket_len];
1059 } __attribute__ (( packed )) session_ticket;
1060 } __attribute__ (( packed )) extensions;
1061 } __attribute__ (( packed )) hello;
1062 struct tls_cipher_suite *suite;
1063 struct tls_signature_hash_algorithm *sighash;
1064 unsigned int i;
1065
1066 /* Construct record */
1067 memset ( &hello, 0, sizeof ( hello ) );
1068 hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
1069 htonl ( sizeof ( hello ) -
1070 sizeof ( hello.type_length ) ) );
1071 hello.version = htons ( tls->version );
1072 memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
1073 hello.session_id_len = tls->session_id_len;
1074 memcpy ( hello.session_id, tls->session_id,
1075 sizeof ( hello.session_id ) );
1076 hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
1077 i = 0 ; for_each_table_entry ( suite, TLS_CIPHER_SUITES )
1078 hello.cipher_suites[i++] = suite->code;
1079 hello.compression_methods_len = sizeof ( hello.compression_methods );
1080 hello.extensions_len = htons ( sizeof ( hello.extensions ) );
1081 hello.extensions.server_name_type = htons ( TLS_SERVER_NAME );
1082 hello.extensions.server_name_len
1083 = htons ( sizeof ( hello.extensions.server_name ) );
1084 hello.extensions.server_name.len
1085 = htons ( sizeof ( hello.extensions.server_name.list ) );
1086 hello.extensions.server_name.list[0].type = TLS_SERVER_NAME_HOST_NAME;
1087 hello.extensions.server_name.list[0].len
1088 = htons ( sizeof ( hello.extensions.server_name.list[0].name ));
1089 memcpy ( hello.extensions.server_name.list[0].name, session->name,
1090 sizeof ( hello.extensions.server_name.list[0].name ) );
1091 hello.extensions.max_fragment_length_type
1092 = htons ( TLS_MAX_FRAGMENT_LENGTH );
1093 hello.extensions.max_fragment_length_len
1094 = htons ( sizeof ( hello.extensions.max_fragment_length ) );
1095 hello.extensions.max_fragment_length.max
1096 = TLS_MAX_FRAGMENT_LENGTH_4096;
1097 hello.extensions.signature_algorithms_type
1098 = htons ( TLS_SIGNATURE_ALGORITHMS );
1099 hello.extensions.signature_algorithms_len
1100 = htons ( sizeof ( hello.extensions.signature_algorithms ) );
1101 hello.extensions.signature_algorithms.len
1102 = htons ( sizeof ( hello.extensions.signature_algorithms.code));
1103 i = 0 ; for_each_table_entry ( sighash, TLS_SIG_HASH_ALGORITHMS )
1104 hello.extensions.signature_algorithms.code[i++] = sighash->code;
1105 hello.extensions.renegotiation_info_type
1106 = htons ( TLS_RENEGOTIATION_INFO );
1107 hello.extensions.renegotiation_info_len
1108 = htons ( sizeof ( hello.extensions.renegotiation_info ) );
1109 hello.extensions.renegotiation_info.len
1110 = sizeof ( hello.extensions.renegotiation_info.data );
1111 memcpy ( hello.extensions.renegotiation_info.data, tls->verify.client,
1112 sizeof ( hello.extensions.renegotiation_info.data ) );
1113 hello.extensions.session_ticket_type = htons ( TLS_SESSION_TICKET );
1114 hello.extensions.session_ticket_len
1115 = htons ( sizeof ( hello.extensions.session_ticket ) );
1116 memcpy ( hello.extensions.session_ticket.data, session->ticket,
1117 sizeof ( hello.extensions.session_ticket.data ) );
1118
1119 return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
1120 }
1121
1122 /**
1123 * Transmit Certificate record
1124 *
1125 * @v tls TLS connection
1126 * @ret rc Return status code
1127 */
1128 static int tls_send_certificate ( struct tls_connection *tls ) {
1129 struct {
1130 uint32_t type_length;
1131 tls24_t length;
1132 struct {
1133 tls24_t length;
1134 uint8_t data[ tls->cert->raw.len ];
1135 } __attribute__ (( packed )) certificates[1];
1136 } __attribute__ (( packed )) *certificate;
1137 int rc;
1138
1139 /* Allocate storage for Certificate record (which may be too
1140 * large for the stack).
1141 */
1142 certificate = zalloc ( sizeof ( *certificate ) );
1143 if ( ! certificate )
1144 return -ENOMEM_CERTIFICATE;
1145
1146 /* Populate record */
1147 certificate->type_length =
1148 ( cpu_to_le32 ( TLS_CERTIFICATE ) |
1149 htonl ( sizeof ( *certificate ) -
1150 sizeof ( certificate->type_length ) ) );
1151 tls_set_uint24 ( &certificate->length,
1152 sizeof ( certificate->certificates ) );
1153 tls_set_uint24 ( &certificate->certificates[0].length,
1154 sizeof ( certificate->certificates[0].data ) );
1155 memcpy ( certificate->certificates[0].data,
1156 tls->cert->raw.data,
1157 sizeof ( certificate->certificates[0].data ) );
1158
1159 /* Transmit record */
1160 rc = tls_send_handshake ( tls, certificate, sizeof ( *certificate ) );
1161
1162 /* Free record */
1163 free ( certificate );
1164
1165 return rc;
1166 }
1167
1168 /**
1169 * Transmit Client Key Exchange record
1170 *
1171 * @v tls TLS connection
1172 * @ret rc Return status code
1173 */
1174 static int tls_send_client_key_exchange ( struct tls_connection *tls ) {
1175 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
1176 struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
1177 size_t max_len = pubkey_max_len ( pubkey, cipherspec->pubkey_ctx );
1178 struct {
1179 uint32_t type_length;
1180 uint16_t encrypted_pre_master_secret_len;
1181 uint8_t encrypted_pre_master_secret[max_len];
1182 } __attribute__ (( packed )) key_xchg;
1183 size_t unused;
1184 int len;
1185 int rc;
1186
1187 /* Encrypt pre-master secret using server's public key */
1188 memset ( &key_xchg, 0, sizeof ( key_xchg ) );
1189 len = pubkey_encrypt ( pubkey, cipherspec->pubkey_ctx,
1190 &tls->pre_master_secret,
1191 sizeof ( tls->pre_master_secret ),
1192 key_xchg.encrypted_pre_master_secret );
1193 if ( len < 0 ) {
1194 rc = len;
1195 DBGC ( tls, "TLS %p could not encrypt pre-master secret: %s\n",
1196 tls, strerror ( rc ) );
1197 return rc;
1198 }
1199 unused = ( max_len - len );
1200 key_xchg.type_length =
1201 ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
1202 htonl ( sizeof ( key_xchg ) -
1203 sizeof ( key_xchg.type_length ) - unused ) );
1204 key_xchg.encrypted_pre_master_secret_len =
1205 htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) -
1206 unused );
1207
1208 return tls_send_handshake ( tls, &key_xchg,
1209 ( sizeof ( key_xchg ) - unused ) );
1210 }
1211
1212 /**
1213 * Transmit Certificate Verify record
1214 *
1215 * @v tls TLS connection
1216 * @ret rc Return status code
1217 */
1218 static int tls_send_certificate_verify ( struct tls_connection *tls ) {
1219 struct digest_algorithm *digest = tls->handshake_digest;
1220 struct x509_certificate *cert = tls->cert;
1221 struct pubkey_algorithm *pubkey = cert->signature_algorithm->pubkey;
1222 uint8_t digest_out[ digest->digestsize ];
1223 uint8_t ctx[ pubkey->ctxsize ];
1224 struct tls_signature_hash_algorithm *sig_hash = NULL;
1225 int rc;
1226
1227 /* Generate digest to be signed */
1228 tls_verify_handshake ( tls, digest_out );
1229
1230 /* Initialise public-key algorithm */
1231 if ( ( rc = pubkey_init ( pubkey, ctx, private_key.data,
1232 private_key.len ) ) != 0 ) {
1233 DBGC ( tls, "TLS %p could not initialise %s client private "
1234 "key: %s\n", tls, pubkey->name, strerror ( rc ) );
1235 goto err_pubkey_init;
1236 }
1237
1238 /* TLSv1.2 and later use explicit algorithm identifiers */
1239 if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
1240 sig_hash = tls_signature_hash_algorithm ( pubkey, digest );
1241 if ( ! sig_hash ) {
1242 DBGC ( tls, "TLS %p could not identify (%s,%s) "
1243 "signature and hash algorithm\n", tls,
1244 pubkey->name, digest->name );
1245 rc = -ENOTSUP_SIG_HASH;
1246 goto err_sig_hash;
1247 }
1248 }
1249
1250 /* Generate and transmit record */
1251 {
1252 size_t max_len = pubkey_max_len ( pubkey, ctx );
1253 int use_sig_hash = ( ( sig_hash == NULL ) ? 0 : 1 );
1254 struct {
1255 uint32_t type_length;
1256 struct tls_signature_hash_id sig_hash[use_sig_hash];
1257 uint16_t signature_len;
1258 uint8_t signature[max_len];
1259 } __attribute__ (( packed )) certificate_verify;
1260 size_t unused;
1261 int len;
1262
1263 /* Sign digest */
1264 len = pubkey_sign ( pubkey, ctx, digest, digest_out,
1265 certificate_verify.signature );
1266 if ( len < 0 ) {
1267 rc = len;
1268 DBGC ( tls, "TLS %p could not sign %s digest using %s "
1269 "client private key: %s\n", tls, digest->name,
1270 pubkey->name, strerror ( rc ) );
1271 goto err_pubkey_sign;
1272 }
1273 unused = ( max_len - len );
1274
1275 /* Construct Certificate Verify record */
1276 certificate_verify.type_length =
1277 ( cpu_to_le32 ( TLS_CERTIFICATE_VERIFY ) |
1278 htonl ( sizeof ( certificate_verify ) -
1279 sizeof ( certificate_verify.type_length ) -
1280 unused ) );
1281 if ( use_sig_hash ) {
1282 memcpy ( &certificate_verify.sig_hash[0],
1283 &sig_hash->code,
1284 sizeof ( certificate_verify.sig_hash[0] ) );
1285 }
1286 certificate_verify.signature_len =
1287 htons ( sizeof ( certificate_verify.signature ) -
1288 unused );
1289
1290 /* Transmit record */
1291 rc = tls_send_handshake ( tls, &certificate_verify,
1292 ( sizeof ( certificate_verify ) - unused ) );
1293 }
1294
1295 err_pubkey_sign:
1296 err_sig_hash:
1297 pubkey_final ( pubkey, ctx );
1298 err_pubkey_init:
1299 return rc;
1300 }
1301
1302 /**
1303 * Transmit Change Cipher record
1304 *
1305 * @v tls TLS connection
1306 * @ret rc Return status code
1307 */
1308 static int tls_send_change_cipher ( struct tls_connection *tls ) {
1309 static const uint8_t change_cipher[1] = { 1 };
1310 return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
1311 change_cipher, sizeof ( change_cipher ) );
1312 }
1313
1314 /**
1315 * Transmit Finished record
1316 *
1317 * @v tls TLS connection
1318 * @ret rc Return status code
1319 */
1320 static int tls_send_finished ( struct tls_connection *tls ) {
1321 struct digest_algorithm *digest = tls->handshake_digest;
1322 struct {
1323 uint32_t type_length;
1324 uint8_t verify_data[ sizeof ( tls->verify.client ) ];
1325 } __attribute__ (( packed )) finished;
1326 uint8_t digest_out[ digest->digestsize ];
1327 int rc;
1328
1329 /* Construct client verification data */
1330 tls_verify_handshake ( tls, digest_out );
1331 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1332 tls->verify.client, sizeof ( tls->verify.client ),
1333 "client finished", digest_out, sizeof ( digest_out ) );
1334
1335 /* Construct record */
1336 memset ( &finished, 0, sizeof ( finished ) );
1337 finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
1338 htonl ( sizeof ( finished ) -
1339 sizeof ( finished.type_length ) ) );
1340 memcpy ( finished.verify_data, tls->verify.client,
1341 sizeof ( finished.verify_data ) );
1342
1343 /* Transmit record */
1344 if ( ( rc = tls_send_handshake ( tls, &finished,
1345 sizeof ( finished ) ) ) != 0 )
1346 return rc;
1347
1348 /* Mark client as finished */
1349 pending_put ( &tls->client_negotiation );
1350
1351 return 0;
1352 }
1353
1354 /**
1355 * Receive new Change Cipher record
1356 *
1357 * @v tls TLS connection
1358 * @v data Plaintext record
1359 * @v len Length of plaintext record
1360 * @ret rc Return status code
1361 */
1362 static int tls_new_change_cipher ( struct tls_connection *tls,
1363 const void *data, size_t len ) {
1364 int rc;
1365
1366 if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
1367 DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
1368 DBGC_HD ( tls, data, len );
1369 return -EINVAL_CHANGE_CIPHER;
1370 }
1371
1372 if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
1373 &tls->rx_cipherspec ) ) != 0 ) {
1374 DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
1375 tls, strerror ( rc ) );
1376 return rc;
1377 }
1378 tls->rx_seq = ~( ( uint64_t ) 0 );
1379
1380 return 0;
1381 }
1382
1383 /**
1384 * Receive new Alert record
1385 *
1386 * @v tls TLS connection
1387 * @v data Plaintext record
1388 * @v len Length of plaintext record
1389 * @ret rc Return status code
1390 */
1391 static int tls_new_alert ( struct tls_connection *tls, const void *data,
1392 size_t len ) {
1393 const struct {
1394 uint8_t level;
1395 uint8_t description;
1396 char next[0];
1397 } __attribute__ (( packed )) *alert = data;
1398
1399 /* Sanity check */
1400 if ( sizeof ( *alert ) != len ) {
1401 DBGC ( tls, "TLS %p received overlength Alert\n", tls );
1402 DBGC_HD ( tls, data, len );
1403 return -EINVAL_ALERT;
1404 }
1405
1406 switch ( alert->level ) {
1407 case TLS_ALERT_WARNING:
1408 DBGC ( tls, "TLS %p received warning alert %d\n",
1409 tls, alert->description );
1410 return 0;
1411 case TLS_ALERT_FATAL:
1412 DBGC ( tls, "TLS %p received fatal alert %d\n",
1413 tls, alert->description );
1414 return -EPERM_ALERT;
1415 default:
1416 DBGC ( tls, "TLS %p received unknown alert level %d"
1417 "(alert %d)\n", tls, alert->level, alert->description );
1418 return -EIO_ALERT;
1419 }
1420 }
1421
1422 /**
1423 * Receive new Hello Request handshake record
1424 *
1425 * @v tls TLS connection
1426 * @v data Plaintext handshake record
1427 * @v len Length of plaintext handshake record
1428 * @ret rc Return status code
1429 */
1430 static int tls_new_hello_request ( struct tls_connection *tls,
1431 const void *data __unused,
1432 size_t len __unused ) {
1433
1434 /* Ignore if a handshake is in progress */
1435 if ( ! tls_ready ( tls ) ) {
1436 DBGC ( tls, "TLS %p ignoring Hello Request\n", tls );
1437 return 0;
1438 }
1439
1440 /* Fail unless server supports secure renegotiation */
1441 if ( ! tls->secure_renegotiation ) {
1442 DBGC ( tls, "TLS %p refusing to renegotiate insecurely\n",
1443 tls );
1444 return -EPERM_RENEG_INSECURE;
1445 }
1446
1447 /* Restart negotiation */
1448 tls_restart ( tls );
1449
1450 return 0;
1451 }
1452
1453 /**
1454 * Receive new Server Hello handshake record
1455 *
1456 * @v tls TLS connection
1457 * @v data Plaintext handshake record
1458 * @v len Length of plaintext handshake record
1459 * @ret rc Return status code
1460 */
1461 static int tls_new_server_hello ( struct tls_connection *tls,
1462 const void *data, size_t len ) {
1463 const struct {
1464 uint16_t version;
1465 uint8_t random[32];
1466 uint8_t session_id_len;
1467 uint8_t session_id[0];
1468 } __attribute__ (( packed )) *hello_a = data;
1469 const uint8_t *session_id;
1470 const struct {
1471 uint16_t cipher_suite;
1472 uint8_t compression_method;
1473 char next[0];
1474 } __attribute__ (( packed )) *hello_b;
1475 const struct {
1476 uint16_t len;
1477 uint8_t data[0];
1478 } __attribute__ (( packed )) *exts;
1479 const struct {
1480 uint16_t type;
1481 uint16_t len;
1482 uint8_t data[0];
1483 } __attribute__ (( packed )) *ext;
1484 const struct {
1485 uint8_t len;
1486 uint8_t data[0];
1487 } __attribute__ (( packed )) *reneg = NULL;
1488 uint16_t version;
1489 size_t exts_len;
1490 size_t ext_len;
1491 size_t remaining;
1492 int rc;
1493
1494 /* Parse header */
1495 if ( ( sizeof ( *hello_a ) > len ) ||
1496 ( hello_a->session_id_len > ( len - sizeof ( *hello_a ) ) ) ||
1497 ( sizeof ( *hello_b ) > ( len - sizeof ( *hello_a ) -
1498 hello_a->session_id_len ) ) ) {
1499 DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
1500 DBGC_HD ( tls, data, len );
1501 return -EINVAL_HELLO;
1502 }
1503 session_id = hello_a->session_id;
1504 hello_b = ( ( void * ) ( session_id + hello_a->session_id_len ) );
1505
1506 /* Parse extensions, if present */
1507 remaining = ( len - sizeof ( *hello_a ) - hello_a->session_id_len -
1508 sizeof ( *hello_b ) );
1509 if ( remaining ) {
1510
1511 /* Parse extensions length */
1512 exts = ( ( void * ) hello_b->next );
1513 if ( ( sizeof ( *exts ) > remaining ) ||
1514 ( ( exts_len = ntohs ( exts->len ) ) >
1515 ( remaining - sizeof ( *exts ) ) ) ) {
1516 DBGC ( tls, "TLS %p received underlength extensions\n",
1517 tls );
1518 DBGC_HD ( tls, data, len );
1519 return -EINVAL_HELLO;
1520 }
1521
1522 /* Parse extensions */
1523 for ( ext = ( ( void * ) exts->data ), remaining = exts_len ;
1524 remaining ;
1525 ext = ( ( ( void * ) ext ) + sizeof ( *ext ) + ext_len ),
1526 remaining -= ( sizeof ( *ext ) + ext_len ) ) {
1527
1528 /* Parse extension length */
1529 if ( ( sizeof ( *ext ) > remaining ) ||
1530 ( ( ext_len = ntohs ( ext->len ) ) >
1531 ( remaining - sizeof ( *ext ) ) ) ) {
1532 DBGC ( tls, "TLS %p received underlength "
1533 "extension\n", tls );
1534 DBGC_HD ( tls, data, len );
1535 return -EINVAL_HELLO;
1536 }
1537
1538 /* Record known extensions */
1539 switch ( ext->type ) {
1540 case htons ( TLS_RENEGOTIATION_INFO ) :
1541 reneg = ( ( void * ) ext->data );
1542 if ( ( sizeof ( *reneg ) > ext_len ) ||
1543 ( reneg->len >
1544 ( ext_len - sizeof ( *reneg ) ) ) ) {
1545 DBGC ( tls, "TLS %p received "
1546 "underlength renegotiation "
1547 "info\n", tls );
1548 DBGC_HD ( tls, data, len );
1549 return -EINVAL_HELLO;
1550 }
1551 break;
1552 }
1553 }
1554 }
1555
1556 /* Check and store protocol version */
1557 version = ntohs ( hello_a->version );
1558 if ( version < TLS_VERSION_TLS_1_0 ) {
1559 DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
1560 tls, ( version >> 8 ), ( version & 0xff ) );
1561 return -ENOTSUP_VERSION;
1562 }
1563 if ( version > tls->version ) {
1564 DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
1565 "protocol version %d.%d\n",
1566 tls, ( version >> 8 ), ( version & 0xff ) );
1567 return -EPROTO_VERSION;
1568 }
1569 tls->version = version;
1570 DBGC ( tls, "TLS %p using protocol version %d.%d\n",
1571 tls, ( version >> 8 ), ( version & 0xff ) );
1572
1573 /* Use MD5+SHA1 digest algorithm for handshake verification
1574 * for versions earlier than TLSv1.2.
1575 */
1576 if ( tls->version < TLS_VERSION_TLS_1_2 ) {
1577 tls->handshake_digest = &md5_sha1_algorithm;
1578 tls->handshake_ctx = tls->handshake_md5_sha1_ctx;
1579 }
1580
1581 /* Copy out server random bytes */
1582 memcpy ( &tls->server_random, &hello_a->random,
1583 sizeof ( tls->server_random ) );
1584
1585 /* Select cipher suite */
1586 if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
1587 return rc;
1588
1589 /* Reuse or generate master secret */
1590 if ( hello_a->session_id_len &&
1591 ( hello_a->session_id_len == tls->session_id_len ) &&
1592 ( memcmp ( session_id, tls->session_id,
1593 tls->session_id_len ) == 0 ) ) {
1594
1595 /* Session ID match: reuse master secret */
1596 DBGC ( tls, "TLS %p resuming session ID:\n", tls );
1597 DBGC_HDA ( tls, 0, tls->session_id, tls->session_id_len );
1598
1599 } else {
1600
1601 /* Generate new master secret */
1602 tls_generate_master_secret ( tls );
1603
1604 /* Record new session ID, if present */
1605 if ( hello_a->session_id_len &&
1606 ( hello_a->session_id_len <= sizeof ( tls->session_id ))){
1607 tls->session_id_len = hello_a->session_id_len;
1608 memcpy ( tls->session_id, session_id,
1609 tls->session_id_len );
1610 DBGC ( tls, "TLS %p new session ID:\n", tls );
1611 DBGC_HDA ( tls, 0, tls->session_id,
1612 tls->session_id_len );
1613 }
1614 }
1615
1616 /* Generate keys */
1617 if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
1618 return rc;
1619
1620 /* Handle secure renegotiation */
1621 if ( tls->secure_renegotiation ) {
1622
1623 /* Secure renegotiation is expected; verify data */
1624 if ( ( reneg == NULL ) ||
1625 ( reneg->len != sizeof ( tls->verify ) ) ||
1626 ( memcmp ( reneg->data, &tls->verify,
1627 sizeof ( tls->verify ) ) != 0 ) ) {
1628 DBGC ( tls, "TLS %p server failed secure "
1629 "renegotiation\n", tls );
1630 return -EPERM_RENEG_VERIFY;
1631 }
1632
1633 } else if ( reneg != NULL ) {
1634
1635 /* Secure renegotiation is being enabled */
1636 if ( reneg->len != 0 ) {
1637 DBGC ( tls, "TLS %p server provided non-empty initial "
1638 "renegotiation\n", tls );
1639 return -EPERM_RENEG_VERIFY;
1640 }
1641 tls->secure_renegotiation = 1;
1642 }
1643
1644 return 0;
1645 }
1646
1647 /**
1648 * Receive New Session Ticket handshake record
1649 *
1650 * @v tls TLS connection
1651 * @v data Plaintext handshake record
1652 * @v len Length of plaintext handshake record
1653 * @ret rc Return status code
1654 */
1655 static int tls_new_session_ticket ( struct tls_connection *tls,
1656 const void *data, size_t len ) {
1657 const struct {
1658 uint32_t lifetime;
1659 uint16_t len;
1660 uint8_t ticket[0];
1661 } __attribute__ (( packed )) *new_session_ticket = data;
1662 size_t ticket_len;
1663
1664 /* Parse header */
1665 if ( sizeof ( *new_session_ticket ) > len ) {
1666 DBGC ( tls, "TLS %p received underlength New Session Ticket\n",
1667 tls );
1668 DBGC_HD ( tls, data, len );
1669 return -EINVAL_TICKET;
1670 }
1671 ticket_len = ntohs ( new_session_ticket->len );
1672 if ( ticket_len > ( len - sizeof ( *new_session_ticket ) ) ) {
1673 DBGC ( tls, "TLS %p received overlength New Session Ticket\n",
1674 tls );
1675 DBGC_HD ( tls, data, len );
1676 return -EINVAL_TICKET;
1677 }
1678
1679 /* Free any unapplied new session ticket */
1680 free ( tls->new_session_ticket );
1681 tls->new_session_ticket = NULL;
1682 tls->new_session_ticket_len = 0;
1683
1684 /* Record ticket */
1685 tls->new_session_ticket = malloc ( ticket_len );
1686 if ( ! tls->new_session_ticket )
1687 return -ENOMEM;
1688 memcpy ( tls->new_session_ticket, new_session_ticket->ticket,
1689 ticket_len );
1690 tls->new_session_ticket_len = ticket_len;
1691 DBGC ( tls, "TLS %p new session ticket:\n", tls );
1692 DBGC_HDA ( tls, 0, tls->new_session_ticket,
1693 tls->new_session_ticket_len );
1694
1695 return 0;
1696 }
1697
1698 /**
1699 * Parse certificate chain
1700 *
1701 * @v tls TLS connection
1702 * @v data Certificate chain
1703 * @v len Length of certificate chain
1704 * @ret rc Return status code
1705 */
1706 static int tls_parse_chain ( struct tls_connection *tls,
1707 const void *data, size_t len ) {
1708 size_t remaining = len;
1709 int rc;
1710
1711 /* Free any existing certificate chain */
1712 x509_chain_put ( tls->chain );
1713 tls->chain = NULL;
1714
1715 /* Create certificate chain */
1716 tls->chain = x509_alloc_chain();
1717 if ( ! tls->chain ) {
1718 rc = -ENOMEM_CHAIN;
1719 goto err_alloc_chain;
1720 }
1721
1722 /* Add certificates to chain */
1723 while ( remaining ) {
1724 const struct {
1725 tls24_t length;
1726 uint8_t data[0];
1727 } __attribute__ (( packed )) *certificate = data;
1728 size_t certificate_len;
1729 size_t record_len;
1730 struct x509_certificate *cert;
1731
1732 /* Parse header */
1733 if ( sizeof ( *certificate ) > remaining ) {
1734 DBGC ( tls, "TLS %p underlength certificate:\n", tls );
1735 DBGC_HDA ( tls, 0, data, remaining );
1736 rc = -EINVAL_CERTIFICATE;
1737 goto err_underlength;
1738 }
1739 certificate_len = tls_uint24 ( &certificate->length );
1740 if ( certificate_len > ( remaining - sizeof ( *certificate ) )){
1741 DBGC ( tls, "TLS %p overlength certificate:\n", tls );
1742 DBGC_HDA ( tls, 0, data, remaining );
1743 rc = -EINVAL_CERTIFICATE;
1744 goto err_overlength;
1745 }
1746 record_len = ( sizeof ( *certificate ) + certificate_len );
1747
1748 /* Add certificate to chain */
1749 if ( ( rc = x509_append_raw ( tls->chain, certificate->data,
1750 certificate_len ) ) != 0 ) {
1751 DBGC ( tls, "TLS %p could not append certificate: %s\n",
1752 tls, strerror ( rc ) );
1753 DBGC_HDA ( tls, 0, data, remaining );
1754 goto err_parse;
1755 }
1756 cert = x509_last ( tls->chain );
1757 DBGC ( tls, "TLS %p found certificate %s\n",
1758 tls, x509_name ( cert ) );
1759
1760 /* Move to next certificate in list */
1761 data += record_len;
1762 remaining -= record_len;
1763 }
1764
1765 return 0;
1766
1767 err_parse:
1768 err_overlength:
1769 err_underlength:
1770 x509_chain_put ( tls->chain );
1771 tls->chain = NULL;
1772 err_alloc_chain:
1773 return rc;
1774 }
1775
1776 /**
1777 * Receive new Certificate handshake record
1778 *
1779 * @v tls TLS connection
1780 * @v data Plaintext handshake record
1781 * @v len Length of plaintext handshake record
1782 * @ret rc Return status code
1783 */
1784 static int tls_new_certificate ( struct tls_connection *tls,
1785 const void *data, size_t len ) {
1786 const struct {
1787 tls24_t length;
1788 uint8_t certificates[0];
1789 } __attribute__ (( packed )) *certificate = data;
1790 size_t certificates_len;
1791 int rc;
1792
1793 /* Parse header */
1794 if ( sizeof ( *certificate ) > len ) {
1795 DBGC ( tls, "TLS %p received underlength Server Certificate\n",
1796 tls );
1797 DBGC_HD ( tls, data, len );
1798 return -EINVAL_CERTIFICATES;
1799 }
1800 certificates_len = tls_uint24 ( &certificate->length );
1801 if ( certificates_len > ( len - sizeof ( *certificate ) ) ) {
1802 DBGC ( tls, "TLS %p received overlength Server Certificate\n",
1803 tls );
1804 DBGC_HD ( tls, data, len );
1805 return -EINVAL_CERTIFICATES;
1806 }
1807
1808 /* Parse certificate chain */
1809 if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
1810 certificates_len ) ) != 0 )
1811 return rc;
1812
1813 return 0;
1814 }
1815
1816 /**
1817 * Receive new Certificate Request handshake record
1818 *
1819 * @v tls TLS connection
1820 * @v data Plaintext handshake record
1821 * @v len Length of plaintext handshake record
1822 * @ret rc Return status code
1823 */
1824 static int tls_new_certificate_request ( struct tls_connection *tls,
1825 const void *data __unused,
1826 size_t len __unused ) {
1827
1828 /* We can only send a single certificate, so there is no point
1829 * in parsing the Certificate Request.
1830 */
1831
1832 /* Free any existing client certificate */
1833 x509_put ( tls->cert );
1834
1835 /* Determine client certificate to be sent */
1836 tls->cert = certstore_find_key ( &private_key );
1837 if ( ! tls->cert ) {
1838 DBGC ( tls, "TLS %p could not find certificate corresponding "
1839 "to private key\n", tls );
1840 return -EPERM_CLIENT_CERT;
1841 }
1842 x509_get ( tls->cert );
1843 DBGC ( tls, "TLS %p sending client certificate %s\n",
1844 tls, x509_name ( tls->cert ) );
1845
1846 return 0;
1847 }
1848
1849 /**
1850 * Receive new Server Hello Done handshake record
1851 *
1852 * @v tls TLS connection
1853 * @v data Plaintext handshake record
1854 * @v len Length of plaintext handshake record
1855 * @ret rc Return status code
1856 */
1857 static int tls_new_server_hello_done ( struct tls_connection *tls,
1858 const void *data, size_t len ) {
1859 const struct {
1860 char next[0];
1861 } __attribute__ (( packed )) *hello_done = data;
1862 int rc;
1863
1864 /* Sanity check */
1865 if ( sizeof ( *hello_done ) != len ) {
1866 DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
1867 tls );
1868 DBGC_HD ( tls, data, len );
1869 return -EINVAL_HELLO_DONE;
1870 }
1871
1872 /* Begin certificate validation */
1873 if ( ( rc = create_validator ( &tls->validator, tls->chain ) ) != 0 ) {
1874 DBGC ( tls, "TLS %p could not start certificate validation: "
1875 "%s\n", tls, strerror ( rc ) );
1876 return rc;
1877 }
1878
1879 return 0;
1880 }
1881
1882 /**
1883 * Receive new Finished handshake record
1884 *
1885 * @v tls TLS connection
1886 * @v data Plaintext handshake record
1887 * @v len Length of plaintext handshake record
1888 * @ret rc Return status code
1889 */
1890 static int tls_new_finished ( struct tls_connection *tls,
1891 const void *data, size_t len ) {
1892 struct tls_session *session = tls->session;
1893 struct digest_algorithm *digest = tls->handshake_digest;
1894 const struct {
1895 uint8_t verify_data[ sizeof ( tls->verify.server ) ];
1896 char next[0];
1897 } __attribute__ (( packed )) *finished = data;
1898 uint8_t digest_out[ digest->digestsize ];
1899
1900 /* Sanity check */
1901 if ( sizeof ( *finished ) != len ) {
1902 DBGC ( tls, "TLS %p received overlength Finished\n", tls );
1903 DBGC_HD ( tls, data, len );
1904 return -EINVAL_FINISHED;
1905 }
1906
1907 /* Verify data */
1908 tls_verify_handshake ( tls, digest_out );
1909 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1910 tls->verify.server, sizeof ( tls->verify.server ),
1911 "server finished", digest_out, sizeof ( digest_out ) );
1912 if ( memcmp ( tls->verify.server, finished->verify_data,
1913 sizeof ( tls->verify.server ) ) != 0 ) {
1914 DBGC ( tls, "TLS %p verification failed\n", tls );
1915 return -EPERM_VERIFY;
1916 }
1917
1918 /* Mark server as finished */
1919 pending_put ( &tls->server_negotiation );
1920
1921 /* If we are resuming a session (i.e. if the server Finished
1922 * arrives before the client Finished is sent), then schedule
1923 * transmission of Change Cipher and Finished.
1924 */
1925 if ( is_pending ( &tls->client_negotiation ) ) {
1926 tls->tx_pending |= ( TLS_TX_CHANGE_CIPHER | TLS_TX_FINISHED );
1927 tls_tx_resume ( tls );
1928 }
1929
1930 /* Record session ID, ticket, and master secret, if applicable */
1931 if ( tls->session_id_len || tls->new_session_ticket_len ) {
1932 memcpy ( session->master_secret, tls->master_secret,
1933 sizeof ( session->master_secret ) );
1934 }
1935 if ( tls->session_id_len ) {
1936 session->id_len = tls->session_id_len;
1937 memcpy ( session->id, tls->session_id, sizeof ( session->id ) );
1938 }
1939 if ( tls->new_session_ticket_len ) {
1940 free ( session->ticket );
1941 session->ticket = tls->new_session_ticket;
1942 session->ticket_len = tls->new_session_ticket_len;
1943 tls->new_session_ticket = NULL;
1944 tls->new_session_ticket_len = 0;
1945 }
1946
1947 /* Move to end of session's connection list and allow other
1948 * connections to start making progress.
1949 */
1950 list_del ( &tls->list );
1951 list_add_tail ( &tls->list, &session->conn );
1952 tls_tx_resume_all ( session );
1953
1954 /* Send notification of a window change */
1955 xfer_window_changed ( &tls->plainstream );
1956
1957 return 0;
1958 }
1959
1960 /**
1961 * Receive new Handshake record
1962 *
1963 * @v tls TLS connection
1964 * @v data Plaintext record
1965 * @v len Length of plaintext record
1966 * @ret rc Return status code
1967 */
1968 static int tls_new_handshake ( struct tls_connection *tls,
1969 const void *data, size_t len ) {
1970 size_t remaining = len;
1971 int rc;
1972
1973 while ( remaining ) {
1974 const struct {
1975 uint8_t type;
1976 tls24_t length;
1977 uint8_t payload[0];
1978 } __attribute__ (( packed )) *handshake = data;
1979 const void *payload;
1980 size_t payload_len;
1981 size_t record_len;
1982
1983 /* Parse header */
1984 if ( sizeof ( *handshake ) > remaining ) {
1985 DBGC ( tls, "TLS %p received underlength Handshake\n",
1986 tls );
1987 DBGC_HD ( tls, data, remaining );
1988 return -EINVAL_HANDSHAKE;
1989 }
1990 payload_len = tls_uint24 ( &handshake->length );
1991 if ( payload_len > ( remaining - sizeof ( *handshake ) ) ) {
1992 DBGC ( tls, "TLS %p received overlength Handshake\n",
1993 tls );
1994 DBGC_HD ( tls, data, len );
1995 return -EINVAL_HANDSHAKE;
1996 }
1997 payload = &handshake->payload;
1998 record_len = ( sizeof ( *handshake ) + payload_len );
1999
2000 /* Handle payload */
2001 switch ( handshake->type ) {
2002 case TLS_HELLO_REQUEST:
2003 rc = tls_new_hello_request ( tls, payload,
2004 payload_len );
2005 break;
2006 case TLS_SERVER_HELLO:
2007 rc = tls_new_server_hello ( tls, payload, payload_len );
2008 break;
2009 case TLS_NEW_SESSION_TICKET:
2010 rc = tls_new_session_ticket ( tls, payload,
2011 payload_len );
2012 break;
2013 case TLS_CERTIFICATE:
2014 rc = tls_new_certificate ( tls, payload, payload_len );
2015 break;
2016 case TLS_CERTIFICATE_REQUEST:
2017 rc = tls_new_certificate_request ( tls, payload,
2018 payload_len );
2019 break;
2020 case TLS_SERVER_HELLO_DONE:
2021 rc = tls_new_server_hello_done ( tls, payload,
2022 payload_len );
2023 break;
2024 case TLS_FINISHED:
2025 rc = tls_new_finished ( tls, payload, payload_len );
2026 break;
2027 default:
2028 DBGC ( tls, "TLS %p ignoring handshake type %d\n",
2029 tls, handshake->type );
2030 rc = 0;
2031 break;
2032 }
2033
2034 /* Add to handshake digest (except for Hello Requests,
2035 * which are explicitly excluded).
2036 */
2037 if ( handshake->type != TLS_HELLO_REQUEST )
2038 tls_add_handshake ( tls, data, record_len );
2039
2040 /* Abort on failure */
2041 if ( rc != 0 )
2042 return rc;
2043
2044 /* Move to next handshake record */
2045 data += record_len;
2046 remaining -= record_len;
2047 }
2048
2049 return 0;
2050 }
2051
2052 /**
2053 * Receive new record
2054 *
2055 * @v tls TLS connection
2056 * @v type Record type
2057 * @v rx_data List of received data buffers
2058 * @ret rc Return status code
2059 */
2060 static int tls_new_record ( struct tls_connection *tls, unsigned int type,
2061 struct list_head *rx_data ) {
2062 struct io_buffer *iobuf;
2063 int ( * handler ) ( struct tls_connection *tls, const void *data,
2064 size_t len );
2065 int rc;
2066
2067 /* Deliver data records to the plainstream interface */
2068 if ( type == TLS_TYPE_DATA ) {
2069
2070 /* Fail unless we are ready to receive data */
2071 if ( ! tls_ready ( tls ) )
2072 return -ENOTCONN;
2073
2074 /* Deliver each I/O buffer in turn */
2075 while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
2076 list ) ) ) {
2077 list_del ( &iobuf->list );
2078 if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
2079 iobuf ) ) != 0 ) {
2080 DBGC ( tls, "TLS %p could not deliver data: "
2081 "%s\n", tls, strerror ( rc ) );
2082 return rc;
2083 }
2084 }
2085 return 0;
2086 }
2087
2088 /* For all other records, merge into a single I/O buffer */
2089 iobuf = iob_concatenate ( rx_data );
2090 if ( ! iobuf ) {
2091 DBGC ( tls, "TLS %p could not concatenate non-data record "
2092 "type %d\n", tls, type );
2093 return -ENOMEM_RX_CONCAT;
2094 }
2095
2096 /* Determine handler */
2097 switch ( type ) {
2098 case TLS_TYPE_CHANGE_CIPHER:
2099 handler = tls_new_change_cipher;
2100 break;
2101 case TLS_TYPE_ALERT:
2102 handler = tls_new_alert;
2103 break;
2104 case TLS_TYPE_HANDSHAKE:
2105 handler = tls_new_handshake;
2106 break;
2107 default:
2108 /* RFC4346 says that we should just ignore unknown
2109 * record types.
2110 */
2111 handler = NULL;
2112 DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
2113 break;
2114 }
2115
2116 /* Handle record and free I/O buffer */
2117 rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
2118 free_iob ( iobuf );
2119 return rc;
2120 }
2121
2122 /******************************************************************************
2123 *
2124 * Record encryption/decryption
2125 *
2126 ******************************************************************************
2127 */
2128
2129 /**
2130 * Initialise HMAC
2131 *
2132 * @v cipherspec Cipher specification
2133 * @v ctx Context
2134 * @v seq Sequence number
2135 * @v tlshdr TLS header
2136 */
2137 static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
2138 uint64_t seq, struct tls_header *tlshdr ) {
2139 struct digest_algorithm *digest = cipherspec->suite->digest;
2140
2141 hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
2142 seq = cpu_to_be64 ( seq );
2143 hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
2144 hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
2145 }
2146
2147 /**
2148 * Update HMAC
2149 *
2150 * @v cipherspec Cipher specification
2151 * @v ctx Context
2152 * @v data Data
2153 * @v len Length of data
2154 */
2155 static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
2156 const void *data, size_t len ) {
2157 struct digest_algorithm *digest = cipherspec->suite->digest;
2158
2159 hmac_update ( digest, ctx, data, len );
2160 }
2161
2162 /**
2163 * Finalise HMAC
2164 *
2165 * @v cipherspec Cipher specification
2166 * @v ctx Context
2167 * @v mac HMAC to fill in
2168 */
2169 static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
2170 void *hmac ) {
2171 struct digest_algorithm *digest = cipherspec->suite->digest;
2172
2173 hmac_final ( digest, ctx, cipherspec->mac_secret,
2174 &digest->digestsize, hmac );
2175 }
2176
2177 /**
2178 * Calculate HMAC
2179 *
2180 * @v cipherspec Cipher specification
2181 * @v seq Sequence number
2182 * @v tlshdr TLS header
2183 * @v data Data
2184 * @v len Length of data
2185 * @v mac HMAC to fill in
2186 */
2187 static void tls_hmac ( struct tls_cipherspec *cipherspec,
2188 uint64_t seq, struct tls_header *tlshdr,
2189 const void *data, size_t len, void *hmac ) {
2190 struct digest_algorithm *digest = cipherspec->suite->digest;
2191 uint8_t ctx[digest->ctxsize];
2192
2193 tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
2194 tls_hmac_update ( cipherspec, ctx, data, len );
2195 tls_hmac_final ( cipherspec, ctx, hmac );
2196 }
2197
2198 /**
2199 * Allocate and assemble stream-ciphered record from data and MAC portions
2200 *
2201 * @v tls TLS connection
2202 * @ret data Data
2203 * @ret len Length of data
2204 * @ret digest MAC digest
2205 * @ret plaintext_len Length of plaintext record
2206 * @ret plaintext Allocated plaintext record
2207 */
2208 static void * __malloc
2209 tls_assemble_stream ( struct tls_connection *tls, const void *data, size_t len,
2210 void *digest, size_t *plaintext_len ) {
2211 size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
2212 void *plaintext;
2213 void *content;
2214 void *mac;
2215
2216 /* Calculate stream-ciphered struct length */
2217 *plaintext_len = ( len + mac_len );
2218
2219 /* Allocate stream-ciphered struct */
2220 plaintext = malloc ( *plaintext_len );
2221 if ( ! plaintext )
2222 return NULL;
2223 content = plaintext;
2224 mac = ( content + len );
2225
2226 /* Fill in stream-ciphered struct */
2227 memcpy ( content, data, len );
2228 memcpy ( mac, digest, mac_len );
2229
2230 return plaintext;
2231 }
2232
2233 /**
2234 * Allocate and assemble block-ciphered record from data and MAC portions
2235 *
2236 * @v tls TLS connection
2237 * @ret data Data
2238 * @ret len Length of data
2239 * @ret digest MAC digest
2240 * @ret plaintext_len Length of plaintext record
2241 * @ret plaintext Allocated plaintext record
2242 */
2243 static void * tls_assemble_block ( struct tls_connection *tls,
2244 const void *data, size_t len,
2245 void *digest, size_t *plaintext_len ) {
2246 size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
2247 size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
2248 size_t iv_len;
2249 size_t padding_len;
2250 void *plaintext;
2251 void *iv;
2252 void *content;
2253 void *mac;
2254 void *padding;
2255
2256 /* TLSv1.1 and later use an explicit IV */
2257 iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
2258
2259 /* Calculate block-ciphered struct length */
2260 padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
2261 *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
2262
2263 /* Allocate block-ciphered struct */
2264 plaintext = malloc ( *plaintext_len );
2265 if ( ! plaintext )
2266 return NULL;
2267 iv = plaintext;
2268 content = ( iv + iv_len );
2269 mac = ( content + len );
2270 padding = ( mac + mac_len );
2271
2272 /* Fill in block-ciphered struct */
2273 tls_generate_random ( tls, iv, iv_len );
2274 memcpy ( content, data, len );
2275 memcpy ( mac, digest, mac_len );
2276 memset ( padding, padding_len, ( padding_len + 1 ) );
2277
2278 return plaintext;
2279 }
2280
2281 /**
2282 * Send plaintext record
2283 *
2284 * @v tls TLS connection
2285 * @v type Record type
2286 * @v data Plaintext record
2287 * @v len Length of plaintext record
2288 * @ret rc Return status code
2289 */
2290 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
2291 const void *data, size_t len ) {
2292 struct tls_header plaintext_tlshdr;
2293 struct tls_header *tlshdr;
2294 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
2295 struct cipher_algorithm *cipher = cipherspec->suite->cipher;
2296 void *plaintext = NULL;
2297 size_t plaintext_len;
2298 struct io_buffer *ciphertext = NULL;
2299 size_t ciphertext_len;
2300 size_t mac_len = cipherspec->suite->digest->digestsize;
2301 uint8_t mac[mac_len];
2302 int rc;
2303
2304 /* Construct header */
2305 plaintext_tlshdr.type = type;
2306 plaintext_tlshdr.version = htons ( tls->version );
2307 plaintext_tlshdr.length = htons ( len );
2308
2309 /* Calculate MAC */
2310 tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
2311
2312 /* Allocate and assemble plaintext struct */
2313 if ( is_stream_cipher ( cipher ) ) {
2314 plaintext = tls_assemble_stream ( tls, data, len, mac,
2315 &plaintext_len );
2316 } else {
2317 plaintext = tls_assemble_block ( tls, data, len, mac,
2318 &plaintext_len );
2319 }
2320 if ( ! plaintext ) {
2321 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
2322 "plaintext\n", tls, plaintext_len );
2323 rc = -ENOMEM_TX_PLAINTEXT;
2324 goto done;
2325 }
2326
2327 DBGC2 ( tls, "Sending plaintext data:\n" );
2328 DBGC2_HD ( tls, plaintext, plaintext_len );
2329
2330 /* Allocate ciphertext */
2331 ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
2332 ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
2333 if ( ! ciphertext ) {
2334 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
2335 "ciphertext\n", tls, ciphertext_len );
2336 rc = -ENOMEM_TX_CIPHERTEXT;
2337 goto done;
2338 }
2339
2340 /* Assemble ciphertext */
2341 tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
2342 tlshdr->type = type;
2343 tlshdr->version = htons ( tls->version );
2344 tlshdr->length = htons ( plaintext_len );
2345 memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
2346 cipher->ctxsize );
2347 cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
2348 iob_put ( ciphertext, plaintext_len ), plaintext_len );
2349
2350 /* Free plaintext as soon as possible to conserve memory */
2351 free ( plaintext );
2352 plaintext = NULL;
2353
2354 /* Send ciphertext */
2355 if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
2356 iob_disown ( ciphertext ) ) ) != 0 ) {
2357 DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
2358 tls, strerror ( rc ) );
2359 goto done;
2360 }
2361
2362 /* Update TX state machine to next record */
2363 tls->tx_seq += 1;
2364 memcpy ( tls->tx_cipherspec.cipher_ctx,
2365 tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
2366
2367 done:
2368 free ( plaintext );
2369 free_iob ( ciphertext );
2370 return rc;
2371 }
2372
2373 /**
2374 * Split stream-ciphered record into data and MAC portions
2375 *
2376 * @v tls TLS connection
2377 * @v rx_data List of received data buffers
2378 * @v mac MAC to fill in
2379 * @ret rc Return status code
2380 */
2381 static int tls_split_stream ( struct tls_connection *tls,
2382 struct list_head *rx_data, void **mac ) {
2383 size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2384 struct io_buffer *iobuf;
2385
2386 /* Extract MAC */
2387 iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2388 assert ( iobuf != NULL );
2389 if ( iob_len ( iobuf ) < mac_len ) {
2390 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2391 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2392 return -EINVAL_STREAM;
2393 }
2394 iob_unput ( iobuf, mac_len );
2395 *mac = iobuf->tail;
2396
2397 return 0;
2398 }
2399
2400 /**
2401 * Split block-ciphered record into data and MAC portions
2402 *
2403 * @v tls TLS connection
2404 * @v rx_data List of received data buffers
2405 * @v mac MAC to fill in
2406 * @ret rc Return status code
2407 */
2408 static int tls_split_block ( struct tls_connection *tls,
2409 struct list_head *rx_data, void **mac ) {
2410 size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2411 struct io_buffer *iobuf;
2412 size_t iv_len;
2413 uint8_t *padding_final;
2414 uint8_t *padding;
2415 size_t padding_len;
2416
2417 /* TLSv1.1 and later use an explicit IV */
2418 iobuf = list_first_entry ( rx_data, struct io_buffer, list );
2419 iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
2420 tls->rx_cipherspec.suite->cipher->blocksize : 0 );
2421 if ( iob_len ( iobuf ) < iv_len ) {
2422 DBGC ( tls, "TLS %p received underlength IV\n", tls );
2423 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2424 return -EINVAL_BLOCK;
2425 }
2426 iob_pull ( iobuf, iv_len );
2427
2428 /* Extract and verify padding */
2429 iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2430 padding_final = ( iobuf->tail - 1 );
2431 padding_len = *padding_final;
2432 if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
2433 DBGC ( tls, "TLS %p received underlength padding\n", tls );
2434 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2435 return -EINVAL_BLOCK;
2436 }
2437 iob_unput ( iobuf, ( padding_len + 1 ) );
2438 for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
2439 if ( *padding != padding_len ) {
2440 DBGC ( tls, "TLS %p received bad padding\n", tls );
2441 DBGC_HD ( tls, padding, padding_len );
2442 return -EINVAL_PADDING;
2443 }
2444 }
2445
2446 /* Extract MAC */
2447 if ( iob_len ( iobuf ) < mac_len ) {
2448 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2449 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2450 return -EINVAL_BLOCK;
2451 }
2452 iob_unput ( iobuf, mac_len );
2453 *mac = iobuf->tail;
2454
2455 return 0;
2456 }
2457
2458 /**
2459 * Receive new ciphertext record
2460 *
2461 * @v tls TLS connection
2462 * @v tlshdr Record header
2463 * @v rx_data List of received data buffers
2464 * @ret rc Return status code
2465 */
2466 static int tls_new_ciphertext ( struct tls_connection *tls,
2467 struct tls_header *tlshdr,
2468 struct list_head *rx_data ) {
2469 struct tls_header plaintext_tlshdr;
2470 struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
2471 struct cipher_algorithm *cipher = cipherspec->suite->cipher;
2472 struct digest_algorithm *digest = cipherspec->suite->digest;
2473 uint8_t ctx[digest->ctxsize];
2474 uint8_t verify_mac[digest->digestsize];
2475 struct io_buffer *iobuf;
2476 void *mac;
2477 size_t len = 0;
2478 int rc;
2479
2480 /* Decrypt the received data */
2481 list_for_each_entry ( iobuf, &tls->rx_data, list ) {
2482 cipher_decrypt ( cipher, cipherspec->cipher_ctx,
2483 iobuf->data, iobuf->data, iob_len ( iobuf ) );
2484 }
2485
2486 /* Split record into content and MAC */
2487 if ( is_stream_cipher ( cipher ) ) {
2488 if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
2489 return rc;
2490 } else {
2491 if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
2492 return rc;
2493 }
2494
2495 /* Calculate total length */
2496 DBGC2 ( tls, "Received plaintext data:\n" );
2497 list_for_each_entry ( iobuf, rx_data, list ) {
2498 DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2499 len += iob_len ( iobuf );
2500 }
2501
2502 /* Verify MAC */
2503 plaintext_tlshdr.type = tlshdr->type;
2504 plaintext_tlshdr.version = tlshdr->version;
2505 plaintext_tlshdr.length = htons ( len );
2506 tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
2507 list_for_each_entry ( iobuf, rx_data, list ) {
2508 tls_hmac_update ( cipherspec, ctx, iobuf->data,
2509 iob_len ( iobuf ) );
2510 }
2511 tls_hmac_final ( cipherspec, ctx, verify_mac );
2512 if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
2513 DBGC ( tls, "TLS %p failed MAC verification\n", tls );
2514 return -EINVAL_MAC;
2515 }
2516
2517 /* Process plaintext record */
2518 if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
2519 return rc;
2520
2521 return 0;
2522 }
2523
2524 /******************************************************************************
2525 *
2526 * Plaintext stream operations
2527 *
2528 ******************************************************************************
2529 */
2530
2531 /**
2532 * Check flow control window
2533 *
2534 * @v tls TLS connection
2535 * @ret len Length of window
2536 */
2537 static size_t tls_plainstream_window ( struct tls_connection *tls ) {
2538
2539 /* Block window unless we are ready to accept data */
2540 if ( ! tls_ready ( tls ) )
2541 return 0;
2542
2543 return xfer_window ( &tls->cipherstream );
2544 }
2545
2546 /**
2547 * Deliver datagram as raw data
2548 *
2549 * @v tls TLS connection
2550 * @v iobuf I/O buffer
2551 * @v meta Data transfer metadata
2552 * @ret rc Return status code
2553 */
2554 static int tls_plainstream_deliver ( struct tls_connection *tls,
2555 struct io_buffer *iobuf,
2556 struct xfer_metadata *meta __unused ) {
2557 int rc;
2558
2559 /* Refuse unless we are ready to accept data */
2560 if ( ! tls_ready ( tls ) ) {
2561 rc = -ENOTCONN;
2562 goto done;
2563 }
2564
2565 if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
2566 iob_len ( iobuf ) ) ) != 0 )
2567 goto done;
2568
2569 done:
2570 free_iob ( iobuf );
2571 return rc;
2572 }
2573
2574 /**
2575 * Report job progress
2576 *
2577 * @v tls TLS connection
2578 * @v progress Progress report to fill in
2579 * @ret ongoing_rc Ongoing job status code (if known)
2580 */
2581 static int tls_progress ( struct tls_connection *tls,
2582 struct job_progress *progress ) {
2583
2584 /* Return cipherstream or validator progress as applicable */
2585 if ( tls_ready ( tls ) ) {
2586 return job_progress ( &tls->cipherstream, progress );
2587 } else {
2588 return job_progress ( &tls->validator, progress );
2589 }
2590 }
2591
2592 /** TLS plaintext stream interface operations */
2593 static struct interface_operation tls_plainstream_ops[] = {
2594 INTF_OP ( xfer_deliver, struct tls_connection *,
2595 tls_plainstream_deliver ),
2596 INTF_OP ( xfer_window, struct tls_connection *,
2597 tls_plainstream_window ),
2598 INTF_OP ( job_progress, struct tls_connection *, tls_progress ),
2599 INTF_OP ( intf_close, struct tls_connection *, tls_close ),
2600 };
2601
2602 /** TLS plaintext stream interface descriptor */
2603 static struct interface_descriptor tls_plainstream_desc =
2604 INTF_DESC_PASSTHRU ( struct tls_connection, plainstream,
2605 tls_plainstream_ops, cipherstream );
2606
2607 /******************************************************************************
2608 *
2609 * Ciphertext stream operations
2610 *
2611 ******************************************************************************
2612 */
2613
2614 /**
2615 * Handle received TLS header
2616 *
2617 * @v tls TLS connection
2618 * @ret rc Returned status code
2619 */
2620 static int tls_newdata_process_header ( struct tls_connection *tls ) {
2621 size_t data_len = ntohs ( tls->rx_header.length );
2622 size_t remaining = data_len;
2623 size_t frag_len;
2624 struct io_buffer *iobuf;
2625 struct io_buffer *tmp;
2626 int rc;
2627
2628 /* Allocate data buffers now that we know the length */
2629 assert ( list_empty ( &tls->rx_data ) );
2630 while ( remaining ) {
2631
2632 /* Calculate fragment length. Ensure that no block is
2633 * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
2634 * allocation length if necessary).
2635 */
2636 frag_len = remaining;
2637 if ( frag_len > TLS_RX_BUFSIZE )
2638 frag_len = TLS_RX_BUFSIZE;
2639 remaining -= frag_len;
2640 if ( remaining < TLS_RX_MIN_BUFSIZE ) {
2641 frag_len += remaining;
2642 remaining = 0;
2643 }
2644
2645 /* Allocate buffer */
2646 iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
2647 if ( ! iobuf ) {
2648 DBGC ( tls, "TLS %p could not allocate %zd of %zd "
2649 "bytes for receive buffer\n", tls,
2650 remaining, data_len );
2651 rc = -ENOMEM_RX_DATA;
2652 goto err;
2653 }
2654
2655 /* Ensure tailroom is exactly what we asked for. This
2656 * will result in unaligned I/O buffers when the
2657 * fragment length is unaligned, which can happen only
2658 * before we switch to using a block cipher.
2659 */
2660 iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
2661
2662 /* Add I/O buffer to list */
2663 list_add_tail ( &iobuf->list, &tls->rx_data );
2664 }
2665
2666 /* Move to data state */
2667 tls->rx_state = TLS_RX_DATA;
2668
2669 return 0;
2670
2671 err:
2672 list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
2673 list_del ( &iobuf->list );
2674 free_iob ( iobuf );
2675 }
2676 return rc;
2677 }
2678
2679 /**
2680 * Handle received TLS data payload
2681 *
2682 * @v tls TLS connection
2683 * @ret rc Returned status code
2684 */
2685 static int tls_newdata_process_data ( struct tls_connection *tls ) {
2686 struct io_buffer *iobuf;
2687 int rc;
2688
2689 /* Move current buffer to end of list */
2690 iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2691 list_del ( &iobuf->list );
2692 list_add_tail ( &iobuf->list, &tls->rx_data );
2693
2694 /* Continue receiving data if any space remains */
2695 iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2696 if ( iob_tailroom ( iobuf ) )
2697 return 0;
2698
2699 /* Process record */
2700 if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
2701 &tls->rx_data ) ) != 0 )
2702 return rc;
2703
2704 /* Increment RX sequence number */
2705 tls->rx_seq += 1;
2706
2707 /* Return to header state */
2708 assert ( list_empty ( &tls->rx_data ) );
2709 tls->rx_state = TLS_RX_HEADER;
2710 iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
2711
2712 return 0;
2713 }
2714
2715 /**
2716 * Check flow control window
2717 *
2718 * @v tls TLS connection
2719 * @ret len Length of window
2720 */
2721 static size_t tls_cipherstream_window ( struct tls_connection *tls ) {
2722
2723 /* Open window until we are ready to accept data */
2724 if ( ! tls_ready ( tls ) )
2725 return -1UL;
2726
2727 return xfer_window ( &tls->plainstream );
2728 }
2729
2730 /**
2731 * Receive new ciphertext
2732 *
2733 * @v tls TLS connection
2734 * @v iobuf I/O buffer
2735 * @v meta Data transfer metadat
2736 * @ret rc Return status code
2737 */
2738 static int tls_cipherstream_deliver ( struct tls_connection *tls,
2739 struct io_buffer *iobuf,
2740 struct xfer_metadata *xfer __unused ) {
2741 size_t frag_len;
2742 int ( * process ) ( struct tls_connection *tls );
2743 struct io_buffer *dest;
2744 int rc;
2745
2746 while ( iob_len ( iobuf ) ) {
2747
2748 /* Select buffer according to current state */
2749 switch ( tls->rx_state ) {
2750 case TLS_RX_HEADER:
2751 dest = &tls->rx_header_iobuf;
2752 process = tls_newdata_process_header;
2753 break;
2754 case TLS_RX_DATA:
2755 dest = list_first_entry ( &tls->rx_data,
2756 struct io_buffer, list );
2757 assert ( dest != NULL );
2758 process = tls_newdata_process_data;
2759 break;
2760 default:
2761 assert ( 0 );
2762 rc = -EINVAL_RX_STATE;
2763 goto done;
2764 }
2765
2766 /* Copy data portion to buffer */
2767 frag_len = iob_len ( iobuf );
2768 if ( frag_len > iob_tailroom ( dest ) )
2769 frag_len = iob_tailroom ( dest );
2770 memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
2771 iob_pull ( iobuf, frag_len );
2772
2773 /* Process data if buffer is now full */
2774 if ( iob_tailroom ( dest ) == 0 ) {
2775 if ( ( rc = process ( tls ) ) != 0 ) {
2776 tls_close ( tls, rc );
2777 goto done;
2778 }
2779 }
2780 }
2781 rc = 0;
2782
2783 done:
2784 free_iob ( iobuf );
2785 return rc;
2786 }
2787
2788 /** TLS ciphertext stream interface operations */
2789 static struct interface_operation tls_cipherstream_ops[] = {
2790 INTF_OP ( xfer_deliver, struct tls_connection *,
2791 tls_cipherstream_deliver ),
2792 INTF_OP ( xfer_window, struct tls_connection *,
2793 tls_cipherstream_window ),
2794 INTF_OP ( xfer_window_changed, struct tls_connection *,
2795 tls_tx_resume ),
2796 INTF_OP ( intf_close, struct tls_connection *, tls_close ),
2797 };
2798
2799 /** TLS ciphertext stream interface descriptor */
2800 static struct interface_descriptor tls_cipherstream_desc =
2801 INTF_DESC_PASSTHRU ( struct tls_connection, cipherstream,
2802 tls_cipherstream_ops, plainstream );
2803
2804 /******************************************************************************
2805 *
2806 * Certificate validator
2807 *
2808 ******************************************************************************
2809 */
2810
2811 /**
2812 * Handle certificate validation completion
2813 *
2814 * @v tls TLS connection
2815 * @v rc Reason for completion
2816 */
2817 static void tls_validator_done ( struct tls_connection *tls, int rc ) {
2818 struct tls_session *session = tls->session;
2819 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
2820 struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
2821 struct x509_certificate *cert;
2822
2823 /* Close validator interface */
2824 intf_restart ( &tls->validator, rc );
2825
2826 /* Check for validation failure */
2827 if ( rc != 0 ) {
2828 DBGC ( tls, "TLS %p certificate validation failed: %s\n",
2829 tls, strerror ( rc ) );
2830 goto err;
2831 }
2832 DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
2833
2834 /* Extract first certificate */
2835 cert = x509_first ( tls->chain );
2836 assert ( cert != NULL );
2837
2838 /* Verify server name */
2839 if ( ( rc = x509_check_name ( cert, session->name ) ) != 0 ) {
2840 DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
2841 tls, session->name, strerror ( rc ) );
2842 goto err;
2843 }
2844
2845 /* Initialise public key algorithm */
2846 if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
2847 cert->subject.public_key.raw.data,
2848 cert->subject.public_key.raw.len ) ) != 0 ) {
2849 DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
2850 tls, strerror ( rc ) );
2851 goto err;
2852 }
2853
2854 /* Schedule Client Key Exchange, Change Cipher, and Finished */
2855 tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
2856 TLS_TX_CHANGE_CIPHER |
2857 TLS_TX_FINISHED );
2858 if ( tls->cert ) {
2859 tls->tx_pending |= ( TLS_TX_CERTIFICATE |
2860 TLS_TX_CERTIFICATE_VERIFY );
2861 }
2862 tls_tx_resume ( tls );
2863
2864 return;
2865
2866 err:
2867 tls_close ( tls, rc );
2868 return;
2869 }
2870
2871 /** TLS certificate validator interface operations */
2872 static struct interface_operation tls_validator_ops[] = {
2873 INTF_OP ( intf_close, struct tls_connection *, tls_validator_done ),
2874 };
2875
2876 /** TLS certificate validator interface descriptor */
2877 static struct interface_descriptor tls_validator_desc =
2878 INTF_DESC ( struct tls_connection, validator, tls_validator_ops );
2879
2880 /******************************************************************************
2881 *
2882 * Controlling process
2883 *
2884 ******************************************************************************
2885 */
2886
2887 /**
2888 * TLS TX state machine
2889 *
2890 * @v tls TLS connection
2891 */
2892 static void tls_tx_step ( struct tls_connection *tls ) {
2893 struct tls_session *session = tls->session;
2894 struct tls_connection *conn;
2895 int rc;
2896
2897 /* Wait for cipherstream to become ready */
2898 if ( ! xfer_window ( &tls->cipherstream ) )
2899 return;
2900
2901 /* Send first pending transmission */
2902 if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
2903 /* Serialise server negotiations within a session, to
2904 * provide a consistent view of session IDs and
2905 * session tickets.
2906 */
2907 list_for_each_entry ( conn, &session->conn, list ) {
2908 if ( conn == tls )
2909 break;
2910 if ( is_pending ( &conn->server_negotiation ) )
2911 return;
2912 }
2913 /* Record or generate session ID and associated master secret */
2914 if ( session->id_len ) {
2915 /* Attempt to resume an existing session */
2916 memcpy ( tls->session_id, session->id,
2917 sizeof ( tls->session_id ) );
2918 tls->session_id_len = session->id_len;
2919 memcpy ( tls->master_secret, session->master_secret,
2920 sizeof ( tls->master_secret ) );
2921 } else {
2922 /* No existing session: use a random session ID */
2923 assert ( sizeof ( tls->session_id ) ==
2924 sizeof ( tls->client_random ) );
2925 memcpy ( tls->session_id, &tls->client_random,
2926 sizeof ( tls->session_id ) );
2927 tls->session_id_len = sizeof ( tls->session_id );
2928 }
2929 /* Send Client Hello */
2930 if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
2931 DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
2932 tls, strerror ( rc ) );
2933 goto err;
2934 }
2935 tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
2936 } else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
2937 /* Send Certificate */
2938 if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
2939 DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
2940 tls, strerror ( rc ) );
2941 goto err;
2942 }
2943 tls->tx_pending &= ~TLS_TX_CERTIFICATE;
2944 } else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
2945 /* Send Client Key Exchange */
2946 if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
2947 DBGC ( tls, "TLS %p could not send Client Key "
2948 "Exchange: %s\n", tls, strerror ( rc ) );
2949 goto err;
2950 }
2951 tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
2952 } else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
2953 /* Send Certificate Verify */
2954 if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
2955 DBGC ( tls, "TLS %p could not send Certificate "
2956 "Verify: %s\n", tls, strerror ( rc ) );
2957 goto err;
2958 }
2959 tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
2960 } else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
2961 /* Send Change Cipher, and then change the cipher in use */
2962 if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
2963 DBGC ( tls, "TLS %p could not send Change Cipher: "
2964 "%s\n", tls, strerror ( rc ) );
2965 goto err;
2966 }
2967 if ( ( rc = tls_change_cipher ( tls,
2968 &tls->tx_cipherspec_pending,
2969 &tls->tx_cipherspec )) != 0 ){
2970 DBGC ( tls, "TLS %p could not activate TX cipher: "
2971 "%s\n", tls, strerror ( rc ) );
2972 goto err;
2973 }
2974 tls->tx_seq = 0;
2975 tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
2976 } else if ( tls->tx_pending & TLS_TX_FINISHED ) {
2977 /* Send Finished */
2978 if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
2979 DBGC ( tls, "TLS %p could not send Finished: %s\n",
2980 tls, strerror ( rc ) );
2981 goto err;
2982 }
2983 tls->tx_pending &= ~TLS_TX_FINISHED;
2984 }
2985
2986 /* Reschedule process if pending transmissions remain,
2987 * otherwise send notification of a window change.
2988 */
2989 if ( tls->tx_pending ) {
2990 tls_tx_resume ( tls );
2991 } else {
2992 xfer_window_changed ( &tls->plainstream );
2993 }
2994
2995 return;
2996
2997 err:
2998 tls_close ( tls, rc );
2999 }
3000
3001 /** TLS TX process descriptor */
3002 static struct process_descriptor tls_process_desc =
3003 PROC_DESC_ONCE ( struct tls_connection, process, tls_tx_step );
3004
3005 /******************************************************************************
3006 *
3007 * Session management
3008 *
3009 ******************************************************************************
3010 */
3011
3012 /**
3013 * Find or create session for TLS connection
3014 *
3015 * @v tls TLS connection
3016 * @v name Server name
3017 * @ret rc Return status code
3018 */
3019 static int tls_session ( struct tls_connection *tls, const char *name ) {
3020 struct tls_session *session;
3021 char *name_copy;
3022 int rc;
3023
3024 /* Find existing matching session, if any */
3025 list_for_each_entry ( session, &tls_sessions, list ) {
3026 if ( strcmp ( name, session->name ) == 0 ) {
3027 ref_get ( &session->refcnt );
3028 tls->session = session;
3029 DBGC ( tls, "TLS %p joining session %s\n", tls, name );
3030 return 0;
3031 }
3032 }
3033
3034 /* Create new session */
3035 session = zalloc ( sizeof ( *session ) + strlen ( name )
3036 + 1 /* NUL */ );
3037 if ( ! session ) {
3038 rc = -ENOMEM;
3039 goto err_alloc;
3040 }
3041 ref_init ( &session->refcnt, free_tls_session );
3042 name_copy = ( ( ( void * ) session ) + sizeof ( *session ) );
3043 strcpy ( name_copy, name );
3044 session->name = name_copy;
3045 INIT_LIST_HEAD ( &session->conn );
3046 list_add ( &session->list, &tls_sessions );
3047
3048 /* Record session */
3049 tls->session = session;
3050
3051 DBGC ( tls, "TLS %p created session %s\n", tls, name );
3052 return 0;
3053
3054 ref_put ( &session->refcnt );
3055 err_alloc:
3056 return rc;
3057 }
3058
3059 /******************************************************************************
3060 *
3061 * Instantiator
3062 *
3063 ******************************************************************************
3064 */
3065
3066 int add_tls ( struct interface *xfer, const char *name,
3067 struct interface **next ) {
3068 struct tls_connection *tls;
3069 int rc;
3070
3071 /* Allocate and initialise TLS structure */
3072 tls = malloc ( sizeof ( *tls ) );
3073 if ( ! tls ) {
3074 rc = -ENOMEM;
3075 goto err_alloc;
3076 }
3077 memset ( tls, 0, sizeof ( *tls ) );
3078 ref_init ( &tls->refcnt, free_tls );
3079 INIT_LIST_HEAD ( &tls->list );
3080 intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
3081 intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
3082 intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
3083 process_init ( &tls->process, &tls_process_desc, &tls->refcnt );
3084 tls->version = TLS_VERSION_TLS_1_2;
3085 tls_clear_cipher ( tls, &tls->tx_cipherspec );
3086 tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
3087 tls_clear_cipher ( tls, &tls->rx_cipherspec );
3088 tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
3089 tls->client_random.gmt_unix_time = time ( NULL );
3090 iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
3091 sizeof ( tls->rx_header ) );
3092 INIT_LIST_HEAD ( &tls->rx_data );
3093 if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
3094 ( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
3095 goto err_random;
3096 }
3097 tls->pre_master_secret.version = htons ( tls->version );
3098 if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
3099 ( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
3100 goto err_random;
3101 }
3102 if ( ( rc = tls_session ( tls, name ) ) != 0 )
3103 goto err_session;
3104 list_add_tail ( &tls->list, &tls->session->conn );
3105
3106 /* Start negotiation */
3107 tls_restart ( tls );
3108
3109 /* Attach to parent interface, mortalise self, and return */
3110 intf_plug_plug ( &tls->plainstream, xfer );
3111 *next = &tls->cipherstream;
3112 ref_put ( &tls->refcnt );
3113 return 0;
3114
3115 err_session:
3116 err_random:
3117 ref_put ( &tls->refcnt );
3118 err_alloc:
3119 return rc;
3120 }
3121
3122 /* Drag in objects via add_tls() */
3123 REQUIRING_SYMBOL ( add_tls );
3124
3125 /* Drag in crypto configuration */
3126 REQUIRE_OBJECT ( config_crypto );