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