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