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;
1276
if ( sizeof ( *alert ) != len ) {
1277
DBGC ( tls, "TLS %p received overlength Alert\n", tls );
1278
DBGC_HD ( tls, data, len );
1279
return -EINVAL_ALERT;
1282
switch ( alert->level ) {
1283
case TLS_ALERT_WARNING:
1284
DBGC ( tls, "TLS %p received warning alert %d\n",
1285
tls, alert->description );
1287
case TLS_ALERT_FATAL:
1288
DBGC ( tls, "TLS %p received fatal alert %d\n",
1289
tls, alert->description );
1290
return -EPERM_ALERT;
1292
DBGC ( tls, "TLS %p received unknown alert level %d"
1293
"(alert %d)\n", tls, alert->level, alert->description );
1299
* Receive new Server Hello handshake record
1301
* @v tls TLS session
1302
* @v data Plaintext handshake record
1303
* @v len Length of plaintext handshake record
1304
* @ret rc Return status code
1306
static int tls_new_server_hello ( struct tls_session *tls,
1307
const void *data, size_t len ) {
1311
uint8_t session_id_len;
1312
uint8_t session_id[0];
1313
} __attribute__ (( packed )) *hello_a = data;
1314
const uint8_t *session_id;
1316
uint16_t cipher_suite;
1317
uint8_t compression_method;
1319
} __attribute__ (( packed )) *hello_b;
1324
if ( ( sizeof ( *hello_a ) > len ) ||
1325
( hello_a->session_id_len > ( len - sizeof ( *hello_a ) ) ) ||
1326
( sizeof ( *hello_b ) > ( len - sizeof ( *hello_a ) -
1327
hello_a->session_id_len ) ) ) {
1328
DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
1329
DBGC_HD ( tls, data, len );
1330
return -EINVAL_HELLO;
1332
session_id = hello_a->session_id;
1333
hello_b = ( ( void * ) ( session_id + hello_a->session_id_len ) );
1335
/* Check and store protocol version */
1336
version = ntohs ( hello_a->version );
1337
if ( version < TLS_VERSION_TLS_1_0 ) {
1338
DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
1339
tls, ( version >> 8 ), ( version & 0xff ) );
1340
return -ENOTSUP_VERSION;
1342
if ( version > tls->version ) {
1343
DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
1344
"protocol version %d.%d\n",
1345
tls, ( version >> 8 ), ( version & 0xff ) );
1346
return -EPROTO_VERSION;
1348
tls->version = version;
1349
DBGC ( tls, "TLS %p using protocol version %d.%d\n",
1350
tls, ( version >> 8 ), ( version & 0xff ) );
1352
/* Use MD5+SHA1 digest algorithm for handshake verification
1353
* for versions earlier than TLSv1.2.
1355
if ( tls->version < TLS_VERSION_TLS_1_2 ) {
1356
tls->handshake_digest = &md5_sha1_algorithm;
1357
tls->handshake_ctx = tls->handshake_md5_sha1_ctx;
1360
/* Copy out server random bytes */
1361
memcpy ( &tls->server_random, &hello_a->random,
1362
sizeof ( tls->server_random ) );
1364
/* Select cipher suite */
1365
if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
1368
/* Generate secrets */
1369
tls_generate_master_secret ( tls );
1370
if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
1377
* Parse certificate chain
1379
* @v tls TLS session
1380
* @v data Certificate chain
1381
* @v len Length of certificate chain
1382
* @ret rc Return status code
1384
static int tls_parse_chain ( struct tls_session *tls,
1385
const void *data, size_t len ) {
1386
size_t remaining = len;
1389
/* Free any existing certificate chain */
1390
x509_chain_put ( tls->chain );
1393
/* Create certificate chain */
1394
tls->chain = x509_alloc_chain();
1395
if ( ! tls->chain ) {
1397
goto err_alloc_chain;
1400
/* Add certificates to chain */
1401
while ( remaining ) {
1405
} __attribute__ (( packed )) *certificate = data;
1406
size_t certificate_len;
1408
struct x509_certificate *cert;
1411
if ( sizeof ( *certificate ) > remaining ) {
1412
DBGC ( tls, "TLS %p underlength certificate:\n", tls );
1413
DBGC_HDA ( tls, 0, data, remaining );
1414
rc = -EINVAL_CERTIFICATE;
1415
goto err_underlength;
1417
certificate_len = tls_uint24 ( &certificate->length );
1418
if ( certificate_len > ( remaining - sizeof ( *certificate ) )){
1419
DBGC ( tls, "TLS %p overlength certificate:\n", tls );
1420
DBGC_HDA ( tls, 0, data, remaining );
1421
rc = -EINVAL_CERTIFICATE;
1422
goto err_overlength;
1424
record_len = ( sizeof ( *certificate ) + certificate_len );
1426
/* Add certificate to chain */
1427
if ( ( rc = x509_append_raw ( tls->chain, certificate->data,
1428
certificate_len ) ) != 0 ) {
1429
DBGC ( tls, "TLS %p could not append certificate: %s\n",
1430
tls, strerror ( rc ) );
1431
DBGC_HDA ( tls, 0, data, remaining );
1434
cert = x509_last ( tls->chain );
1435
DBGC ( tls, "TLS %p found certificate %s\n",
1436
tls, x509_name ( cert ) );
1438
/* Move to next certificate in list */
1440
remaining -= record_len;
1448
x509_chain_put ( tls->chain );
1455
* Receive new Certificate handshake record
1457
* @v tls TLS session
1458
* @v data Plaintext handshake record
1459
* @v len Length of plaintext handshake record
1460
* @ret rc Return status code
1462
static int tls_new_certificate ( struct tls_session *tls,
1463
const void *data, size_t len ) {
1466
uint8_t certificates[0];
1467
} __attribute__ (( packed )) *certificate = data;
1468
size_t certificates_len;
1472
if ( sizeof ( *certificate ) > len ) {
1473
DBGC ( tls, "TLS %p received underlength Server Certificate\n",
1475
DBGC_HD ( tls, data, len );
1476
return -EINVAL_CERTIFICATES;
1478
certificates_len = tls_uint24 ( &certificate->length );
1479
if ( certificates_len > ( len - sizeof ( *certificate ) ) ) {
1480
DBGC ( tls, "TLS %p received overlength Server Certificate\n",
1482
DBGC_HD ( tls, data, len );
1483
return -EINVAL_CERTIFICATES;
1486
/* Parse certificate chain */
1487
if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
1488
certificates_len ) ) != 0 )
1495
* Receive new Certificate Request handshake record
1497
* @v tls TLS session
1498
* @v data Plaintext handshake record
1499
* @v len Length of plaintext handshake record
1500
* @ret rc Return status code
1502
static int tls_new_certificate_request ( struct tls_session *tls,
1503
const void *data __unused,
1504
size_t len __unused ) {
1506
/* We can only send a single certificate, so there is no point
1507
* in parsing the Certificate Request.
1510
/* Free any existing client certificate */
1511
x509_put ( tls->cert );
1513
/* Determine client certificate to be sent */
1514
tls->cert = certstore_find_key ( &private_key );
1515
if ( ! tls->cert ) {
1516
DBGC ( tls, "TLS %p could not find certificate corresponding "
1517
"to private key\n", tls );
1518
return -EPERM_CLIENT_CERT;
1520
x509_get ( tls->cert );
1521
DBGC ( tls, "TLS %p sending client certificate %s\n",
1522
tls, x509_name ( tls->cert ) );
1528
* Receive new Server Hello Done handshake record
1530
* @v tls TLS session
1531
* @v data Plaintext handshake record
1532
* @v len Length of plaintext handshake record
1533
* @ret rc Return status code
1535
static int tls_new_server_hello_done ( struct tls_session *tls,
1536
const void *data, size_t len ) {
1539
} __attribute__ (( packed )) *hello_done = data;
1543
if ( sizeof ( *hello_done ) != len ) {
1544
DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
1546
DBGC_HD ( tls, data, len );
1547
return -EINVAL_HELLO_DONE;
1550
/* Begin certificate validation */
1551
if ( ( rc = create_validator ( &tls->validator, tls->chain ) ) != 0 ) {
1552
DBGC ( tls, "TLS %p could not start certificate validation: "
1553
"%s\n", tls, strerror ( rc ) );
1561
* Receive new Finished handshake record
1563
* @v tls TLS session
1564
* @v data Plaintext handshake record
1565
* @v len Length of plaintext handshake record
1566
* @ret rc Return status code
1568
static int tls_new_finished ( struct tls_session *tls,
1569
const void *data, size_t len ) {
1570
struct digest_algorithm *digest = tls->handshake_digest;
1572
uint8_t verify_data[12];
1574
} __attribute__ (( packed )) *finished = data;
1575
uint8_t digest_out[ digest->digestsize ];
1576
uint8_t verify_data[ sizeof ( finished->verify_data ) ];
1579
if ( sizeof ( *finished ) != len ) {
1580
DBGC ( tls, "TLS %p received overlength Finished\n", tls );
1581
DBGC_HD ( tls, data, len );
1582
return -EINVAL_FINISHED;
1586
tls_verify_handshake ( tls, digest_out );
1587
tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1588
verify_data, sizeof ( verify_data ), "server finished",
1589
digest_out, sizeof ( digest_out ) );
1590
if ( memcmp ( verify_data, finished->verify_data,
1591
sizeof ( verify_data ) ) != 0 ) {
1592
DBGC ( tls, "TLS %p verification failed\n", tls );
1593
return -EPERM_VERIFY;
1596
/* Mark server as finished */
1597
pending_put ( &tls->server_negotiation );
1599
/* Send notification of a window change */
1600
xfer_window_changed ( &tls->plainstream );
1606
* Receive new Handshake record
1608
* @v tls TLS session
1609
* @v data Plaintext record
1610
* @v len Length of plaintext record
1611
* @ret rc Return status code
1613
static int tls_new_handshake ( struct tls_session *tls,
1614
const void *data, size_t len ) {
1615
size_t remaining = len;
1618
while ( remaining ) {
1623
} __attribute__ (( packed )) *handshake = data;
1624
const void *payload;
1629
if ( sizeof ( *handshake ) > remaining ) {
1630
DBGC ( tls, "TLS %p received underlength Handshake\n",
1632
DBGC_HD ( tls, data, remaining );
1633
return -EINVAL_HANDSHAKE;
1635
payload_len = tls_uint24 ( &handshake->length );
1636
if ( payload_len > ( remaining - sizeof ( *handshake ) ) ) {
1637
DBGC ( tls, "TLS %p received overlength Handshake\n",
1639
DBGC_HD ( tls, data, len );
1640
return -EINVAL_HANDSHAKE;
1642
payload = &handshake->payload;
1643
record_len = ( sizeof ( *handshake ) + payload_len );
1645
/* Handle payload */
1646
switch ( handshake->type ) {
1647
case TLS_SERVER_HELLO:
1648
rc = tls_new_server_hello ( tls, payload, payload_len );
1650
case TLS_CERTIFICATE:
1651
rc = tls_new_certificate ( tls, payload, payload_len );
1653
case TLS_CERTIFICATE_REQUEST:
1654
rc = tls_new_certificate_request ( tls, payload,
1657
case TLS_SERVER_HELLO_DONE:
1658
rc = tls_new_server_hello_done ( tls, payload,
1662
rc = tls_new_finished ( tls, payload, payload_len );
1665
DBGC ( tls, "TLS %p ignoring handshake type %d\n",
1666
tls, handshake->type );
1671
/* Add to handshake digest (except for Hello Requests,
1672
* which are explicitly excluded).
1674
if ( handshake->type != TLS_HELLO_REQUEST )
1675
tls_add_handshake ( tls, data, record_len );
1677
/* Abort on failure */
1681
/* Move to next handshake record */
1683
remaining -= record_len;
1690
* Receive new record
1692
* @v tls TLS session
1693
* @v type Record type
1694
* @v rx_data List of received data buffers
1695
* @ret rc Return status code
1697
static int tls_new_record ( struct tls_session *tls, unsigned int type,
1698
struct list_head *rx_data ) {
1699
struct io_buffer *iobuf;
1700
int ( * handler ) ( struct tls_session *tls, const void *data,
1704
/* Deliver data records to the plainstream interface */
1705
if ( type == TLS_TYPE_DATA ) {
1707
/* Fail unless we are ready to receive data */
1708
if ( ! tls_ready ( tls ) )
1711
/* Deliver each I/O buffer in turn */
1712
while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
1714
list_del ( &iobuf->list );
1715
if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
1717
DBGC ( tls, "TLS %p could not deliver data: "
1718
"%s\n", tls, strerror ( rc ) );
1725
/* For all other records, merge into a single I/O buffer */
1726
iobuf = iob_concatenate ( rx_data );
1728
DBGC ( tls, "TLS %p could not concatenate non-data record "
1729
"type %d\n", tls, type );
1730
return -ENOMEM_RX_CONCAT;
1733
/* Determine handler */
1735
case TLS_TYPE_CHANGE_CIPHER:
1736
handler = tls_new_change_cipher;
1738
case TLS_TYPE_ALERT:
1739
handler = tls_new_alert;
1741
case TLS_TYPE_HANDSHAKE:
1742
handler = tls_new_handshake;
1745
/* RFC4346 says that we should just ignore unknown
1749
DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
1753
/* Handle record and free I/O buffer */
1754
rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
1759
/******************************************************************************
1761
* Record encryption/decryption
1763
******************************************************************************
1769
* @v cipherspec Cipher specification
1771
* @v seq Sequence number
1772
* @v tlshdr TLS header
1774
static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
1775
uint64_t seq, struct tls_header *tlshdr ) {
1776
struct digest_algorithm *digest = cipherspec->suite->digest;
1778
hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
1779
seq = cpu_to_be64 ( seq );
1780
hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
1781
hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
1787
* @v cipherspec Cipher specification
1790
* @v len Length of data
1792
static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
1793
const void *data, size_t len ) {
1794
struct digest_algorithm *digest = cipherspec->suite->digest;
1796
hmac_update ( digest, ctx, data, len );
1802
* @v cipherspec Cipher specification
1804
* @v mac HMAC to fill in
1806
static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
1808
struct digest_algorithm *digest = cipherspec->suite->digest;
1810
hmac_final ( digest, ctx, cipherspec->mac_secret,
1811
&digest->digestsize, hmac );
1817
* @v cipherspec Cipher specification
1818
* @v seq Sequence number
1819
* @v tlshdr TLS header
1821
* @v len Length of data
1822
* @v mac HMAC to fill in
1824
static void tls_hmac ( struct tls_cipherspec *cipherspec,
1825
uint64_t seq, struct tls_header *tlshdr,
1826
const void *data, size_t len, void *hmac ) {
1827
struct digest_algorithm *digest = cipherspec->suite->digest;
1828
uint8_t ctx[digest->ctxsize];
1830
tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
1831
tls_hmac_update ( cipherspec, ctx, data, len );
1832
tls_hmac_final ( cipherspec, ctx, hmac );
1836
* Allocate and assemble stream-ciphered record from data and MAC portions
1838
* @v tls TLS session
1840
* @ret len Length of data
1841
* @ret digest MAC digest
1842
* @ret plaintext_len Length of plaintext record
1843
* @ret plaintext Allocated plaintext record
1845
static void * __malloc tls_assemble_stream ( struct tls_session *tls,
1846
const void *data, size_t len,
1847
void *digest, size_t *plaintext_len ) {
1848
size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
1853
/* Calculate stream-ciphered struct length */
1854
*plaintext_len = ( len + mac_len );
1856
/* Allocate stream-ciphered struct */
1857
plaintext = malloc ( *plaintext_len );
1860
content = plaintext;
1861
mac = ( content + len );
1863
/* Fill in stream-ciphered struct */
1864
memcpy ( content, data, len );
1865
memcpy ( mac, digest, mac_len );
1871
* Allocate and assemble block-ciphered record from data and MAC portions
1873
* @v tls TLS session
1875
* @ret len Length of data
1876
* @ret digest MAC digest
1877
* @ret plaintext_len Length of plaintext record
1878
* @ret plaintext Allocated plaintext record
1880
static void * tls_assemble_block ( struct tls_session *tls,
1881
const void *data, size_t len,
1882
void *digest, size_t *plaintext_len ) {
1883
size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
1884
size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
1893
/* TLSv1.1 and later use an explicit IV */
1894
iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
1896
/* Calculate block-ciphered struct length */
1897
padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
1898
*plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
1900
/* Allocate block-ciphered struct */
1901
plaintext = malloc ( *plaintext_len );
1905
content = ( iv + iv_len );
1906
mac = ( content + len );
1907
padding = ( mac + mac_len );
1909
/* Fill in block-ciphered struct */
1910
tls_generate_random ( tls, iv, iv_len );
1911
memcpy ( content, data, len );
1912
memcpy ( mac, digest, mac_len );
1913
memset ( padding, padding_len, ( padding_len + 1 ) );
1919
* Send plaintext record
1921
* @v tls TLS session
1922
* @v type Record type
1923
* @v data Plaintext record
1924
* @v len Length of plaintext record
1925
* @ret rc Return status code
1927
static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
1928
const void *data, size_t len ) {
1929
struct tls_header plaintext_tlshdr;
1930
struct tls_header *tlshdr;
1931
struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
1932
struct cipher_algorithm *cipher = cipherspec->suite->cipher;
1933
void *plaintext = NULL;
1934
size_t plaintext_len;
1935
struct io_buffer *ciphertext = NULL;
1936
size_t ciphertext_len;
1937
size_t mac_len = cipherspec->suite->digest->digestsize;
1938
uint8_t mac[mac_len];
1941
/* Construct header */
1942
plaintext_tlshdr.type = type;
1943
plaintext_tlshdr.version = htons ( tls->version );
1944
plaintext_tlshdr.length = htons ( len );
1947
tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
1949
/* Allocate and assemble plaintext struct */
1950
if ( is_stream_cipher ( cipher ) ) {
1951
plaintext = tls_assemble_stream ( tls, data, len, mac,
1954
plaintext = tls_assemble_block ( tls, data, len, mac,
1957
if ( ! plaintext ) {
1958
DBGC ( tls, "TLS %p could not allocate %zd bytes for "
1959
"plaintext\n", tls, plaintext_len );
1960
rc = -ENOMEM_TX_PLAINTEXT;
1964
DBGC2 ( tls, "Sending plaintext data:\n" );
1965
DBGC2_HD ( tls, plaintext, plaintext_len );
1967
/* Allocate ciphertext */
1968
ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
1969
ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
1970
if ( ! ciphertext ) {
1971
DBGC ( tls, "TLS %p could not allocate %zd bytes for "
1972
"ciphertext\n", tls, ciphertext_len );
1973
rc = -ENOMEM_TX_CIPHERTEXT;
1977
/* Assemble ciphertext */
1978
tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
1979
tlshdr->type = type;
1980
tlshdr->version = htons ( tls->version );
1981
tlshdr->length = htons ( plaintext_len );
1982
memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
1984
cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
1985
iob_put ( ciphertext, plaintext_len ), plaintext_len );
1987
/* Free plaintext as soon as possible to conserve memory */
1991
/* Send ciphertext */
1992
if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
1993
iob_disown ( ciphertext ) ) ) != 0 ) {
1994
DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
1995
tls, strerror ( rc ) );
1999
/* Update TX state machine to next record */
2001
memcpy ( tls->tx_cipherspec.cipher_ctx,
2002
tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
2006
free_iob ( ciphertext );
2011
* Split stream-ciphered record into data and MAC portions
2013
* @v tls TLS session
2014
* @v rx_data List of received data buffers
2015
* @v mac MAC to fill in
2016
* @ret rc Return status code
2018
static int tls_split_stream ( struct tls_session *tls,
2019
struct list_head *rx_data, void **mac ) {
2020
size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2021
struct io_buffer *iobuf;
2024
iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2025
assert ( iobuf != NULL );
2026
if ( iob_len ( iobuf ) < mac_len ) {
2027
DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2028
DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2029
return -EINVAL_STREAM;
2031
iob_unput ( iobuf, mac_len );
2038
* Split block-ciphered record into data and MAC portions
2040
* @v tls TLS session
2041
* @v rx_data List of received data buffers
2042
* @v mac MAC to fill in
2043
* @ret rc Return status code
2045
static int tls_split_block ( struct tls_session *tls,
2046
struct list_head *rx_data, void **mac ) {
2047
size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
2048
struct io_buffer *iobuf;
2050
uint8_t *padding_final;
2054
/* TLSv1.1 and later use an explicit IV */
2055
iobuf = list_first_entry ( rx_data, struct io_buffer, list );
2056
iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
2057
tls->rx_cipherspec.suite->cipher->blocksize : 0 );
2058
if ( iob_len ( iobuf ) < iv_len ) {
2059
DBGC ( tls, "TLS %p received underlength IV\n", tls );
2060
DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2061
return -EINVAL_BLOCK;
2063
iob_pull ( iobuf, iv_len );
2065
/* Extract and verify padding */
2066
iobuf = list_last_entry ( rx_data, struct io_buffer, list );
2067
padding_final = ( iobuf->tail - 1 );
2068
padding_len = *padding_final;
2069
if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
2070
DBGC ( tls, "TLS %p received underlength padding\n", tls );
2071
DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2072
return -EINVAL_BLOCK;
2074
iob_unput ( iobuf, ( padding_len + 1 ) );
2075
for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
2076
if ( *padding != padding_len ) {
2077
DBGC ( tls, "TLS %p received bad padding\n", tls );
2078
DBGC_HD ( tls, padding, padding_len );
2079
return -EINVAL_PADDING;
2084
if ( iob_len ( iobuf ) < mac_len ) {
2085
DBGC ( tls, "TLS %p received underlength MAC\n", tls );
2086
DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2087
return -EINVAL_BLOCK;
2089
iob_unput ( iobuf, mac_len );
2096
* Receive new ciphertext record
2098
* @v tls TLS session
2099
* @v tlshdr Record header
2100
* @v rx_data List of received data buffers
2101
* @ret rc Return status code
2103
static int tls_new_ciphertext ( struct tls_session *tls,
2104
struct tls_header *tlshdr,
2105
struct list_head *rx_data ) {
2106
struct tls_header plaintext_tlshdr;
2107
struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
2108
struct cipher_algorithm *cipher = cipherspec->suite->cipher;
2109
struct digest_algorithm *digest = cipherspec->suite->digest;
2110
uint8_t ctx[digest->ctxsize];
2111
uint8_t verify_mac[digest->digestsize];
2112
struct io_buffer *iobuf;
2117
/* Decrypt the received data */
2118
list_for_each_entry ( iobuf, &tls->rx_data, list ) {
2119
cipher_decrypt ( cipher, cipherspec->cipher_ctx,
2120
iobuf->data, iobuf->data, iob_len ( iobuf ) );
2123
/* Split record into content and MAC */
2124
if ( is_stream_cipher ( cipher ) ) {
2125
if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
2128
if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
2132
/* Calculate total length */
2133
DBGC2 ( tls, "Received plaintext data:\n" );
2134
list_for_each_entry ( iobuf, rx_data, list ) {
2135
DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
2136
len += iob_len ( iobuf );
2140
plaintext_tlshdr.type = tlshdr->type;
2141
plaintext_tlshdr.version = tlshdr->version;
2142
plaintext_tlshdr.length = htons ( len );
2143
tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
2144
list_for_each_entry ( iobuf, rx_data, list ) {
2145
tls_hmac_update ( cipherspec, ctx, iobuf->data,
2146
iob_len ( iobuf ) );
2148
tls_hmac_final ( cipherspec, ctx, verify_mac );
2149
if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
2150
DBGC ( tls, "TLS %p failed MAC verification\n", tls );
2154
/* Process plaintext record */
2155
if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
2161
/******************************************************************************
2163
* Plaintext stream operations
2165
******************************************************************************
2169
* Check flow control window
2171
* @v tls TLS session
2172
* @ret len Length of window
2174
static size_t tls_plainstream_window ( struct tls_session *tls ) {
2176
/* Block window unless we are ready to accept data */
2177
if ( ! tls_ready ( tls ) )
2180
return xfer_window ( &tls->cipherstream );
2184
* Deliver datagram as raw data
2186
* @v tls TLS session
2187
* @v iobuf I/O buffer
2188
* @v meta Data transfer metadata
2189
* @ret rc Return status code
2191
static int tls_plainstream_deliver ( struct tls_session *tls,
2192
struct io_buffer *iobuf,
2193
struct xfer_metadata *meta __unused ) {
2196
/* Refuse unless we are ready to accept data */
2197
if ( ! tls_ready ( tls ) ) {
2202
if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
2203
iob_len ( iobuf ) ) ) != 0 )
2211
/** TLS plaintext stream interface operations */
2212
static struct interface_operation tls_plainstream_ops[] = {
2213
INTF_OP ( xfer_deliver, struct tls_session *, tls_plainstream_deliver ),
2214
INTF_OP ( xfer_window, struct tls_session *, tls_plainstream_window ),
2215
INTF_OP ( intf_close, struct tls_session *, tls_close ),
2218
/** TLS plaintext stream interface descriptor */
2219
static struct interface_descriptor tls_plainstream_desc =
2220
INTF_DESC_PASSTHRU ( struct tls_session, plainstream,
2221
tls_plainstream_ops, cipherstream );
2223
/******************************************************************************
2225
* Ciphertext stream operations
2227
******************************************************************************
2231
* Handle received TLS header
2233
* @v tls TLS session
2234
* @ret rc Returned status code
2236
static int tls_newdata_process_header ( struct tls_session *tls ) {
2237
size_t data_len = ntohs ( tls->rx_header.length );
2238
size_t remaining = data_len;
2240
struct io_buffer *iobuf;
2241
struct io_buffer *tmp;
2244
/* Allocate data buffers now that we know the length */
2245
assert ( list_empty ( &tls->rx_data ) );
2246
while ( remaining ) {
2248
/* Calculate fragment length. Ensure that no block is
2249
* smaller than TLS_RX_MIN_BUFSIZE (by increasing the
2250
* allocation length if necessary).
2252
frag_len = remaining;
2253
if ( frag_len > TLS_RX_BUFSIZE )
2254
frag_len = TLS_RX_BUFSIZE;
2255
remaining -= frag_len;
2256
if ( remaining < TLS_RX_MIN_BUFSIZE ) {
2257
frag_len += remaining;
2261
/* Allocate buffer */
2262
iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
2264
DBGC ( tls, "TLS %p could not allocate %zd of %zd "
2265
"bytes for receive buffer\n", tls,
2266
remaining, data_len );
2267
rc = -ENOMEM_RX_DATA;
2271
/* Ensure tailroom is exactly what we asked for. This
2272
* will result in unaligned I/O buffers when the
2273
* fragment length is unaligned, which can happen only
2274
* before we switch to using a block cipher.
2276
iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
2278
/* Add I/O buffer to list */
2279
list_add_tail ( &iobuf->list, &tls->rx_data );
2282
/* Move to data state */
2283
tls->rx_state = TLS_RX_DATA;
2288
list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
2289
list_del ( &iobuf->list );
2296
* Handle received TLS data payload
2298
* @v tls TLS session
2299
* @ret rc Returned status code
2301
static int tls_newdata_process_data ( struct tls_session *tls ) {
2302
struct io_buffer *iobuf;
2305
/* Move current buffer to end of list */
2306
iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2307
list_del ( &iobuf->list );
2308
list_add_tail ( &iobuf->list, &tls->rx_data );
2310
/* Continue receiving data if any space remains */
2311
iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
2312
if ( iob_tailroom ( iobuf ) )
2315
/* Process record */
2316
if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
2317
&tls->rx_data ) ) != 0 )
2320
/* Increment RX sequence number */
2323
/* Return to header state */
2324
assert ( list_empty ( &tls->rx_data ) );
2325
tls->rx_state = TLS_RX_HEADER;
2326
iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
2332
* Receive new ciphertext
2334
* @v tls TLS session
2335
* @v iobuf I/O buffer
2336
* @v meta Data transfer metadat
2337
* @ret rc Return status code
2339
static int tls_cipherstream_deliver ( struct tls_session *tls,
2340
struct io_buffer *iobuf,
2341
struct xfer_metadata *xfer __unused ) {
2343
int ( * process ) ( struct tls_session *tls );
2344
struct io_buffer *dest;
2347
while ( iob_len ( iobuf ) ) {
2349
/* Select buffer according to current state */
2350
switch ( tls->rx_state ) {
2352
dest = &tls->rx_header_iobuf;
2353
process = tls_newdata_process_header;
2356
dest = list_first_entry ( &tls->rx_data,
2357
struct io_buffer, list );
2358
assert ( dest != NULL );
2359
process = tls_newdata_process_data;
2363
rc = -EINVAL_RX_STATE;
2367
/* Copy data portion to buffer */
2368
frag_len = iob_len ( iobuf );
2369
if ( frag_len > iob_tailroom ( dest ) )
2370
frag_len = iob_tailroom ( dest );
2371
memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
2372
iob_pull ( iobuf, frag_len );
2374
/* Process data if buffer is now full */
2375
if ( iob_tailroom ( dest ) == 0 ) {
2376
if ( ( rc = process ( tls ) ) != 0 ) {
2377
tls_close ( tls, rc );
2389
/** TLS ciphertext stream interface operations */
2390
static struct interface_operation tls_cipherstream_ops[] = {
2391
INTF_OP ( xfer_deliver, struct tls_session *,
2392
tls_cipherstream_deliver ),
2393
INTF_OP ( xfer_window_changed, struct tls_session *, tls_tx_resume ),
2394
INTF_OP ( intf_close, struct tls_session *, tls_close ),
2397
/** TLS ciphertext stream interface descriptor */
2398
static struct interface_descriptor tls_cipherstream_desc =
2399
INTF_DESC_PASSTHRU ( struct tls_session, cipherstream,
2400
tls_cipherstream_ops, plainstream );
2402
/******************************************************************************
2404
* Certificate validator
2406
******************************************************************************
2410
* Handle certificate validation completion
2412
* @v tls TLS session
2413
* @v rc Reason for completion
2415
static void tls_validator_done ( struct tls_session *tls, int rc ) {
2416
struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
2417
struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
2418
struct x509_certificate *cert;
2420
/* Close validator interface */
2421
intf_restart ( &tls->validator, rc );
2423
/* Check for validation failure */
2425
DBGC ( tls, "TLS %p certificate validation failed: %s\n",
2426
tls, strerror ( rc ) );
2429
DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
2431
/* Extract first certificate */
2432
cert = x509_first ( tls->chain );
2433
assert ( cert != NULL );
2435
/* Verify server name */
2436
if ( ( rc = x509_check_name ( cert, tls->name ) ) != 0 ) {
2437
DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
2438
tls, tls->name, strerror ( rc ) );
2442
/* Initialise public key algorithm */
2443
if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
2444
cert->subject.public_key.raw.data,
2445
cert->subject.public_key.raw.len ) ) != 0 ) {
2446
DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
2447
tls, strerror ( rc ) );
2451
/* Schedule Client Key Exchange, Change Cipher, and Finished */
2452
tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
2453
TLS_TX_CHANGE_CIPHER |
2456
tls->tx_pending |= ( TLS_TX_CERTIFICATE |
2457
TLS_TX_CERTIFICATE_VERIFY );
2459
tls_tx_resume ( tls );
2464
tls_close ( tls, rc );
2468
/** TLS certificate validator interface operations */
2469
static struct interface_operation tls_validator_ops[] = {
2470
INTF_OP ( intf_close, struct tls_session *, tls_validator_done ),
2473
/** TLS certificate validator interface descriptor */
2474
static struct interface_descriptor tls_validator_desc =
2475
INTF_DESC ( struct tls_session, validator, tls_validator_ops );
2477
/******************************************************************************
2479
* Controlling process
2481
******************************************************************************
2485
* TLS TX state machine
2487
* @v tls TLS session
2489
static void tls_tx_step ( struct tls_session *tls ) {
2492
/* Wait for cipherstream to become ready */
2493
if ( ! xfer_window ( &tls->cipherstream ) )
2496
/* Send first pending transmission */
2497
if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
2498
/* Send Client Hello */
2499
if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
2500
DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
2501
tls, strerror ( rc ) );
2504
tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
2505
} else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
2506
/* Send Certificate */
2507
if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
2508
DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
2509
tls, strerror ( rc ) );
2512
tls->tx_pending &= ~TLS_TX_CERTIFICATE;
2513
} else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
2514
/* Send Client Key Exchange */
2515
if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
2516
DBGC ( tls, "TLS %p could not send Client Key "
2517
"Exchange: %s\n", tls, strerror ( rc ) );
2520
tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
2521
} else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
2522
/* Send Certificate Verify */
2523
if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
2524
DBGC ( tls, "TLS %p could not send Certificate "
2525
"Verify: %s\n", tls, strerror ( rc ) );
2528
tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
2529
} else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
2530
/* Send Change Cipher, and then change the cipher in use */
2531
if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
2532
DBGC ( tls, "TLS %p could not send Change Cipher: "
2533
"%s\n", tls, strerror ( rc ) );
2536
if ( ( rc = tls_change_cipher ( tls,
2537
&tls->tx_cipherspec_pending,
2538
&tls->tx_cipherspec )) != 0 ){
2539
DBGC ( tls, "TLS %p could not activate TX cipher: "
2540
"%s\n", tls, strerror ( rc ) );
2544
tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
2545
} else if ( tls->tx_pending & TLS_TX_FINISHED ) {
2547
if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
2548
DBGC ( tls, "TLS %p could not send Finished: %s\n",
2549
tls, strerror ( rc ) );
2552
tls->tx_pending &= ~TLS_TX_FINISHED;
2555
/* Reschedule process if pending transmissions remain */
2556
if ( tls->tx_pending )
2557
tls_tx_resume ( tls );
2562
tls_close ( tls, rc );
2565
/** TLS TX process descriptor */
2566
static struct process_descriptor tls_process_desc =
2567
PROC_DESC_ONCE ( struct tls_session, process, tls_tx_step );
2569
/******************************************************************************
2573
******************************************************************************
2576
int add_tls ( struct interface *xfer, const char *name,
2577
struct interface **next ) {
2578
struct tls_session *tls;
2581
/* Allocate and initialise TLS structure */
2582
tls = malloc ( sizeof ( *tls ) );
2587
memset ( tls, 0, sizeof ( *tls ) );
2588
ref_init ( &tls->refcnt, free_tls );
2590
intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
2591
intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
2592
intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
2593
process_init ( &tls->process, &tls_process_desc, &tls->refcnt );
2594
tls->version = TLS_VERSION_TLS_1_2;
2595
tls_clear_cipher ( tls, &tls->tx_cipherspec );
2596
tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
2597
tls_clear_cipher ( tls, &tls->rx_cipherspec );
2598
tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
2599
tls->client_random.gmt_unix_time = time ( NULL );
2600
if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
2601
( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
2604
tls->pre_master_secret.version = htons ( tls->version );
2605
if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
2606
( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
2609
digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
2610
digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
2611
tls->handshake_digest = &sha256_algorithm;
2612
tls->handshake_ctx = tls->handshake_sha256_ctx;
2613
tls->tx_pending = TLS_TX_CLIENT_HELLO;
2614
iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
2615
sizeof ( tls->rx_header ) );
2616
INIT_LIST_HEAD ( &tls->rx_data );
2618
/* Add pending operations for server and client Finished messages */
2619
pending_get ( &tls->client_negotiation );
2620
pending_get ( &tls->server_negotiation );
2622
/* Attach to parent interface, mortalise self, and return */
2623
intf_plug_plug ( &tls->plainstream, xfer );
2624
*next = &tls->cipherstream;
2625
ref_put ( &tls->refcnt );
2629
ref_put ( &tls->refcnt );
2634
/* Drag in objects via add_tls() */
2635
REQUIRING_SYMBOL ( add_tls );
2637
/* Drag in crypto configuration */
2638
REQUIRE_OBJECT ( config_crypto );