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 ******************************************************************************
182 /** A TLS 24-bit integer
184 * TLS uses 24-bit integers in several places, which are awkward to
192 } __attribute__ (( packed
)) tls24_t
;
195 * Extract 24-bit field value
197 * @v field24 24-bit field
198 * @ret value Field value
201 static inline __attribute__ (( always_inline
)) unsigned long
202 tls_uint24 ( const tls24_t
*field24
) {
204 return ( ( field24
->high
<< 16 ) | be16_to_cpu ( field24
->low
) );
208 * Set 24-bit field value
210 * @v field24 24-bit field
211 * @v value Field value
213 static void tls_set_uint24 ( tls24_t
*field24
, unsigned long value
) {
215 field24
->high
= ( value
>> 16 );
216 field24
->low
= cpu_to_be16 ( value
);
220 * Determine if TLS session is ready for application data
223 * @ret is_ready TLS session is ready
225 static int tls_ready ( struct tls_session
*tls
) {
226 return ( ( ! is_pending ( &tls
->client_negotiation
) ) &&
227 ( ! is_pending ( &tls
->server_negotiation
) ) );
230 /******************************************************************************
232 * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
234 ******************************************************************************
238 * Initialise MD5+SHA1 algorithm
240 * @v ctx MD5+SHA1 context
242 static void md5_sha1_init ( void *ctx
) {
243 struct md5_sha1_context
*context
= ctx
;
245 digest_init ( &md5_algorithm
, context
->md5
);
246 digest_init ( &sha1_algorithm
, context
->sha1
);
250 * Accumulate data with MD5+SHA1 algorithm
252 * @v ctx MD5+SHA1 context
254 * @v len Length of data
256 static void md5_sha1_update ( void *ctx
, const void *data
, size_t len
) {
257 struct md5_sha1_context
*context
= ctx
;
259 digest_update ( &md5_algorithm
, context
->md5
, data
, len
);
260 digest_update ( &sha1_algorithm
, context
->sha1
, data
, len
);
264 * Generate MD5+SHA1 digest
266 * @v ctx MD5+SHA1 context
267 * @v out Output buffer
269 static void md5_sha1_final ( void *ctx
, void *out
) {
270 struct md5_sha1_context
*context
= ctx
;
271 struct md5_sha1_digest
*digest
= out
;
273 digest_final ( &md5_algorithm
, context
->md5
, digest
->md5
);
274 digest_final ( &sha1_algorithm
, context
->sha1
, digest
->sha1
);
277 /** Hybrid MD5+SHA1 digest algorithm */
278 static struct digest_algorithm md5_sha1_algorithm
= {
280 .ctxsize
= sizeof ( struct md5_sha1_context
),
281 .blocksize
= 0, /* Not applicable */
282 .digestsize
= sizeof ( struct md5_sha1_digest
),
283 .init
= md5_sha1_init
,
284 .update
= md5_sha1_update
,
285 .final
= md5_sha1_final
,
288 /** RSA digestInfo prefix for MD5+SHA1 algorithm */
289 struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix
= {
290 .digest
= &md5_sha1_algorithm
,
291 .data
= NULL
, /* MD5+SHA1 signatures have no digestInfo */
295 /******************************************************************************
299 ******************************************************************************
305 * @v refcnt Reference counter
307 static void free_tls ( struct refcnt
*refcnt
) {
308 struct tls_session
*tls
=
309 container_of ( refcnt
, struct tls_session
, refcnt
);
310 struct io_buffer
*iobuf
;
311 struct io_buffer
*tmp
;
313 /* Free dynamically-allocated resources */
314 tls_clear_cipher ( tls
, &tls
->tx_cipherspec
);
315 tls_clear_cipher ( tls
, &tls
->tx_cipherspec_pending
);
316 tls_clear_cipher ( tls
, &tls
->rx_cipherspec
);
317 tls_clear_cipher ( tls
, &tls
->rx_cipherspec_pending
);
318 list_for_each_entry_safe ( iobuf
, tmp
, &tls
->rx_data
, list
) {
319 list_del ( &iobuf
->list
);
322 x509_put ( tls
->cert
);
323 x509_chain_put ( tls
->chain
);
325 /* Free TLS structure itself */
330 * Finish with TLS session
335 static void tls_close ( struct tls_session
*tls
, int rc
) {
337 /* Remove pending operations, if applicable */
338 pending_put ( &tls
->client_negotiation
);
339 pending_put ( &tls
->server_negotiation
);
342 process_del ( &tls
->process
);
344 /* Close all interfaces */
345 intf_shutdown ( &tls
->cipherstream
, rc
);
346 intf_shutdown ( &tls
->plainstream
, rc
);
347 intf_shutdown ( &tls
->validator
, rc
);
350 /******************************************************************************
352 * Random number generation
354 ******************************************************************************
358 * Generate random data
361 * @v data Buffer to fill
362 * @v len Length of buffer
363 * @ret rc Return status code
365 static int tls_generate_random ( struct tls_session
*tls
,
366 void *data
, size_t len
) {
369 /* Generate random bits with no additional input and without
370 * prediction resistance
372 if ( ( rc
= rbg_generate ( NULL
, 0, 0, data
, len
) ) != 0 ) {
373 DBGC ( tls
, "TLS %p could not generate random data: %s\n",
374 tls
, strerror ( rc
) );
382 * Update HMAC with a list of ( data, len ) pairs
384 * @v digest Hash function to use
385 * @v digest_ctx Digest context
386 * @v args ( data, len ) pairs of data, terminated by NULL
388 static void tls_hmac_update_va ( struct digest_algorithm
*digest
,
389 void *digest_ctx
, va_list args
) {
393 while ( ( data
= va_arg ( args
, void * ) ) ) {
394 len
= va_arg ( args
, size_t );
395 hmac_update ( digest
, digest_ctx
, data
, len
);
400 * Generate secure pseudo-random data using a single hash function
403 * @v digest Hash function to use
405 * @v secret_len Length of secret
406 * @v out Output buffer
407 * @v out_len Length of output buffer
408 * @v seeds ( data, len ) pairs of seed data, terminated by NULL
410 static void tls_p_hash_va ( struct tls_session
*tls
,
411 struct digest_algorithm
*digest
,
412 void *secret
, size_t secret_len
,
413 void *out
, size_t out_len
,
415 uint8_t secret_copy
[secret_len
];
416 uint8_t digest_ctx
[digest
->ctxsize
];
417 uint8_t digest_ctx_partial
[digest
->ctxsize
];
418 uint8_t a
[digest
->digestsize
];
419 uint8_t out_tmp
[digest
->digestsize
];
420 size_t frag_len
= digest
->digestsize
;
423 /* Copy the secret, in case HMAC modifies it */
424 memcpy ( secret_copy
, secret
, secret_len
);
425 secret
= secret_copy
;
426 DBGC2 ( tls
, "TLS %p %s secret:\n", tls
, digest
->name
);
427 DBGC2_HD ( tls
, secret
, secret_len
);
430 hmac_init ( digest
, digest_ctx
, secret
, &secret_len
);
431 va_copy ( tmp
, seeds
);
432 tls_hmac_update_va ( digest
, digest_ctx
, tmp
);
434 hmac_final ( digest
, digest_ctx
, secret
, &secret_len
, a
);
435 DBGC2 ( tls
, "TLS %p %s A(1):\n", tls
, digest
->name
);
436 DBGC2_HD ( tls
, &a
, sizeof ( a
) );
438 /* Generate as much data as required */
440 /* Calculate output portion */
441 hmac_init ( digest
, digest_ctx
, secret
, &secret_len
);
442 hmac_update ( digest
, digest_ctx
, a
, sizeof ( a
) );
443 memcpy ( digest_ctx_partial
, digest_ctx
, digest
->ctxsize
);
444 va_copy ( tmp
, seeds
);
445 tls_hmac_update_va ( digest
, digest_ctx
, tmp
);
447 hmac_final ( digest
, digest_ctx
,
448 secret
, &secret_len
, out_tmp
);
451 if ( frag_len
> out_len
)
453 memcpy ( out
, out_tmp
, frag_len
);
454 DBGC2 ( tls
, "TLS %p %s output:\n", tls
, digest
->name
);
455 DBGC2_HD ( tls
, out
, frag_len
);
458 hmac_final ( digest
, digest_ctx_partial
,
459 secret
, &secret_len
, a
);
460 DBGC2 ( tls
, "TLS %p %s A(n):\n", tls
, digest
->name
);
461 DBGC2_HD ( tls
, &a
, sizeof ( a
) );
469 * Generate secure pseudo-random data
473 * @v secret_len Length of secret
474 * @v out Output buffer
475 * @v out_len Length of output buffer
476 * @v ... ( data, len ) pairs of seed data, terminated by NULL
478 static void tls_prf ( struct tls_session
*tls
, void *secret
, size_t secret_len
,
479 void *out
, size_t out_len
, ... ) {
482 size_t subsecret_len
;
485 uint8_t buf
[out_len
];
488 va_start ( seeds
, out_len
);
490 if ( tls
->version
>= TLS_VERSION_TLS_1_2
) {
491 /* Use P_SHA256 for TLSv1.2 and later */
492 tls_p_hash_va ( tls
, &sha256_algorithm
, secret
, secret_len
,
493 out
, out_len
, seeds
);
495 /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
499 /* Split secret into two, with an overlap of up to one byte */
500 subsecret_len
= ( ( secret_len
+ 1 ) / 2 );
502 sha1_secret
= ( secret
+ secret_len
- subsecret_len
);
504 /* Calculate MD5 portion */
505 va_copy ( tmp
, seeds
);
506 tls_p_hash_va ( tls
, &md5_algorithm
, md5_secret
,
507 subsecret_len
, out
, out_len
, seeds
);
510 /* Calculate SHA1 portion */
511 va_copy ( tmp
, seeds
);
512 tls_p_hash_va ( tls
, &sha1_algorithm
, sha1_secret
,
513 subsecret_len
, buf
, out_len
, seeds
);
516 /* XOR the two portions together into the final output buffer */
517 for ( i
= 0 ; i
< out_len
; i
++ )
518 *( ( uint8_t * ) out
+ i
) ^= buf
[i
];
525 * Generate secure pseudo-random data
528 * @v secret_len Length of secret
529 * @v out Output buffer
530 * @v out_len Length of output buffer
531 * @v label String literal label
532 * @v ... ( data, len ) pairs of seed data
534 #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
535 tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
536 label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
538 /******************************************************************************
542 ******************************************************************************
546 * Generate master secret
550 * The pre-master secret and the client and server random values must
553 static void tls_generate_master_secret ( struct tls_session
*tls
) {
554 DBGC ( tls
, "TLS %p pre-master-secret:\n", tls
);
555 DBGC_HD ( tls
, &tls
->pre_master_secret
,
556 sizeof ( tls
->pre_master_secret
) );
557 DBGC ( tls
, "TLS %p client random bytes:\n", tls
);
558 DBGC_HD ( tls
, &tls
->client_random
, sizeof ( tls
->client_random
) );
559 DBGC ( tls
, "TLS %p server random bytes:\n", tls
);
560 DBGC_HD ( tls
, &tls
->server_random
, sizeof ( tls
->server_random
) );
562 tls_prf_label ( tls
, &tls
->pre_master_secret
,
563 sizeof ( tls
->pre_master_secret
),
564 &tls
->master_secret
, sizeof ( tls
->master_secret
),
566 &tls
->client_random
, sizeof ( tls
->client_random
),
567 &tls
->server_random
, sizeof ( tls
->server_random
) );
569 DBGC ( tls
, "TLS %p generated master secret:\n", tls
);
570 DBGC_HD ( tls
, &tls
->master_secret
, sizeof ( tls
->master_secret
) );
574 * Generate key material
578 * The master secret must already be known.
580 static int tls_generate_keys ( struct tls_session
*tls
) {
581 struct tls_cipherspec
*tx_cipherspec
= &tls
->tx_cipherspec_pending
;
582 struct tls_cipherspec
*rx_cipherspec
= &tls
->rx_cipherspec_pending
;
583 size_t hash_size
= tx_cipherspec
->suite
->digest
->digestsize
;
584 size_t key_size
= tx_cipherspec
->suite
->key_len
;
585 size_t iv_size
= tx_cipherspec
->suite
->cipher
->blocksize
;
586 size_t total
= ( 2 * ( hash_size
+ key_size
+ iv_size
) );
587 uint8_t key_block
[total
];
591 /* Generate key block */
592 tls_prf_label ( tls
, &tls
->master_secret
, sizeof ( tls
->master_secret
),
593 key_block
, sizeof ( key_block
), "key expansion",
594 &tls
->server_random
, sizeof ( tls
->server_random
),
595 &tls
->client_random
, sizeof ( tls
->client_random
) );
597 /* Split key block into portions */
601 memcpy ( tx_cipherspec
->mac_secret
, key
, hash_size
);
602 DBGC ( tls
, "TLS %p TX MAC secret:\n", tls
);
603 DBGC_HD ( tls
, key
, hash_size
);
607 memcpy ( rx_cipherspec
->mac_secret
, key
, hash_size
);
608 DBGC ( tls
, "TLS %p RX MAC secret:\n", tls
);
609 DBGC_HD ( tls
, key
, hash_size
);
613 if ( ( rc
= cipher_setkey ( tx_cipherspec
->suite
->cipher
,
614 tx_cipherspec
->cipher_ctx
,
615 key
, key_size
) ) != 0 ) {
616 DBGC ( tls
, "TLS %p could not set TX key: %s\n",
617 tls
, strerror ( rc
) );
620 DBGC ( tls
, "TLS %p TX key:\n", tls
);
621 DBGC_HD ( tls
, key
, key_size
);
625 if ( ( rc
= cipher_setkey ( rx_cipherspec
->suite
->cipher
,
626 rx_cipherspec
->cipher_ctx
,
627 key
, key_size
) ) != 0 ) {
628 DBGC ( tls
, "TLS %p could not set TX key: %s\n",
629 tls
, strerror ( rc
) );
632 DBGC ( tls
, "TLS %p RX key:\n", tls
);
633 DBGC_HD ( tls
, key
, key_size
);
636 /* TX initialisation vector */
637 cipher_setiv ( tx_cipherspec
->suite
->cipher
,
638 tx_cipherspec
->cipher_ctx
, key
);
639 DBGC ( tls
, "TLS %p TX IV:\n", tls
);
640 DBGC_HD ( tls
, key
, iv_size
);
643 /* RX initialisation vector */
644 cipher_setiv ( rx_cipherspec
->suite
->cipher
,
645 rx_cipherspec
->cipher_ctx
, key
);
646 DBGC ( tls
, "TLS %p RX IV:\n", tls
);
647 DBGC_HD ( tls
, key
, iv_size
);
650 assert ( ( key_block
+ total
) == key
);
655 /******************************************************************************
657 * Cipher suite management
659 ******************************************************************************
662 /** Null cipher suite */
663 struct tls_cipher_suite tls_cipher_suite_null
= {
664 .pubkey
= &pubkey_null
,
665 .cipher
= &cipher_null
,
666 .digest
= &digest_null
,
669 /** Number of supported cipher suites */
670 #define TLS_NUM_CIPHER_SUITES table_num_entries ( TLS_CIPHER_SUITES )
673 * Identify cipher suite
675 * @v cipher_suite Cipher suite specification
676 * @ret suite Cipher suite, or NULL
678 static struct tls_cipher_suite
*
679 tls_find_cipher_suite ( unsigned int cipher_suite
) {
680 struct tls_cipher_suite
*suite
;
682 /* Identify cipher suite */
683 for_each_table_entry ( suite
, TLS_CIPHER_SUITES
) {
684 if ( suite
->code
== cipher_suite
)
694 * @v cipherspec TLS cipher specification
696 static void tls_clear_cipher ( struct tls_session
*tls __unused
,
697 struct tls_cipherspec
*cipherspec
) {
699 if ( cipherspec
->suite
) {
700 pubkey_final ( cipherspec
->suite
->pubkey
,
701 cipherspec
->pubkey_ctx
);
703 free ( cipherspec
->dynamic
);
704 memset ( cipherspec
, 0, sizeof ( *cipherspec
) );
705 cipherspec
->suite
= &tls_cipher_suite_null
;
712 * @v cipherspec TLS cipher specification
713 * @v suite Cipher suite
714 * @ret rc Return status code
716 static int tls_set_cipher ( struct tls_session
*tls
,
717 struct tls_cipherspec
*cipherspec
,
718 struct tls_cipher_suite
*suite
) {
719 struct pubkey_algorithm
*pubkey
= suite
->pubkey
;
720 struct cipher_algorithm
*cipher
= suite
->cipher
;
721 struct digest_algorithm
*digest
= suite
->digest
;
725 /* Clear out old cipher contents, if any */
726 tls_clear_cipher ( tls
, cipherspec
);
728 /* Allocate dynamic storage */
729 total
= ( pubkey
->ctxsize
+ 2 * cipher
->ctxsize
+ digest
->digestsize
);
730 dynamic
= zalloc ( total
);
732 DBGC ( tls
, "TLS %p could not allocate %zd bytes for crypto "
733 "context\n", tls
, total
);
734 return -ENOMEM_CONTEXT
;
738 cipherspec
->dynamic
= dynamic
;
739 cipherspec
->pubkey_ctx
= dynamic
; dynamic
+= pubkey
->ctxsize
;
740 cipherspec
->cipher_ctx
= dynamic
; dynamic
+= cipher
->ctxsize
;
741 cipherspec
->cipher_next_ctx
= dynamic
; dynamic
+= cipher
->ctxsize
;
742 cipherspec
->mac_secret
= dynamic
; dynamic
+= digest
->digestsize
;
743 assert ( ( cipherspec
->dynamic
+ total
) == dynamic
);
745 /* Store parameters */
746 cipherspec
->suite
= suite
;
752 * Select next cipher suite
755 * @v cipher_suite Cipher suite specification
756 * @ret rc Return status code
758 static int tls_select_cipher ( struct tls_session
*tls
,
759 unsigned int cipher_suite
) {
760 struct tls_cipher_suite
*suite
;
763 /* Identify cipher suite */
764 suite
= tls_find_cipher_suite ( cipher_suite
);
766 DBGC ( tls
, "TLS %p does not support cipher %04x\n",
767 tls
, ntohs ( cipher_suite
) );
768 return -ENOTSUP_CIPHER
;
772 if ( ( rc
= tls_set_cipher ( tls
, &tls
->tx_cipherspec_pending
,
775 if ( ( rc
= tls_set_cipher ( tls
, &tls
->rx_cipherspec_pending
,
779 DBGC ( tls
, "TLS %p selected %s-%s-%d-%s\n", tls
, suite
->pubkey
->name
,
780 suite
->cipher
->name
, ( suite
->key_len
* 8 ),
781 suite
->digest
->name
);
787 * Activate next cipher suite
790 * @v pending Pending cipher specification
791 * @v active Active cipher specification to replace
792 * @ret rc Return status code
794 static int tls_change_cipher ( struct tls_session
*tls
,
795 struct tls_cipherspec
*pending
,
796 struct tls_cipherspec
*active
) {
799 if ( pending
->suite
== &tls_cipher_suite_null
) {
800 DBGC ( tls
, "TLS %p refusing to use null cipher\n", tls
);
801 return -ENOTSUP_NULL
;
804 tls_clear_cipher ( tls
, active
);
805 memswap ( active
, pending
, sizeof ( *active
) );
809 /******************************************************************************
811 * Signature and hash algorithms
813 ******************************************************************************
816 /** Number of supported signature and hash algorithms */
817 #define TLS_NUM_SIG_HASH_ALGORITHMS \
818 table_num_entries ( TLS_SIG_HASH_ALGORITHMS )
821 * Find TLS signature and hash algorithm
823 * @v pubkey Public-key algorithm
824 * @v digest Digest algorithm
825 * @ret sig_hash Signature and hash algorithm, or NULL
827 static struct tls_signature_hash_algorithm
*
828 tls_signature_hash_algorithm ( struct pubkey_algorithm
*pubkey
,
829 struct digest_algorithm
*digest
) {
830 struct tls_signature_hash_algorithm
*sig_hash
;
832 /* Identify signature and hash algorithm */
833 for_each_table_entry ( sig_hash
, TLS_SIG_HASH_ALGORITHMS
) {
834 if ( ( sig_hash
->pubkey
== pubkey
) &&
835 ( sig_hash
->digest
== digest
) ) {
843 /******************************************************************************
845 * Handshake verification
847 ******************************************************************************
851 * Add handshake record to verification hash
854 * @v data Handshake record
855 * @v len Length of handshake record
857 static void tls_add_handshake ( struct tls_session
*tls
,
858 const void *data
, size_t len
) {
860 digest_update ( &md5_sha1_algorithm
, tls
->handshake_md5_sha1_ctx
,
862 digest_update ( &sha256_algorithm
, tls
->handshake_sha256_ctx
,
867 * Calculate handshake verification hash
870 * @v out Output buffer
872 * Calculates the MD5+SHA1 or SHA256 digest over all handshake
873 * messages seen so far.
875 static void tls_verify_handshake ( struct tls_session
*tls
, void *out
) {
876 struct digest_algorithm
*digest
= tls
->handshake_digest
;
877 uint8_t ctx
[ digest
->ctxsize
];
879 memcpy ( ctx
, tls
->handshake_ctx
, sizeof ( ctx
) );
880 digest_final ( digest
, ctx
, out
);
883 /******************************************************************************
887 ******************************************************************************
891 * Resume TX state machine
895 static void tls_tx_resume ( struct tls_session
*tls
) {
896 process_add ( &tls
->process
);
900 * Transmit Handshake record
903 * @v data Plaintext record
904 * @v len Length of plaintext record
905 * @ret rc Return status code
907 static int tls_send_handshake ( struct tls_session
*tls
,
908 void *data
, size_t len
) {
910 /* Add to handshake digest */
911 tls_add_handshake ( tls
, data
, len
);
914 return tls_send_plaintext ( tls
, TLS_TYPE_HANDSHAKE
, data
, len
);
918 * Transmit Client Hello record
921 * @ret rc Return status code
923 static int tls_send_client_hello ( struct tls_session
*tls
) {
925 uint32_t type_length
;
928 uint8_t session_id_len
;
929 uint16_t cipher_suite_len
;
930 uint16_t cipher_suites
[TLS_NUM_CIPHER_SUITES
];
931 uint8_t compression_methods_len
;
932 uint8_t compression_methods
[1];
933 uint16_t extensions_len
;
935 uint16_t server_name_type
;
936 uint16_t server_name_len
;
942 uint8_t name
[ strlen ( tls
->name
) ];
943 } __attribute__ (( packed
)) list
[1];
944 } __attribute__ (( packed
)) server_name
;
945 uint16_t max_fragment_length_type
;
946 uint16_t max_fragment_length_len
;
949 } __attribute__ (( packed
)) max_fragment_length
;
950 uint16_t signature_algorithms_type
;
951 uint16_t signature_algorithms_len
;
954 struct tls_signature_hash_id
955 code
[TLS_NUM_SIG_HASH_ALGORITHMS
];
956 } __attribute__ (( packed
)) signature_algorithms
;
957 } __attribute__ (( packed
)) extensions
;
958 } __attribute__ (( packed
)) hello
;
959 struct tls_cipher_suite
*suite
;
960 struct tls_signature_hash_algorithm
*sighash
;
963 memset ( &hello
, 0, sizeof ( hello
) );
964 hello
.type_length
= ( cpu_to_le32 ( TLS_CLIENT_HELLO
) |
965 htonl ( sizeof ( hello
) -
966 sizeof ( hello
.type_length
) ) );
967 hello
.version
= htons ( tls
->version
);
968 memcpy ( &hello
.random
, &tls
->client_random
, sizeof ( hello
.random
) );
969 hello
.cipher_suite_len
= htons ( sizeof ( hello
.cipher_suites
) );
970 i
= 0 ; for_each_table_entry ( suite
, TLS_CIPHER_SUITES
)
971 hello
.cipher_suites
[i
++] = suite
->code
;
972 hello
.compression_methods_len
= sizeof ( hello
.compression_methods
);
973 hello
.extensions_len
= htons ( sizeof ( hello
.extensions
) );
974 hello
.extensions
.server_name_type
= htons ( TLS_SERVER_NAME
);
975 hello
.extensions
.server_name_len
976 = htons ( sizeof ( hello
.extensions
.server_name
) );
977 hello
.extensions
.server_name
.len
978 = htons ( sizeof ( hello
.extensions
.server_name
.list
) );
979 hello
.extensions
.server_name
.list
[0].type
= TLS_SERVER_NAME_HOST_NAME
;
980 hello
.extensions
.server_name
.list
[0].len
981 = htons ( sizeof ( hello
.extensions
.server_name
.list
[0].name
));
982 memcpy ( hello
.extensions
.server_name
.list
[0].name
, tls
->name
,
983 sizeof ( hello
.extensions
.server_name
.list
[0].name
) );
984 hello
.extensions
.max_fragment_length_type
985 = htons ( TLS_MAX_FRAGMENT_LENGTH
);
986 hello
.extensions
.max_fragment_length_len
987 = htons ( sizeof ( hello
.extensions
.max_fragment_length
) );
988 hello
.extensions
.max_fragment_length
.max
989 = TLS_MAX_FRAGMENT_LENGTH_4096
;
990 hello
.extensions
.signature_algorithms_type
991 = htons ( TLS_SIGNATURE_ALGORITHMS
);
992 hello
.extensions
.signature_algorithms_len
993 = htons ( sizeof ( hello
.extensions
.signature_algorithms
) );
994 hello
.extensions
.signature_algorithms
.len
995 = htons ( sizeof ( hello
.extensions
.signature_algorithms
.code
));
996 i
= 0 ; for_each_table_entry ( sighash
, TLS_SIG_HASH_ALGORITHMS
)
997 hello
.extensions
.signature_algorithms
.code
[i
++] = sighash
->code
;
999 return tls_send_handshake ( tls
, &hello
, sizeof ( hello
) );
1003 * Transmit Certificate record
1005 * @v tls TLS session
1006 * @ret rc Return status code
1008 static int tls_send_certificate ( struct tls_session
*tls
) {
1010 uint32_t type_length
;
1014 uint8_t data
[ tls
->cert
->raw
.len
];
1015 } __attribute__ (( packed
)) certificates
[1];
1016 } __attribute__ (( packed
)) *certificate
;
1019 /* Allocate storage for Certificate record (which may be too
1020 * large for the stack).
1022 certificate
= zalloc ( sizeof ( *certificate
) );
1023 if ( ! certificate
)
1024 return -ENOMEM_CERTIFICATE
;
1026 /* Populate record */
1027 certificate
->type_length
=
1028 ( cpu_to_le32 ( TLS_CERTIFICATE
) |
1029 htonl ( sizeof ( *certificate
) -
1030 sizeof ( certificate
->type_length
) ) );
1031 tls_set_uint24 ( &certificate
->length
,
1032 sizeof ( certificate
->certificates
) );
1033 tls_set_uint24 ( &certificate
->certificates
[0].length
,
1034 sizeof ( certificate
->certificates
[0].data
) );
1035 memcpy ( certificate
->certificates
[0].data
,
1036 tls
->cert
->raw
.data
,
1037 sizeof ( certificate
->certificates
[0].data
) );
1039 /* Transmit record */
1040 rc
= tls_send_handshake ( tls
, certificate
, sizeof ( *certificate
) );
1043 free ( certificate
);
1049 * Transmit Client Key Exchange record
1051 * @v tls TLS session
1052 * @ret rc Return status code
1054 static int tls_send_client_key_exchange ( struct tls_session
*tls
) {
1055 struct tls_cipherspec
*cipherspec
= &tls
->tx_cipherspec_pending
;
1056 struct pubkey_algorithm
*pubkey
= cipherspec
->suite
->pubkey
;
1057 size_t max_len
= pubkey_max_len ( pubkey
, cipherspec
->pubkey_ctx
);
1059 uint32_t type_length
;
1060 uint16_t encrypted_pre_master_secret_len
;
1061 uint8_t encrypted_pre_master_secret
[max_len
];
1062 } __attribute__ (( packed
)) key_xchg
;
1067 /* Encrypt pre-master secret using server's public key */
1068 memset ( &key_xchg
, 0, sizeof ( key_xchg
) );
1069 len
= pubkey_encrypt ( pubkey
, cipherspec
->pubkey_ctx
,
1070 &tls
->pre_master_secret
,
1071 sizeof ( tls
->pre_master_secret
),
1072 key_xchg
.encrypted_pre_master_secret
);
1075 DBGC ( tls
, "TLS %p could not encrypt pre-master secret: %s\n",
1076 tls
, strerror ( rc
) );
1079 unused
= ( max_len
- len
);
1080 key_xchg
.type_length
=
1081 ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE
) |
1082 htonl ( sizeof ( key_xchg
) -
1083 sizeof ( key_xchg
.type_length
) - unused
) );
1084 key_xchg
.encrypted_pre_master_secret_len
=
1085 htons ( sizeof ( key_xchg
.encrypted_pre_master_secret
) -
1088 return tls_send_handshake ( tls
, &key_xchg
,
1089 ( sizeof ( key_xchg
) - unused
) );
1093 * Transmit Certificate Verify record
1095 * @v tls TLS session
1096 * @ret rc Return status code
1098 static int tls_send_certificate_verify ( struct tls_session
*tls
) {
1099 struct digest_algorithm
*digest
= tls
->handshake_digest
;
1100 struct x509_certificate
*cert
= tls
->cert
;
1101 struct pubkey_algorithm
*pubkey
= cert
->signature_algorithm
->pubkey
;
1102 uint8_t digest_out
[ digest
->digestsize
];
1103 uint8_t ctx
[ pubkey
->ctxsize
];
1104 struct tls_signature_hash_algorithm
*sig_hash
= NULL
;
1107 /* Generate digest to be signed */
1108 tls_verify_handshake ( tls
, digest_out
);
1110 /* Initialise public-key algorithm */
1111 if ( ( rc
= pubkey_init ( pubkey
, ctx
, private_key
.data
,
1112 private_key
.len
) ) != 0 ) {
1113 DBGC ( tls
, "TLS %p could not initialise %s client private "
1114 "key: %s\n", tls
, pubkey
->name
, strerror ( rc
) );
1115 goto err_pubkey_init
;
1118 /* TLSv1.2 and later use explicit algorithm identifiers */
1119 if ( tls
->version
>= TLS_VERSION_TLS_1_2
) {
1120 sig_hash
= tls_signature_hash_algorithm ( pubkey
, digest
);
1122 DBGC ( tls
, "TLS %p could not identify (%s,%s) "
1123 "signature and hash algorithm\n", tls
,
1124 pubkey
->name
, digest
->name
);
1125 rc
= -ENOTSUP_SIG_HASH
;
1130 /* Generate and transmit record */
1132 size_t max_len
= pubkey_max_len ( pubkey
, ctx
);
1133 int use_sig_hash
= ( ( sig_hash
== NULL
) ?
0 : 1 );
1135 uint32_t type_length
;
1136 struct tls_signature_hash_id sig_hash
[use_sig_hash
];
1137 uint16_t signature_len
;
1138 uint8_t signature
[max_len
];
1139 } __attribute__ (( packed
)) certificate_verify
;
1144 len
= pubkey_sign ( pubkey
, ctx
, digest
, digest_out
,
1145 certificate_verify
.signature
);
1148 DBGC ( tls
, "TLS %p could not sign %s digest using %s "
1149 "client private key: %s\n", tls
, digest
->name
,
1150 pubkey
->name
, strerror ( rc
) );
1151 goto err_pubkey_sign
;
1153 unused
= ( max_len
- len
);
1155 /* Construct Certificate Verify record */
1156 certificate_verify
.type_length
=
1157 ( cpu_to_le32 ( TLS_CERTIFICATE_VERIFY
) |
1158 htonl ( sizeof ( certificate_verify
) -
1159 sizeof ( certificate_verify
.type_length
) -
1161 if ( use_sig_hash
) {
1162 memcpy ( &certificate_verify
.sig_hash
[0],
1164 sizeof ( certificate_verify
.sig_hash
[0] ) );
1166 certificate_verify
.signature_len
=
1167 htons ( sizeof ( certificate_verify
.signature
) -
1170 /* Transmit record */
1171 rc
= tls_send_handshake ( tls
, &certificate_verify
,
1172 ( sizeof ( certificate_verify
) - unused
) );
1177 pubkey_final ( pubkey
, ctx
);
1183 * Transmit Change Cipher record
1185 * @v tls TLS session
1186 * @ret rc Return status code
1188 static int tls_send_change_cipher ( struct tls_session
*tls
) {
1189 static const uint8_t change_cipher
[1] = { 1 };
1190 return tls_send_plaintext ( tls
, TLS_TYPE_CHANGE_CIPHER
,
1191 change_cipher
, sizeof ( change_cipher
) );
1195 * Transmit Finished record
1197 * @v tls TLS session
1198 * @ret rc Return status code
1200 static int tls_send_finished ( struct tls_session
*tls
) {
1201 struct digest_algorithm
*digest
= tls
->handshake_digest
;
1203 uint32_t type_length
;
1204 uint8_t verify_data
[12];
1205 } __attribute__ (( packed
)) finished
;
1206 uint8_t digest_out
[ digest
->digestsize
];
1209 /* Construct record */
1210 memset ( &finished
, 0, sizeof ( finished
) );
1211 finished
.type_length
= ( cpu_to_le32 ( TLS_FINISHED
) |
1212 htonl ( sizeof ( finished
) -
1213 sizeof ( finished
.type_length
) ) );
1214 tls_verify_handshake ( tls
, digest_out
);
1215 tls_prf_label ( tls
, &tls
->master_secret
, sizeof ( tls
->master_secret
),
1216 finished
.verify_data
, sizeof ( finished
.verify_data
),
1217 "client finished", digest_out
, sizeof ( digest_out
) );
1219 /* Transmit record */
1220 if ( ( rc
= tls_send_handshake ( tls
, &finished
,
1221 sizeof ( finished
) ) ) != 0 )
1224 /* Mark client as finished */
1225 pending_put ( &tls
->client_negotiation
);
1231 * Receive new Change Cipher record
1233 * @v tls TLS session
1234 * @v data Plaintext record
1235 * @v len Length of plaintext record
1236 * @ret rc Return status code
1238 static int tls_new_change_cipher ( struct tls_session
*tls
,
1239 const void *data
, size_t len
) {
1242 if ( ( len
!= 1 ) || ( *( ( uint8_t * ) data
) != 1 ) ) {
1243 DBGC ( tls
, "TLS %p received invalid Change Cipher\n", tls
);
1244 DBGC_HD ( tls
, data
, len
);
1245 return -EINVAL_CHANGE_CIPHER
;
1248 if ( ( rc
= tls_change_cipher ( tls
, &tls
->rx_cipherspec_pending
,
1249 &tls
->rx_cipherspec
) ) != 0 ) {
1250 DBGC ( tls
, "TLS %p could not activate RX cipher: %s\n",
1251 tls
, strerror ( rc
) );
1254 tls
->rx_seq
= ~( ( uint64_t ) 0 );
1260 * Receive new Alert record
1262 * @v tls TLS session
1263 * @v data Plaintext record
1264 * @v len Length of plaintext record
1265 * @ret rc Return status code
1267 static int tls_new_alert ( struct tls_session
*tls
, const void *data
,
1271 uint8_t description
;
1273 } __attribute__ (( packed
)) *alert
= data
;
1274 const void *end
= alert
->next
;
1277 if ( end
!= ( data
+ len
) ) {
1278 DBGC ( tls
, "TLS %p received overlength Alert\n", tls
);
1279 DBGC_HD ( tls
, data
, len
);
1280 return -EINVAL_ALERT
;
1283 switch ( alert
->level
) {
1284 case TLS_ALERT_WARNING
:
1285 DBGC ( tls
, "TLS %p received warning alert %d\n",
1286 tls
, alert
->description
);
1288 case TLS_ALERT_FATAL
:
1289 DBGC ( tls
, "TLS %p received fatal alert %d\n",
1290 tls
, alert
->description
);
1291 return -EPERM_ALERT
;
1293 DBGC ( tls
, "TLS %p received unknown alert level %d"
1294 "(alert %d)\n", tls
, alert
->level
, alert
->description
);
1300 * Receive new Server Hello handshake record
1302 * @v tls TLS session
1303 * @v data Plaintext handshake record
1304 * @v len Length of plaintext handshake record
1305 * @ret rc Return status code
1307 static int tls_new_server_hello ( struct tls_session
*tls
,
1308 const void *data
, size_t len
) {
1312 uint8_t session_id_len
;
1314 } __attribute__ (( packed
)) *hello_a
= data
;
1316 uint8_t session_id
[hello_a
->session_id_len
];
1317 uint16_t cipher_suite
;
1318 uint8_t compression_method
;
1320 } __attribute__ (( packed
)) *hello_b
= ( void * ) &hello_a
->next
;
1321 const void *end
= hello_b
->next
;
1326 if ( end
> ( data
+ len
) ) {
1327 DBGC ( tls
, "TLS %p received underlength Server Hello\n", tls
);
1328 DBGC_HD ( tls
, data
, len
);
1329 return -EINVAL_HELLO
;
1332 /* Check and store protocol version */
1333 version
= ntohs ( hello_a
->version
);
1334 if ( version
< TLS_VERSION_TLS_1_0
) {
1335 DBGC ( tls
, "TLS %p does not support protocol version %d.%d\n",
1336 tls
, ( version
>> 8 ), ( version
& 0xff ) );
1337 return -ENOTSUP_VERSION
;
1339 if ( version
> tls
->version
) {
1340 DBGC ( tls
, "TLS %p server attempted to illegally upgrade to "
1341 "protocol version %d.%d\n",
1342 tls
, ( version
>> 8 ), ( version
& 0xff ) );
1343 return -EPROTO_VERSION
;
1345 tls
->version
= version
;
1346 DBGC ( tls
, "TLS %p using protocol version %d.%d\n",
1347 tls
, ( version
>> 8 ), ( version
& 0xff ) );
1349 /* Use MD5+SHA1 digest algorithm for handshake verification
1350 * for versions earlier than TLSv1.2.
1352 if ( tls
->version
< TLS_VERSION_TLS_1_2
) {
1353 tls
->handshake_digest
= &md5_sha1_algorithm
;
1354 tls
->handshake_ctx
= tls
->handshake_md5_sha1_ctx
;
1357 /* Copy out server random bytes */
1358 memcpy ( &tls
->server_random
, &hello_a
->random
,
1359 sizeof ( tls
->server_random
) );
1361 /* Select cipher suite */
1362 if ( ( rc
= tls_select_cipher ( tls
, hello_b
->cipher_suite
) ) != 0 )
1365 /* Generate secrets */
1366 tls_generate_master_secret ( tls
);
1367 if ( ( rc
= tls_generate_keys ( tls
) ) != 0 )
1374 * Parse certificate chain
1376 * @v tls TLS session
1377 * @v data Certificate chain
1378 * @v len Length of certificate chain
1379 * @ret rc Return status code
1381 static int tls_parse_chain ( struct tls_session
*tls
,
1382 const void *data
, size_t len
) {
1383 const void *end
= ( data
+ len
);
1387 } __attribute__ (( packed
)) *certificate
;
1388 size_t certificate_len
;
1389 struct x509_certificate
*cert
;
1393 /* Free any existing certificate chain */
1394 x509_chain_put ( tls
->chain
);
1397 /* Create certificate chain */
1398 tls
->chain
= x509_alloc_chain();
1399 if ( ! tls
->chain
) {
1401 goto err_alloc_chain
;
1404 /* Add certificates to chain */
1405 while ( data
< end
) {
1407 /* Extract raw certificate data */
1409 certificate_len
= tls_uint24 ( &certificate
->length
);
1410 next
= ( certificate
->data
+ certificate_len
);
1412 DBGC ( tls
, "TLS %p overlength certificate:\n", tls
);
1413 DBGC_HDA ( tls
, 0, data
, ( end
- data
) );
1414 rc
= -EINVAL_CERTIFICATE
;
1415 goto err_overlength
;
1418 /* Add certificate to chain */
1419 if ( ( rc
= x509_append_raw ( tls
->chain
, certificate
->data
,
1420 certificate_len
) ) != 0 ) {
1421 DBGC ( tls
, "TLS %p could not append certificate: %s\n",
1422 tls
, strerror ( rc
) );
1423 DBGC_HDA ( tls
, 0, data
, ( end
- data
) );
1426 cert
= x509_last ( tls
->chain
);
1427 DBGC ( tls
, "TLS %p found certificate %s\n",
1428 tls
, x509_name ( cert
) );
1430 /* Move to next certificate in list */
1438 x509_chain_put ( tls
->chain
);
1445 * Receive new Certificate handshake record
1447 * @v tls TLS session
1448 * @v data Plaintext handshake record
1449 * @v len Length of plaintext handshake record
1450 * @ret rc Return status code
1452 static int tls_new_certificate ( struct tls_session
*tls
,
1453 const void *data
, size_t len
) {
1456 uint8_t certificates
[0];
1457 } __attribute__ (( packed
)) *certificate
= data
;
1458 size_t certificates_len
= tls_uint24 ( &certificate
->length
);
1459 const void *end
= ( certificate
->certificates
+ certificates_len
);
1463 if ( end
!= ( data
+ len
) ) {
1464 DBGC ( tls
, "TLS %p received overlength Server Certificate\n",
1466 DBGC_HD ( tls
, data
, len
);
1467 return -EINVAL_CERTIFICATES
;
1470 /* Parse certificate chain */
1471 if ( ( rc
= tls_parse_chain ( tls
, certificate
->certificates
,
1472 certificates_len
) ) != 0 )
1479 * Receive new Certificate Request handshake record
1481 * @v tls TLS session
1482 * @v data Plaintext handshake record
1483 * @v len Length of plaintext handshake record
1484 * @ret rc Return status code
1486 static int tls_new_certificate_request ( struct tls_session
*tls
,
1487 const void *data __unused
,
1488 size_t len __unused
) {
1490 /* We can only send a single certificate, so there is no point
1491 * in parsing the Certificate Request.
1494 /* Free any existing client certificate */
1495 x509_put ( tls
->cert
);
1497 /* Determine client certificate to be sent */
1498 tls
->cert
= certstore_find_key ( &private_key
);
1499 if ( ! tls
->cert
) {
1500 DBGC ( tls
, "TLS %p could not find certificate corresponding "
1501 "to private key\n", tls
);
1502 return -EPERM_CLIENT_CERT
;
1504 x509_get ( tls
->cert
);
1505 DBGC ( tls
, "TLS %p sending client certificate %s\n",
1506 tls
, x509_name ( tls
->cert
) );
1512 * Receive new Server Hello Done handshake record
1514 * @v tls TLS session
1515 * @v data Plaintext handshake record
1516 * @v len Length of plaintext handshake record
1517 * @ret rc Return status code
1519 static int tls_new_server_hello_done ( struct tls_session
*tls
,
1520 const void *data
, size_t len
) {
1523 } __attribute__ (( packed
)) *hello_done
= data
;
1524 const void *end
= hello_done
->next
;
1528 if ( end
!= ( data
+ len
) ) {
1529 DBGC ( tls
, "TLS %p received overlength Server Hello Done\n",
1531 DBGC_HD ( tls
, data
, len
);
1532 return -EINVAL_HELLO_DONE
;
1535 /* Begin certificate validation */
1536 if ( ( rc
= create_validator ( &tls
->validator
, tls
->chain
) ) != 0 ) {
1537 DBGC ( tls
, "TLS %p could not start certificate validation: "
1538 "%s\n", tls
, strerror ( rc
) );
1546 * Receive new Finished handshake record
1548 * @v tls TLS session
1549 * @v data Plaintext handshake record
1550 * @v len Length of plaintext handshake record
1551 * @ret rc Return status code
1553 static int tls_new_finished ( struct tls_session
*tls
,
1554 const void *data
, size_t len
) {
1555 struct digest_algorithm
*digest
= tls
->handshake_digest
;
1557 uint8_t verify_data
[12];
1559 } __attribute__ (( packed
)) *finished
= data
;
1560 const void *end
= finished
->next
;
1561 uint8_t digest_out
[ digest
->digestsize
];
1562 uint8_t verify_data
[ sizeof ( finished
->verify_data
) ];
1565 if ( end
!= ( data
+ len
) ) {
1566 DBGC ( tls
, "TLS %p received overlength Finished\n", tls
);
1567 DBGC_HD ( tls
, data
, len
);
1568 return -EINVAL_FINISHED
;
1572 tls_verify_handshake ( tls
, digest_out
);
1573 tls_prf_label ( tls
, &tls
->master_secret
, sizeof ( tls
->master_secret
),
1574 verify_data
, sizeof ( verify_data
), "server finished",
1575 digest_out
, sizeof ( digest_out
) );
1576 if ( memcmp ( verify_data
, finished
->verify_data
,
1577 sizeof ( verify_data
) ) != 0 ) {
1578 DBGC ( tls
, "TLS %p verification failed\n", tls
);
1579 return -EPERM_VERIFY
;
1582 /* Mark server as finished */
1583 pending_put ( &tls
->server_negotiation
);
1585 /* Send notification of a window change */
1586 xfer_window_changed ( &tls
->plainstream
);
1592 * Receive new Handshake record
1594 * @v tls TLS session
1595 * @v data Plaintext record
1596 * @v len Length of plaintext record
1597 * @ret rc Return status code
1599 static int tls_new_handshake ( struct tls_session
*tls
,
1600 const void *data
, size_t len
) {
1601 const void *end
= ( data
+ len
);
1604 while ( data
!= end
) {
1609 } __attribute__ (( packed
)) *handshake
= data
;
1610 const void *payload
= &handshake
->payload
;
1611 size_t payload_len
= tls_uint24 ( &handshake
->length
);
1612 const void *next
= ( payload
+ payload_len
);
1616 DBGC ( tls
, "TLS %p received overlength Handshake\n",
1618 DBGC_HD ( tls
, data
, len
);
1619 return -EINVAL_HANDSHAKE
;
1622 switch ( handshake
->type
) {
1623 case TLS_SERVER_HELLO
:
1624 rc
= tls_new_server_hello ( tls
, payload
, payload_len
);
1626 case TLS_CERTIFICATE
:
1627 rc
= tls_new_certificate ( tls
, payload
, payload_len
);
1629 case TLS_CERTIFICATE_REQUEST
:
1630 rc
= tls_new_certificate_request ( tls
, payload
,
1633 case TLS_SERVER_HELLO_DONE
:
1634 rc
= tls_new_server_hello_done ( tls
, payload
,
1638 rc
= tls_new_finished ( tls
, payload
, payload_len
);
1641 DBGC ( tls
, "TLS %p ignoring handshake type %d\n",
1642 tls
, handshake
->type
);
1647 /* Add to handshake digest (except for Hello Requests,
1648 * which are explicitly excluded).
1650 if ( handshake
->type
!= TLS_HELLO_REQUEST
)
1651 tls_add_handshake ( tls
, data
,
1652 sizeof ( *handshake
) +
1655 /* Abort on failure */
1659 /* Move to next handshake record */
1667 * Receive new record
1669 * @v tls TLS session
1670 * @v type Record type
1671 * @v rx_data List of received data buffers
1672 * @ret rc Return status code
1674 static int tls_new_record ( struct tls_session
*tls
, unsigned int type
,
1675 struct list_head
*rx_data
) {
1676 struct io_buffer
*iobuf
;
1677 int ( * handler
) ( struct tls_session
*tls
, const void *data
,
1681 /* Deliver data records to the plainstream interface */
1682 if ( type
== TLS_TYPE_DATA
) {
1684 /* Fail unless we are ready to receive data */
1685 if ( ! tls_ready ( tls
) )
1688 /* Deliver each I/O buffer in turn */
1689 while ( ( iobuf
= list_first_entry ( rx_data
, struct io_buffer
,
1691 list_del ( &iobuf
->list
);
1692 if ( ( rc
= xfer_deliver_iob ( &tls
->plainstream
,
1694 DBGC ( tls
, "TLS %p could not deliver data: "
1695 "%s\n", tls
, strerror ( rc
) );
1702 /* For all other records, merge into a single I/O buffer */
1703 iobuf
= iob_concatenate ( rx_data
);
1705 DBGC ( tls
, "TLS %p could not concatenate non-data record "
1706 "type %d\n", tls
, type
);
1707 return -ENOMEM_RX_CONCAT
;
1710 /* Determine handler */
1712 case TLS_TYPE_CHANGE_CIPHER
:
1713 handler
= tls_new_change_cipher
;
1715 case TLS_TYPE_ALERT
:
1716 handler
= tls_new_alert
;
1718 case TLS_TYPE_HANDSHAKE
:
1719 handler
= tls_new_handshake
;
1722 /* RFC4346 says that we should just ignore unknown
1726 DBGC ( tls
, "TLS %p ignoring record type %d\n", tls
, type
);
1730 /* Handle record and free I/O buffer */
1731 rc
= ( handler ?
handler ( tls
, iobuf
->data
, iob_len ( iobuf
) ) : 0 );
1736 /******************************************************************************
1738 * Record encryption/decryption
1740 ******************************************************************************
1746 * @v cipherspec Cipher specification
1748 * @v seq Sequence number
1749 * @v tlshdr TLS header
1751 static void tls_hmac_init ( struct tls_cipherspec
*cipherspec
, void *ctx
,
1752 uint64_t seq
, struct tls_header
*tlshdr
) {
1753 struct digest_algorithm
*digest
= cipherspec
->suite
->digest
;
1755 hmac_init ( digest
, ctx
, cipherspec
->mac_secret
, &digest
->digestsize
);
1756 seq
= cpu_to_be64 ( seq
);
1757 hmac_update ( digest
, ctx
, &seq
, sizeof ( seq
) );
1758 hmac_update ( digest
, ctx
, tlshdr
, sizeof ( *tlshdr
) );
1764 * @v cipherspec Cipher specification
1767 * @v len Length of data
1769 static void tls_hmac_update ( struct tls_cipherspec
*cipherspec
, void *ctx
,
1770 const void *data
, size_t len
) {
1771 struct digest_algorithm
*digest
= cipherspec
->suite
->digest
;
1773 hmac_update ( digest
, ctx
, data
, len
);
1779 * @v cipherspec Cipher specification
1781 * @v mac HMAC to fill in
1783 static void tls_hmac_final ( struct tls_cipherspec
*cipherspec
, void *ctx
,
1785 struct digest_algorithm
*digest
= cipherspec
->suite
->digest
;
1787 hmac_final ( digest
, ctx
, cipherspec
->mac_secret
,
1788 &digest
->digestsize
, hmac
);
1794 * @v cipherspec Cipher specification
1795 * @v seq Sequence number
1796 * @v tlshdr TLS header
1798 * @v len Length of data
1799 * @v mac HMAC to fill in
1801 static void tls_hmac ( struct tls_cipherspec
*cipherspec
,
1802 uint64_t seq
, struct tls_header
*tlshdr
,
1803 const void *data
, size_t len
, void *hmac
) {
1804 struct digest_algorithm
*digest
= cipherspec
->suite
->digest
;
1805 uint8_t ctx
[digest
->ctxsize
];
1807 tls_hmac_init ( cipherspec
, ctx
, seq
, tlshdr
);
1808 tls_hmac_update ( cipherspec
, ctx
, data
, len
);
1809 tls_hmac_final ( cipherspec
, ctx
, hmac
);
1813 * Allocate and assemble stream-ciphered record from data and MAC portions
1815 * @v tls TLS session
1817 * @ret len Length of data
1818 * @ret digest MAC digest
1819 * @ret plaintext_len Length of plaintext record
1820 * @ret plaintext Allocated plaintext record
1822 static void * __malloc
tls_assemble_stream ( struct tls_session
*tls
,
1823 const void *data
, size_t len
,
1824 void *digest
, size_t *plaintext_len
) {
1825 size_t mac_len
= tls
->tx_cipherspec
.suite
->digest
->digestsize
;
1830 /* Calculate stream-ciphered struct length */
1831 *plaintext_len
= ( len
+ mac_len
);
1833 /* Allocate stream-ciphered struct */
1834 plaintext
= malloc ( *plaintext_len
);
1837 content
= plaintext
;
1838 mac
= ( content
+ len
);
1840 /* Fill in stream-ciphered struct */
1841 memcpy ( content
, data
, len
);
1842 memcpy ( mac
, digest
, mac_len
);
1848 * Allocate and assemble block-ciphered record from data and MAC portions
1850 * @v tls TLS session
1852 * @ret len Length of data
1853 * @ret digest MAC digest
1854 * @ret plaintext_len Length of plaintext record
1855 * @ret plaintext Allocated plaintext record
1857 static void * tls_assemble_block ( struct tls_session
*tls
,
1858 const void *data
, size_t len
,
1859 void *digest
, size_t *plaintext_len
) {
1860 size_t blocksize
= tls
->tx_cipherspec
.suite
->cipher
->blocksize
;
1861 size_t mac_len
= tls
->tx_cipherspec
.suite
->digest
->digestsize
;
1870 /* TLSv1.1 and later use an explicit IV */
1871 iv_len
= ( ( tls
->version
>= TLS_VERSION_TLS_1_1
) ? blocksize
: 0 );
1873 /* Calculate block-ciphered struct length */
1874 padding_len
= ( ( blocksize
- 1 ) & -( iv_len
+ len
+ mac_len
+ 1 ) );
1875 *plaintext_len
= ( iv_len
+ len
+ mac_len
+ padding_len
+ 1 );
1877 /* Allocate block-ciphered struct */
1878 plaintext
= malloc ( *plaintext_len
);
1882 content
= ( iv
+ iv_len
);
1883 mac
= ( content
+ len
);
1884 padding
= ( mac
+ mac_len
);
1886 /* Fill in block-ciphered struct */
1887 tls_generate_random ( tls
, iv
, iv_len
);
1888 memcpy ( content
, data
, len
);
1889 memcpy ( mac
, digest
, mac_len
);
1890 memset ( padding
, padding_len
, ( padding_len
+ 1 ) );
1896 * Send plaintext record
1898 * @v tls TLS session
1899 * @v type Record type
1900 * @v data Plaintext record
1901 * @v len Length of plaintext record
1902 * @ret rc Return status code
1904 static int tls_send_plaintext ( struct tls_session
*tls
, unsigned int type
,
1905 const void *data
, size_t len
) {
1906 struct tls_header plaintext_tlshdr
;
1907 struct tls_header
*tlshdr
;
1908 struct tls_cipherspec
*cipherspec
= &tls
->tx_cipherspec
;
1909 struct cipher_algorithm
*cipher
= cipherspec
->suite
->cipher
;
1910 void *plaintext
= NULL
;
1911 size_t plaintext_len
;
1912 struct io_buffer
*ciphertext
= NULL
;
1913 size_t ciphertext_len
;
1914 size_t mac_len
= cipherspec
->suite
->digest
->digestsize
;
1915 uint8_t mac
[mac_len
];
1918 /* Construct header */
1919 plaintext_tlshdr
.type
= type
;
1920 plaintext_tlshdr
.version
= htons ( tls
->version
);
1921 plaintext_tlshdr
.length
= htons ( len
);
1924 tls_hmac ( cipherspec
, tls
->tx_seq
, &plaintext_tlshdr
, data
, len
, mac
);
1926 /* Allocate and assemble plaintext struct */
1927 if ( is_stream_cipher ( cipher
) ) {
1928 plaintext
= tls_assemble_stream ( tls
, data
, len
, mac
,
1931 plaintext
= tls_assemble_block ( tls
, data
, len
, mac
,
1934 if ( ! plaintext
) {
1935 DBGC ( tls
, "TLS %p could not allocate %zd bytes for "
1936 "plaintext\n", tls
, plaintext_len
);
1937 rc
= -ENOMEM_TX_PLAINTEXT
;
1941 DBGC2 ( tls
, "Sending plaintext data:\n" );
1942 DBGC2_HD ( tls
, plaintext
, plaintext_len
);
1944 /* Allocate ciphertext */
1945 ciphertext_len
= ( sizeof ( *tlshdr
) + plaintext_len
);
1946 ciphertext
= xfer_alloc_iob ( &tls
->cipherstream
, ciphertext_len
);
1947 if ( ! ciphertext
) {
1948 DBGC ( tls
, "TLS %p could not allocate %zd bytes for "
1949 "ciphertext\n", tls
, ciphertext_len
);
1950 rc
= -ENOMEM_TX_CIPHERTEXT
;
1954 /* Assemble ciphertext */
1955 tlshdr
= iob_put ( ciphertext
, sizeof ( *tlshdr
) );
1956 tlshdr
->type
= type
;
1957 tlshdr
->version
= htons ( tls
->version
);
1958 tlshdr
->length
= htons ( plaintext_len
);
1959 memcpy ( cipherspec
->cipher_next_ctx
, cipherspec
->cipher_ctx
,
1961 cipher_encrypt ( cipher
, cipherspec
->cipher_next_ctx
, plaintext
,
1962 iob_put ( ciphertext
, plaintext_len
), plaintext_len
);
1964 /* Free plaintext as soon as possible to conserve memory */
1968 /* Send ciphertext */
1969 if ( ( rc
= xfer_deliver_iob ( &tls
->cipherstream
,
1970 iob_disown ( ciphertext
) ) ) != 0 ) {
1971 DBGC ( tls
, "TLS %p could not deliver ciphertext: %s\n",
1972 tls
, strerror ( rc
) );
1976 /* Update TX state machine to next record */
1978 memcpy ( tls
->tx_cipherspec
.cipher_ctx
,
1979 tls
->tx_cipherspec
.cipher_next_ctx
, cipher
->ctxsize
);
1983 free_iob ( ciphertext
);
1988 * Split stream-ciphered record into data and MAC portions
1990 * @v tls TLS session
1991 * @v rx_data List of received data buffers
1992 * @v mac MAC to fill in
1993 * @ret rc Return status code
1995 static int tls_split_stream ( struct tls_session
*tls
,
1996 struct list_head
*rx_data
, void **mac
) {
1997 size_t mac_len
= tls
->rx_cipherspec
.suite
->digest
->digestsize
;
1998 struct io_buffer
*iobuf
;
2001 iobuf
= list_last_entry ( rx_data
, struct io_buffer
, list
);
2002 assert ( iobuf
!= NULL
);
2003 if ( iob_len ( iobuf
) < mac_len
) {
2004 DBGC ( tls
, "TLS %p received underlength MAC\n", tls
);
2005 DBGC_HD ( tls
, iobuf
->data
, iob_len ( iobuf
) );
2006 return -EINVAL_STREAM
;
2008 iob_unput ( iobuf
, mac_len
);
2015 * Split block-ciphered record into data and MAC portions
2017 * @v tls TLS session
2018 * @v rx_data List of received data buffers
2019 * @v mac MAC to fill in
2020 * @ret rc Return status code
2022 static int tls_split_block ( struct tls_session
*tls
,
2023 struct list_head
*rx_data
, void **mac
) {
2024 size_t mac_len
= tls
->rx_cipherspec
.suite
->digest
->digestsize
;
2025 struct io_buffer
*iobuf
;
2027 uint8_t *padding_final
;
2031 /* TLSv1.1 and later use an explicit IV */
2032 iobuf
= list_first_entry ( rx_data
, struct io_buffer
, list
);
2033 iv_len
= ( ( tls
->version
>= TLS_VERSION_TLS_1_1
) ?
2034 tls
->rx_cipherspec
.suite
->cipher
->blocksize
: 0 );
2035 if ( iob_len ( iobuf
) < iv_len
) {
2036 DBGC ( tls
, "TLS %p received underlength IV\n", tls
);
2037 DBGC_HD ( tls
, iobuf
->data
, iob_len ( iobuf
) );
2038 return -EINVAL_BLOCK
;
2040 iob_pull ( iobuf
, iv_len
);
2042 /* Extract and verify padding */
2043 iobuf
= list_last_entry ( rx_data
, struct io_buffer
, list
);
2044 padding_final
= ( iobuf
->tail
- 1 );
2045 padding_len
= *padding_final
;
2046 if ( ( padding_len
+ 1 ) > iob_len ( iobuf
) ) {
2047 DBGC ( tls
, "TLS %p received underlength padding\n", tls
);
2048 DBGC_HD ( tls
, iobuf
->data
, iob_len ( iobuf
) );
2049 return -EINVAL_BLOCK
;
2051 iob_unput ( iobuf
, ( padding_len
+ 1 ) );
2052 for ( padding
= iobuf
->tail
; padding
< padding_final
; padding
++ ) {
2053 if ( *padding
!= padding_len
) {
2054 DBGC ( tls
, "TLS %p received bad padding\n", tls
);
2055 DBGC_HD ( tls
, padding
, padding_len
);
2056 return -EINVAL_PADDING
;
2061 if ( iob_len ( iobuf
) < mac_len
) {
2062 DBGC ( tls
, "TLS %p received underlength MAC\n", tls
);
2063 DBGC_HD ( tls
, iobuf
->data
, iob_len ( iobuf
) );
2064 return -EINVAL_BLOCK
;
2066 iob_unput ( iobuf
, mac_len
);
2073 * Receive new ciphertext record
2075 * @v tls TLS session
2076 * @v tlshdr Record header
2077 * @v rx_data List of received data buffers
2078 * @ret rc Return status code
2080 static int tls_new_ciphertext ( struct tls_session
*tls
,
2081 struct tls_header
*tlshdr
,
2082 struct list_head
*rx_data
) {
2083 struct tls_header plaintext_tlshdr
;
2084 struct tls_cipherspec
*cipherspec
= &tls
->rx_cipherspec
;
2085 struct cipher_algorithm
*cipher
= cipherspec
->suite
->cipher
;
2086 struct digest_algorithm
*digest
= cipherspec
->suite
->digest
;
2087 uint8_t ctx
[digest
->ctxsize
];
2088 uint8_t verify_mac
[digest
->digestsize
];
2089 struct io_buffer
*iobuf
;
2094 /* Decrypt the received data */
2095 list_for_each_entry ( iobuf
, &tls
->rx_data
, list
) {
2096 cipher_decrypt ( cipher
, cipherspec
->cipher_ctx
,
2097 iobuf
->data
, iobuf
->data
, iob_len ( iobuf
) );
2100 /* Split record into content and MAC */
2101 if ( is_stream_cipher ( cipher
) ) {
2102 if ( ( rc
= tls_split_stream ( tls
, rx_data
, &mac
) ) != 0 )
2105 if ( ( rc
= tls_split_block ( tls
, rx_data
, &mac
) ) != 0 )
2109 /* Calculate total length */
2110 DBGC2 ( tls
, "Received plaintext data:\n" );
2111 list_for_each_entry ( iobuf
, rx_data
, list
) {
2112 DBGC2_HD ( tls
, iobuf
->data
, iob_len ( iobuf
) );
2113 len
+= iob_len ( iobuf
);
2117 plaintext_tlshdr
.type
= tlshdr
->type
;
2118 plaintext_tlshdr
.version
= tlshdr
->version
;
2119 plaintext_tlshdr
.length
= htons ( len
);
2120 tls_hmac_init ( cipherspec
, ctx
, tls
->rx_seq
, &plaintext_tlshdr
);
2121 list_for_each_entry ( iobuf
, rx_data
, list
) {
2122 tls_hmac_update ( cipherspec
, ctx
, iobuf
->data
,
2123 iob_len ( iobuf
) );
2125 tls_hmac_final ( cipherspec
, ctx
, verify_mac
);
2126 if ( memcmp ( mac
, verify_mac
, sizeof ( verify_mac
) ) != 0 ) {
2127 DBGC ( tls
, "TLS %p failed MAC verification\n", tls
);
2131 /* Process plaintext record */
2132 if ( ( rc
= tls_new_record ( tls
, tlshdr
->type
, rx_data
) ) != 0 )
2138 /******************************************************************************
2140 * Plaintext stream operations
2142 ******************************************************************************
2146 * Check flow control window
2148 * @v tls TLS session
2149 * @ret len Length of window
2151 static size_t tls_plainstream_window ( struct tls_session
*tls
) {
2153 /* Block window unless we are ready to accept data */
2154 if ( ! tls_ready ( tls
) )
2157 return xfer_window ( &tls
->cipherstream
);
2161 * Deliver datagram as raw data
2163 * @v tls TLS session
2164 * @v iobuf I/O buffer
2165 * @v meta Data transfer metadata
2166 * @ret rc Return status code
2168 static int tls_plainstream_deliver ( struct tls_session
*tls
,
2169 struct io_buffer
*iobuf
,
2170 struct xfer_metadata
*meta __unused
) {
2173 /* Refuse unless we are ready to accept data */
2174 if ( ! tls_ready ( tls
) ) {
2179 if ( ( rc
= tls_send_plaintext ( tls
, TLS_TYPE_DATA
, iobuf
->data
,
2180 iob_len ( iobuf
) ) ) != 0 )
2188 /** TLS plaintext stream interface operations */
2189 static struct interface_operation tls_plainstream_ops
[] = {
2190 INTF_OP ( xfer_deliver
, struct tls_session
*, tls_plainstream_deliver
),
2191 INTF_OP ( xfer_window
, struct tls_session
*, tls_plainstream_window
),
2192 INTF_OP ( intf_close
, struct tls_session
*, tls_close
),
2195 /** TLS plaintext stream interface descriptor */
2196 static struct interface_descriptor tls_plainstream_desc
=
2197 INTF_DESC_PASSTHRU ( struct tls_session
, plainstream
,
2198 tls_plainstream_ops
, cipherstream
);
2200 /******************************************************************************
2202 * Ciphertext stream operations
2204 ******************************************************************************
2208 * Handle received TLS header
2210 * @v tls TLS session
2211 * @ret rc Returned status code
2213 static int tls_newdata_process_header ( struct tls_session
*tls
) {
2214 size_t data_len
= ntohs ( tls
->rx_header
.length
);
2215 size_t remaining
= data_len
;
2217 struct io_buffer
*iobuf
;
2218 struct io_buffer
*tmp
;
2221 /* Allocate data buffers now that we know the length */
2222 assert ( list_empty ( &tls
->rx_data
) );
2223 while ( remaining
) {
2225 /* Calculate fragment length. Ensure that no block is
2226 * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
2227 * allocation length if necessary).
2229 frag_len
= remaining
;
2230 if ( frag_len
> TLS_RX_BUFSIZE
)
2231 frag_len
= TLS_RX_BUFSIZE
;
2232 remaining
-= frag_len
;
2233 if ( remaining
< TLS_RX_MIN_BUFSIZE
) {
2234 frag_len
+= remaining
;
2238 /* Allocate buffer */
2239 iobuf
= alloc_iob_raw ( frag_len
, TLS_RX_ALIGN
, 0 );
2241 DBGC ( tls
, "TLS %p could not allocate %zd of %zd "
2242 "bytes for receive buffer\n", tls
,
2243 remaining
, data_len
);
2244 rc
= -ENOMEM_RX_DATA
;
2248 /* Ensure tailroom is exactly what we asked for. This
2249 * will result in unaligned I/O buffers when the
2250 * fragment length is unaligned, which can happen only
2251 * before we switch to using a block cipher.
2253 iob_reserve ( iobuf
, ( iob_tailroom ( iobuf
) - frag_len
) );
2255 /* Add I/O buffer to list */
2256 list_add_tail ( &iobuf
->list
, &tls
->rx_data
);
2259 /* Move to data state */
2260 tls
->rx_state
= TLS_RX_DATA
;
2265 list_for_each_entry_safe ( iobuf
, tmp
, &tls
->rx_data
, list
) {
2266 list_del ( &iobuf
->list
);
2273 * Handle received TLS data payload
2275 * @v tls TLS session
2276 * @ret rc Returned status code
2278 static int tls_newdata_process_data ( struct tls_session
*tls
) {
2279 struct io_buffer
*iobuf
;
2282 /* Move current buffer to end of list */
2283 iobuf
= list_first_entry ( &tls
->rx_data
, struct io_buffer
, list
);
2284 list_del ( &iobuf
->list
);
2285 list_add_tail ( &iobuf
->list
, &tls
->rx_data
);
2287 /* Continue receiving data if any space remains */
2288 iobuf
= list_first_entry ( &tls
->rx_data
, struct io_buffer
, list
);
2289 if ( iob_tailroom ( iobuf
) )
2292 /* Process record */
2293 if ( ( rc
= tls_new_ciphertext ( tls
, &tls
->rx_header
,
2294 &tls
->rx_data
) ) != 0 )
2297 /* Increment RX sequence number */
2300 /* Return to header state */
2301 assert ( list_empty ( &tls
->rx_data
) );
2302 tls
->rx_state
= TLS_RX_HEADER
;
2303 iob_unput ( &tls
->rx_header_iobuf
, sizeof ( tls
->rx_header
) );
2309 * Receive new ciphertext
2311 * @v tls TLS session
2312 * @v iobuf I/O buffer
2313 * @v meta Data transfer metadat
2314 * @ret rc Return status code
2316 static int tls_cipherstream_deliver ( struct tls_session
*tls
,
2317 struct io_buffer
*iobuf
,
2318 struct xfer_metadata
*xfer __unused
) {
2320 int ( * process
) ( struct tls_session
*tls
);
2321 struct io_buffer
*dest
;
2324 while ( iob_len ( iobuf
) ) {
2326 /* Select buffer according to current state */
2327 switch ( tls
->rx_state
) {
2329 dest
= &tls
->rx_header_iobuf
;
2330 process
= tls_newdata_process_header
;
2333 dest
= list_first_entry ( &tls
->rx_data
,
2334 struct io_buffer
, list
);
2335 assert ( dest
!= NULL
);
2336 process
= tls_newdata_process_data
;
2340 rc
= -EINVAL_RX_STATE
;
2344 /* Copy data portion to buffer */
2345 frag_len
= iob_len ( iobuf
);
2346 if ( frag_len
> iob_tailroom ( dest
) )
2347 frag_len
= iob_tailroom ( dest
);
2348 memcpy ( iob_put ( dest
, frag_len
), iobuf
->data
, frag_len
);
2349 iob_pull ( iobuf
, frag_len
);
2351 /* Process data if buffer is now full */
2352 if ( iob_tailroom ( dest
) == 0 ) {
2353 if ( ( rc
= process ( tls
) ) != 0 ) {
2354 tls_close ( tls
, rc
);
2366 /** TLS ciphertext stream interface operations */
2367 static struct interface_operation tls_cipherstream_ops
[] = {
2368 INTF_OP ( xfer_deliver
, struct tls_session
*,
2369 tls_cipherstream_deliver
),
2370 INTF_OP ( xfer_window_changed
, struct tls_session
*, tls_tx_resume
),
2371 INTF_OP ( intf_close
, struct tls_session
*, tls_close
),
2374 /** TLS ciphertext stream interface descriptor */
2375 static struct interface_descriptor tls_cipherstream_desc
=
2376 INTF_DESC_PASSTHRU ( struct tls_session
, cipherstream
,
2377 tls_cipherstream_ops
, plainstream
);
2379 /******************************************************************************
2381 * Certificate validator
2383 ******************************************************************************
2387 * Handle certificate validation completion
2389 * @v tls TLS session
2390 * @v rc Reason for completion
2392 static void tls_validator_done ( struct tls_session
*tls
, int rc
) {
2393 struct tls_cipherspec
*cipherspec
= &tls
->tx_cipherspec_pending
;
2394 struct pubkey_algorithm
*pubkey
= cipherspec
->suite
->pubkey
;
2395 struct x509_certificate
*cert
;
2397 /* Close validator interface */
2398 intf_restart ( &tls
->validator
, rc
);
2400 /* Check for validation failure */
2402 DBGC ( tls
, "TLS %p certificate validation failed: %s\n",
2403 tls
, strerror ( rc
) );
2406 DBGC ( tls
, "TLS %p certificate validation succeeded\n", tls
);
2408 /* Extract first certificate */
2409 cert
= x509_first ( tls
->chain
);
2410 assert ( cert
!= NULL
);
2412 /* Verify server name */
2413 if ( ( rc
= x509_check_name ( cert
, tls
->name
) ) != 0 ) {
2414 DBGC ( tls
, "TLS %p server certificate does not match %s: %s\n",
2415 tls
, tls
->name
, strerror ( rc
) );
2419 /* Initialise public key algorithm */
2420 if ( ( rc
= pubkey_init ( pubkey
, cipherspec
->pubkey_ctx
,
2421 cert
->subject
.public_key
.raw
.data
,
2422 cert
->subject
.public_key
.raw
.len
) ) != 0 ) {
2423 DBGC ( tls
, "TLS %p cannot initialise public key: %s\n",
2424 tls
, strerror ( rc
) );
2428 /* Schedule Client Key Exchange, Change Cipher, and Finished */
2429 tls
->tx_pending
|= ( TLS_TX_CLIENT_KEY_EXCHANGE
|
2430 TLS_TX_CHANGE_CIPHER
|
2433 tls
->tx_pending
|= ( TLS_TX_CERTIFICATE
|
2434 TLS_TX_CERTIFICATE_VERIFY
);
2436 tls_tx_resume ( tls
);
2441 tls_close ( tls
, rc
);
2445 /** TLS certificate validator interface operations */
2446 static struct interface_operation tls_validator_ops
[] = {
2447 INTF_OP ( intf_close
, struct tls_session
*, tls_validator_done
),
2450 /** TLS certificate validator interface descriptor */
2451 static struct interface_descriptor tls_validator_desc
=
2452 INTF_DESC ( struct tls_session
, validator
, tls_validator_ops
);
2454 /******************************************************************************
2456 * Controlling process
2458 ******************************************************************************
2462 * TLS TX state machine
2464 * @v tls TLS session
2466 static void tls_tx_step ( struct tls_session
*tls
) {
2469 /* Wait for cipherstream to become ready */
2470 if ( ! xfer_window ( &tls
->cipherstream
) )
2473 /* Send first pending transmission */
2474 if ( tls
->tx_pending
& TLS_TX_CLIENT_HELLO
) {
2475 /* Send Client Hello */
2476 if ( ( rc
= tls_send_client_hello ( tls
) ) != 0 ) {
2477 DBGC ( tls
, "TLS %p could not send Client Hello: %s\n",
2478 tls
, strerror ( rc
) );
2481 tls
->tx_pending
&= ~TLS_TX_CLIENT_HELLO
;
2482 } else if ( tls
->tx_pending
& TLS_TX_CERTIFICATE
) {
2483 /* Send Certificate */
2484 if ( ( rc
= tls_send_certificate ( tls
) ) != 0 ) {
2485 DBGC ( tls
, "TLS %p cold not send Certificate: %s\n",
2486 tls
, strerror ( rc
) );
2489 tls
->tx_pending
&= ~TLS_TX_CERTIFICATE
;
2490 } else if ( tls
->tx_pending
& TLS_TX_CLIENT_KEY_EXCHANGE
) {
2491 /* Send Client Key Exchange */
2492 if ( ( rc
= tls_send_client_key_exchange ( tls
) ) != 0 ) {
2493 DBGC ( tls
, "TLS %p could not send Client Key "
2494 "Exchange: %s\n", tls
, strerror ( rc
) );
2497 tls
->tx_pending
&= ~TLS_TX_CLIENT_KEY_EXCHANGE
;
2498 } else if ( tls
->tx_pending
& TLS_TX_CERTIFICATE_VERIFY
) {
2499 /* Send Certificate Verify */
2500 if ( ( rc
= tls_send_certificate_verify ( tls
) ) != 0 ) {
2501 DBGC ( tls
, "TLS %p could not send Certificate "
2502 "Verify: %s\n", tls
, strerror ( rc
) );
2505 tls
->tx_pending
&= ~TLS_TX_CERTIFICATE_VERIFY
;
2506 } else if ( tls
->tx_pending
& TLS_TX_CHANGE_CIPHER
) {
2507 /* Send Change Cipher, and then change the cipher in use */
2508 if ( ( rc
= tls_send_change_cipher ( tls
) ) != 0 ) {
2509 DBGC ( tls
, "TLS %p could not send Change Cipher: "
2510 "%s\n", tls
, strerror ( rc
) );
2513 if ( ( rc
= tls_change_cipher ( tls
,
2514 &tls
->tx_cipherspec_pending
,
2515 &tls
->tx_cipherspec
)) != 0 ){
2516 DBGC ( tls
, "TLS %p could not activate TX cipher: "
2517 "%s\n", tls
, strerror ( rc
) );
2521 tls
->tx_pending
&= ~TLS_TX_CHANGE_CIPHER
;
2522 } else if ( tls
->tx_pending
& TLS_TX_FINISHED
) {
2524 if ( ( rc
= tls_send_finished ( tls
) ) != 0 ) {
2525 DBGC ( tls
, "TLS %p could not send Finished: %s\n",
2526 tls
, strerror ( rc
) );
2529 tls
->tx_pending
&= ~TLS_TX_FINISHED
;
2532 /* Reschedule process if pending transmissions remain */
2533 if ( tls
->tx_pending
)
2534 tls_tx_resume ( tls
);
2539 tls_close ( tls
, rc
);
2542 /** TLS TX process descriptor */
2543 static struct process_descriptor tls_process_desc
=
2544 PROC_DESC_ONCE ( struct tls_session
, process
, tls_tx_step
);
2546 /******************************************************************************
2550 ******************************************************************************
2553 int add_tls ( struct interface
*xfer
, const char *name
,
2554 struct interface
**next
) {
2555 struct tls_session
*tls
;
2558 /* Allocate and initialise TLS structure */
2559 tls
= malloc ( sizeof ( *tls
) );
2564 memset ( tls
, 0, sizeof ( *tls
) );
2565 ref_init ( &tls
->refcnt
, free_tls
);
2567 intf_init ( &tls
->plainstream
, &tls_plainstream_desc
, &tls
->refcnt
);
2568 intf_init ( &tls
->cipherstream
, &tls_cipherstream_desc
, &tls
->refcnt
);
2569 intf_init ( &tls
->validator
, &tls_validator_desc
, &tls
->refcnt
);
2570 process_init ( &tls
->process
, &tls_process_desc
, &tls
->refcnt
);
2571 tls
->version
= TLS_VERSION_TLS_1_2
;
2572 tls_clear_cipher ( tls
, &tls
->tx_cipherspec
);
2573 tls_clear_cipher ( tls
, &tls
->tx_cipherspec_pending
);
2574 tls_clear_cipher ( tls
, &tls
->rx_cipherspec
);
2575 tls_clear_cipher ( tls
, &tls
->rx_cipherspec_pending
);
2576 tls
->client_random
.gmt_unix_time
= time ( NULL
);
2577 if ( ( rc
= tls_generate_random ( tls
, &tls
->client_random
.random
,
2578 ( sizeof ( tls
->client_random
.random
) ) ) ) != 0 ) {
2581 tls
->pre_master_secret
.version
= htons ( tls
->version
);
2582 if ( ( rc
= tls_generate_random ( tls
, &tls
->pre_master_secret
.random
,
2583 ( sizeof ( tls
->pre_master_secret
.random
) ) ) ) != 0 ) {
2586 digest_init ( &md5_sha1_algorithm
, tls
->handshake_md5_sha1_ctx
);
2587 digest_init ( &sha256_algorithm
, tls
->handshake_sha256_ctx
);
2588 tls
->handshake_digest
= &sha256_algorithm
;
2589 tls
->handshake_ctx
= tls
->handshake_sha256_ctx
;
2590 tls
->tx_pending
= TLS_TX_CLIENT_HELLO
;
2591 iob_populate ( &tls
->rx_header_iobuf
, &tls
->rx_header
, 0,
2592 sizeof ( tls
->rx_header
) );
2593 INIT_LIST_HEAD ( &tls
->rx_data
);
2595 /* Add pending operations for server and client Finished messages */
2596 pending_get ( &tls
->client_negotiation
);
2597 pending_get ( &tls
->server_negotiation
);
2599 /* Attach to parent interface, mortalise self, and return */
2600 intf_plug_plug ( &tls
->plainstream
, xfer
);
2601 *next
= &tls
->cipherstream
;
2602 ref_put ( &tls
->refcnt
);
2606 ref_put ( &tls
->refcnt
);
2611 /* Drag in objects via add_tls() */
2612 REQUIRING_SYMBOL ( add_tls
);
2614 /* Drag in crypto configuration */
2615 REQUIRE_OBJECT ( config_crypto
);