2 * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
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.
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.
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
20 FILE_LICENCE ( GPL2_OR_LATER );
25 * Transport Layer Security Protocol
35 #include <ipxe/pending.h>
36 #include <ipxe/hmac.h>
38 #include <ipxe/sha1.h>
39 #include <ipxe/sha256.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>
49 #include <ipxe/validator.h>
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, \
105 #define EIO_ALERT __einfo_error ( EINFO_EIO_ALERT )
106 #define EINFO_EIO_ALERT \
107 __einfo_uniqify ( EINFO_EINVAL, 0x01, \
108 "Unknown alert level" )
109 #define ENOMEM_CONTEXT __einfo_error ( EINFO_ENOMEM_CONTEXT )
110 #define EINFO_ENOMEM_CONTEXT \
111 __einfo_uniqify ( EINFO_ENOMEM, 0x01, \
112 "Not enough space for crypto context" )
113 #define ENOMEM_CERTIFICATE __einfo_error ( EINFO_ENOMEM_CERTIFICATE )
114 #define EINFO_ENOMEM_CERTIFICATE \
115 __einfo_uniqify ( EINFO_ENOMEM, 0x02, \
116 "Not enough space for certificate" )
117 #define ENOMEM_CHAIN __einfo_error ( EINFO_ENOMEM_CHAIN )
118 #define EINFO_ENOMEM_CHAIN \
119 __einfo_uniqify ( EINFO_ENOMEM, 0x03, \
120 "Not enough space for certificate chain" )
121 #define ENOMEM_TX_PLAINTEXT __einfo_error ( EINFO_ENOMEM_TX_PLAINTEXT )
122 #define EINFO_ENOMEM_TX_PLAINTEXT \
123 __einfo_uniqify ( EINFO_ENOMEM, 0x04, \
124 "Not enough space for transmitted plaintext" )
125 #define ENOMEM_TX_CIPHERTEXT __einfo_error ( EINFO_ENOMEM_TX_CIPHERTEXT )
126 #define EINFO_ENOMEM_TX_CIPHERTEXT \
127 __einfo_uniqify ( EINFO_ENOMEM, 0x05, \
128 "Not enough space for transmitted ciphertext" )
129 #define ENOMEM_RX_DATA __einfo_error ( EINFO_ENOMEM_RX_DATA )
130 #define EINFO_ENOMEM_RX_DATA \
131 __einfo_uniqify ( EINFO_ENOMEM, 0x07, \
132 "Not enough space for received data" )
133 #define ENOMEM_RX_CONCAT __einfo_error ( EINFO_ENOMEM_RX_CONCAT )
134 #define EINFO_ENOMEM_RX_CONCAT \
135 __einfo_uniqify ( EINFO_ENOMEM, 0x08, \
136 "Not enough space to concatenate received data" )
137 #define ENOTSUP_CIPHER __einfo_error ( EINFO_ENOTSUP_CIPHER )
138 #define EINFO_ENOTSUP_CIPHER \
139 __einfo_uniqify ( EINFO_ENOTSUP, 0x01, \
140 "Unsupported cipher" )
141 #define ENOTSUP_NULL __einfo_error ( EINFO_ENOTSUP_NULL )
142 #define EINFO_ENOTSUP_NULL \
143 __einfo_uniqify ( EINFO_ENOTSUP, 0x02, \
144 "Refusing to use null cipher" )
145 #define ENOTSUP_SIG_HASH __einfo_error ( EINFO_ENOTSUP_SIG_HASH )
146 #define EINFO_ENOTSUP_SIG_HASH \
147 __einfo_uniqify ( EINFO_ENOTSUP, 0x03, \
148 "Unsupported signature and hash algorithm" )
149 #define ENOTSUP_VERSION __einfo_error ( EINFO_ENOTSUP_VERSION )
150 #define EINFO_ENOTSUP_VERSION \
151 __einfo_uniqify ( EINFO_ENOTSUP, 0x04, \
152 "Unsupported protocol version" )
153 #define EPERM_ALERT __einfo_error ( EINFO_EPERM_ALERT )
154 #define EINFO_EPERM_ALERT \
155 __einfo_uniqify ( EINFO_EPERM, 0x01, \
156 "Received fatal alert" )
157 #define EPERM_VERIFY __einfo_error ( EINFO_EPERM_VERIFY )
158 #define EINFO_EPERM_VERIFY \
159 __einfo_uniqify ( EINFO_EPERM, 0x02, \
160 "Handshake verification failed" )
161 #define EPERM_CLIENT_CERT __einfo_error ( EINFO_EPERM_CLIENT_CERT )
162 #define EINFO_EPERM_CLIENT_CERT \
163 __einfo_uniqify ( EINFO_EPERM, 0x03, \
164 "No suitable client certificate available" )
165 #define EPROTO_VERSION __einfo_error ( EINFO_EPROTO_VERSION )
166 #define EINFO_EPROTO_VERSION \
167 __einfo_uniqify ( EINFO_EPROTO, 0x01, \
168 "Illegal protocol version upgrade" )
170 static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
171 const void *data, size_t len );
172 static void tls_clear_cipher ( struct tls_session *tls,
173 struct tls_cipherspec *cipherspec );
175 /******************************************************************************
179 ******************************************************************************
183 * Extract 24-bit field value
185 * @v field24 24-bit field
186 * @ret value Field value
188 * TLS uses 24-bit integers in several places, which are awkward to
191 static inline __attribute__ (( always_inline )) unsigned long
192 tls_uint24 ( const uint8_t field24[3] ) {
193 const uint32_t *field32 __attribute__ (( may_alias )) =
194 ( ( const void * ) field24 );
195 return ( be32_to_cpu ( *field32 ) >> 8 );
199 * Set 24-bit field value
201 * @v field24 24-bit field
202 * @v value Field value
204 * The field must be pre-zeroed.
206 static void tls_set_uint24 ( uint8_t field24[3], unsigned long value ) {
207 uint32_t *field32 __attribute__ (( may_alias )) =
208 ( ( void * ) field24 );
209 *field32 |= cpu_to_be32 ( value << 8 );
213 * Determine if TLS session is ready for application data
216 * @ret is_ready TLS session is ready
218 static int tls_ready ( struct tls_session *tls ) {
219 return ( ( ! is_pending ( &tls->client_negotiation ) ) &&
220 ( ! is_pending ( &tls->server_negotiation ) ) );
223 /******************************************************************************
225 * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
227 ******************************************************************************
231 * Initialise MD5+SHA1 algorithm
233 * @v ctx MD5+SHA1 context
235 static void md5_sha1_init ( void *ctx ) {
236 struct md5_sha1_context *context = ctx;
238 digest_init ( &md5_algorithm, context->md5 );
239 digest_init ( &sha1_algorithm, context->sha1 );
243 * Accumulate data with MD5+SHA1 algorithm
245 * @v ctx MD5+SHA1 context
247 * @v len Length of data
249 static void md5_sha1_update ( void *ctx, const void *data, size_t len ) {
250 struct md5_sha1_context *context = ctx;
252 digest_update ( &md5_algorithm, context->md5, data, len );
253 digest_update ( &sha1_algorithm, context->sha1, data, len );
257 * Generate MD5+SHA1 digest
259 * @v ctx MD5+SHA1 context
260 * @v out Output buffer
262 static void md5_sha1_final ( void *ctx, void *out ) {
263 struct md5_sha1_context *context = ctx;
264 struct md5_sha1_digest *digest = out;
266 digest_final ( &md5_algorithm, context->md5, digest->md5 );
267 digest_final ( &sha1_algorithm, context->sha1, digest->sha1 );
270 /** Hybrid MD5+SHA1 digest algorithm */
271 static struct digest_algorithm md5_sha1_algorithm = {
273 .ctxsize = sizeof ( struct md5_sha1_context ),
274 .blocksize = 0, /* Not applicable */
275 .digestsize = sizeof ( struct md5_sha1_digest ),
276 .init = md5_sha1_init,
277 .update = md5_sha1_update,
278 .final = md5_sha1_final,
281 /** RSA digestInfo prefix for MD5+SHA1 algorithm */
282 struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix = {
283 .digest = &md5_sha1_algorithm,
284 .data = NULL, /* MD5+SHA1 signatures have no digestInfo */
288 /******************************************************************************
292 ******************************************************************************
298 * @v refcnt Reference counter
300 static void free_tls ( struct refcnt *refcnt ) {
301 struct tls_session *tls =
302 container_of ( refcnt, struct tls_session, refcnt );
303 struct io_buffer *iobuf;
304 struct io_buffer *tmp;
306 /* Free dynamically-allocated resources */
307 tls_clear_cipher ( tls, &tls->tx_cipherspec );
308 tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
309 tls_clear_cipher ( tls, &tls->rx_cipherspec );
310 tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
311 list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
312 list_del ( &iobuf->list );
315 x509_put ( tls->cert );
316 x509_chain_put ( tls->chain );
318 /* Free TLS structure itself */
323 * Finish with TLS session
328 static void tls_close ( struct tls_session *tls, int rc ) {
330 /* Remove pending operations, if applicable */
331 pending_put ( &tls->client_negotiation );
332 pending_put ( &tls->server_negotiation );
335 process_del ( &tls->process );
337 /* Close all interfaces */
338 intf_shutdown ( &tls->cipherstream, rc );
339 intf_shutdown ( &tls->plainstream, rc );
340 intf_shutdown ( &tls->validator, rc );
343 /******************************************************************************
345 * Random number generation
347 ******************************************************************************
351 * Generate random data
354 * @v data Buffer to fill
355 * @v len Length of buffer
356 * @ret rc Return status code
358 static int tls_generate_random ( struct tls_session *tls,
359 void *data, size_t len ) {
362 /* Generate random bits with no additional input and without
363 * prediction resistance
365 if ( ( rc = rbg_generate ( NULL, 0, 0, data, len ) ) != 0 ) {
366 DBGC ( tls, "TLS %p could not generate random data: %s\n",
367 tls, strerror ( rc ) );
375 * Update HMAC with a list of ( data, len ) pairs
377 * @v digest Hash function to use
378 * @v digest_ctx Digest context
379 * @v args ( data, len ) pairs of data, terminated by NULL
381 static void tls_hmac_update_va ( struct digest_algorithm *digest,
382 void *digest_ctx, va_list args ) {
386 while ( ( data = va_arg ( args, void * ) ) ) {
387 len = va_arg ( args, size_t );
388 hmac_update ( digest, digest_ctx, data, len );
393 * Generate secure pseudo-random data using a single hash function
396 * @v digest Hash function to use
398 * @v secret_len Length of secret
399 * @v out Output buffer
400 * @v out_len Length of output buffer
401 * @v seeds ( data, len ) pairs of seed data, terminated by NULL
403 static void tls_p_hash_va ( struct tls_session *tls,
404 struct digest_algorithm *digest,
405 void *secret, size_t secret_len,
406 void *out, size_t out_len,
408 uint8_t secret_copy[secret_len];
409 uint8_t digest_ctx[digest->ctxsize];
410 uint8_t digest_ctx_partial[digest->ctxsize];
411 uint8_t a[digest->digestsize];
412 uint8_t out_tmp[digest->digestsize];
413 size_t frag_len = digest->digestsize;
416 /* Copy the secret, in case HMAC modifies it */
417 memcpy ( secret_copy, secret, secret_len );
418 secret = secret_copy;
419 DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
420 DBGC2_HD ( tls, secret, secret_len );
423 hmac_init ( digest, digest_ctx, secret, &secret_len );
424 va_copy ( tmp, seeds );
425 tls_hmac_update_va ( digest, digest_ctx, tmp );
427 hmac_final ( digest, digest_ctx, secret, &secret_len, a );
428 DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
429 DBGC2_HD ( tls, &a, sizeof ( a ) );
431 /* Generate as much data as required */
433 /* Calculate output portion */
434 hmac_init ( digest, digest_ctx, secret, &secret_len );
435 hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
436 memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
437 va_copy ( tmp, seeds );
438 tls_hmac_update_va ( digest, digest_ctx, tmp );
440 hmac_final ( digest, digest_ctx,
441 secret, &secret_len, out_tmp );
444 if ( frag_len > out_len )
446 memcpy ( out, out_tmp, frag_len );
447 DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
448 DBGC2_HD ( tls, out, frag_len );
451 hmac_final ( digest, digest_ctx_partial,
452 secret, &secret_len, a );
453 DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
454 DBGC2_HD ( tls, &a, sizeof ( a ) );
462 * Generate secure pseudo-random data
466 * @v secret_len Length of secret
467 * @v out Output buffer
468 * @v out_len Length of output buffer
469 * @v ... ( data, len ) pairs of seed data, terminated by NULL
471 static void tls_prf ( struct tls_session *tls, void *secret, size_t secret_len,
472 void *out, size_t out_len, ... ) {
475 size_t subsecret_len;
478 uint8_t buf[out_len];
481 va_start ( seeds, out_len );
483 if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
484 /* Use P_SHA256 for TLSv1.2 and later */
485 tls_p_hash_va ( tls, &sha256_algorithm, secret, secret_len,
486 out, out_len, seeds );
488 /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
492 /* Split secret into two, with an overlap of up to one byte */
493 subsecret_len = ( ( secret_len + 1 ) / 2 );
495 sha1_secret = ( secret + secret_len - subsecret_len );
497 /* Calculate MD5 portion */
498 va_copy ( tmp, seeds );
499 tls_p_hash_va ( tls, &md5_algorithm, md5_secret,
500 subsecret_len, out, out_len, seeds );
503 /* Calculate SHA1 portion */
504 va_copy ( tmp, seeds );
505 tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret,
506 subsecret_len, buf, out_len, seeds );
509 /* XOR the two portions together into the final output buffer */
510 for ( i = 0 ; i < out_len ; i++ )
511 *( ( uint8_t * ) out + i ) ^= buf[i];
518 * Generate secure pseudo-random data
521 * @v secret_len Length of secret
522 * @v out Output buffer
523 * @v out_len Length of output buffer
524 * @v label String literal label
525 * @v ... ( data, len ) pairs of seed data
527 #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
528 tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
529 label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
531 /******************************************************************************
535 ******************************************************************************
539 * Generate master secret
543 * The pre-master secret and the client and server random values must
546 static void tls_generate_master_secret ( struct tls_session *tls ) {
547 DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
548 DBGC_HD ( tls, &tls->pre_master_secret,
549 sizeof ( tls->pre_master_secret ) );
550 DBGC ( tls, "TLS %p client random bytes:\n", tls );
551 DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
552 DBGC ( tls, "TLS %p server random bytes:\n", tls );
553 DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
555 tls_prf_label ( tls, &tls->pre_master_secret,
556 sizeof ( tls->pre_master_secret ),
557 &tls->master_secret, sizeof ( tls->master_secret ),
559 &tls->client_random, sizeof ( tls->client_random ),
560 &tls->server_random, sizeof ( tls->server_random ) );
562 DBGC ( tls, "TLS %p generated master secret:\n", tls );
563 DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
567 * Generate key material
571 * The master secret must already be known.
573 static int tls_generate_keys ( struct tls_session *tls ) {
574 struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
575 struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
576 size_t hash_size = tx_cipherspec->suite->digest->digestsize;
577 size_t key_size = tx_cipherspec->suite->key_len;
578 size_t iv_size = tx_cipherspec->suite->cipher->blocksize;
579 size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
580 uint8_t key_block[total];
584 /* Generate key block */
585 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
586 key_block, sizeof ( key_block ), "key expansion",
587 &tls->server_random, sizeof ( tls->server_random ),
588 &tls->client_random, sizeof ( tls->client_random ) );
590 /* Split key block into portions */
594 memcpy ( tx_cipherspec->mac_secret, key, hash_size );
595 DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
596 DBGC_HD ( tls, key, hash_size );
600 memcpy ( rx_cipherspec->mac_secret, key, hash_size );
601 DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
602 DBGC_HD ( tls, key, hash_size );
606 if ( ( rc = cipher_setkey ( tx_cipherspec->suite->cipher,
607 tx_cipherspec->cipher_ctx,
608 key, key_size ) ) != 0 ) {
609 DBGC ( tls, "TLS %p could not set TX key: %s\n",
610 tls, strerror ( rc ) );
613 DBGC ( tls, "TLS %p TX key:\n", tls );
614 DBGC_HD ( tls, key, key_size );
618 if ( ( rc = cipher_setkey ( rx_cipherspec->suite->cipher,
619 rx_cipherspec->cipher_ctx,
620 key, key_size ) ) != 0 ) {
621 DBGC ( tls, "TLS %p could not set TX key: %s\n",
622 tls, strerror ( rc ) );
625 DBGC ( tls, "TLS %p RX key:\n", tls );
626 DBGC_HD ( tls, key, key_size );
629 /* TX initialisation vector */
630 cipher_setiv ( tx_cipherspec->suite->cipher,
631 tx_cipherspec->cipher_ctx, key );
632 DBGC ( tls, "TLS %p TX IV:\n", tls );
633 DBGC_HD ( tls, key, iv_size );
636 /* RX initialisation vector */
637 cipher_setiv ( rx_cipherspec->suite->cipher,
638 rx_cipherspec->cipher_ctx, key );
639 DBGC ( tls, "TLS %p RX IV:\n", tls );
640 DBGC_HD ( tls, key, iv_size );
643 assert ( ( key_block + total ) == key );
648 /******************************************************************************
650 * Cipher suite management
652 ******************************************************************************
655 /** Null cipher suite */
656 struct tls_cipher_suite tls_cipher_suite_null = {
657 .pubkey = &pubkey_null,
658 .cipher = &cipher_null,
659 .digest = &digest_null,
662 /** Supported cipher suites, in order of preference */
663 struct tls_cipher_suite tls_cipher_suites[] = {
665 .code = htons ( TLS_RSA_WITH_AES_256_CBC_SHA256 ),
666 .key_len = ( 256 / 8 ),
667 .pubkey = &rsa_algorithm,
668 .cipher = &aes_cbc_algorithm,
669 .digest = &sha256_algorithm,
672 .code = htons ( TLS_RSA_WITH_AES_128_CBC_SHA256 ),
673 .key_len = ( 128 / 8 ),
674 .pubkey = &rsa_algorithm,
675 .cipher = &aes_cbc_algorithm,
676 .digest = &sha256_algorithm,
679 .code = htons ( TLS_RSA_WITH_AES_256_CBC_SHA ),
680 .key_len = ( 256 / 8 ),
681 .pubkey = &rsa_algorithm,
682 .cipher = &aes_cbc_algorithm,
683 .digest = &sha1_algorithm,
686 .code = htons ( TLS_RSA_WITH_AES_128_CBC_SHA ),
687 .key_len = ( 128 / 8 ),
688 .pubkey = &rsa_algorithm,
689 .cipher = &aes_cbc_algorithm,
690 .digest = &sha1_algorithm,
694 /** Number of supported cipher suites */
695 #define TLS_NUM_CIPHER_SUITES \
696 ( sizeof ( tls_cipher_suites ) / sizeof ( tls_cipher_suites[0] ) )
699 * Identify cipher suite
701 * @v cipher_suite Cipher suite specification
702 * @ret suite Cipher suite, or NULL
704 static struct tls_cipher_suite *
705 tls_find_cipher_suite ( unsigned int cipher_suite ) {
706 struct tls_cipher_suite *suite;
709 /* Identify cipher suite */
710 for ( i = 0 ; i < TLS_NUM_CIPHER_SUITES ; i++ ) {
711 suite = &tls_cipher_suites[i];
712 if ( suite->code == cipher_suite )
722 * @v cipherspec TLS cipher specification
724 static void tls_clear_cipher ( struct tls_session *tls __unused,
725 struct tls_cipherspec *cipherspec ) {
727 if ( cipherspec->suite ) {
728 pubkey_final ( cipherspec->suite->pubkey,
729 cipherspec->pubkey_ctx );
731 free ( cipherspec->dynamic );
732 memset ( cipherspec, 0, sizeof ( *cipherspec ) );
733 cipherspec->suite = &tls_cipher_suite_null;
740 * @v cipherspec TLS cipher specification
741 * @v suite Cipher suite
742 * @ret rc Return status code
744 static int tls_set_cipher ( struct tls_session *tls,
745 struct tls_cipherspec *cipherspec,
746 struct tls_cipher_suite *suite ) {
747 struct pubkey_algorithm *pubkey = suite->pubkey;
748 struct cipher_algorithm *cipher = suite->cipher;
749 struct digest_algorithm *digest = suite->digest;
753 /* Clear out old cipher contents, if any */
754 tls_clear_cipher ( tls, cipherspec );
756 /* Allocate dynamic storage */
757 total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
758 dynamic = zalloc ( total );
760 DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
761 "context\n", tls, total );
762 return -ENOMEM_CONTEXT;
766 cipherspec->dynamic = dynamic;
767 cipherspec->pubkey_ctx = dynamic; dynamic += pubkey->ctxsize;
768 cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
769 cipherspec->cipher_next_ctx = dynamic; dynamic += cipher->ctxsize;
770 cipherspec->mac_secret = dynamic; dynamic += digest->digestsize;
771 assert ( ( cipherspec->dynamic + total ) == dynamic );
773 /* Store parameters */
774 cipherspec->suite = suite;
780 * Select next cipher suite
783 * @v cipher_suite Cipher suite specification
784 * @ret rc Return status code
786 static int tls_select_cipher ( struct tls_session *tls,
787 unsigned int cipher_suite ) {
788 struct tls_cipher_suite *suite;
791 /* Identify cipher suite */
792 suite = tls_find_cipher_suite ( cipher_suite );
794 DBGC ( tls, "TLS %p does not support cipher %04x\n",
795 tls, ntohs ( cipher_suite ) );
796 return -ENOTSUP_CIPHER;
800 if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending,
803 if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending,
807 DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls, suite->pubkey->name,
808 suite->cipher->name, ( suite->key_len * 8 ),
809 suite->digest->name );
815 * Activate next cipher suite
818 * @v pending Pending cipher specification
819 * @v active Active cipher specification to replace
820 * @ret rc Return status code
822 static int tls_change_cipher ( struct tls_session *tls,
823 struct tls_cipherspec *pending,
824 struct tls_cipherspec *active ) {
827 if ( pending->suite == &tls_cipher_suite_null ) {
828 DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
829 return -ENOTSUP_NULL;
832 tls_clear_cipher ( tls, active );
833 memswap ( active, pending, sizeof ( *active ) );
837 /******************************************************************************
839 * Signature and hash algorithms
841 ******************************************************************************
844 /** Supported signature and hash algorithms
846 * Note that the default (TLSv1.1 and earlier) algorithm using
847 * MD5+SHA1 is never explicitly specified.
849 struct tls_signature_hash_algorithm tls_signature_hash_algorithms[] = {
852 .signature = TLS_RSA_ALGORITHM,
853 .hash = TLS_SHA256_ALGORITHM,
855 .pubkey = &rsa_algorithm,
856 .digest = &sha256_algorithm,
860 /** Number of supported signature and hash algorithms */
861 #define TLS_NUM_SIG_HASH_ALGORITHMS \
862 ( sizeof ( tls_signature_hash_algorithms ) / \
863 sizeof ( tls_signature_hash_algorithms[0] ) )
866 * Find TLS signature and hash algorithm
868 * @v pubkey Public-key algorithm
869 * @v digest Digest algorithm
870 * @ret sig_hash Signature and hash algorithm, or NULL
872 static struct tls_signature_hash_algorithm *
873 tls_signature_hash_algorithm ( struct pubkey_algorithm *pubkey,
874 struct digest_algorithm *digest ) {
875 struct tls_signature_hash_algorithm *sig_hash;
878 /* Identify signature and hash algorithm */
879 for ( i = 0 ; i < TLS_NUM_SIG_HASH_ALGORITHMS ; i++ ) {
880 sig_hash = &tls_signature_hash_algorithms[i];
881 if ( ( sig_hash->pubkey == pubkey ) &&
882 ( sig_hash->digest == digest ) ) {
890 /******************************************************************************
892 * Handshake verification
894 ******************************************************************************
898 * Add handshake record to verification hash
901 * @v data Handshake record
902 * @v len Length of handshake record
904 static void tls_add_handshake ( struct tls_session *tls,
905 const void *data, size_t len ) {
907 digest_update ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx,
909 digest_update ( &sha256_algorithm, tls->handshake_sha256_ctx,
914 * Calculate handshake verification hash
917 * @v out Output buffer
919 * Calculates the MD5+SHA1 or SHA256 digest over all handshake
920 * messages seen so far.
922 static void tls_verify_handshake ( struct tls_session *tls, void *out ) {
923 struct digest_algorithm *digest = tls->handshake_digest;
924 uint8_t ctx[ digest->ctxsize ];
926 memcpy ( ctx, tls->handshake_ctx, sizeof ( ctx ) );
927 digest_final ( digest, ctx, out );
930 /******************************************************************************
934 ******************************************************************************
938 * Resume TX state machine
942 static void tls_tx_resume ( struct tls_session *tls ) {
943 process_add ( &tls->process );
947 * Transmit Handshake record
950 * @v data Plaintext record
951 * @v len Length of plaintext record
952 * @ret rc Return status code
954 static int tls_send_handshake ( struct tls_session *tls,
955 void *data, size_t len ) {
957 /* Add to handshake digest */
958 tls_add_handshake ( tls, data, len );
961 return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
965 * Transmit Client Hello record
968 * @ret rc Return status code
970 static int tls_send_client_hello ( struct tls_session *tls ) {
972 uint32_t type_length;
975 uint8_t session_id_len;
976 uint16_t cipher_suite_len;
977 uint16_t cipher_suites[TLS_NUM_CIPHER_SUITES];
978 uint8_t compression_methods_len;
979 uint8_t compression_methods[1];
980 uint16_t extensions_len;
982 uint16_t server_name_type;
983 uint16_t server_name_len;
989 uint8_t name[ strlen ( tls->name ) ];
990 } __attribute__ (( packed )) list[1];
991 } __attribute__ (( packed )) server_name;
992 uint16_t max_fragment_length_type;
993 uint16_t max_fragment_length_len;
996 } __attribute__ (( packed )) max_fragment_length;
997 } __attribute__ (( packed )) extensions;
998 } __attribute__ (( packed )) hello;
1001 memset ( &hello, 0, sizeof ( hello ) );
1002 hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
1003 htonl ( sizeof ( hello ) -
1004 sizeof ( hello.type_length ) ) );
1005 hello.version = htons ( tls->version );
1006 memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
1007 hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
1008 for ( i = 0 ; i < TLS_NUM_CIPHER_SUITES ; i++ )
1009 hello.cipher_suites[i] = tls_cipher_suites[i].code;
1010 hello.compression_methods_len = sizeof ( hello.compression_methods );
1011 hello.extensions_len = htons ( sizeof ( hello.extensions ) );
1012 hello.extensions.server_name_type = htons ( TLS_SERVER_NAME );
1013 hello.extensions.server_name_len
1014 = htons ( sizeof ( hello.extensions.server_name ) );
1015 hello.extensions.server_name.len
1016 = htons ( sizeof ( hello.extensions.server_name.list ) );
1017 hello.extensions.server_name.list[0].type = TLS_SERVER_NAME_HOST_NAME;
1018 hello.extensions.server_name.list[0].len
1019 = htons ( sizeof ( hello.extensions.server_name.list[0].name ));
1020 memcpy ( hello.extensions.server_name.list[0].name, tls->name,
1021 sizeof ( hello.extensions.server_name.list[0].name ) );
1022 hello.extensions.max_fragment_length_type
1023 = htons ( TLS_MAX_FRAGMENT_LENGTH );
1024 hello.extensions.max_fragment_length_len
1025 = htons ( sizeof ( hello.extensions.max_fragment_length ) );
1026 hello.extensions.max_fragment_length.max
1027 = TLS_MAX_FRAGMENT_LENGTH_4096;
1029 return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
1033 * Transmit Certificate record
1035 * @v tls TLS session
1036 * @ret rc Return status code
1038 static int tls_send_certificate ( struct tls_session *tls ) {
1040 uint32_t type_length;
1044 uint8_t data[ tls->cert->raw.len ];
1045 } __attribute__ (( packed )) certificates[1];
1046 } __attribute__ (( packed )) *certificate;
1049 /* Allocate storage for Certificate record (which may be too
1050 * large for the stack).
1052 certificate = zalloc ( sizeof ( *certificate ) );
1053 if ( ! certificate )
1054 return -ENOMEM_CERTIFICATE;
1056 /* Populate record */
1057 certificate->type_length =
1058 ( cpu_to_le32 ( TLS_CERTIFICATE ) |
1059 htonl ( sizeof ( *certificate ) -
1060 sizeof ( certificate->type_length ) ) );
1061 tls_set_uint24 ( certificate->length,
1062 sizeof ( certificate->certificates ) );
1063 tls_set_uint24 ( certificate->certificates[0].length,
1064 sizeof ( certificate->certificates[0].data ) );
1065 memcpy ( certificate->certificates[0].data,
1066 tls->cert->raw.data,
1067 sizeof ( certificate->certificates[0].data ) );
1069 /* Transmit record */
1070 rc = tls_send_handshake ( tls, certificate, sizeof ( *certificate ) );
1073 free ( certificate );
1079 * Transmit Client Key Exchange record
1081 * @v tls TLS session
1082 * @ret rc Return status code
1084 static int tls_send_client_key_exchange ( struct tls_session *tls ) {
1085 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
1086 struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
1087 size_t max_len = pubkey_max_len ( pubkey, cipherspec->pubkey_ctx );
1089 uint32_t type_length;
1090 uint16_t encrypted_pre_master_secret_len;
1091 uint8_t encrypted_pre_master_secret[max_len];
1092 } __attribute__ (( packed )) key_xchg;
1097 /* Encrypt pre-master secret using server's public key */
1098 memset ( &key_xchg, 0, sizeof ( key_xchg ) );
1099 len = pubkey_encrypt ( pubkey, cipherspec->pubkey_ctx,
1100 &tls->pre_master_secret,
1101 sizeof ( tls->pre_master_secret ),
1102 key_xchg.encrypted_pre_master_secret );
1105 DBGC ( tls, "TLS %p could not encrypt pre-master secret: %s\n",
1106 tls, strerror ( rc ) );
1109 unused = ( max_len - len );
1110 key_xchg.type_length =
1111 ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
1112 htonl ( sizeof ( key_xchg ) -
1113 sizeof ( key_xchg.type_length ) - unused ) );
1114 key_xchg.encrypted_pre_master_secret_len =
1115 htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) -
1118 return tls_send_handshake ( tls, &key_xchg,
1119 ( sizeof ( key_xchg ) - unused ) );
1123 * Transmit Certificate Verify record
1125 * @v tls TLS session
1126 * @ret rc Return status code
1128 static int tls_send_certificate_verify ( struct tls_session *tls ) {
1129 struct digest_algorithm *digest = tls->handshake_digest;
1130 struct x509_certificate *cert = tls->cert;
1131 struct pubkey_algorithm *pubkey = cert->signature_algorithm->pubkey;
1132 uint8_t digest_out[ digest->digestsize ];
1133 uint8_t ctx[ pubkey->ctxsize ];
1134 struct tls_signature_hash_algorithm *sig_hash = NULL;
1137 /* Generate digest to be signed */
1138 tls_verify_handshake ( tls, digest_out );
1140 /* Initialise public-key algorithm */
1141 if ( ( rc = pubkey_init ( pubkey, ctx, private_key.data,
1142 private_key.len ) ) != 0 ) {
1143 DBGC ( tls, "TLS %p could not initialise %s client private "
1144 "key: %s\n", tls, pubkey->name, strerror ( rc ) );
1145 goto err_pubkey_init;
1148 /* TLSv1.2 and later use explicit algorithm identifiers */
1149 if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
1150 sig_hash = tls_signature_hash_algorithm ( pubkey, digest );
1152 DBGC ( tls, "TLS %p could not identify (%s,%s) "
1153 "signature and hash algorithm\n", tls,
1154 pubkey->name, digest->name );
1155 rc = -ENOTSUP_SIG_HASH;
1160 /* Generate and transmit record */
1162 size_t max_len = pubkey_max_len ( pubkey, ctx );
1163 int use_sig_hash = ( ( sig_hash == NULL ) ? 0 : 1 );
1165 uint32_t type_length;
1166 struct tls_signature_hash_id sig_hash[use_sig_hash];
1167 uint16_t signature_len;
1168 uint8_t signature[max_len];
1169 } __attribute__ (( packed )) certificate_verify;
1174 len = pubkey_sign ( pubkey, ctx, digest, digest_out,
1175 certificate_verify.signature );
1178 DBGC ( tls, "TLS %p could not sign %s digest using %s "
1179 "client private key: %s\n", tls, digest->name,
1180 pubkey->name, strerror ( rc ) );
1181 goto err_pubkey_sign;
1183 unused = ( max_len - len );
1185 /* Construct Certificate Verify record */
1186 certificate_verify.type_length =
1187 ( cpu_to_le32 ( TLS_CERTIFICATE_VERIFY ) |
1188 htonl ( sizeof ( certificate_verify ) -
1189 sizeof ( certificate_verify.type_length ) -
1191 if ( use_sig_hash ) {
1192 memcpy ( &certificate_verify.sig_hash[0],
1194 sizeof ( certificate_verify.sig_hash[0] ) );
1196 certificate_verify.signature_len =
1197 htons ( sizeof ( certificate_verify.signature ) -
1200 /* Transmit record */
1201 rc = tls_send_handshake ( tls, &certificate_verify,
1202 ( sizeof ( certificate_verify ) - unused ) );
1207 pubkey_final ( pubkey, ctx );
1213 * Transmit Change Cipher record
1215 * @v tls TLS session
1216 * @ret rc Return status code
1218 static int tls_send_change_cipher ( struct tls_session *tls ) {
1219 static const uint8_t change_cipher[1] = { 1 };
1220 return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
1221 change_cipher, sizeof ( change_cipher ) );
1225 * Transmit Finished record
1227 * @v tls TLS session
1228 * @ret rc Return status code
1230 static int tls_send_finished ( struct tls_session *tls ) {
1231 struct digest_algorithm *digest = tls->handshake_digest;
1233 uint32_t type_length;
1234 uint8_t verify_data[12];
1235 } __attribute__ (( packed )) finished;
1236 uint8_t digest_out[ digest->digestsize ];
1239 /* Construct record */
1240 memset ( &finished, 0, sizeof ( finished ) );
1241 finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
1242 htonl ( sizeof ( finished ) -
1243 sizeof ( finished.type_length ) ) );
1244 tls_verify_handshake ( tls, digest_out );
1245 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1246 finished.verify_data, sizeof ( finished.verify_data ),
1247 "client finished", digest_out, sizeof ( digest_out ) );
1249 /* Transmit record */
1250 if ( ( rc = tls_send_handshake ( tls, &finished,
1251 sizeof ( finished ) ) ) != 0 )
1254 /* Mark client as finished */
1255 pending_put ( &tls->client_negotiation );
1261 * Receive new Change Cipher record
1263 * @v tls TLS session
1264 * @v data Plaintext record
1265 * @v len Length of plaintext record
1266 * @ret rc Return status code
1268 static int tls_new_change_cipher ( struct tls_session *tls,
1269 const void *data, size_t len ) {
1272 if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
1273 DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
1274 DBGC_HD ( tls, data, len );
1275 return -EINVAL_CHANGE_CIPHER;
1278 if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
1279 &tls->rx_cipherspec ) ) != 0 ) {
1280 DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
1281 tls, strerror ( rc ) );
1284 tls->rx_seq = ~( ( uint64_t ) 0 );
1290 * Receive new Alert record
1292 * @v tls TLS session
1293 * @v data Plaintext record
1294 * @v len Length of plaintext record
1295 * @ret rc Return status code
1297 static int tls_new_alert ( struct tls_session *tls, const void *data,
1301 uint8_t description;
1303 } __attribute__ (( packed )) *alert = data;
1304 const void *end = alert->next;
1307 if ( end != ( data + len ) ) {
1308 DBGC ( tls, "TLS %p received overlength Alert\n", tls );
1309 DBGC_HD ( tls, data, len );
1310 return -EINVAL_ALERT;
1313 switch ( alert->level ) {
1314 case TLS_ALERT_WARNING:
1315 DBGC ( tls, "TLS %p received warning alert %d\n",
1316 tls, alert->description );
1318 case TLS_ALERT_FATAL:
1319 DBGC ( tls, "TLS %p received fatal alert %d\n",
1320 tls, alert->description );
1321 return -EPERM_ALERT;
1323 DBGC ( tls, "TLS %p received unknown alert level %d"
1324 "(alert %d)\n", tls, alert->level, alert->description );
1330 * Receive new Server Hello handshake record
1332 * @v tls TLS session
1333 * @v data Plaintext handshake record
1334 * @v len Length of plaintext handshake record
1335 * @ret rc Return status code
1337 static int tls_new_server_hello ( struct tls_session *tls,
1338 const void *data, size_t len ) {
1342 uint8_t session_id_len;
1344 } __attribute__ (( packed )) *hello_a = data;
1346 uint8_t session_id[hello_a->session_id_len];
1347 uint16_t cipher_suite;
1348 uint8_t compression_method;
1350 } __attribute__ (( packed )) *hello_b = ( void * ) &hello_a->next;
1351 const void *end = hello_b->next;
1356 if ( end > ( data + len ) ) {
1357 DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
1358 DBGC_HD ( tls, data, len );
1359 return -EINVAL_HELLO;
1362 /* Check and store protocol version */
1363 version = ntohs ( hello_a->version );
1364 if ( version < TLS_VERSION_TLS_1_0 ) {
1365 DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
1366 tls, ( version >> 8 ), ( version & 0xff ) );
1367 return -ENOTSUP_VERSION;
1369 if ( version > tls->version ) {
1370 DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
1371 "protocol version %d.%d\n",
1372 tls, ( version >> 8 ), ( version & 0xff ) );
1373 return -EPROTO_VERSION;
1375 tls->version = version;
1376 DBGC ( tls, "TLS %p using protocol version %d.%d\n",
1377 tls, ( version >> 8 ), ( version & 0xff ) );
1379 /* Use MD5+SHA1 digest algorithm for handshake verification
1380 * for versions earlier than TLSv1.2.
1382 if ( tls->version < TLS_VERSION_TLS_1_2 ) {
1383 tls->handshake_digest = &md5_sha1_algorithm;
1384 tls->handshake_ctx = tls->handshake_md5_sha1_ctx;
1387 /* Copy out server random bytes */
1388 memcpy ( &tls->server_random, &hello_a->random,
1389 sizeof ( tls->server_random ) );
1391 /* Select cipher suite */
1392 if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
1395 /* Generate secrets */
1396 tls_generate_master_secret ( tls );
1397 if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
1404 * Parse certificate chain
1406 * @v tls TLS session
1407 * @v data Certificate chain
1408 * @v len Length of certificate chain
1409 * @ret rc Return status code
1411 static int tls_parse_chain ( struct tls_session *tls,
1412 const void *data, size_t len ) {
1413 const void *end = ( data + len );
1417 } __attribute__ (( packed )) *certificate;
1418 size_t certificate_len;
1419 struct x509_certificate *cert;
1423 /* Free any existing certificate chain */
1424 x509_chain_put ( tls->chain );
1427 /* Create certificate chain */
1428 tls->chain = x509_alloc_chain();
1429 if ( ! tls->chain ) {
1431 goto err_alloc_chain;
1434 /* Add certificates to chain */
1435 while ( data < end ) {
1437 /* Extract raw certificate data */
1439 certificate_len = tls_uint24 ( certificate->length );
1440 next = ( certificate->data + certificate_len );
1442 DBGC ( tls, "TLS %p overlength certificate:\n", tls );
1443 DBGC_HDA ( tls, 0, data, ( end - data ) );
1444 rc = -EINVAL_CERTIFICATE;
1445 goto err_overlength;
1448 /* Add certificate to chain */
1449 if ( ( rc = x509_append_raw ( tls->chain, certificate->data,
1450 certificate_len ) ) != 0 ) {
1451 DBGC ( tls, "TLS %p could not append certificate: %s\n",
1452 tls, strerror ( rc ) );
1453 DBGC_HDA ( tls, 0, data, ( end - data ) );
1456 cert = x509_last ( tls->chain );
1457 DBGC ( tls, "TLS %p found certificate %s\n",
1458 tls, x509_name ( cert ) );
1460 /* Move to next certificate in list */
1468 x509_chain_put ( tls->chain );
1475 * Receive new Certificate handshake record
1477 * @v tls TLS session
1478 * @v data Plaintext handshake record
1479 * @v len Length of plaintext handshake record
1480 * @ret rc Return status code
1482 static int tls_new_certificate ( struct tls_session *tls,
1483 const void *data, size_t len ) {
1486 uint8_t certificates[0];
1487 } __attribute__ (( packed )) *certificate = data;
1488 size_t certificates_len = tls_uint24 ( certificate->length );
1489 const void *end = ( certificate->certificates + certificates_len );
1493 if ( end != ( data + len ) ) {
1494 DBGC ( tls, "TLS %p received overlength Server Certificate\n",
1496 DBGC_HD ( tls, data, len );
1497 return -EINVAL_CERTIFICATES;
1500 /* Parse certificate chain */
1501 if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
1502 certificates_len ) ) != 0 )
1509 * Receive new Certificate Request handshake record
1511 * @v tls TLS session
1512 * @v data Plaintext handshake record
1513 * @v len Length of plaintext handshake record
1514 * @ret rc Return status code
1516 static int tls_new_certificate_request ( struct tls_session *tls,
1517 const void *data __unused,
1518 size_t len __unused ) {
1520 /* We can only send a single certificate, so there is no point
1521 * in parsing the Certificate Request.
1524 /* Free any existing client certificate */
1525 x509_put ( tls->cert );
1527 /* Determine client certificate to be sent */
1528 tls->cert = certstore_find_key ( &private_key );
1529 if ( ! tls->cert ) {
1530 DBGC ( tls, "TLS %p could not find certificate corresponding "
1531 "to private key\n", tls );
1532 return -EPERM_CLIENT_CERT;
1534 x509_get ( tls->cert );
1535 DBGC ( tls, "TLS %p sending client certificate %s\n",
1536 tls, x509_name ( tls->cert ) );
1542 * Receive new Server Hello Done handshake record
1544 * @v tls TLS session
1545 * @v data Plaintext handshake record
1546 * @v len Length of plaintext handshake record
1547 * @ret rc Return status code
1549 static int tls_new_server_hello_done ( struct tls_session *tls,
1550 const void *data, size_t len ) {
1553 } __attribute__ (( packed )) *hello_done = data;
1554 const void *end = hello_done->next;
1558 if ( end != ( data + len ) ) {
1559 DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
1561 DBGC_HD ( tls, data, len );
1562 return -EINVAL_HELLO_DONE;
1565 /* Begin certificate validation */
1566 if ( ( rc = create_validator ( &tls->validator, tls->chain ) ) != 0 ) {
1567 DBGC ( tls, "TLS %p could not start certificate validation: "
1568 "%s\n", tls, strerror ( rc ) );
1576 * Receive new Finished handshake record
1578 * @v tls TLS session
1579 * @v data Plaintext handshake record
1580 * @v len Length of plaintext handshake record
1581 * @ret rc Return status code
1583 static int tls_new_finished ( struct tls_session *tls,
1584 const void *data, size_t len ) {
1585 struct digest_algorithm *digest = tls->handshake_digest;
1587 uint8_t verify_data[12];
1589 } __attribute__ (( packed )) *finished = data;
1590 const void *end = finished->next;
1591 uint8_t digest_out[ digest->digestsize ];
1592 uint8_t verify_data[ sizeof ( finished->verify_data ) ];
1595 if ( end != ( data + len ) ) {
1596 DBGC ( tls, "TLS %p received overlength Finished\n", tls );
1597 DBGC_HD ( tls, data, len );
1598 return -EINVAL_FINISHED;
1602 tls_verify_handshake ( tls, digest_out );
1603 tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1604 verify_data, sizeof ( verify_data ), "server finished",
1605 digest_out, sizeof ( digest_out ) );
1606 if ( memcmp ( verify_data, finished->verify_data,
1607 sizeof ( verify_data ) ) != 0 ) {
1608 DBGC ( tls, "TLS %p verification failed\n", tls );
1609 return -EPERM_VERIFY;
1612 /* Mark server as finished */
1613 pending_put ( &tls->server_negotiation );
1615 /* Send notification of a window change */
1616 xfer_window_changed ( &tls->plainstream );
1622 * Receive new Handshake record
1624 * @v tls TLS session
1625 * @v data Plaintext record
1626 * @v len Length of plaintext record
1627 * @ret rc Return status code
1629 static int tls_new_handshake ( struct tls_session *tls,
1630 const void *data, size_t len ) {
1631 const void *end = ( data + len );
1634 while ( data != end ) {
1639 } __attribute__ (( packed )) *handshake = data;
1640 void *payload = &handshake->payload;
1641 size_t payload_len = tls_uint24 ( handshake->length );
1642 void *next = ( payload + payload_len );
1646 DBGC ( tls, "TLS %p received overlength Handshake\n",
1648 DBGC_HD ( tls, data, len );
1649 return -EINVAL_HANDSHAKE;
1652 switch ( handshake->type ) {
1653 case TLS_SERVER_HELLO:
1654 rc = tls_new_server_hello ( tls, payload, payload_len );
1656 case TLS_CERTIFICATE:
1657 rc = tls_new_certificate ( tls, payload, payload_len );
1659 case TLS_CERTIFICATE_REQUEST:
1660 rc = tls_new_certificate_request ( tls, payload,
1663 case TLS_SERVER_HELLO_DONE:
1664 rc = tls_new_server_hello_done ( tls, payload,
1668 rc = tls_new_finished ( tls, payload, payload_len );
1671 DBGC ( tls, "TLS %p ignoring handshake type %d\n",
1672 tls, handshake->type );
1677 /* Add to handshake digest (except for Hello Requests,
1678 * which are explicitly excluded).
1680 if ( handshake->type != TLS_HELLO_REQUEST )
1681 tls_add_handshake ( tls, data,
1682 sizeof ( *handshake ) +
1685 /* Abort on failure */
1689 /* Move to next handshake record */
1697 * Receive new record
1699 * @v tls TLS session
1700 * @v type Record type
1701 * @v rx_data List of received data buffers
1702 * @ret rc Return status code
1704 static int tls_new_record ( struct tls_session *tls, unsigned int type,
1705 struct list_head *rx_data ) {
1706 struct io_buffer *iobuf;
1707 int ( * handler ) ( struct tls_session *tls, const void *data,
1711 /* Deliver data records to the plainstream interface */
1712 if ( type == TLS_TYPE_DATA ) {
1714 /* Fail unless we are ready to receive data */
1715 if ( ! tls_ready ( tls ) )
1718 /* Deliver each I/O buffer in turn */
1719 while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
1721 list_del ( &iobuf->list );
1722 if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
1724 DBGC ( tls, "TLS %p could not deliver data: "
1725 "%s\n", tls, strerror ( rc ) );
1732 /* For all other records, merge into a single I/O buffer */
1733 iobuf = iob_concatenate ( rx_data );
1735 DBGC ( tls, "TLS %p could not concatenate non-data record "
1736 "type %d\n", tls, type );
1737 return -ENOMEM_RX_CONCAT;
1740 /* Determine handler */
1742 case TLS_TYPE_CHANGE_CIPHER:
1743 handler = tls_new_change_cipher;
1745 case TLS_TYPE_ALERT:
1746 handler = tls_new_alert;
1748 case TLS_TYPE_HANDSHAKE:
1749 handler = tls_new_handshake;
1752 /* RFC4346 says that we should just ignore unknown
1756 DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
1760 /* Handle record and free I/O buffer */
1761 rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
1766 /******************************************************************************
1768 * Record encryption/decryption
1770 ******************************************************************************
1776 * @v cipherspec Cipher specification
1778 * @v seq Sequence number
1779 * @v tlshdr TLS header
1781 static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
1782 uint64_t seq, struct tls_header *tlshdr ) {
1783 struct digest_algorithm *digest = cipherspec->suite->digest;
1785 hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
1786 seq = cpu_to_be64 ( seq );
1787 hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
1788 hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
1794 * @v cipherspec Cipher specification
1797 * @v len Length of data
1799 static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
1800 const void *data, size_t len ) {
1801 struct digest_algorithm *digest = cipherspec->suite->digest;
1803 hmac_update ( digest, ctx, data, len );
1809 * @v cipherspec Cipher specification
1811 * @v mac HMAC to fill in
1813 static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
1815 struct digest_algorithm *digest = cipherspec->suite->digest;
1817 hmac_final ( digest, ctx, cipherspec->mac_secret,
1818 &digest->digestsize, hmac );
1824 * @v cipherspec Cipher specification
1825 * @v seq Sequence number
1826 * @v tlshdr TLS header
1828 * @v len Length of data
1829 * @v mac HMAC to fill in
1831 static void tls_hmac ( struct tls_cipherspec *cipherspec,
1832 uint64_t seq, struct tls_header *tlshdr,
1833 const void *data, size_t len, void *hmac ) {
1834 struct digest_algorithm *digest = cipherspec->suite->digest;
1835 uint8_t ctx[digest->ctxsize];
1837 tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
1838 tls_hmac_update ( cipherspec, ctx, data, len );
1839 tls_hmac_final ( cipherspec, ctx, hmac );
1843 * Allocate and assemble stream-ciphered record from data and MAC portions
1845 * @v tls TLS session
1847 * @ret len Length of data
1848 * @ret digest MAC digest
1849 * @ret plaintext_len Length of plaintext record
1850 * @ret plaintext Allocated plaintext record
1852 static void * __malloc tls_assemble_stream ( struct tls_session *tls,
1853 const void *data, size_t len,
1854 void *digest, size_t *plaintext_len ) {
1855 size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
1860 /* Calculate stream-ciphered struct length */
1861 *plaintext_len = ( len + mac_len );
1863 /* Allocate stream-ciphered struct */
1864 plaintext = malloc ( *plaintext_len );
1867 content = plaintext;
1868 mac = ( content + len );
1870 /* Fill in stream-ciphered struct */
1871 memcpy ( content, data, len );
1872 memcpy ( mac, digest, mac_len );
1878 * Allocate and assemble block-ciphered record from data and MAC portions
1880 * @v tls TLS session
1882 * @ret len Length of data
1883 * @ret digest MAC digest
1884 * @ret plaintext_len Length of plaintext record
1885 * @ret plaintext Allocated plaintext record
1887 static void * tls_assemble_block ( struct tls_session *tls,
1888 const void *data, size_t len,
1889 void *digest, size_t *plaintext_len ) {
1890 size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
1891 size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
1900 /* TLSv1.1 and later use an explicit IV */
1901 iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
1903 /* Calculate block-ciphered struct length */
1904 padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
1905 *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
1907 /* Allocate block-ciphered struct */
1908 plaintext = malloc ( *plaintext_len );
1912 content = ( iv + iv_len );
1913 mac = ( content + len );
1914 padding = ( mac + mac_len );
1916 /* Fill in block-ciphered struct */
1917 tls_generate_random ( tls, iv, iv_len );
1918 memcpy ( content, data, len );
1919 memcpy ( mac, digest, mac_len );
1920 memset ( padding, padding_len, ( padding_len + 1 ) );
1926 * Send plaintext record
1928 * @v tls TLS session
1929 * @v type Record type
1930 * @v data Plaintext record
1931 * @v len Length of plaintext record
1932 * @ret rc Return status code
1934 static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
1935 const void *data, size_t len ) {
1936 struct tls_header plaintext_tlshdr;
1937 struct tls_header *tlshdr;
1938 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
1939 struct cipher_algorithm *cipher = cipherspec->suite->cipher;
1940 void *plaintext = NULL;
1941 size_t plaintext_len;
1942 struct io_buffer *ciphertext = NULL;
1943 size_t ciphertext_len;
1944 size_t mac_len = cipherspec->suite->digest->digestsize;
1945 uint8_t mac[mac_len];
1948 /* Construct header */
1949 plaintext_tlshdr.type = type;
1950 plaintext_tlshdr.version = htons ( tls->version );
1951 plaintext_tlshdr.length = htons ( len );
1954 tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
1956 /* Allocate and assemble plaintext struct */
1957 if ( is_stream_cipher ( cipher ) ) {
1958 plaintext = tls_assemble_stream ( tls, data, len, mac,
1961 plaintext = tls_assemble_block ( tls, data, len, mac,
1964 if ( ! plaintext ) {
1965 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
1966 "plaintext\n", tls, plaintext_len );
1967 rc = -ENOMEM_TX_PLAINTEXT;
1971 DBGC2 ( tls, "Sending plaintext data:\n" );
1972 DBGC2_HD ( tls, plaintext, plaintext_len );
1974 /* Allocate ciphertext */
1975 ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
1976 ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
1977 if ( ! ciphertext ) {
1978 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
1979 "ciphertext\n", tls, ciphertext_len );
1980 rc = -ENOMEM_TX_CIPHERTEXT;
1984 /* Assemble ciphertext */
1985 tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
1986 tlshdr->type = type;
1987 tlshdr->version = htons ( tls->version );
1988 tlshdr->length = htons ( plaintext_len );
1989 memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
1991 cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
1992 iob_put ( ciphertext, plaintext_len ), plaintext_len );
1994 /* Free plaintext as soon as possible to conserve memory */
1998 /* Send ciphertext */
1999 if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
2000 iob_disown ( ciphertext ) ) ) != 0 ) {
2001 DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
2002 tls, strerror ( rc ) );
2006 /* Update TX state machine to next record */
2008 memcpy ( tls->tx_cipherspec.cipher_ctx,
2009 tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
2013 free_iob ( ciphertext );
2018 * Split stream-ciphered record into data and MAC portions
2020 * @v tls TLS session
2021 * @v rx_data List of received data buffers
2022 * @v mac MAC to fill in
2023 * @ret rc Return status code
2025 static int tls_split_stream ( struct tls_session *tls,
2026 struct list_head *rx_data, void **mac ) {
2027 size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2028 struct io_buffer *iobuf;
2031 iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2032 assert ( iobuf != NULL );
2033 if ( iob_len ( iobuf ) < mac_len ) {
2034 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2035 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2036 return -EINVAL_STREAM;
2038 iob_unput ( iobuf, mac_len );
2045 * Split block-ciphered record into data and MAC portions
2047 * @v tls TLS session
2048 * @v rx_data List of received data buffers
2049 * @v mac MAC to fill in
2050 * @ret rc Return status code
2052 static int tls_split_block ( struct tls_session *tls,
2053 struct list_head *rx_data, void **mac ) {
2054 size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2055 struct io_buffer *iobuf;
2057 uint8_t *padding_final;
2061 /* TLSv1.1 and later use an explicit IV */
2062 iobuf = list_first_entry ( rx_data, struct io_buffer, list );
2063 iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
2064 tls->rx_cipherspec.suite->cipher->blocksize : 0 );
2065 if ( iob_len ( iobuf ) < iv_len ) {
2066 DBGC ( tls, "TLS %p received underlength IV\n", tls );
2067 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2068 return -EINVAL_BLOCK;
2070 iob_pull ( iobuf, iv_len );
2072 /* Extract and verify padding */
2073 iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2074 padding_final = ( iobuf->tail - 1 );
2075 padding_len = *padding_final;
2076 if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
2077 DBGC ( tls, "TLS %p received underlength padding\n", tls );
2078 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2079 return -EINVAL_BLOCK;
2081 iob_unput ( iobuf, ( padding_len + 1 ) );
2082 for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
2083 if ( *padding != padding_len ) {
2084 DBGC ( tls, "TLS %p received bad padding\n", tls );
2085 DBGC_HD ( tls, padding, padding_len );
2086 return -EINVAL_PADDING;
2091 if ( iob_len ( iobuf ) < mac_len ) {
2092 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2093 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2094 return -EINVAL_BLOCK;
2096 iob_unput ( iobuf, mac_len );
2103 * Receive new ciphertext record
2105 * @v tls TLS session
2106 * @v tlshdr Record header
2107 * @v rx_data List of received data buffers
2108 * @ret rc Return status code
2110 static int tls_new_ciphertext ( struct tls_session *tls,
2111 struct tls_header *tlshdr,
2112 struct list_head *rx_data ) {
2113 struct tls_header plaintext_tlshdr;
2114 struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
2115 struct cipher_algorithm *cipher = cipherspec->suite->cipher;
2116 struct digest_algorithm *digest = cipherspec->suite->digest;
2117 uint8_t ctx[digest->ctxsize];
2118 uint8_t verify_mac[digest->digestsize];
2119 struct io_buffer *iobuf;
2124 /* Decrypt the received data */
2125 list_for_each_entry ( iobuf, &tls->rx_data, list ) {
2126 cipher_decrypt ( cipher, cipherspec->cipher_ctx,
2127 iobuf->data, iobuf->data, iob_len ( iobuf ) );
2130 /* Split record into content and MAC */
2131 if ( is_stream_cipher ( cipher ) ) {
2132 if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
2135 if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
2139 /* Calculate total length */
2140 DBGC2 ( tls, "Received plaintext data:\n" );
2141 list_for_each_entry ( iobuf, rx_data, list ) {
2142 DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2143 len += iob_len ( iobuf );
2147 plaintext_tlshdr.type = tlshdr->type;
2148 plaintext_tlshdr.version = tlshdr->version;
2149 plaintext_tlshdr.length = htons ( len );
2150 tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
2151 list_for_each_entry ( iobuf, rx_data, list ) {
2152 tls_hmac_update ( cipherspec, ctx, iobuf->data,
2153 iob_len ( iobuf ) );
2155 tls_hmac_final ( cipherspec, ctx, verify_mac );
2156 if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
2157 DBGC ( tls, "TLS %p failed MAC verification\n", tls );
2161 /* Process plaintext record */
2162 if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
2168 /******************************************************************************
2170 * Plaintext stream operations
2172 ******************************************************************************
2176 * Check flow control window
2178 * @v tls TLS session
2179 * @ret len Length of window
2181 static size_t tls_plainstream_window ( struct tls_session *tls ) {
2183 /* Block window unless we are ready to accept data */
2184 if ( ! tls_ready ( tls ) )
2187 return xfer_window ( &tls->cipherstream );
2191 * Deliver datagram as raw data
2193 * @v tls TLS session
2194 * @v iobuf I/O buffer
2195 * @v meta Data transfer metadata
2196 * @ret rc Return status code
2198 static int tls_plainstream_deliver ( struct tls_session *tls,
2199 struct io_buffer *iobuf,
2200 struct xfer_metadata *meta __unused ) {
2203 /* Refuse unless we are ready to accept data */
2204 if ( ! tls_ready ( tls ) ) {
2209 if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
2210 iob_len ( iobuf ) ) ) != 0 )
2218 /** TLS plaintext stream interface operations */
2219 static struct interface_operation tls_plainstream_ops[] = {
2220 INTF_OP ( xfer_deliver, struct tls_session *, tls_plainstream_deliver ),
2221 INTF_OP ( xfer_window, struct tls_session *, tls_plainstream_window ),
2222 INTF_OP ( intf_close, struct tls_session *, tls_close ),
2225 /** TLS plaintext stream interface descriptor */
2226 static struct interface_descriptor tls_plainstream_desc =
2227 INTF_DESC_PASSTHRU ( struct tls_session, plainstream,
2228 tls_plainstream_ops, cipherstream );
2230 /******************************************************************************
2232 * Ciphertext stream operations
2234 ******************************************************************************
2238 * Handle received TLS header
2240 * @v tls TLS session
2241 * @ret rc Returned status code
2243 static int tls_newdata_process_header ( struct tls_session *tls ) {
2244 size_t data_len = ntohs ( tls->rx_header.length );
2245 size_t remaining = data_len;
2247 struct io_buffer *iobuf;
2248 struct io_buffer *tmp;
2251 /* Allocate data buffers now that we know the length */
2252 assert ( list_empty ( &tls->rx_data ) );
2253 while ( remaining ) {
2255 /* Calculate fragment length. Ensure that no block is
2256 * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
2257 * allocation length if necessary).
2259 frag_len = remaining;
2260 if ( frag_len > TLS_RX_BUFSIZE )
2261 frag_len = TLS_RX_BUFSIZE;
2262 remaining -= frag_len;
2263 if ( remaining < TLS_RX_MIN_BUFSIZE ) {
2264 frag_len += remaining;
2268 /* Allocate buffer */
2269 iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
2271 DBGC ( tls, "TLS %p could not allocate %zd of %zd "
2272 "bytes for receive buffer\n", tls,
2273 remaining, data_len );
2274 rc = -ENOMEM_RX_DATA;
2278 /* Ensure tailroom is exactly what we asked for. This
2279 * will result in unaligned I/O buffers when the
2280 * fragment length is unaligned, which can happen only
2281 * before we switch to using a block cipher.
2283 iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
2285 /* Add I/O buffer to list */
2286 list_add_tail ( &iobuf->list, &tls->rx_data );
2289 /* Move to data state */
2290 tls->rx_state = TLS_RX_DATA;
2295 list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
2296 list_del ( &iobuf->list );
2303 * Handle received TLS data payload
2305 * @v tls TLS session
2306 * @ret rc Returned status code
2308 static int tls_newdata_process_data ( struct tls_session *tls ) {
2309 struct io_buffer *iobuf;
2312 /* Move current buffer to end of list */
2313 iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2314 list_del ( &iobuf->list );
2315 list_add_tail ( &iobuf->list, &tls->rx_data );
2317 /* Continue receiving data if any space remains */
2318 iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2319 if ( iob_tailroom ( iobuf ) )
2322 /* Process record */
2323 if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
2324 &tls->rx_data ) ) != 0 )
2327 /* Increment RX sequence number */
2330 /* Return to header state */
2331 assert ( list_empty ( &tls->rx_data ) );
2332 tls->rx_state = TLS_RX_HEADER;
2333 iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
2339 * Receive new ciphertext
2341 * @v tls TLS session
2342 * @v iobuf I/O buffer
2343 * @v meta Data transfer metadat
2344 * @ret rc Return status code
2346 static int tls_cipherstream_deliver ( struct tls_session *tls,
2347 struct io_buffer *iobuf,
2348 struct xfer_metadata *xfer __unused ) {
2350 int ( * process ) ( struct tls_session *tls );
2351 struct io_buffer *dest;
2354 while ( iob_len ( iobuf ) ) {
2356 /* Select buffer according to current state */
2357 switch ( tls->rx_state ) {
2359 dest = &tls->rx_header_iobuf;
2360 process = tls_newdata_process_header;
2363 dest = list_first_entry ( &tls->rx_data,
2364 struct io_buffer, list );
2365 assert ( dest != NULL );
2366 process = tls_newdata_process_data;
2370 rc = -EINVAL_RX_STATE;
2374 /* Copy data portion to buffer */
2375 frag_len = iob_len ( iobuf );
2376 if ( frag_len > iob_tailroom ( dest ) )
2377 frag_len = iob_tailroom ( dest );
2378 memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
2379 iob_pull ( iobuf, frag_len );
2381 /* Process data if buffer is now full */
2382 if ( iob_tailroom ( dest ) == 0 ) {
2383 if ( ( rc = process ( tls ) ) != 0 ) {
2384 tls_close ( tls, rc );
2396 /** TLS ciphertext stream interface operations */
2397 static struct interface_operation tls_cipherstream_ops[] = {
2398 INTF_OP ( xfer_deliver, struct tls_session *,
2399 tls_cipherstream_deliver ),
2400 INTF_OP ( xfer_window_changed, struct tls_session *, tls_tx_resume ),
2401 INTF_OP ( intf_close, struct tls_session *, tls_close ),
2404 /** TLS ciphertext stream interface descriptor */
2405 static struct interface_descriptor tls_cipherstream_desc =
2406 INTF_DESC_PASSTHRU ( struct tls_session, cipherstream,
2407 tls_cipherstream_ops, plainstream );
2409 /******************************************************************************
2411 * Certificate validator
2413 ******************************************************************************
2417 * Handle certificate validation completion
2419 * @v tls TLS session
2420 * @v rc Reason for completion
2422 static void tls_validator_done ( struct tls_session *tls, int rc ) {
2423 struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
2424 struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
2425 struct x509_certificate *cert;
2427 /* Close validator interface */
2428 intf_restart ( &tls->validator, rc );
2430 /* Check for validation failure */
2432 DBGC ( tls, "TLS %p certificate validation failed: %s\n",
2433 tls, strerror ( rc ) );
2436 DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
2438 /* Extract first certificate */
2439 cert = x509_first ( tls->chain );
2440 assert ( cert != NULL );
2442 /* Verify server name */
2443 if ( ( rc = x509_check_name ( cert, tls->name ) ) != 0 ) {
2444 DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
2445 tls, tls->name, strerror ( rc ) );
2449 /* Initialise public key algorithm */
2450 if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
2451 cert->subject.public_key.raw.data,
2452 cert->subject.public_key.raw.len ) ) != 0 ) {
2453 DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
2454 tls, strerror ( rc ) );
2458 /* Schedule Client Key Exchange, Change Cipher, and Finished */
2459 tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
2460 TLS_TX_CHANGE_CIPHER |
2463 tls->tx_pending |= ( TLS_TX_CERTIFICATE |
2464 TLS_TX_CERTIFICATE_VERIFY );
2466 tls_tx_resume ( tls );
2471 tls_close ( tls, rc );
2475 /** TLS certificate validator interface operations */
2476 static struct interface_operation tls_validator_ops[] = {
2477 INTF_OP ( intf_close, struct tls_session *, tls_validator_done ),
2480 /** TLS certificate validator interface descriptor */
2481 static struct interface_descriptor tls_validator_desc =
2482 INTF_DESC ( struct tls_session, validator, tls_validator_ops );
2484 /******************************************************************************
2486 * Controlling process
2488 ******************************************************************************
2492 * TLS TX state machine
2494 * @v tls TLS session
2496 static void tls_tx_step ( struct tls_session *tls ) {
2499 /* Wait for cipherstream to become ready */
2500 if ( ! xfer_window ( &tls->cipherstream ) )
2503 /* Send first pending transmission */
2504 if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
2505 /* Send Client Hello */
2506 if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
2507 DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
2508 tls, strerror ( rc ) );
2511 tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
2512 } else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
2513 /* Send Certificate */
2514 if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
2515 DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
2516 tls, strerror ( rc ) );
2519 tls->tx_pending &= ~TLS_TX_CERTIFICATE;
2520 } else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
2521 /* Send Client Key Exchange */
2522 if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
2523 DBGC ( tls, "TLS %p could not send Client Key "
2524 "Exchange: %s\n", tls, strerror ( rc ) );
2527 tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
2528 } else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
2529 /* Send Certificate Verify */
2530 if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
2531 DBGC ( tls, "TLS %p could not send Certificate "
2532 "Verify: %s\n", tls, strerror ( rc ) );
2535 tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
2536 } else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
2537 /* Send Change Cipher, and then change the cipher in use */
2538 if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
2539 DBGC ( tls, "TLS %p could not send Change Cipher: "
2540 "%s\n", tls, strerror ( rc ) );
2543 if ( ( rc = tls_change_cipher ( tls,
2544 &tls->tx_cipherspec_pending,
2545 &tls->tx_cipherspec )) != 0 ){
2546 DBGC ( tls, "TLS %p could not activate TX cipher: "
2547 "%s\n", tls, strerror ( rc ) );
2551 tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
2552 } else if ( tls->tx_pending & TLS_TX_FINISHED ) {
2554 if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
2555 DBGC ( tls, "TLS %p could not send Finished: %s\n",
2556 tls, strerror ( rc ) );
2559 tls->tx_pending &= ~TLS_TX_FINISHED;
2562 /* Reschedule process if pending transmissions remain */
2563 if ( tls->tx_pending )
2564 tls_tx_resume ( tls );
2569 tls_close ( tls, rc );
2572 /** TLS TX process descriptor */
2573 static struct process_descriptor tls_process_desc =
2574 PROC_DESC_ONCE ( struct tls_session, process, tls_tx_step );
2576 /******************************************************************************
2580 ******************************************************************************
2583 int add_tls ( struct interface *xfer, const char *name,
2584 struct interface **next ) {
2585 struct tls_session *tls;
2588 /* Allocate and initialise TLS structure */
2589 tls = malloc ( sizeof ( *tls ) );
2594 memset ( tls, 0, sizeof ( *tls ) );
2595 ref_init ( &tls->refcnt, free_tls );
2597 intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
2598 intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
2599 intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
2600 process_init ( &tls->process, &tls_process_desc, &tls->refcnt );
2601 tls->version = TLS_VERSION_TLS_1_2;
2602 tls_clear_cipher ( tls, &tls->tx_cipherspec );
2603 tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
2604 tls_clear_cipher ( tls, &tls->rx_cipherspec );
2605 tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
2606 tls->client_random.gmt_unix_time = time ( NULL );
2607 if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
2608 ( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
2611 tls->pre_master_secret.version = htons ( tls->version );
2612 if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
2613 ( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
2616 digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
2617 digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
2618 tls->handshake_digest = &sha256_algorithm;
2619 tls->handshake_ctx = tls->handshake_sha256_ctx;
2620 tls->tx_pending = TLS_TX_CLIENT_HELLO;
2621 iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
2622 sizeof ( tls->rx_header ) );
2623 INIT_LIST_HEAD ( &tls->rx_data );
2625 /* Add pending operations for server and client Finished messages */
2626 pending_get ( &tls->client_negotiation );
2627 pending_get ( &tls->server_negotiation );
2629 /* Attach to parent interface, mortalise self, and return */
2630 intf_plug_plug ( &tls->plainstream, xfer );
2631 *next = &tls->cipherstream;
2632 ref_put ( &tls->refcnt );
2636 ref_put ( &tls->refcnt );