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