iPXE
tls.c
Go to the documentation of this file.
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/rootcert.h>
49 #include <ipxe/rbg.h>
50 #include <ipxe/validator.h>
51 #include <ipxe/job.h>
52 #include <ipxe/dhe.h>
53 #include <ipxe/tls.h>
54 #include <config/crypto.h>
55 
56 /* Disambiguate the various error causes */
57 #define EINVAL_CHANGE_CIPHER __einfo_error ( EINFO_EINVAL_CHANGE_CIPHER )
58 #define EINFO_EINVAL_CHANGE_CIPHER \
59  __einfo_uniqify ( EINFO_EINVAL, 0x01, \
60  "Invalid Change Cipher record" )
61 #define EINVAL_ALERT __einfo_error ( EINFO_EINVAL_ALERT )
62 #define EINFO_EINVAL_ALERT \
63  __einfo_uniqify ( EINFO_EINVAL, 0x02, \
64  "Invalid Alert record" )
65 #define EINVAL_HELLO __einfo_error ( EINFO_EINVAL_HELLO )
66 #define EINFO_EINVAL_HELLO \
67  __einfo_uniqify ( EINFO_EINVAL, 0x03, \
68  "Invalid Server Hello record" )
69 #define EINVAL_CERTIFICATE __einfo_error ( EINFO_EINVAL_CERTIFICATE )
70 #define EINFO_EINVAL_CERTIFICATE \
71  __einfo_uniqify ( EINFO_EINVAL, 0x04, \
72  "Invalid Certificate" )
73 #define EINVAL_CERTIFICATES __einfo_error ( EINFO_EINVAL_CERTIFICATES )
74 #define EINFO_EINVAL_CERTIFICATES \
75  __einfo_uniqify ( EINFO_EINVAL, 0x05, \
76  "Invalid Server Certificate record" )
77 #define EINVAL_HELLO_DONE __einfo_error ( EINFO_EINVAL_HELLO_DONE )
78 #define EINFO_EINVAL_HELLO_DONE \
79  __einfo_uniqify ( EINFO_EINVAL, 0x06, \
80  "Invalid Server Hello Done record" )
81 #define EINVAL_FINISHED __einfo_error ( EINFO_EINVAL_FINISHED )
82 #define EINFO_EINVAL_FINISHED \
83  __einfo_uniqify ( EINFO_EINVAL, 0x07, \
84  "Invalid Server Finished record" )
85 #define EINVAL_HANDSHAKE __einfo_error ( EINFO_EINVAL_HANDSHAKE )
86 #define EINFO_EINVAL_HANDSHAKE \
87  __einfo_uniqify ( EINFO_EINVAL, 0x08, \
88  "Invalid Handshake record" )
89 #define EINVAL_IV __einfo_error ( EINFO_EINVAL_IV )
90 #define EINFO_EINVAL_IV \
91  __einfo_uniqify ( EINFO_EINVAL, 0x0a, \
92  "Invalid initialisation vector" )
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 or authentication tag" )
105 #define EINVAL_TICKET __einfo_error ( EINFO_EINVAL_TICKET )
106 #define EINFO_EINVAL_TICKET \
107  __einfo_uniqify ( EINFO_EINVAL, 0x0e, \
108  "Invalid New Session Ticket record")
109 #define EINVAL_KEY_EXCHANGE __einfo_error ( EINFO_EINVAL_KEY_EXCHANGE )
110 #define EINFO_EINVAL_KEY_EXCHANGE \
111  __einfo_uniqify ( EINFO_EINVAL, 0x0f, \
112  "Invalid Server Key Exchange record" )
113 #define EIO_ALERT __einfo_error ( EINFO_EIO_ALERT )
114 #define EINFO_EIO_ALERT \
115  __einfo_uniqify ( EINFO_EIO, 0x01, \
116  "Unknown alert level" )
117 #define ENOMEM_CONTEXT __einfo_error ( EINFO_ENOMEM_CONTEXT )
118 #define EINFO_ENOMEM_CONTEXT \
119  __einfo_uniqify ( EINFO_ENOMEM, 0x01, \
120  "Not enough space for crypto context" )
121 #define ENOMEM_CERTIFICATE __einfo_error ( EINFO_ENOMEM_CERTIFICATE )
122 #define EINFO_ENOMEM_CERTIFICATE \
123  __einfo_uniqify ( EINFO_ENOMEM, 0x02, \
124  "Not enough space for certificate" )
125 #define ENOMEM_CHAIN __einfo_error ( EINFO_ENOMEM_CHAIN )
126 #define EINFO_ENOMEM_CHAIN \
127  __einfo_uniqify ( EINFO_ENOMEM, 0x03, \
128  "Not enough space for certificate chain" )
129 #define ENOMEM_TX_PLAINTEXT __einfo_error ( EINFO_ENOMEM_TX_PLAINTEXT )
130 #define EINFO_ENOMEM_TX_PLAINTEXT \
131  __einfo_uniqify ( EINFO_ENOMEM, 0x04, \
132  "Not enough space for transmitted plaintext" )
133 #define ENOMEM_TX_CIPHERTEXT __einfo_error ( EINFO_ENOMEM_TX_CIPHERTEXT )
134 #define EINFO_ENOMEM_TX_CIPHERTEXT \
135  __einfo_uniqify ( EINFO_ENOMEM, 0x05, \
136  "Not enough space for transmitted ciphertext" )
137 #define ENOMEM_RX_DATA __einfo_error ( EINFO_ENOMEM_RX_DATA )
138 #define EINFO_ENOMEM_RX_DATA \
139  __einfo_uniqify ( EINFO_ENOMEM, 0x07, \
140  "Not enough space for received data" )
141 #define ENOMEM_RX_CONCAT __einfo_error ( EINFO_ENOMEM_RX_CONCAT )
142 #define EINFO_ENOMEM_RX_CONCAT \
143  __einfo_uniqify ( EINFO_ENOMEM, 0x08, \
144  "Not enough space to concatenate received data" )
145 #define ENOTSUP_CIPHER __einfo_error ( EINFO_ENOTSUP_CIPHER )
146 #define EINFO_ENOTSUP_CIPHER \
147  __einfo_uniqify ( EINFO_ENOTSUP, 0x01, \
148  "Unsupported cipher" )
149 #define ENOTSUP_NULL __einfo_error ( EINFO_ENOTSUP_NULL )
150 #define EINFO_ENOTSUP_NULL \
151  __einfo_uniqify ( EINFO_ENOTSUP, 0x02, \
152  "Refusing to use null cipher" )
153 #define ENOTSUP_SIG_HASH __einfo_error ( EINFO_ENOTSUP_SIG_HASH )
154 #define EINFO_ENOTSUP_SIG_HASH \
155  __einfo_uniqify ( EINFO_ENOTSUP, 0x03, \
156  "Unsupported signature and hash algorithm" )
157 #define ENOTSUP_VERSION __einfo_error ( EINFO_ENOTSUP_VERSION )
158 #define EINFO_ENOTSUP_VERSION \
159  __einfo_uniqify ( EINFO_ENOTSUP, 0x04, \
160  "Unsupported protocol version" )
161 #define ENOTSUP_CURVE __einfo_error ( EINFO_ENOTSUP_CURVE )
162 #define EINFO_ENOTSUP_CURVE \
163  __einfo_uniqify ( EINFO_ENOTSUP, 0x05, \
164  "Unsupported elliptic curve" )
165 #define EPERM_ALERT __einfo_error ( EINFO_EPERM_ALERT )
166 #define EINFO_EPERM_ALERT \
167  __einfo_uniqify ( EINFO_EPERM, 0x01, \
168  "Received fatal alert" )
169 #define EPERM_VERIFY __einfo_error ( EINFO_EPERM_VERIFY )
170 #define EINFO_EPERM_VERIFY \
171  __einfo_uniqify ( EINFO_EPERM, 0x02, \
172  "Handshake verification failed" )
173 #define EPERM_CLIENT_CERT __einfo_error ( EINFO_EPERM_CLIENT_CERT )
174 #define EINFO_EPERM_CLIENT_CERT \
175  __einfo_uniqify ( EINFO_EPERM, 0x03, \
176  "No suitable client certificate available" )
177 #define EPERM_RENEG_INSECURE __einfo_error ( EINFO_EPERM_RENEG_INSECURE )
178 #define EINFO_EPERM_RENEG_INSECURE \
179  __einfo_uniqify ( EINFO_EPERM, 0x04, \
180  "Secure renegotiation not supported" )
181 #define EPERM_RENEG_VERIFY __einfo_error ( EINFO_EPERM_RENEG_VERIFY )
182 #define EINFO_EPERM_RENEG_VERIFY \
183  __einfo_uniqify ( EINFO_EPERM, 0x05, \
184  "Secure renegotiation verification failed" )
185 #define EPERM_KEY_EXCHANGE __einfo_error ( EINFO_EPERM_KEY_EXCHANGE )
186 #define EINFO_EPERM_KEY_EXCHANGE \
187  __einfo_uniqify ( EINFO_EPERM, 0x06, \
188  "ServerKeyExchange verification failed" )
189 #define EPROTO_VERSION __einfo_error ( EINFO_EPROTO_VERSION )
190 #define EINFO_EPROTO_VERSION \
191  __einfo_uniqify ( EINFO_EPROTO, 0x01, \
192  "Illegal protocol version upgrade" )
193 
194 /** List of TLS session */
195 static LIST_HEAD ( tls_sessions );
196 
197 static void tls_tx_resume_all ( struct tls_session *session );
198 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
199  const void *data, size_t len );
200 static void tls_clear_cipher ( struct tls_connection *tls,
201  struct tls_cipherspec *cipherspec );
202 
203 /******************************************************************************
204  *
205  * Utility functions
206  *
207  ******************************************************************************
208  */
209 
210 /** A TLS 24-bit integer
211  *
212  * TLS uses 24-bit integers in several places, which are awkward to
213  * parse in C.
214  */
215 typedef struct {
216  /** High byte */
218  /** Low word */
220 } __attribute__ (( packed )) tls24_t;
221 
222 /**
223  * Extract 24-bit field value
224  *
225  * @v field24 24-bit field
226  * @ret value Field value
227  *
228  */
229 static inline __attribute__ (( always_inline )) unsigned long
230 tls_uint24 ( const tls24_t *field24 ) {
231 
232  return ( ( field24->high << 16 ) | be16_to_cpu ( field24->low ) );
233 }
234 
235 /**
236  * Set 24-bit field value
237  *
238  * @v field24 24-bit field
239  * @v value Field value
240  */
241 static void tls_set_uint24 ( tls24_t *field24, unsigned long value ) {
242 
243  field24->high = ( value >> 16 );
244  field24->low = cpu_to_be16 ( value );
245 }
246 
247 /**
248  * Determine if TLS connection is ready for application data
249  *
250  * @v tls TLS connection
251  * @ret is_ready TLS connection is ready
252  */
253 static int tls_ready ( struct tls_connection *tls ) {
254  return ( ( ! is_pending ( &tls->client.negotiation ) ) &&
255  ( ! is_pending ( &tls->server.negotiation ) ) );
256 }
257 
258 /**
259  * Check for TLS version
260  *
261  * @v tls TLS connection
262  * @v version TLS version
263  * @ret at_least TLS connection is using at least the specified version
264  *
265  * Check that TLS connection uses at least the specified protocol
266  * version. Optimise down to a compile-time constant true result if
267  * this is already guaranteed by the minimum supported version check.
268  */
269 static inline __attribute__ (( always_inline )) int
270 tls_version ( struct tls_connection *tls, unsigned int version ) {
271  return ( ( TLS_VERSION_MIN >= version ) ||
272  ( tls->version >= version ) );
273 }
274 
275 /******************************************************************************
276  *
277  * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
278  *
279  ******************************************************************************
280  */
281 
282 /**
283  * Initialise MD5+SHA1 algorithm
284  *
285  * @v ctx MD5+SHA1 context
286  */
287 static void md5_sha1_init ( void *ctx ) {
288  struct md5_sha1_context *context = ctx;
289 
290  digest_init ( &md5_algorithm, context->md5 );
291  digest_init ( &sha1_algorithm, context->sha1 );
292 }
293 
294 /**
295  * Accumulate data with MD5+SHA1 algorithm
296  *
297  * @v ctx MD5+SHA1 context
298  * @v data Data
299  * @v len Length of data
300  */
301 static void md5_sha1_update ( void *ctx, const void *data, size_t len ) {
302  struct md5_sha1_context *context = ctx;
303 
304  digest_update ( &md5_algorithm, context->md5, data, len );
305  digest_update ( &sha1_algorithm, context->sha1, data, len );
306 }
307 
308 /**
309  * Generate MD5+SHA1 digest
310  *
311  * @v ctx MD5+SHA1 context
312  * @v out Output buffer
313  */
314 static void md5_sha1_final ( void *ctx, void *out ) {
315  struct md5_sha1_context *context = ctx;
316  struct md5_sha1_digest *digest = out;
317 
318  digest_final ( &md5_algorithm, context->md5, digest->md5 );
319  digest_final ( &sha1_algorithm, context->sha1, digest->sha1 );
320 }
321 
322 /** Hybrid MD5+SHA1 digest algorithm */
324  .name = "md5+sha1",
325  .ctxsize = sizeof ( struct md5_sha1_context ),
326  .blocksize = 0, /* Not applicable */
327  .digestsize = sizeof ( struct md5_sha1_digest ),
328  .init = md5_sha1_init,
329  .update = md5_sha1_update,
330  .final = md5_sha1_final,
331 };
332 
333 /** RSA digestInfo prefix for MD5+SHA1 algorithm */
334 struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix = {
336  .data = NULL, /* MD5+SHA1 signatures have no digestInfo */
337  .len = 0,
338 };
339 
340 /******************************************************************************
341  *
342  * Cleanup functions
343  *
344  ******************************************************************************
345  */
346 
347 /**
348  * Free TLS session
349  *
350  * @v refcnt Reference counter
351  */
352 static void free_tls_session ( struct refcnt *refcnt ) {
353  struct tls_session *session =
354  container_of ( refcnt, struct tls_session, refcnt );
355 
356  /* Sanity check */
357  assert ( list_empty ( &session->conn ) );
358 
359  /* Remove from list of sessions */
360  list_del ( &session->list );
361 
362  /* Free dynamically-allocated resources */
363  x509_root_put ( session->root );
364  privkey_put ( session->key );
365  free ( session->ticket );
366 
367  /* Free session */
368  free ( session );
369 }
370 
371 /**
372  * Free TLS connection
373  *
374  * @v refcnt Reference counter
375  */
376 static void free_tls ( struct refcnt *refcnt ) {
377  struct tls_connection *tls =
379  struct tls_session *session = tls->session;
380  struct io_buffer *iobuf;
381  struct io_buffer *tmp;
382 
383  /* Free dynamically-allocated resources */
384  free ( tls->new_session_ticket );
385  tls_clear_cipher ( tls, &tls->tx.cipherspec.active );
386  tls_clear_cipher ( tls, &tls->tx.cipherspec.pending );
387  tls_clear_cipher ( tls, &tls->rx.cipherspec.active );
388  tls_clear_cipher ( tls, &tls->rx.cipherspec.pending );
389  free ( tls->server.exchange );
390  free ( tls->handshake_ctx );
391  list_for_each_entry_safe ( iobuf, tmp, &tls->rx.data, list ) {
392  list_del ( &iobuf->list );
393  free_iob ( iobuf );
394  }
395  free_iob ( tls->rx.handshake );
396  privkey_put ( tls->client.key );
397  x509_chain_put ( tls->client.chain );
398  x509_chain_put ( tls->server.chain );
399  x509_root_put ( tls->server.root );
400 
401  /* Drop reference to session */
402  assert ( list_empty ( &tls->list ) );
403  ref_put ( &session->refcnt );
404 
405  /* Free TLS structure itself */
406  free ( tls );
407 }
408 
409 /**
410  * Finish with TLS connection
411  *
412  * @v tls TLS connection
413  * @v rc Status code
414  */
415 static void tls_close ( struct tls_connection *tls, int rc ) {
416 
417  /* Remove pending operations, if applicable */
418  pending_put ( &tls->client.negotiation );
419  pending_put ( &tls->server.negotiation );
420  pending_put ( &tls->server.validation );
421 
422  /* Remove process */
423  process_del ( &tls->tx.process );
424 
425  /* Close all interfaces */
426  intf_shutdown ( &tls->cipherstream, rc );
427  intf_shutdown ( &tls->plainstream, rc );
428  intf_shutdown ( &tls->server.validator, rc );
429 
430  /* Remove from session */
431  list_del ( &tls->list );
432  INIT_LIST_HEAD ( &tls->list );
433 
434  /* Resume all other connections, in case we were the lead connection */
435  tls_tx_resume_all ( tls->session );
436 }
437 
438 /******************************************************************************
439  *
440  * Random number generation
441  *
442  ******************************************************************************
443  */
444 
445 /**
446  * Generate random data
447  *
448  * @v tls TLS connection
449  * @v data Buffer to fill
450  * @v len Length of buffer
451  * @ret rc Return status code
452  */
453 static int tls_generate_random ( struct tls_connection *tls,
454  void *data, size_t len ) {
455  int rc;
456 
457  /* Generate random bits with no additional input and without
458  * prediction resistance
459  */
460  if ( ( rc = rbg_generate ( NULL, 0, 0, data, len ) ) != 0 ) {
461  DBGC ( tls, "TLS %p could not generate random data: %s\n",
462  tls, strerror ( rc ) );
463  return rc;
464  }
465 
466  return 0;
467 }
468 
469 /**
470  * Update HMAC with a list of ( data, len ) pairs
471  *
472  * @v digest Hash function to use
473  * @v ctx HMAC context
474  * @v args ( data, len ) pairs of data, terminated by NULL
475  */
476 static void tls_hmac_update_va ( struct digest_algorithm *digest,
477  void *ctx, va_list args ) {
478  void *data;
479  size_t len;
480 
481  while ( ( data = va_arg ( args, void * ) ) ) {
482  len = va_arg ( args, size_t );
483  hmac_update ( digest, ctx, data, len );
484  }
485 }
486 
487 /**
488  * Generate secure pseudo-random data using a single hash function
489  *
490  * @v tls TLS connection
491  * @v digest Hash function to use
492  * @v secret Secret
493  * @v secret_len Length of secret
494  * @v out Output buffer
495  * @v out_len Length of output buffer
496  * @v seeds ( data, len ) pairs of seed data, terminated by NULL
497  */
498 static void tls_p_hash_va ( struct tls_connection *tls,
499  struct digest_algorithm *digest,
500  const void *secret, size_t secret_len,
501  void *out, size_t out_len,
502  va_list seeds ) {
503  uint8_t ctx[ hmac_ctxsize ( digest ) ];
504  uint8_t ctx_partial[ sizeof ( ctx ) ];
505  uint8_t a[digest->digestsize];
506  uint8_t out_tmp[digest->digestsize];
507  size_t frag_len = digest->digestsize;
508  va_list tmp;
509 
510  DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
511  DBGC2_HD ( tls, secret, secret_len );
512 
513  /* Calculate A(1) */
514  hmac_init ( digest, ctx, secret, secret_len );
515  va_copy ( tmp, seeds );
516  tls_hmac_update_va ( digest, ctx, tmp );
517  va_end ( tmp );
518  hmac_final ( digest, ctx, a );
519  DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
520  DBGC2_HD ( tls, &a, sizeof ( a ) );
521 
522  /* Generate as much data as required */
523  while ( out_len ) {
524  /* Calculate output portion */
525  hmac_init ( digest, ctx, secret, secret_len );
526  hmac_update ( digest, ctx, a, sizeof ( a ) );
527  memcpy ( ctx_partial, ctx, sizeof ( ctx_partial ) );
528  va_copy ( tmp, seeds );
529  tls_hmac_update_va ( digest, ctx, tmp );
530  va_end ( tmp );
531  hmac_final ( digest, ctx, out_tmp );
532 
533  /* Copy output */
534  if ( frag_len > out_len )
535  frag_len = out_len;
536  memcpy ( out, out_tmp, frag_len );
537  DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
538  DBGC2_HD ( tls, out, frag_len );
539 
540  /* Calculate A(i) */
541  hmac_final ( digest, ctx_partial, a );
542  DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
543  DBGC2_HD ( tls, &a, sizeof ( a ) );
544 
545  out += frag_len;
546  out_len -= frag_len;
547  }
548 }
549 
550 /**
551  * Generate secure pseudo-random data
552  *
553  * @v tls TLS connection
554  * @v secret Secret
555  * @v secret_len Length of secret
556  * @v out Output buffer
557  * @v out_len Length of output buffer
558  * @v ... ( data, len ) pairs of seed data, terminated by NULL
559  */
560 static void tls_prf ( struct tls_connection *tls, const void *secret,
561  size_t secret_len, void *out, size_t out_len, ... ) {
562  va_list seeds;
563  va_list tmp;
564  size_t subsecret_len;
565  const void *md5_secret;
566  const void *sha1_secret;
567  uint8_t buf[out_len];
568  unsigned int i;
569 
570  va_start ( seeds, out_len );
571 
572  if ( tls_version ( tls, TLS_VERSION_TLS_1_2 ) ) {
573  /* Use handshake digest PRF for TLSv1.2 and later */
574  tls_p_hash_va ( tls, tls->handshake_digest, secret, secret_len,
575  out, out_len, seeds );
576  } else {
577  /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
578  * and earlier
579  */
580 
581  /* Split secret into two, with an overlap of up to one byte */
582  subsecret_len = ( ( secret_len + 1 ) / 2 );
583  md5_secret = secret;
584  sha1_secret = ( secret + secret_len - subsecret_len );
585 
586  /* Calculate MD5 portion */
587  va_copy ( tmp, seeds );
588  tls_p_hash_va ( tls, &md5_algorithm, md5_secret,
589  subsecret_len, out, out_len, seeds );
590  va_end ( tmp );
591 
592  /* Calculate SHA1 portion */
593  va_copy ( tmp, seeds );
594  tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret,
595  subsecret_len, buf, out_len, seeds );
596  va_end ( tmp );
597 
598  /* XOR the two portions together into the final output buffer */
599  for ( i = 0 ; i < out_len ; i++ )
600  *( ( uint8_t * ) out + i ) ^= buf[i];
601  }
602 
603  va_end ( seeds );
604 }
605 
606 /**
607  * Generate secure pseudo-random data
608  *
609  * @v secret Secret
610  * @v secret_len Length of secret
611  * @v out Output buffer
612  * @v out_len Length of output buffer
613  * @v label String literal label
614  * @v ... ( data, len ) pairs of seed data
615  */
616 #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
617  tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
618  label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
619 
620 /******************************************************************************
621  *
622  * Secret management
623  *
624  ******************************************************************************
625  */
626 
627 /**
628  * Generate master secret
629  *
630  * @v tls TLS connection
631  * @v pre_master_secret Pre-master secret
632  * @v pre_master_secret_len Length of pre-master secret
633  *
634  * The client and server random values must already be known.
635  */
636 static void tls_generate_master_secret ( struct tls_connection *tls,
637  const void *pre_master_secret,
638  size_t pre_master_secret_len ) {
639 
640  DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
641  DBGC_HD ( tls, pre_master_secret, pre_master_secret_len );
642  DBGC ( tls, "TLS %p client random bytes:\n", tls );
643  DBGC_HD ( tls, &tls->client.random, sizeof ( tls->client.random ) );
644  DBGC ( tls, "TLS %p server random bytes:\n", tls );
645  DBGC_HD ( tls, &tls->server.random, sizeof ( tls->server.random ) );
646 
647  tls_prf_label ( tls, pre_master_secret, pre_master_secret_len,
648  &tls->master_secret, sizeof ( tls->master_secret ),
649  "master secret",
650  &tls->client.random, sizeof ( tls->client.random ),
651  &tls->server.random, sizeof ( tls->server.random ) );
652 
653  DBGC ( tls, "TLS %p generated master secret:\n", tls );
654  DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
655 }
656 
657 /**
658  * Generate key material
659  *
660  * @v tls TLS connection
661  *
662  * The master secret must already be known.
663  */
664 static int tls_generate_keys ( struct tls_connection *tls ) {
665  struct tls_cipherspec *tx_cipherspec = &tls->tx.cipherspec.pending;
666  struct tls_cipherspec *rx_cipherspec = &tls->rx.cipherspec.pending;
667  size_t hash_size = tx_cipherspec->suite->mac_len;
668  size_t key_size = tx_cipherspec->suite->key_len;
669  size_t iv_size = tx_cipherspec->suite->fixed_iv_len;
670  size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
671  uint8_t key_block[total];
672  uint8_t *key;
673  int rc;
674 
675  /* Generate key block */
676  tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
677  key_block, sizeof ( key_block ), "key expansion",
678  &tls->server.random, sizeof ( tls->server.random ),
679  &tls->client.random, sizeof ( tls->client.random ) );
680 
681  /* Split key block into portions */
682  key = key_block;
683 
684  /* TX MAC secret */
685  memcpy ( tx_cipherspec->mac_secret, key, hash_size );
686  DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
687  DBGC_HD ( tls, key, hash_size );
688  key += hash_size;
689 
690  /* RX MAC secret */
691  memcpy ( rx_cipherspec->mac_secret, key, hash_size );
692  DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
693  DBGC_HD ( tls, key, hash_size );
694  key += hash_size;
695 
696  /* TX key */
697  if ( ( rc = cipher_setkey ( tx_cipherspec->suite->cipher,
698  tx_cipherspec->cipher_ctx,
699  key, key_size ) ) != 0 ) {
700  DBGC ( tls, "TLS %p could not set TX key: %s\n",
701  tls, strerror ( rc ) );
702  return rc;
703  }
704  DBGC ( tls, "TLS %p TX key:\n", tls );
705  DBGC_HD ( tls, key, key_size );
706  key += key_size;
707 
708  /* RX key */
709  if ( ( rc = cipher_setkey ( rx_cipherspec->suite->cipher,
710  rx_cipherspec->cipher_ctx,
711  key, key_size ) ) != 0 ) {
712  DBGC ( tls, "TLS %p could not set TX key: %s\n",
713  tls, strerror ( rc ) );
714  return rc;
715  }
716  DBGC ( tls, "TLS %p RX key:\n", tls );
717  DBGC_HD ( tls, key, key_size );
718  key += key_size;
719 
720  /* TX initialisation vector */
721  memcpy ( tx_cipherspec->fixed_iv, key, iv_size );
722  DBGC ( tls, "TLS %p TX IV:\n", tls );
723  DBGC_HD ( tls, key, iv_size );
724  key += iv_size;
725 
726  /* RX initialisation vector */
727  memcpy ( rx_cipherspec->fixed_iv, key, iv_size );
728  DBGC ( tls, "TLS %p RX IV:\n", tls );
729  DBGC_HD ( tls, key, iv_size );
730  key += iv_size;
731 
732  assert ( ( key_block + total ) == key );
733 
734  return 0;
735 }
736 
737 /******************************************************************************
738  *
739  * Handshake verification
740  *
741  ******************************************************************************
742  */
743 
744 /**
745  * Clear handshake digest algorithm
746  *
747  * @v tls TLS connection
748  */
749 static void tls_clear_handshake ( struct tls_connection *tls ) {
750 
751  /* Select null digest algorithm */
753 
754  /* Free any existing context */
755  free ( tls->handshake_ctx );
756  tls->handshake_ctx = NULL;
757 }
758 
759 /**
760  * Select handshake digest algorithm
761  *
762  * @v tls TLS connection
763  * @v digest Handshake digest algorithm
764  * @ret rc Return status code
765  */
766 static int tls_select_handshake ( struct tls_connection *tls,
767  struct digest_algorithm *digest ) {
768 
769  /* Clear existing handshake digest */
770  tls_clear_handshake ( tls );
771 
772  /* Allocate and initialise context */
773  tls->handshake_ctx = malloc ( digest->ctxsize );
774  if ( ! tls->handshake_ctx )
775  return -ENOMEM;
776  tls->handshake_digest = digest;
777  digest_init ( digest, tls->handshake_ctx );
778 
779  return 0;
780 }
781 
782 /**
783  * Add handshake record to verification hash
784  *
785  * @v tls TLS connection
786  * @v data Handshake record
787  * @v len Length of handshake record
788  * @ret rc Return status code
789  */
790 static int tls_add_handshake ( struct tls_connection *tls,
791  const void *data, size_t len ) {
792  struct digest_algorithm *digest = tls->handshake_digest;
793 
794  digest_update ( digest, tls->handshake_ctx, data, len );
795  return 0;
796 }
797 
798 /**
799  * Calculate handshake verification hash
800  *
801  * @v tls TLS connection
802  * @v out Output buffer
803  *
804  * Calculates the digest over all handshake messages seen so far.
805  */
806 static void tls_verify_handshake ( struct tls_connection *tls, void *out ) {
807  struct digest_algorithm *digest = tls->handshake_digest;
808  uint8_t ctx[ digest->ctxsize ];
809 
810  memcpy ( ctx, tls->handshake_ctx, sizeof ( ctx ) );
811  digest_final ( digest, ctx, out );
812 }
813 
814 /******************************************************************************
815  *
816  * Cipher suite management
817  *
818  ******************************************************************************
819  */
820 
821 /** Null cipher suite */
824  .pubkey = &pubkey_null,
825  .cipher = &cipher_null,
826  .digest = &digest_null,
827 };
828 
829 /** Number of supported cipher suites */
830 #define TLS_NUM_CIPHER_SUITES table_num_entries ( TLS_CIPHER_SUITES )
831 
832 /**
833  * Identify cipher suite
834  *
835  * @v cipher_suite Cipher suite specification
836  * @ret suite Cipher suite, or NULL
837  */
838 static struct tls_cipher_suite *
839 tls_find_cipher_suite ( unsigned int cipher_suite ) {
840  struct tls_cipher_suite *suite;
841 
842  /* Identify cipher suite */
844  if ( suite->code == cipher_suite )
845  return suite;
846  }
847 
848  return NULL;
849 }
850 
851 /**
852  * Clear cipher suite
853  *
854  * @v cipherspec TLS cipher specification
855  */
856 static void tls_clear_cipher ( struct tls_connection *tls __unused,
857  struct tls_cipherspec *cipherspec ) {
858 
859  free ( cipherspec->dynamic );
860  memset ( cipherspec, 0, sizeof ( *cipherspec ) );
861  cipherspec->suite = &tls_cipher_suite_null;
862 }
863 
864 /**
865  * Set cipher suite
866  *
867  * @v tls TLS connection
868  * @v cipherspec TLS cipher specification
869  * @v suite Cipher suite
870  * @ret rc Return status code
871  */
872 static int tls_set_cipher ( struct tls_connection *tls,
873  struct tls_cipherspec *cipherspec,
874  struct tls_cipher_suite *suite ) {
875  struct cipher_algorithm *cipher = suite->cipher;
876  size_t total;
877  void *dynamic;
878 
879  /* Clear out old cipher contents, if any */
880  tls_clear_cipher ( tls, cipherspec );
881 
882  /* Allocate dynamic storage */
883  total = ( cipher->ctxsize + suite->mac_len + suite->fixed_iv_len );
884  dynamic = zalloc ( total );
885  if ( ! dynamic ) {
886  DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
887  "context\n", tls, total );
888  return -ENOMEM_CONTEXT;
889  }
890 
891  /* Assign storage */
892  cipherspec->dynamic = dynamic;
893  cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
894  cipherspec->mac_secret = dynamic; dynamic += suite->mac_len;
895  cipherspec->fixed_iv = dynamic; dynamic += suite->fixed_iv_len;
896  assert ( ( cipherspec->dynamic + total ) == dynamic );
897 
898  /* Store parameters */
899  cipherspec->suite = suite;
900 
901  return 0;
902 }
903 
904 /**
905  * Select next cipher suite
906  *
907  * @v tls TLS connection
908  * @v cipher_suite Cipher suite specification
909  * @ret rc Return status code
910  */
911 static int tls_select_cipher ( struct tls_connection *tls,
912  unsigned int cipher_suite ) {
913  struct tls_cipher_suite *suite;
914  struct digest_algorithm *digest;
915  int rc;
916 
917  /* Identify cipher suite */
918  suite = tls_find_cipher_suite ( cipher_suite );
919  if ( ! suite ) {
920  DBGC ( tls, "TLS %p does not support cipher %04x\n",
921  tls, ntohs ( cipher_suite ) );
922  return -ENOTSUP_CIPHER;
923  }
924 
925  /* Set handshake digest algorithm */
926  digest = ( tls_version ( tls, TLS_VERSION_TLS_1_2 ) ?
927  suite->handshake : &md5_sha1_algorithm );
928  if ( ( rc = tls_select_handshake ( tls, digest ) ) != 0 )
929  return rc;
930 
931  /* Set ciphers */
932  if ( ( rc = tls_set_cipher ( tls, &tls->tx.cipherspec.pending,
933  suite ) ) != 0 )
934  return rc;
935  if ( ( rc = tls_set_cipher ( tls, &tls->rx.cipherspec.pending,
936  suite ) ) != 0 )
937  return rc;
938 
939  DBGC ( tls, "TLS %p selected %s-%s-%s-%d-%s\n", tls,
940  suite->exchange->name, suite->pubkey->name,
941  suite->cipher->name, ( suite->key_len * 8 ),
942  suite->digest->name );
943 
944  return 0;
945 }
946 
947 /**
948  * Activate next cipher suite
949  *
950  * @v tls TLS connection
951  * @v pair Cipher specification pair
952  * @ret rc Return status code
953  */
954 static int tls_change_cipher ( struct tls_connection *tls,
955  struct tls_cipherspec_pair *pair ) {
956 
957  /* Sanity check */
958  if ( pair->pending.suite == &tls_cipher_suite_null ) {
959  DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
960  return -ENOTSUP_NULL;
961  }
962 
963  tls_clear_cipher ( tls, &pair->active );
964  memswap ( &pair->active, &pair->pending, sizeof ( pair->active ) );
965  return 0;
966 }
967 
968 /******************************************************************************
969  *
970  * Signature and hash algorithms
971  *
972  ******************************************************************************
973  */
974 
975 /** Number of supported signature and hash algorithms */
976 #define TLS_NUM_SIG_HASH_ALGORITHMS \
977  table_num_entries ( TLS_SIG_HASH_ALGORITHMS )
978 
979 /**
980  * Find TLS signature and hash algorithm
981  *
982  * @v pubkey Public-key algorithm
983  * @v digest Digest algorithm
984  * @ret sig_hash Signature and hash algorithm, or NULL
985  */
986 static struct tls_signature_hash_algorithm *
988  struct digest_algorithm *digest ) {
989  struct tls_signature_hash_algorithm *sig_hash;
990 
991  /* Identify signature and hash algorithm */
993  if ( ( sig_hash->pubkey == pubkey ) &&
994  ( sig_hash->digest == digest ) ) {
995  return sig_hash;
996  }
997  }
998 
999  return NULL;
1000 }
1001 
1002 /**
1003  * Find TLS signature algorithm
1004  *
1005  * @v code Signature and hash algorithm identifier
1006  * @ret pubkey Public key algorithm, or NULL
1007  */
1008 static struct pubkey_algorithm *
1010  struct tls_signature_hash_algorithm *sig_hash;
1011 
1012  /* Identify signature and hash algorithm */
1014  if ( sig_hash->code.signature == code.signature )
1015  return sig_hash->pubkey;
1016  }
1017 
1018  return NULL;
1019 }
1020 
1021 /**
1022  * Find TLS hash algorithm
1023  *
1024  * @v code Signature and hash algorithm identifier
1025  * @ret digest Digest algorithm, or NULL
1026  */
1027 static struct digest_algorithm *
1029  struct tls_signature_hash_algorithm *sig_hash;
1030 
1031  /* Identify signature and hash algorithm */
1033  if ( sig_hash->code.hash == code.hash )
1034  return sig_hash->digest;
1035  }
1036 
1037  return NULL;
1038 }
1039 
1040 /******************************************************************************
1041  *
1042  * Ephemeral Elliptic Curve Diffie-Hellman key exchange
1043  *
1044  ******************************************************************************
1045  */
1046 
1047 /** Number of supported named curves */
1048 #define TLS_NUM_NAMED_CURVES table_num_entries ( TLS_NAMED_CURVES )
1049 
1050 /**
1051  * Identify named curve
1052  *
1053  * @v named_curve Named curve specification
1054  * @ret curve Named curve, or NULL
1055  */
1056 static struct tls_named_curve *
1057 tls_find_named_curve ( unsigned int named_curve ) {
1058  struct tls_named_curve *curve;
1059 
1060  /* Identify named curve */
1062  if ( curve->code == named_curve )
1063  return curve;
1064  }
1065 
1066  return NULL;
1067 }
1068 
1069 /******************************************************************************
1070  *
1071  * Record handling
1072  *
1073  ******************************************************************************
1074  */
1075 
1076 /**
1077  * Resume TX state machine
1078  *
1079  * @v tls TLS connection
1080  */
1081 static void tls_tx_resume ( struct tls_connection *tls ) {
1082  process_add ( &tls->tx.process );
1083 }
1084 
1085 /**
1086  * Resume TX state machine for all connections within a session
1087  *
1088  * @v session TLS session
1089  */
1090 static void tls_tx_resume_all ( struct tls_session *session ) {
1091  struct tls_connection *tls;
1092 
1093  list_for_each_entry ( tls, &session->conn, list )
1094  tls_tx_resume ( tls );
1095 }
1096 
1097 /**
1098  * Restart negotiation
1099  *
1100  * @v tls TLS connection
1101  */
1102 static void tls_restart ( struct tls_connection *tls ) {
1103 
1104  /* Sanity check */
1105  assert ( ! tls->tx.pending );
1106  assert ( ! is_pending ( &tls->client.negotiation ) );
1107  assert ( ! is_pending ( &tls->server.negotiation ) );
1108  assert ( ! is_pending ( &tls->server.validation ) );
1109 
1110  /* (Re)start negotiation */
1112  tls_tx_resume ( tls );
1113  pending_get ( &tls->client.negotiation );
1114  pending_get ( &tls->server.negotiation );
1115 }
1116 
1117 /**
1118  * Transmit Handshake record
1119  *
1120  * @v tls TLS connection
1121  * @v data Plaintext record
1122  * @v len Length of plaintext record
1123  * @ret rc Return status code
1124  */
1125 static int tls_send_handshake ( struct tls_connection *tls,
1126  const void *data, size_t len ) {
1127 
1128  /* Add to handshake digest */
1129  tls_add_handshake ( tls, data, len );
1130 
1131  /* Send record */
1132  return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
1133 }
1134 
1135 /**
1136  * Digest or transmit Client Hello record
1137  *
1138  * @v tls TLS connection
1139  * @v action Action to take on Client Hello record
1140  * @ret rc Return status code
1141  */
1142 static int tls_client_hello ( struct tls_connection *tls,
1143  int ( * action ) ( struct tls_connection *tls,
1144  const void *data,
1145  size_t len ) ) {
1146  struct tls_session *session = tls->session;
1147  size_t name_len = strlen ( session->name );
1148  struct {
1149  uint16_t type;
1150  uint16_t len;
1151  struct {
1152  uint16_t len;
1153  struct {
1154  uint8_t type;
1155  uint16_t len;
1156  uint8_t name[name_len];
1157  } __attribute__ (( packed )) list[1];
1158  } __attribute__ (( packed )) data;
1159  } __attribute__ (( packed )) *server_name_ext;
1160  struct {
1161  uint16_t type;
1162  uint16_t len;
1163  struct {
1164  uint8_t max;
1165  } __attribute__ (( packed )) data;
1166  } __attribute__ (( packed )) *max_fragment_length_ext;
1167  struct {
1168  uint16_t type;
1169  uint16_t len;
1170  struct {
1171  uint16_t len;
1172  struct tls_signature_hash_id
1174  } __attribute__ (( packed )) data;
1175  } __attribute__ (( packed )) *signature_algorithms_ext;
1176  struct {
1177  uint16_t type;
1178  uint16_t len;
1179  struct {
1180  uint8_t len;
1182  sizeof ( tls->verify.client ) :0 ];
1183  } __attribute__ (( packed )) data;
1184  } __attribute__ (( packed )) *renegotiation_info_ext;
1185  struct {
1186  uint16_t type;
1187  uint16_t len;
1188  struct {
1189  uint8_t data[session->ticket_len];
1190  } __attribute__ (( packed )) data;
1191  } __attribute__ (( packed )) *session_ticket_ext;
1192  struct {
1193  uint16_t type;
1194  uint16_t len;
1195  struct {
1196  uint16_t len;
1198  } __attribute__ (( packed )) data;
1199  } __attribute__ (( packed )) *named_curve_ext;
1200  struct {
1201  typeof ( *server_name_ext ) server_name;
1202  typeof ( *max_fragment_length_ext ) max_fragment_length;
1203  typeof ( *signature_algorithms_ext ) signature_algorithms;
1204  typeof ( *renegotiation_info_ext ) renegotiation_info;
1205  typeof ( *session_ticket_ext ) session_ticket;
1206  typeof ( *named_curve_ext )
1207  named_curve[TLS_NUM_NAMED_CURVES ? 1 : 0];
1208  } __attribute__ (( packed )) *extensions;
1209  struct {
1210  uint32_t type_length;
1211  uint16_t version;
1212  uint8_t random[32];
1213  uint8_t session_id_len;
1214  uint8_t session_id[tls->session_id_len];
1215  uint16_t cipher_suite_len;
1216  uint16_t cipher_suites[TLS_NUM_CIPHER_SUITES];
1217  uint8_t compression_methods_len;
1218  uint8_t compression_methods[1];
1219  uint16_t extensions_len;
1220  typeof ( *extensions ) extensions;
1221  } __attribute__ (( packed )) hello;
1222  struct tls_cipher_suite *suite;
1223  struct tls_signature_hash_algorithm *sighash;
1224  struct tls_named_curve *curve;
1225  unsigned int i;
1226 
1227  /* Construct record */
1228  memset ( &hello, 0, sizeof ( hello ) );
1229  hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
1230  htonl ( sizeof ( hello ) -
1231  sizeof ( hello.type_length ) ) );
1232  hello.version = htons ( TLS_VERSION_MAX );
1233  memcpy ( &hello.random, &tls->client.random, sizeof ( hello.random ) );
1234  hello.session_id_len = tls->session_id_len;
1235  memcpy ( hello.session_id, tls->session_id,
1236  sizeof ( hello.session_id ) );
1237  hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
1238  i = 0 ; for_each_table_entry ( suite, TLS_CIPHER_SUITES )
1239  hello.cipher_suites[i++] = suite->code;
1240  hello.compression_methods_len = sizeof ( hello.compression_methods );
1241  hello.extensions_len = htons ( sizeof ( hello.extensions ) );
1242  extensions = &hello.extensions;
1243 
1244  /* Construct server name extension */
1245  server_name_ext = &extensions->server_name;
1246  server_name_ext->type = htons ( TLS_SERVER_NAME );
1247  server_name_ext->len = htons ( sizeof ( server_name_ext->data ) );
1248  server_name_ext->data.len
1249  = htons ( sizeof ( server_name_ext->data.list ) );
1250  server_name_ext->data.list[0].type = TLS_SERVER_NAME_HOST_NAME;
1251  server_name_ext->data.list[0].len
1252  = htons ( sizeof ( server_name_ext->data.list[0].name ) );
1253  memcpy ( server_name_ext->data.list[0].name, session->name,
1254  sizeof ( server_name_ext->data.list[0].name ) );
1255 
1256  /* Construct maximum fragment length extension */
1257  max_fragment_length_ext = &extensions->max_fragment_length;
1258  max_fragment_length_ext->type = htons ( TLS_MAX_FRAGMENT_LENGTH );
1259  max_fragment_length_ext->len
1260  = htons ( sizeof ( max_fragment_length_ext->data ) );
1261  max_fragment_length_ext->data.max = TLS_MAX_FRAGMENT_LENGTH_4096;
1262 
1263  /* Construct supported signature algorithms extension */
1264  signature_algorithms_ext = &extensions->signature_algorithms;
1265  signature_algorithms_ext->type = htons ( TLS_SIGNATURE_ALGORITHMS );
1266  signature_algorithms_ext->len
1267  = htons ( sizeof ( signature_algorithms_ext->data ) );
1268  signature_algorithms_ext->data.len
1269  = htons ( sizeof ( signature_algorithms_ext->data.code ) );
1270  i = 0 ; for_each_table_entry ( sighash, TLS_SIG_HASH_ALGORITHMS )
1271  signature_algorithms_ext->data.code[i++] = sighash->code;
1272 
1273  /* Construct renegotiation information extension */
1274  renegotiation_info_ext = &extensions->renegotiation_info;
1275  renegotiation_info_ext->type = htons ( TLS_RENEGOTIATION_INFO );
1276  renegotiation_info_ext->len
1277  = htons ( sizeof ( renegotiation_info_ext->data ) );
1278  renegotiation_info_ext->data.len
1279  = sizeof ( renegotiation_info_ext->data.data );
1280  memcpy ( renegotiation_info_ext->data.data, tls->verify.client,
1281  sizeof ( renegotiation_info_ext->data.data ) );
1282 
1283  /* Construct session ticket extension */
1284  session_ticket_ext = &extensions->session_ticket;
1285  session_ticket_ext->type = htons ( TLS_SESSION_TICKET );
1286  session_ticket_ext->len
1287  = htons ( sizeof ( session_ticket_ext->data ) );
1288  memcpy ( session_ticket_ext->data.data, session->ticket,
1289  sizeof ( session_ticket_ext->data.data ) );
1290 
1291  /* Construct named curves extension, if applicable */
1292  if ( sizeof ( extensions->named_curve ) ) {
1293  named_curve_ext = &extensions->named_curve[0];
1294  named_curve_ext->type = htons ( TLS_NAMED_CURVE );
1295  named_curve_ext->len
1296  = htons ( sizeof ( named_curve_ext->data ) );
1297  named_curve_ext->data.len
1298  = htons ( sizeof ( named_curve_ext->data.code ) );
1300  named_curve_ext->data.code[i++] = curve->code;
1301  }
1302 
1303  return action ( tls, &hello, sizeof ( hello ) );
1304 }
1305 
1306 /**
1307  * Transmit Client Hello record
1308  *
1309  * @v tls TLS connection
1310  * @ret rc Return status code
1311  */
1312 static int tls_send_client_hello ( struct tls_connection *tls ) {
1313 
1314  return tls_client_hello ( tls, tls_send_handshake );
1315 }
1316 
1317 /**
1318  * Transmit Certificate record
1319  *
1320  * @v tls TLS connection
1321  * @ret rc Return status code
1322  */
1323 static int tls_send_certificate ( struct tls_connection *tls ) {
1324  struct {
1325  tls24_t length;
1326  uint8_t data[0];
1327  } __attribute__ (( packed )) *certificate;
1328  struct {
1329  uint32_t type_length;
1330  tls24_t length;
1331  typeof ( *certificate ) certificates[0];
1332  } __attribute__ (( packed )) *certificates;
1333  struct x509_link *link;
1334  struct x509_certificate *cert;
1335  size_t len;
1336  int rc;
1337 
1338  /* Calculate length of client certificates */
1339  len = 0;
1340  list_for_each_entry ( link, &tls->client.chain->links, list ) {
1341  cert = link->cert;
1342  len += ( sizeof ( *certificate ) + cert->raw.len );
1343  DBGC ( tls, "TLS %p sending client certificate %s\n",
1344  tls, x509_name ( cert ) );
1345  }
1346 
1347  /* Allocate storage for Certificate record (which may be too
1348  * large for the stack).
1349  */
1350  certificates = zalloc ( sizeof ( *certificates ) + len );
1351  if ( ! certificates )
1352  return -ENOMEM_CERTIFICATE;
1353 
1354  /* Populate record */
1355  certificates->type_length =
1357  htonl ( sizeof ( *certificates ) + len -
1358  sizeof ( certificates->type_length ) ) );
1359  tls_set_uint24 ( &certificates->length, len );
1360  certificate = &certificates->certificates[0];
1361  list_for_each_entry ( link, &tls->client.chain->links, list ) {
1362  cert = link->cert;
1363  tls_set_uint24 ( &certificate->length, cert->raw.len );
1364  memcpy ( certificate->data, cert->raw.data, cert->raw.len );
1365  certificate = ( ( ( void * ) certificate->data ) +
1366  cert->raw.len );
1367  }
1368 
1369  /* Transmit record */
1370  rc = tls_send_handshake ( tls, certificates,
1371  ( sizeof ( *certificates ) + len ) );
1372 
1373  /* Free record */
1374  free ( certificates );
1375 
1376  return rc;
1377 }
1378 
1379 /**
1380  * Transmit Client Key Exchange record using public key exchange
1381  *
1382  * @v tls TLS connection
1383  * @ret rc Return status code
1384  */
1386  struct tls_cipherspec *cipherspec = &tls->tx.cipherspec.pending;
1387  struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
1388  size_t max_len = pubkey_max_len ( pubkey, &tls->server.key );
1389  struct {
1390  uint16_t version;
1391  uint8_t random[46];
1392  } __attribute__ (( packed )) pre_master_secret;
1393  struct {
1394  uint32_t type_length;
1395  uint16_t encrypted_pre_master_secret_len;
1396  uint8_t encrypted_pre_master_secret[max_len];
1397  } __attribute__ (( packed )) key_xchg;
1398  size_t unused;
1399  int len;
1400  int rc;
1401 
1402  /* Generate pre-master secret */
1403  pre_master_secret.version = htons ( TLS_VERSION_MAX );
1404  if ( ( rc = tls_generate_random ( tls, &pre_master_secret.random,
1405  ( sizeof ( pre_master_secret.random ) ) ) ) != 0 ) {
1406  return rc;
1407  }
1408 
1409  /* Generate master secret */
1410  tls_generate_master_secret ( tls, &pre_master_secret,
1411  sizeof ( pre_master_secret ) );
1412 
1413  /* Encrypt pre-master secret using server's public key */
1414  memset ( &key_xchg, 0, sizeof ( key_xchg ) );
1415  len = pubkey_encrypt ( pubkey, &tls->server.key, &pre_master_secret,
1416  sizeof ( pre_master_secret ),
1417  key_xchg.encrypted_pre_master_secret );
1418  if ( len < 0 ) {
1419  rc = len;
1420  DBGC ( tls, "TLS %p could not encrypt pre-master secret: %s\n",
1421  tls, strerror ( rc ) );
1422  return rc;
1423  }
1424  unused = ( max_len - len );
1425  key_xchg.type_length =
1427  htonl ( sizeof ( key_xchg ) -
1428  sizeof ( key_xchg.type_length ) - unused ) );
1429  key_xchg.encrypted_pre_master_secret_len =
1430  htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) -
1431  unused );
1432 
1433  return tls_send_handshake ( tls, &key_xchg,
1434  ( sizeof ( key_xchg ) - unused ) );
1435 }
1436 
1437 /** Public key exchange algorithm */
1439  .name = "pubkey",
1441 };
1442 
1443 /**
1444  * Verify Diffie-Hellman parameter signature
1445  *
1446  * @v tls TLS connection
1447  * @v param_len Diffie-Hellman parameter length
1448  * @ret rc Return status code
1449  */
1450 static int tls_verify_dh_params ( struct tls_connection *tls,
1451  size_t param_len ) {
1452  struct tls_cipherspec *cipherspec = &tls->tx.cipherspec.pending;
1453  struct pubkey_algorithm *pubkey;
1454  struct digest_algorithm *digest;
1455  int use_sig_hash = tls_version ( tls, TLS_VERSION_TLS_1_2 );
1456  const struct {
1457  struct tls_signature_hash_id sig_hash[use_sig_hash];
1458  uint16_t signature_len;
1459  uint8_t signature[0];
1460  } __attribute__ (( packed )) *sig;
1461  const void *data;
1462  size_t remaining;
1463  int rc;
1464 
1465  /* Signature follows parameters */
1466  assert ( param_len <= tls->server.exchange_len );
1467  data = ( tls->server.exchange + param_len );
1468  remaining = ( tls->server.exchange_len - param_len );
1469 
1470  /* Parse signature from ServerKeyExchange */
1471  sig = data;
1472  if ( ( sizeof ( *sig ) > remaining ) ||
1473  ( ntohs ( sig->signature_len ) > ( remaining -
1474  sizeof ( *sig ) ) ) ) {
1475  DBGC ( tls, "TLS %p received underlength ServerKeyExchange\n",
1476  tls );
1477  DBGC_HDA ( tls, 0, tls->server.exchange,
1478  tls->server.exchange_len );
1479  return -EINVAL_KEY_EXCHANGE;
1480  }
1481 
1482  /* Identify signature and hash algorithm */
1483  if ( use_sig_hash ) {
1484  pubkey = tls_signature_hash_pubkey ( sig->sig_hash[0] );
1485  digest = tls_signature_hash_digest ( sig->sig_hash[0] );
1486  if ( ( ! pubkey ) || ( ! digest ) ) {
1487  DBGC ( tls, "TLS %p ServerKeyExchange unsupported "
1488  "signature and hash algorithm\n", tls );
1489  return -ENOTSUP_SIG_HASH;
1490  }
1491  if ( pubkey != cipherspec->suite->pubkey ) {
1492  DBGC ( tls, "TLS %p ServerKeyExchange incorrect "
1493  "signature algorithm %s (expected %s)\n", tls,
1494  pubkey->name, cipherspec->suite->pubkey->name );
1495  return -EPERM_KEY_EXCHANGE;
1496  }
1497  } else {
1498  pubkey = cipherspec->suite->pubkey;
1499  digest = &md5_sha1_algorithm;
1500  }
1501 
1502  /* Verify signature */
1503  {
1504  const void *signature = sig->signature;
1505  size_t signature_len = ntohs ( sig->signature_len );
1506  uint8_t ctx[digest->ctxsize];
1507  uint8_t hash[digest->digestsize];
1508 
1509  /* Calculate digest */
1510  digest_init ( digest, ctx );
1511  digest_update ( digest, ctx, &tls->client.random,
1512  sizeof ( tls->client.random ) );
1513  digest_update ( digest, ctx, tls->server.random,
1514  sizeof ( tls->server.random ) );
1515  digest_update ( digest, ctx, tls->server.exchange, param_len );
1516  digest_final ( digest, ctx, hash );
1517 
1518  /* Verify signature */
1519  if ( ( rc = pubkey_verify ( pubkey, &tls->server.key,
1520  digest, hash, signature,
1521  signature_len ) ) != 0 ) {
1522  DBGC ( tls, "TLS %p ServerKeyExchange failed "
1523  "verification\n", tls );
1524  DBGC_HDA ( tls, 0, tls->server.exchange,
1525  tls->server.exchange_len );
1526  return -EPERM_KEY_EXCHANGE;
1527  }
1528  }
1529 
1530  return 0;
1531 }
1532 
1533 /**
1534  * Transmit Client Key Exchange record using DHE key exchange
1535  *
1536  * @v tls TLS connection
1537  * @ret rc Return status code
1538  */
1540  uint8_t private[ sizeof ( tls->client.random.random ) ];
1541  const struct {
1542  uint16_t len;
1543  uint8_t data[0];
1544  } __attribute__ (( packed )) *dh_val[3];
1545  const void *data;
1546  size_t remaining;
1547  size_t frag_len;
1548  size_t param_len;
1549  unsigned int i;
1550  int rc;
1551 
1552  /* Parse ServerKeyExchange */
1553  data = tls->server.exchange;
1554  remaining = tls->server.exchange_len;
1555  for ( i = 0 ; i < ( sizeof ( dh_val ) / sizeof ( dh_val[0] ) ) ; i++ ){
1556  dh_val[i] = data;
1557  if ( ( sizeof ( *dh_val[i] ) > remaining ) ||
1558  ( ntohs ( dh_val[i]->len ) > ( remaining -
1559  sizeof ( *dh_val[i] ) ) )){
1560  DBGC ( tls, "TLS %p received underlength "
1561  "ServerKeyExchange\n", tls );
1562  DBGC_HDA ( tls, 0, tls->server.exchange,
1563  tls->server.exchange_len );
1565  goto err_header;
1566  }
1567  frag_len = ( sizeof ( *dh_val[i] ) + ntohs ( dh_val[i]->len ));
1568  data += frag_len;
1569  remaining -= frag_len;
1570  }
1571  param_len = ( tls->server.exchange_len - remaining );
1572 
1573  /* Verify parameter signature */
1574  if ( ( rc = tls_verify_dh_params ( tls, param_len ) ) != 0 )
1575  goto err_verify;
1576 
1577  /* Generate Diffie-Hellman private key */
1578  if ( ( rc = tls_generate_random ( tls, private,
1579  sizeof ( private ) ) ) != 0 ) {
1580  goto err_random;
1581  }
1582 
1583  /* Construct pre-master secret and ClientKeyExchange record */
1584  {
1585  typeof ( dh_val[0] ) dh_p = dh_val[0];
1586  typeof ( dh_val[1] ) dh_g = dh_val[1];
1587  typeof ( dh_val[2] ) dh_ys = dh_val[2];
1588  size_t len = ntohs ( dh_p->len );
1589  struct {
1590  uint32_t type_length;
1591  uint16_t dh_xs_len;
1592  uint8_t dh_xs[len];
1593  } __attribute__ (( packed )) *key_xchg;
1594  struct {
1595  uint8_t pre_master_secret[len];
1596  typeof ( *key_xchg ) key_xchg;
1597  } *dynamic;
1598  uint8_t *pre_master_secret;
1599 
1600  /* Allocate space */
1601  dynamic = malloc ( sizeof ( *dynamic ) );
1602  if ( ! dynamic ) {
1603  rc = -ENOMEM;
1604  goto err_alloc;
1605  }
1606  pre_master_secret = dynamic->pre_master_secret;
1607  key_xchg = &dynamic->key_xchg;
1608  key_xchg->type_length =
1610  htonl ( sizeof ( *key_xchg ) -
1611  sizeof ( key_xchg->type_length ) ) );
1612  key_xchg->dh_xs_len = htons ( len );
1613 
1614  /* Calculate pre-master secret and client public value */
1615  if ( ( rc = dhe_key ( dh_p->data, len,
1616  dh_g->data, ntohs ( dh_g->len ),
1617  dh_ys->data, ntohs ( dh_ys->len ),
1618  private, sizeof ( private ),
1619  key_xchg->dh_xs,
1620  pre_master_secret ) ) != 0 ) {
1621  DBGC ( tls, "TLS %p could not calculate DHE key: %s\n",
1622  tls, strerror ( rc ) );
1623  goto err_dhe_key;
1624  }
1625 
1626  /* Strip leading zeroes from pre-master secret */
1627  while ( len && ( ! *pre_master_secret ) ) {
1628  pre_master_secret++;
1629  len--;
1630  }
1631 
1632  /* Generate master secret */
1633  tls_generate_master_secret ( tls, pre_master_secret, len );
1634 
1635  /* Transmit Client Key Exchange record */
1636  if ( ( rc = tls_send_handshake ( tls, key_xchg,
1637  sizeof ( *key_xchg ) ) ) !=0){
1638  goto err_send_handshake;
1639  }
1640 
1641  err_send_handshake:
1642  err_dhe_key:
1643  free ( dynamic );
1644  }
1645  err_alloc:
1646  err_random:
1647  err_verify:
1648  err_header:
1649  return rc;
1650 }
1651 
1652 /** Ephemeral Diffie-Hellman key exchange algorithm */
1654  .name = "dhe",
1656 };
1657 
1658 /**
1659  * Transmit Client Key Exchange record using ECDHE key exchange
1660  *
1661  * @v tls TLS connection
1662  * @ret rc Return status code
1663  */
1665  struct tls_named_curve *curve;
1666  const struct {
1667  uint8_t curve_type;
1668  uint16_t named_curve;
1669  uint8_t public_len;
1670  uint8_t public[0];
1671  } __attribute__ (( packed )) *ecdh;
1672  size_t param_len;
1673  int rc;
1674 
1675  /* Parse ServerKeyExchange record */
1676  ecdh = tls->server.exchange;
1677  if ( ( sizeof ( *ecdh ) > tls->server.exchange_len ) ||
1678  ( ecdh->public_len > ( tls->server.exchange_len -
1679  sizeof ( *ecdh ) ) ) ) {
1680  DBGC ( tls, "TLS %p received underlength ServerKeyExchange\n",
1681  tls );
1682  DBGC_HDA ( tls, 0, tls->server.exchange,
1683  tls->server.exchange_len );
1684  return -EINVAL_KEY_EXCHANGE;
1685  }
1686  param_len = ( sizeof ( *ecdh ) + ecdh->public_len );
1687 
1688  /* Verify parameter signature */
1689  if ( ( rc = tls_verify_dh_params ( tls, param_len ) ) != 0 )
1690  return rc;
1691 
1692  /* Identify named curve */
1693  if ( ecdh->curve_type != TLS_NAMED_CURVE_TYPE ) {
1694  DBGC ( tls, "TLS %p unsupported curve type %d\n",
1695  tls, ecdh->curve_type );
1696  DBGC_HDA ( tls, 0, tls->server.exchange,
1697  tls->server.exchange_len );
1698  return -ENOTSUP_CURVE;
1699  }
1700  curve = tls_find_named_curve ( ecdh->named_curve );
1701  if ( ! curve ) {
1702  DBGC ( tls, "TLS %p unsupported named curve %d\n",
1703  tls, ntohs ( ecdh->named_curve ) );
1704  DBGC_HDA ( tls, 0, tls->server.exchange,
1705  tls->server.exchange_len );
1706  return -ENOTSUP_CURVE;
1707  }
1708 
1709  /* Check key length */
1710  if ( ecdh->public_len != curve->curve->keysize ) {
1711  DBGC ( tls, "TLS %p invalid %s key\n",
1712  tls, curve->curve->name );
1713  DBGC_HDA ( tls, 0, tls->server.exchange,
1714  tls->server.exchange_len );
1715  return -EINVAL_KEY_EXCHANGE;
1716  }
1717 
1718  /* Construct pre-master secret and ClientKeyExchange record */
1719  {
1720  size_t len = curve->curve->keysize;
1721  uint8_t private[len];
1722  uint8_t pre_master_secret[len];
1723  struct {
1724  uint32_t type_length;
1725  uint8_t public_len;
1726  uint8_t public[len];
1727  } __attribute__ (( packed )) key_xchg;
1728 
1729  /* Generate ephemeral private key */
1730  if ( ( rc = tls_generate_random ( tls, private,
1731  sizeof ( private ) ) ) != 0){
1732  return rc;
1733  }
1734 
1735  /* Calculate pre-master secret */
1736  if ( ( rc = elliptic_multiply ( curve->curve,
1737  ecdh->public, private,
1738  pre_master_secret ) ) != 0 ) {
1739  DBGC ( tls, "TLS %p could not exchange ECDHE key: %s\n",
1740  tls, strerror ( rc ) );
1741  return rc;
1742  }
1743 
1744  /* Generate master secret */
1745  tls_generate_master_secret ( tls, pre_master_secret, len );
1746 
1747  /* Generate Client Key Exchange record */
1748  key_xchg.type_length =
1750  htonl ( sizeof ( key_xchg ) -
1751  sizeof ( key_xchg.type_length ) ) );
1752  key_xchg.public_len = len;
1753  if ( ( rc = elliptic_multiply ( curve->curve, NULL, private,
1754  key_xchg.public ) ) != 0 ) {
1755  DBGC ( tls, "TLS %p could not generate ECDHE key: %s\n",
1756  tls, strerror ( rc ) );
1757  return rc;
1758  }
1759 
1760  /* Transmit Client Key Exchange record */
1761  if ( ( rc = tls_send_handshake ( tls, &key_xchg,
1762  sizeof ( key_xchg ) ) ) !=0){
1763  return rc;
1764  }
1765  }
1766 
1767  return 0;
1768 }
1769 
1770 /** Ephemeral Elliptic Curve Diffie-Hellman key exchange algorithm */
1772  .name = "ecdhe",
1774 };
1775 
1776 /**
1777  * Transmit Client Key Exchange record
1778  *
1779  * @v tls TLS connection
1780  * @ret rc Return status code
1781  */
1782 static int tls_send_client_key_exchange ( struct tls_connection *tls ) {
1783  struct tls_cipherspec *cipherspec = &tls->tx.cipherspec.pending;
1784  struct tls_cipher_suite *suite = cipherspec->suite;
1785  int rc;
1786 
1787  /* Transmit Client Key Exchange record via key exchange algorithm */
1788  if ( ( rc = suite->exchange->exchange ( tls ) ) != 0 ) {
1789  DBGC ( tls, "TLS %p could not exchange keys: %s\n",
1790  tls, strerror ( rc ) );
1791  return rc;
1792  }
1793 
1794  /* Generate keys from master secret */
1795  if ( ( rc = tls_generate_keys ( tls ) ) != 0 ) {
1796  DBGC ( tls, "TLS %p could not generate keys: %s\n",
1797  tls, strerror ( rc ) );
1798  return rc;
1799  }
1800 
1801  return 0;
1802 }
1803 
1804 /**
1805  * Transmit Certificate Verify record
1806  *
1807  * @v tls TLS connection
1808  * @ret rc Return status code
1809  */
1810 static int tls_send_certificate_verify ( struct tls_connection *tls ) {
1811  struct digest_algorithm *digest = tls->handshake_digest;
1812  struct x509_certificate *cert = x509_first ( tls->client.chain );
1813  struct pubkey_algorithm *pubkey = cert->signature_algorithm->pubkey;
1814  struct asn1_cursor *key = privkey_cursor ( tls->client.key );
1815  uint8_t digest_out[ digest->digestsize ];
1816  struct tls_signature_hash_algorithm *sig_hash = NULL;
1817  int rc;
1818 
1819  /* Generate digest to be signed */
1820  tls_verify_handshake ( tls, digest_out );
1821 
1822  /* TLSv1.2 and later use explicit algorithm identifiers */
1823  if ( tls_version ( tls, TLS_VERSION_TLS_1_2 ) ) {
1824  sig_hash = tls_signature_hash_algorithm ( pubkey, digest );
1825  if ( ! sig_hash ) {
1826  DBGC ( tls, "TLS %p could not identify (%s,%s) "
1827  "signature and hash algorithm\n", tls,
1828  pubkey->name, digest->name );
1829  rc = -ENOTSUP_SIG_HASH;
1830  goto err_sig_hash;
1831  }
1832  }
1833 
1834  /* Generate and transmit record */
1835  {
1836  size_t max_len = pubkey_max_len ( pubkey, key );
1837  int use_sig_hash = ( ( sig_hash == NULL ) ? 0 : 1 );
1838  struct {
1839  uint32_t type_length;
1840  struct tls_signature_hash_id sig_hash[use_sig_hash];
1841  uint16_t signature_len;
1842  uint8_t signature[max_len];
1843  } __attribute__ (( packed )) certificate_verify;
1844  size_t unused;
1845  int len;
1846 
1847  /* Sign digest */
1848  len = pubkey_sign ( pubkey, key, digest, digest_out,
1849  certificate_verify.signature );
1850  if ( len < 0 ) {
1851  rc = len;
1852  DBGC ( tls, "TLS %p could not sign %s digest using %s "
1853  "client private key: %s\n", tls, digest->name,
1854  pubkey->name, strerror ( rc ) );
1855  goto err_pubkey_sign;
1856  }
1857  unused = ( max_len - len );
1858 
1859  /* Construct Certificate Verify record */
1860  certificate_verify.type_length =
1862  htonl ( sizeof ( certificate_verify ) -
1863  sizeof ( certificate_verify.type_length ) -
1864  unused ) );
1865  if ( use_sig_hash ) {
1866  memcpy ( &certificate_verify.sig_hash[0],
1867  &sig_hash->code,
1868  sizeof ( certificate_verify.sig_hash[0] ) );
1869  }
1870  certificate_verify.signature_len =
1871  htons ( sizeof ( certificate_verify.signature ) -
1872  unused );
1873 
1874  /* Transmit record */
1875  rc = tls_send_handshake ( tls, &certificate_verify,
1876  ( sizeof ( certificate_verify ) - unused ) );
1877  }
1878 
1879  err_pubkey_sign:
1880  err_sig_hash:
1881  return rc;
1882 }
1883 
1884 /**
1885  * Transmit Change Cipher record
1886  *
1887  * @v tls TLS connection
1888  * @ret rc Return status code
1889  */
1890 static int tls_send_change_cipher ( struct tls_connection *tls ) {
1891  static const struct {
1892  uint8_t spec;
1893  } __attribute__ (( packed )) change_cipher = {
1894  .spec = TLS_CHANGE_CIPHER_SPEC,
1895  };
1896 
1898  &change_cipher, sizeof ( change_cipher ) );
1899 }
1900 
1901 /**
1902  * Transmit Finished record
1903  *
1904  * @v tls TLS connection
1905  * @ret rc Return status code
1906  */
1907 static int tls_send_finished ( struct tls_connection *tls ) {
1908  struct digest_algorithm *digest = tls->handshake_digest;
1909  struct {
1910  uint32_t type_length;
1911  uint8_t verify_data[ sizeof ( tls->verify.client ) ];
1912  } __attribute__ (( packed )) finished;
1913  uint8_t digest_out[ digest->digestsize ];
1914  int rc;
1915 
1916  /* Construct client verification data */
1917  tls_verify_handshake ( tls, digest_out );
1918  tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
1919  tls->verify.client, sizeof ( tls->verify.client ),
1920  "client finished", digest_out, sizeof ( digest_out ) );
1921 
1922  /* Construct record */
1923  memset ( &finished, 0, sizeof ( finished ) );
1924  finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
1925  htonl ( sizeof ( finished ) -
1926  sizeof ( finished.type_length ) ) );
1927  memcpy ( finished.verify_data, tls->verify.client,
1928  sizeof ( finished.verify_data ) );
1929 
1930  /* Transmit record */
1931  if ( ( rc = tls_send_handshake ( tls, &finished,
1932  sizeof ( finished ) ) ) != 0 )
1933  return rc;
1934 
1935  /* Mark client as finished */
1936  pending_put ( &tls->client.negotiation );
1937 
1938  return 0;
1939 }
1940 
1941 /**
1942  * Receive new Change Cipher record
1943  *
1944  * @v tls TLS connection
1945  * @v iobuf I/O buffer
1946  * @ret rc Return status code
1947  */
1948 static int tls_new_change_cipher ( struct tls_connection *tls,
1949  struct io_buffer *iobuf ) {
1950  const struct {
1951  uint8_t spec;
1952  } __attribute__ (( packed )) *change_cipher = iobuf->data;
1953  size_t len = iob_len ( iobuf );
1954  int rc;
1955 
1956  /* Sanity check */
1957  if ( ( sizeof ( *change_cipher ) != len ) ||
1958  ( change_cipher->spec != TLS_CHANGE_CIPHER_SPEC ) ) {
1959  DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
1960  DBGC_HD ( tls, change_cipher, len );
1961  return -EINVAL_CHANGE_CIPHER;
1962  }
1963  iob_pull ( iobuf, sizeof ( *change_cipher ) );
1964 
1965  /* Change receive cipher spec */
1966  if ( ( rc = tls_change_cipher ( tls, &tls->rx.cipherspec ) ) != 0 ) {
1967  DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
1968  tls, strerror ( rc ) );
1969  return rc;
1970  }
1971  tls->rx.seq = ~( ( uint64_t ) 0 );
1972 
1973  return 0;
1974 }
1975 
1976 /**
1977  * Receive new Alert record
1978  *
1979  * @v tls TLS connection
1980  * @v iobuf I/O buffer
1981  * @ret rc Return status code
1982  */
1983 static int tls_new_alert ( struct tls_connection *tls,
1984  struct io_buffer *iobuf ) {
1985  const struct {
1986  uint8_t level;
1987  uint8_t description;
1988  char next[0];
1989  } __attribute__ (( packed )) *alert = iobuf->data;
1990  size_t len = iob_len ( iobuf );
1991 
1992  /* Sanity check */
1993  if ( sizeof ( *alert ) != len ) {
1994  DBGC ( tls, "TLS %p received overlength Alert\n", tls );
1995  DBGC_HD ( tls, alert, len );
1996  return -EINVAL_ALERT;
1997  }
1998  iob_pull ( iobuf, sizeof ( *alert ) );
1999 
2000  /* Handle alert */
2001  switch ( alert->level ) {
2002  case TLS_ALERT_WARNING:
2003  DBGC ( tls, "TLS %p received warning alert %d\n",
2004  tls, alert->description );
2005  return 0;
2006  case TLS_ALERT_FATAL:
2007  DBGC ( tls, "TLS %p received fatal alert %d\n",
2008  tls, alert->description );
2009  return -EPERM_ALERT;
2010  default:
2011  DBGC ( tls, "TLS %p received unknown alert level %d"
2012  "(alert %d)\n", tls, alert->level, alert->description );
2013  return -EIO_ALERT;
2014  }
2015 }
2016 
2017 /**
2018  * Receive new Hello Request handshake record
2019  *
2020  * @v tls TLS connection
2021  * @v data Plaintext handshake record
2022  * @v len Length of plaintext handshake record
2023  * @ret rc Return status code
2024  */
2025 static int tls_new_hello_request ( struct tls_connection *tls,
2026  const void *data __unused,
2027  size_t len __unused ) {
2028 
2029  /* Ignore if a handshake is in progress */
2030  if ( ! tls_ready ( tls ) ) {
2031  DBGC ( tls, "TLS %p ignoring Hello Request\n", tls );
2032  return 0;
2033  }
2034 
2035  /* Fail unless server supports secure renegotiation */
2036  if ( ! tls->secure_renegotiation ) {
2037  DBGC ( tls, "TLS %p refusing to renegotiate insecurely\n",
2038  tls );
2039  return -EPERM_RENEG_INSECURE;
2040  }
2041 
2042  /* Restart negotiation */
2043  tls_restart ( tls );
2044 
2045  return 0;
2046 }
2047 
2048 /**
2049  * Receive new Server Hello handshake record
2050  *
2051  * @v tls TLS connection
2052  * @v data Plaintext handshake record
2053  * @v len Length of plaintext handshake record
2054  * @ret rc Return status code
2055  */
2056 static int tls_new_server_hello ( struct tls_connection *tls,
2057  const void *data, size_t len ) {
2058  const struct {
2059  uint16_t version;
2060  uint8_t random[32];
2061  uint8_t session_id_len;
2062  uint8_t session_id[0];
2063  } __attribute__ (( packed )) *hello_a = data;
2064  const uint8_t *session_id;
2065  const struct {
2066  uint16_t cipher_suite;
2067  uint8_t compression_method;
2068  char next[0];
2069  } __attribute__ (( packed )) *hello_b;
2070  const struct {
2071  uint16_t len;
2072  uint8_t data[0];
2073  } __attribute__ (( packed )) *exts;
2074  const struct {
2075  uint16_t type;
2076  uint16_t len;
2077  uint8_t data[0];
2078  } __attribute__ (( packed )) *ext;
2079  const struct {
2080  uint8_t len;
2081  uint8_t data[0];
2082  } __attribute__ (( packed )) *reneg = NULL;
2083  uint16_t version;
2084  size_t exts_len;
2085  size_t ext_len;
2086  size_t remaining;
2087  int rc;
2088 
2089  /* Parse header */
2090  if ( ( sizeof ( *hello_a ) > len ) ||
2091  ( hello_a->session_id_len > ( len - sizeof ( *hello_a ) ) ) ||
2092  ( sizeof ( *hello_b ) > ( len - sizeof ( *hello_a ) -
2093  hello_a->session_id_len ) ) ) {
2094  DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
2095  DBGC_HD ( tls, data, len );
2096  return -EINVAL_HELLO;
2097  }
2098  session_id = hello_a->session_id;
2099  hello_b = ( ( void * ) ( session_id + hello_a->session_id_len ) );
2100 
2101  /* Parse extensions, if present */
2102  remaining = ( len - sizeof ( *hello_a ) - hello_a->session_id_len -
2103  sizeof ( *hello_b ) );
2104  if ( remaining ) {
2105 
2106  /* Parse extensions length */
2107  exts = ( ( void * ) hello_b->next );
2108  if ( ( sizeof ( *exts ) > remaining ) ||
2109  ( ( exts_len = ntohs ( exts->len ) ) >
2110  ( remaining - sizeof ( *exts ) ) ) ) {
2111  DBGC ( tls, "TLS %p received underlength extensions\n",
2112  tls );
2113  DBGC_HD ( tls, data, len );
2114  return -EINVAL_HELLO;
2115  }
2116 
2117  /* Parse extensions */
2118  for ( ext = ( ( void * ) exts->data ), remaining = exts_len ;
2119  remaining ;
2120  ext = ( ( ( void * ) ext ) + sizeof ( *ext ) + ext_len ),
2121  remaining -= ( sizeof ( *ext ) + ext_len ) ) {
2122 
2123  /* Parse extension length */
2124  if ( ( sizeof ( *ext ) > remaining ) ||
2125  ( ( ext_len = ntohs ( ext->len ) ) >
2126  ( remaining - sizeof ( *ext ) ) ) ) {
2127  DBGC ( tls, "TLS %p received underlength "
2128  "extension\n", tls );
2129  DBGC_HD ( tls, data, len );
2130  return -EINVAL_HELLO;
2131  }
2132 
2133  /* Record known extensions */
2134  switch ( ext->type ) {
2135  case htons ( TLS_RENEGOTIATION_INFO ) :
2136  reneg = ( ( void * ) ext->data );
2137  if ( ( sizeof ( *reneg ) > ext_len ) ||
2138  ( reneg->len >
2139  ( ext_len - sizeof ( *reneg ) ) ) ) {
2140  DBGC ( tls, "TLS %p received "
2141  "underlength renegotiation "
2142  "info\n", tls );
2143  DBGC_HD ( tls, data, len );
2144  return -EINVAL_HELLO;
2145  }
2146  break;
2147  }
2148  }
2149  }
2150 
2151  /* Check and store protocol version */
2152  version = ntohs ( hello_a->version );
2153  if ( version < TLS_VERSION_MIN ) {
2154  DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
2155  tls, ( version >> 8 ), ( version & 0xff ) );
2156  return -ENOTSUP_VERSION;
2157  }
2158  if ( version > tls->version ) {
2159  DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
2160  "protocol version %d.%d\n",
2161  tls, ( version >> 8 ), ( version & 0xff ) );
2162  return -EPROTO_VERSION;
2163  }
2164  tls->version = version;
2165  DBGC ( tls, "TLS %p using protocol version %d.%d\n",
2166  tls, ( version >> 8 ), ( version & 0xff ) );
2167 
2168  /* Select cipher suite */
2169  if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
2170  return rc;
2171 
2172  /* Add preceding Client Hello to handshake digest */
2173  if ( ( rc = tls_client_hello ( tls, tls_add_handshake ) ) != 0 )
2174  return rc;
2175 
2176  /* Copy out server random bytes */
2177  memcpy ( &tls->server.random, &hello_a->random,
2178  sizeof ( tls->server.random ) );
2179 
2180  /* Check session ID */
2181  if ( hello_a->session_id_len &&
2182  ( hello_a->session_id_len == tls->session_id_len ) &&
2183  ( memcmp ( session_id, tls->session_id,
2184  tls->session_id_len ) == 0 ) ) {
2185 
2186  /* Session ID match: reuse master secret */
2187  DBGC ( tls, "TLS %p resuming session ID:\n", tls );
2188  DBGC_HDA ( tls, 0, tls->session_id, tls->session_id_len );
2189  if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
2190  return rc;
2191 
2192  } else {
2193 
2194  /* Record new session ID, if present */
2195  if ( hello_a->session_id_len &&
2196  ( hello_a->session_id_len <= sizeof ( tls->session_id ))){
2197  tls->session_id_len = hello_a->session_id_len;
2198  memcpy ( tls->session_id, session_id,
2199  tls->session_id_len );
2200  DBGC ( tls, "TLS %p new session ID:\n", tls );
2201  DBGC_HDA ( tls, 0, tls->session_id,
2202  tls->session_id_len );
2203  }
2204  }
2205 
2206  /* Handle secure renegotiation */
2207  if ( tls->secure_renegotiation ) {
2208 
2209  /* Secure renegotiation is expected; verify data */
2210  if ( ( reneg == NULL ) ||
2211  ( reneg->len != sizeof ( tls->verify ) ) ||
2212  ( memcmp ( reneg->data, &tls->verify,
2213  sizeof ( tls->verify ) ) != 0 ) ) {
2214  DBGC ( tls, "TLS %p server failed secure "
2215  "renegotiation\n", tls );
2216  return -EPERM_RENEG_VERIFY;
2217  }
2218 
2219  } else if ( reneg != NULL ) {
2220 
2221  /* Secure renegotiation is being enabled */
2222  if ( reneg->len != 0 ) {
2223  DBGC ( tls, "TLS %p server provided non-empty initial "
2224  "renegotiation\n", tls );
2225  return -EPERM_RENEG_VERIFY;
2226  }
2227  tls->secure_renegotiation = 1;
2228  }
2229 
2230  return 0;
2231 }
2232 
2233 /**
2234  * Receive New Session Ticket handshake record
2235  *
2236  * @v tls TLS connection
2237  * @v data Plaintext handshake record
2238  * @v len Length of plaintext handshake record
2239  * @ret rc Return status code
2240  */
2241 static int tls_new_session_ticket ( struct tls_connection *tls,
2242  const void *data, size_t len ) {
2243  const struct {
2245  uint16_t len;
2246  uint8_t ticket[0];
2247  } __attribute__ (( packed )) *new_session_ticket = data;
2248  size_t ticket_len;
2249 
2250  /* Parse header */
2251  if ( sizeof ( *new_session_ticket ) > len ) {
2252  DBGC ( tls, "TLS %p received underlength New Session Ticket\n",
2253  tls );
2254  DBGC_HD ( tls, data, len );
2255  return -EINVAL_TICKET;
2256  }
2257  ticket_len = ntohs ( new_session_ticket->len );
2258  if ( ticket_len > ( len - sizeof ( *new_session_ticket ) ) ) {
2259  DBGC ( tls, "TLS %p received overlength New Session Ticket\n",
2260  tls );
2261  DBGC_HD ( tls, data, len );
2262  return -EINVAL_TICKET;
2263  }
2264 
2265  /* Free any unapplied new session ticket */
2266  free ( tls->new_session_ticket );
2267  tls->new_session_ticket = NULL;
2268  tls->new_session_ticket_len = 0;
2269 
2270  /* Record ticket */
2271  tls->new_session_ticket = malloc ( ticket_len );
2272  if ( ! tls->new_session_ticket )
2273  return -ENOMEM;
2274  memcpy ( tls->new_session_ticket, new_session_ticket->ticket,
2275  ticket_len );
2276  tls->new_session_ticket_len = ticket_len;
2277  DBGC ( tls, "TLS %p new session ticket:\n", tls );
2278  DBGC_HDA ( tls, 0, tls->new_session_ticket,
2279  tls->new_session_ticket_len );
2280 
2281  return 0;
2282 }
2283 
2284 /**
2285  * Parse certificate chain
2286  *
2287  * @v tls TLS connection
2288  * @v data Certificate chain
2289  * @v len Length of certificate chain
2290  * @ret rc Return status code
2291  */
2292 static int tls_parse_chain ( struct tls_connection *tls,
2293  const void *data, size_t len ) {
2294  size_t remaining = len;
2295  int rc;
2296 
2297  /* Free any existing certificate chain */
2298  memset ( &tls->server.key, 0, sizeof ( tls->server.key ) );
2299  x509_chain_put ( tls->server.chain );
2300  tls->server.chain = NULL;
2301 
2302  /* Create certificate chain */
2303  tls->server.chain = x509_alloc_chain();
2304  if ( ! tls->server.chain ) {
2305  rc = -ENOMEM_CHAIN;
2306  goto err_alloc_chain;
2307  }
2308 
2309  /* Add certificates to chain */
2310  while ( remaining ) {
2311  const struct {
2312  tls24_t length;
2313  uint8_t data[0];
2314  } __attribute__ (( packed )) *certificate = data;
2315  size_t certificate_len;
2316  size_t record_len;
2317  struct x509_certificate *cert;
2318 
2319  /* Parse header */
2320  if ( sizeof ( *certificate ) > remaining ) {
2321  DBGC ( tls, "TLS %p underlength certificate:\n", tls );
2322  DBGC_HDA ( tls, 0, data, remaining );
2324  goto err_underlength;
2325  }
2326  certificate_len = tls_uint24 ( &certificate->length );
2327  if ( certificate_len > ( remaining - sizeof ( *certificate ) )){
2328  DBGC ( tls, "TLS %p overlength certificate:\n", tls );
2329  DBGC_HDA ( tls, 0, data, remaining );
2331  goto err_overlength;
2332  }
2333  record_len = ( sizeof ( *certificate ) + certificate_len );
2334 
2335  /* Add certificate to chain */
2336  if ( ( rc = x509_append_raw ( tls->server.chain,
2337  certificate->data,
2338  certificate_len ) ) != 0 ) {
2339  DBGC ( tls, "TLS %p could not append certificate: %s\n",
2340  tls, strerror ( rc ) );
2341  DBGC_HDA ( tls, 0, data, remaining );
2342  goto err_parse;
2343  }
2344  cert = x509_last ( tls->server.chain );
2345  DBGC ( tls, "TLS %p found certificate %s\n",
2346  tls, x509_name ( cert ) );
2347 
2348  /* Move to next certificate in list */
2349  data += record_len;
2350  remaining -= record_len;
2351  }
2352 
2353  return 0;
2354 
2355  err_parse:
2356  err_overlength:
2357  err_underlength:
2358  memset ( &tls->server.key, 0, sizeof ( tls->server.key ) );
2359  x509_chain_put ( tls->server.chain );
2360  tls->server.chain = NULL;
2361  err_alloc_chain:
2362  return rc;
2363 }
2364 
2365 /**
2366  * Receive new Certificate handshake record
2367  *
2368  * @v tls TLS connection
2369  * @v data Plaintext handshake record
2370  * @v len Length of plaintext handshake record
2371  * @ret rc Return status code
2372  */
2373 static int tls_new_certificate ( struct tls_connection *tls,
2374  const void *data, size_t len ) {
2375  const struct {
2376  tls24_t length;
2377  uint8_t certificates[0];
2378  } __attribute__ (( packed )) *certificate = data;
2379  size_t certificates_len;
2380  int rc;
2381 
2382  /* Parse header */
2383  if ( sizeof ( *certificate ) > len ) {
2384  DBGC ( tls, "TLS %p received underlength Server Certificate\n",
2385  tls );
2386  DBGC_HD ( tls, data, len );
2387  return -EINVAL_CERTIFICATES;
2388  }
2389  certificates_len = tls_uint24 ( &certificate->length );
2390  if ( certificates_len > ( len - sizeof ( *certificate ) ) ) {
2391  DBGC ( tls, "TLS %p received overlength Server Certificate\n",
2392  tls );
2393  DBGC_HD ( tls, data, len );
2394  return -EINVAL_CERTIFICATES;
2395  }
2396 
2397  /* Parse certificate chain */
2398  if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
2399  certificates_len ) ) != 0 )
2400  return rc;
2401 
2402  return 0;
2403 }
2404 
2405 /**
2406  * Receive new Server Key Exchange handshake record
2407  *
2408  * @v tls TLS connection
2409  * @v data Plaintext handshake record
2410  * @v len Length of plaintext handshake record
2411  * @ret rc Return status code
2412  */
2414  const void *data, size_t len ) {
2415 
2416  /* Free any existing server key exchange record */
2417  free ( tls->server.exchange );
2418  tls->server.exchange_len = 0;
2419 
2420  /* Allocate copy of server key exchange record */
2421  tls->server.exchange = malloc ( len );
2422  if ( ! tls->server.exchange )
2423  return -ENOMEM;
2424 
2425  /* Store copy of server key exchange record for later
2426  * processing. We cannot verify the signature at this point
2427  * since the certificate validation will not yet have
2428  * completed.
2429  */
2430  memcpy ( tls->server.exchange, data, len );
2431  tls->server.exchange_len = len;
2432 
2433  return 0;
2434 }
2435 
2436 /**
2437  * Receive new Certificate Request handshake record
2438  *
2439  * @v tls TLS connection
2440  * @v data Plaintext handshake record
2441  * @v len Length of plaintext handshake record
2442  * @ret rc Return status code
2443  */
2445  const void *data __unused,
2446  size_t len __unused ) {
2447  struct x509_certificate *cert;
2448  int rc;
2449 
2450  /* We can only send a single certificate, so there is no point
2451  * in parsing the Certificate Request.
2452  */
2453 
2454  /* Free any existing client certificate chain */
2455  x509_chain_put ( tls->client.chain );
2456  tls->client.chain = NULL;
2457 
2458  /* Determine client certificate to be sent */
2459  cert = x509_find_key ( NULL, tls->client.key );
2460  if ( ! cert ) {
2461  DBGC ( tls, "TLS %p could not find certificate corresponding "
2462  "to private key\n", tls );
2463  rc = -EPERM_CLIENT_CERT;
2464  goto err_find;
2465  }
2466  x509_get ( cert );
2467  DBGC ( tls, "TLS %p selected client certificate %s\n",
2468  tls, x509_name ( cert ) );
2469 
2470  /* Create client certificate chain */
2471  tls->client.chain = x509_alloc_chain();
2472  if ( ! tls->client.chain ) {
2473  rc = -ENOMEM;
2474  goto err_alloc;
2475  }
2476 
2477  /* Append client certificate to chain */
2478  if ( ( rc = x509_append ( tls->client.chain, cert ) ) != 0 )
2479  goto err_append;
2480 
2481  /* Append any relevant issuer certificates */
2482  if ( ( rc = x509_auto_append ( tls->client.chain, &certstore ) ) != 0 )
2483  goto err_auto_append;
2484 
2485  /* Drop local reference to client certificate */
2486  x509_put ( cert );
2487 
2488  return 0;
2489 
2490  err_auto_append:
2491  err_append:
2492  x509_chain_put ( tls->client.chain );
2493  tls->client.chain = NULL;
2494  err_alloc:
2495  x509_put ( cert );
2496  err_find:
2497  return rc;
2498 }
2499 
2500 /**
2501  * Receive new Server Hello Done handshake record
2502  *
2503  * @v tls TLS connection
2504  * @v data Plaintext handshake record
2505  * @v len Length of plaintext handshake record
2506  * @ret rc Return status code
2507  */
2509  const void *data, size_t len ) {
2510  const struct {
2511  char next[0];
2512  } __attribute__ (( packed )) *hello_done = data;
2513  int rc;
2514 
2515  /* Sanity check */
2516  if ( sizeof ( *hello_done ) != len ) {
2517  DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
2518  tls );
2519  DBGC_HD ( tls, data, len );
2520  return -EINVAL_HELLO_DONE;
2521  }
2522 
2523  /* Begin certificate validation */
2524  if ( ( rc = create_validator ( &tls->server.validator,
2525  tls->server.chain,
2526  tls->server.root ) ) != 0 ) {
2527  DBGC ( tls, "TLS %p could not start certificate validation: "
2528  "%s\n", tls, strerror ( rc ) );
2529  return rc;
2530  }
2531  pending_get ( &tls->server.validation );
2532 
2533  return 0;
2534 }
2535 
2536 /**
2537  * Receive new Finished handshake record
2538  *
2539  * @v tls TLS connection
2540  * @v data Plaintext handshake record
2541  * @v len Length of plaintext handshake record
2542  * @ret rc Return status code
2543  */
2544 static int tls_new_finished ( struct tls_connection *tls,
2545  const void *data, size_t len ) {
2546  struct tls_session *session = tls->session;
2547  struct digest_algorithm *digest = tls->handshake_digest;
2548  const struct {
2549  uint8_t verify_data[ sizeof ( tls->verify.server ) ];
2550  char next[0];
2551  } __attribute__ (( packed )) *finished = data;
2552  uint8_t digest_out[ digest->digestsize ];
2553 
2554  /* Sanity check */
2555  if ( sizeof ( *finished ) != len ) {
2556  DBGC ( tls, "TLS %p received overlength Finished\n", tls );
2557  DBGC_HD ( tls, data, len );
2558  return -EINVAL_FINISHED;
2559  }
2560 
2561  /* Verify data */
2562  tls_verify_handshake ( tls, digest_out );
2563  tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
2564  tls->verify.server, sizeof ( tls->verify.server ),
2565  "server finished", digest_out, sizeof ( digest_out ) );
2566  if ( memcmp ( tls->verify.server, finished->verify_data,
2567  sizeof ( tls->verify.server ) ) != 0 ) {
2568  DBGC ( tls, "TLS %p verification failed\n", tls );
2569  return -EPERM_VERIFY;
2570  }
2571 
2572  /* Mark server as finished */
2573  pending_put ( &tls->server.negotiation );
2574 
2575  /* If we are resuming a session (i.e. if the server Finished
2576  * arrives before the client Finished is sent), then schedule
2577  * transmission of Change Cipher and Finished.
2578  */
2579  if ( is_pending ( &tls->client.negotiation ) ) {
2581  tls_tx_resume ( tls );
2582  }
2583 
2584  /* Record session ID, ticket, and master secret, if applicable */
2585  if ( tls->session_id_len || tls->new_session_ticket_len ) {
2586  memcpy ( session->master_secret, tls->master_secret,
2587  sizeof ( session->master_secret ) );
2588  }
2589  if ( tls->session_id_len ) {
2590  session->id_len = tls->session_id_len;
2591  memcpy ( session->id, tls->session_id, sizeof ( session->id ) );
2592  }
2593  if ( tls->new_session_ticket_len ) {
2594  free ( session->ticket );
2595  session->ticket = tls->new_session_ticket;
2596  session->ticket_len = tls->new_session_ticket_len;
2597  tls->new_session_ticket = NULL;
2598  tls->new_session_ticket_len = 0;
2599  }
2600 
2601  /* Move to end of session's connection list and allow other
2602  * connections to start making progress.
2603  */
2604  list_del ( &tls->list );
2605  list_add_tail ( &tls->list, &session->conn );
2606  tls_tx_resume_all ( session );
2607 
2608  /* Send notification of a window change */
2609  xfer_window_changed ( &tls->plainstream );
2610 
2611  return 0;
2612 }
2613 
2614 /**
2615  * Receive new Handshake record
2616  *
2617  * @v tls TLS connection
2618  * @v iobuf I/O buffer
2619  * @ret rc Return status code
2620  */
2621 static int tls_new_handshake ( struct tls_connection *tls,
2622  struct io_buffer *iobuf ) {
2623  size_t remaining;
2624  int rc;
2625 
2626  while ( ( remaining = iob_len ( iobuf ) ) ) {
2627  const struct {
2628  uint8_t type;
2629  tls24_t length;
2630  uint8_t payload[0];
2631  } __attribute__ (( packed )) *handshake = iobuf->data;
2632  const void *payload;
2633  size_t payload_len;
2634  size_t record_len;
2635 
2636  /* Parse header */
2637  if ( sizeof ( *handshake ) > remaining ) {
2638  /* Leave remaining fragment unconsumed */
2639  break;
2640  }
2641  payload_len = tls_uint24 ( &handshake->length );
2642  if ( payload_len > ( remaining - sizeof ( *handshake ) ) ) {
2643  /* Leave remaining fragment unconsumed */
2644  break;
2645  }
2646  payload = &handshake->payload;
2647  record_len = ( sizeof ( *handshake ) + payload_len );
2648 
2649  /* Handle payload */
2650  switch ( handshake->type ) {
2651  case TLS_HELLO_REQUEST:
2652  rc = tls_new_hello_request ( tls, payload,
2653  payload_len );
2654  break;
2655  case TLS_SERVER_HELLO:
2656  rc = tls_new_server_hello ( tls, payload, payload_len );
2657  break;
2659  rc = tls_new_session_ticket ( tls, payload,
2660  payload_len );
2661  break;
2662  case TLS_CERTIFICATE:
2663  rc = tls_new_certificate ( tls, payload, payload_len );
2664  break;
2666  rc = tls_new_server_key_exchange ( tls, payload,
2667  payload_len );
2668  break;
2670  rc = tls_new_certificate_request ( tls, payload,
2671  payload_len );
2672  break;
2673  case TLS_SERVER_HELLO_DONE:
2674  rc = tls_new_server_hello_done ( tls, payload,
2675  payload_len );
2676  break;
2677  case TLS_FINISHED:
2678  rc = tls_new_finished ( tls, payload, payload_len );
2679  break;
2680  default:
2681  DBGC ( tls, "TLS %p ignoring handshake type %d\n",
2682  tls, handshake->type );
2683  rc = 0;
2684  break;
2685  }
2686 
2687  /* Add to handshake digest (except for Hello Requests,
2688  * which are explicitly excluded).
2689  */
2690  if ( handshake->type != TLS_HELLO_REQUEST )
2691  tls_add_handshake ( tls, handshake, record_len );
2692 
2693  /* Abort on failure */
2694  if ( rc != 0 )
2695  return rc;
2696 
2697  /* Move to next handshake record */
2698  iob_pull ( iobuf, record_len );
2699  }
2700 
2701  return 0;
2702 }
2703 
2704 /**
2705  * Receive new unknown record
2706  *
2707  * @v tls TLS connection
2708  * @v iobuf I/O buffer
2709  * @ret rc Return status code
2710  */
2711 static int tls_new_unknown ( struct tls_connection *tls __unused,
2712  struct io_buffer *iobuf ) {
2713 
2714  /* RFC4346 says that we should just ignore unknown record types */
2715  iob_pull ( iobuf, iob_len ( iobuf ) );
2716  return 0;
2717 }
2718 
2719 /**
2720  * Receive new data record
2721  *
2722  * @v tls TLS connection
2723  * @v rx_data List of received data buffers
2724  * @ret rc Return status code
2725  */
2726 static int tls_new_data ( struct tls_connection *tls,
2727  struct list_head *rx_data ) {
2728  struct io_buffer *iobuf;
2729  int rc;
2730 
2731  /* Fail unless we are ready to receive data */
2732  if ( ! tls_ready ( tls ) )
2733  return -ENOTCONN;
2734 
2735  /* Deliver each I/O buffer in turn */
2736  while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
2737  list ) ) ) {
2738  list_del ( &iobuf->list );
2739  if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
2740  iobuf ) ) != 0 ) {
2741  DBGC ( tls, "TLS %p could not deliver data: "
2742  "%s\n", tls, strerror ( rc ) );
2743  return rc;
2744  }
2745  }
2746 
2747  return 0;
2748 }
2749 
2750 /**
2751  * Receive new record
2752  *
2753  * @v tls TLS connection
2754  * @v type Record type
2755  * @v rx_data List of received data buffers
2756  * @ret rc Return status code
2757  */
2758 static int tls_new_record ( struct tls_connection *tls, unsigned int type,
2759  struct list_head *rx_data ) {
2760  int ( * handler ) ( struct tls_connection *tls,
2761  struct io_buffer *iobuf );
2762  struct io_buffer *tmp = NULL;
2763  struct io_buffer **iobuf;
2764  int rc;
2765 
2766  /* Deliver data records as-is to the plainstream interface */
2767  if ( type == TLS_TYPE_DATA )
2768  return tls_new_data ( tls, rx_data );
2769 
2770  /* Determine handler and fragment buffer */
2771  iobuf = &tmp;
2772  switch ( type ) {
2774  handler = tls_new_change_cipher;
2775  break;
2776  case TLS_TYPE_ALERT:
2777  handler = tls_new_alert;
2778  break;
2779  case TLS_TYPE_HANDSHAKE:
2780  handler = tls_new_handshake;
2781  iobuf = &tls->rx.handshake;
2782  break;
2783  default:
2784  DBGC ( tls, "TLS %p unknown record type %d\n", tls, type );
2785  handler = tls_new_unknown;
2786  break;
2787  }
2788 
2789  /* Merge into a single I/O buffer */
2790  if ( *iobuf )
2791  list_add ( &(*iobuf)->list, rx_data );
2792  *iobuf = iob_concatenate ( rx_data );
2793  if ( ! *iobuf ) {
2794  DBGC ( tls, "TLS %p could not concatenate non-data record "
2795  "type %d\n", tls, type );
2796  rc = -ENOMEM_RX_CONCAT;
2797  goto err_concatenate;
2798  }
2799 
2800  /* Handle record */
2801  if ( ( rc = handler ( tls, *iobuf ) ) != 0 )
2802  goto err_handle;
2803 
2804  /* Discard I/O buffer if empty */
2805  if ( ! iob_len ( *iobuf ) ) {
2806  free_iob ( *iobuf );
2807  *iobuf = NULL;
2808  }
2809 
2810  /* Sanity check */
2811  assert ( tmp == NULL );
2812 
2813  return 0;
2814 
2815  err_handle:
2816  free_iob ( *iobuf );
2817  *iobuf = NULL;
2818  err_concatenate:
2819  return rc;
2820 }
2821 
2822 /******************************************************************************
2823  *
2824  * Record encryption/decryption
2825  *
2826  ******************************************************************************
2827  */
2828 
2829 /**
2830  * Initialise HMAC
2831  *
2832  * @v cipherspec Cipher specification
2833  * @v ctx Context
2834  * @v authhdr Authentication header
2835  */
2836 static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
2837  struct tls_auth_header *authhdr ) {
2838  struct tls_cipher_suite *suite = cipherspec->suite;
2839  struct digest_algorithm *digest = suite->digest;
2840 
2841  hmac_init ( digest, ctx, cipherspec->mac_secret, suite->mac_len );
2842  hmac_update ( digest, ctx, authhdr, sizeof ( *authhdr ) );
2843 }
2844 
2845 /**
2846  * Update HMAC
2847  *
2848  * @v cipherspec Cipher specification
2849  * @v ctx Context
2850  * @v data Data
2851  * @v len Length of data
2852  */
2853 static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
2854  const void *data, size_t len ) {
2855  struct digest_algorithm *digest = cipherspec->suite->digest;
2856 
2857  hmac_update ( digest, ctx, data, len );
2858 }
2859 
2860 /**
2861  * Finalise HMAC
2862  *
2863  * @v cipherspec Cipher specification
2864  * @v ctx Context
2865  * @v mac HMAC to fill in
2866  */
2867 static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
2868  void *hmac ) {
2869  struct digest_algorithm *digest = cipherspec->suite->digest;
2870 
2871  hmac_final ( digest, ctx, hmac );
2872 }
2873 
2874 /**
2875  * Calculate HMAC
2876  *
2877  * @v cipherspec Cipher specification
2878  * @v authhdr Authentication header
2879  * @v data Data
2880  * @v len Length of data
2881  * @v mac HMAC to fill in
2882  */
2883 static void tls_hmac ( struct tls_cipherspec *cipherspec,
2884  struct tls_auth_header *authhdr,
2885  const void *data, size_t len, void *hmac ) {
2886  struct digest_algorithm *digest = cipherspec->suite->digest;
2887  uint8_t ctx[ hmac_ctxsize ( digest ) ];
2888 
2889  tls_hmac_init ( cipherspec, ctx, authhdr );
2890  tls_hmac_update ( cipherspec, ctx, data, len );
2891  tls_hmac_final ( cipherspec, ctx, hmac );
2892 }
2893 
2894 /**
2895  * Calculate HMAC over list of I/O buffers
2896  *
2897  * @v cipherspec Cipher specification
2898  * @v authhdr Authentication header
2899  * @v list List of I/O buffers
2900  * @v mac HMAC to fill in
2901  */
2902 static void tls_hmac_list ( struct tls_cipherspec *cipherspec,
2903  struct tls_auth_header *authhdr,
2904  struct list_head *list, void *hmac ) {
2905  struct digest_algorithm *digest = cipherspec->suite->digest;
2906  uint8_t ctx[ hmac_ctxsize ( digest ) ];
2907  struct io_buffer *iobuf;
2908 
2909  tls_hmac_init ( cipherspec, ctx, authhdr );
2910  list_for_each_entry ( iobuf, list, list ) {
2911  tls_hmac_update ( cipherspec, ctx, iobuf->data,
2912  iob_len ( iobuf ) );
2913  }
2914  tls_hmac_final ( cipherspec, ctx, hmac );
2915 }
2916 
2917 /**
2918  * Send plaintext record
2919  *
2920  * @v tls TLS connection
2921  * @v type Record type
2922  * @v data Plaintext record
2923  * @v len Length of plaintext record
2924  * @ret rc Return status code
2925  */
2926 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
2927  const void *data, size_t len ) {
2928  struct tls_cipherspec *cipherspec = &tls->tx.cipherspec.active;
2929  struct tls_cipher_suite *suite = cipherspec->suite;
2930  struct cipher_algorithm *cipher = suite->cipher;
2931  struct digest_algorithm *digest = suite->digest;
2932  struct {
2933  uint8_t fixed[suite->fixed_iv_len];
2934  uint8_t record[suite->record_iv_len];
2935  } __attribute__ (( packed )) iv;
2936  struct tls_auth_header authhdr;
2937  struct tls_header *tlshdr;
2938  void *plaintext;
2939  size_t plaintext_len;
2940  struct io_buffer *ciphertext;
2941  size_t ciphertext_len;
2942  size_t padding_len;
2943  uint8_t mac[digest->digestsize];
2944  void *tmp;
2945  int rc;
2946 
2947  /* Construct initialisation vector */
2948  memcpy ( iv.fixed, cipherspec->fixed_iv, sizeof ( iv.fixed ) );
2949  if ( ( rc = tls_generate_random ( tls, iv.record,
2950  sizeof ( iv.record ) ) ) != 0 ) {
2951  goto err_random;
2952  }
2953 
2954  /* Construct authentication data */
2955  authhdr.seq = cpu_to_be64 ( tls->tx.seq );
2956  authhdr.header.type = type;
2957  authhdr.header.version = htons ( tls->version );
2958  authhdr.header.length = htons ( len );
2959 
2960  /* Calculate padding length */
2961  plaintext_len = ( len + suite->mac_len );
2962  if ( is_block_cipher ( cipher ) ) {
2963  padding_len = ( ( ( cipher->blocksize - 1 ) &
2964  -( plaintext_len + 1 ) ) + 1 );
2965  } else {
2966  padding_len = 0;
2967  }
2968  plaintext_len += padding_len;
2969 
2970  /* Allocate plaintext */
2971  plaintext = malloc ( plaintext_len );
2972  if ( ! plaintext ) {
2973  DBGC ( tls, "TLS %p could not allocate %zd bytes for "
2974  "plaintext\n", tls, plaintext_len );
2976  goto err_plaintext;
2977  }
2978 
2979  /* Assemble plaintext */
2980  tmp = plaintext;
2981  memcpy ( tmp, data, len );
2982  tmp += len;
2983  if ( suite->mac_len )
2984  tls_hmac ( cipherspec, &authhdr, data, len, mac );
2985  memcpy ( tmp, mac, suite->mac_len );
2986  tmp += suite->mac_len;
2987  memset ( tmp, ( padding_len - 1 ), padding_len );
2988  tmp += padding_len;
2989  assert ( tmp == ( plaintext + plaintext_len ) );
2990  DBGC2 ( tls, "Sending plaintext data:\n" );
2991  DBGC2_HD ( tls, plaintext, plaintext_len );
2992 
2993  /* Set initialisation vector */
2994  cipher_setiv ( cipher, cipherspec->cipher_ctx, &iv, sizeof ( iv ) );
2995 
2996  /* Process authentication data, if applicable */
2997  if ( is_auth_cipher ( cipher ) ) {
2998  cipher_encrypt ( cipher, cipherspec->cipher_ctx, &authhdr,
2999  NULL, sizeof ( authhdr ) );
3000  }
3001 
3002  /* Allocate ciphertext */
3003  ciphertext_len = ( sizeof ( *tlshdr ) + sizeof ( iv.record ) +
3004  plaintext_len + cipher->authsize );
3005  ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
3006  if ( ! ciphertext ) {
3007  DBGC ( tls, "TLS %p could not allocate %zd bytes for "
3008  "ciphertext\n", tls, ciphertext_len );
3010  goto err_ciphertext;
3011  }
3012 
3013  /* Assemble ciphertext */
3014  tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
3015  tlshdr->type = type;
3016  tlshdr->version = htons ( tls->version );
3017  tlshdr->length = htons ( ciphertext_len - sizeof ( *tlshdr ) );
3018  memcpy ( iob_put ( ciphertext, sizeof ( iv.record ) ), iv.record,
3019  sizeof ( iv.record ) );
3020  cipher_encrypt ( cipher, cipherspec->cipher_ctx, plaintext,
3021  iob_put ( ciphertext, plaintext_len ), plaintext_len );
3022  cipher_auth ( cipher, cipherspec->cipher_ctx,
3023  iob_put ( ciphertext, cipher->authsize ) );
3024  assert ( iob_len ( ciphertext ) == ciphertext_len );
3025 
3026  /* Free plaintext as soon as possible to conserve memory */
3027  free ( plaintext );
3028  plaintext = NULL;
3029 
3030  /* Send ciphertext */
3031  if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
3032  iob_disown ( ciphertext ) ) ) != 0 ) {
3033  DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
3034  tls, strerror ( rc ) );
3035  goto err_deliver;
3036  }
3037 
3038  /* Update TX state machine to next record */
3039  tls->tx.seq += 1;
3040 
3041  assert ( plaintext == NULL );
3042  assert ( ciphertext == NULL );
3043  return 0;
3044 
3045  err_deliver:
3046  free_iob ( ciphertext );
3047  err_ciphertext:
3048  free ( plaintext );
3049  err_plaintext:
3050  err_random:
3051  return rc;
3052 }
3053 
3054 /**
3055  * Verify block padding
3056  *
3057  * @v tls TLS connection
3058  * @v iobuf Last received I/O buffer
3059  * @ret len Padding length, or negative error
3060  * @ret rc Return status code
3061  */
3062 static int tls_verify_padding ( struct tls_connection *tls,
3063  struct io_buffer *iobuf ) {
3064  uint8_t *padding;
3065  unsigned int pad;
3066  unsigned int i;
3067  size_t len;
3068 
3069  /* Extract and verify padding */
3070  padding = ( iobuf->tail - 1 );
3071  pad = *padding;
3072  len = ( pad + 1 );
3073  if ( len > iob_len ( iobuf ) ) {
3074  DBGC ( tls, "TLS %p received underlength padding\n", tls );
3075  DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
3076  return -EINVAL_PADDING;
3077  }
3078  for ( i = 0 ; i < pad ; i++ ) {
3079  if ( *(--padding) != pad ) {
3080  DBGC ( tls, "TLS %p received bad padding\n", tls );
3081  DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
3082  return -EINVAL_PADDING;
3083  }
3084  }
3085 
3086  return len;
3087 }
3088 
3089 /**
3090  * Receive new ciphertext record
3091  *
3092  * @v tls TLS connection
3093  * @v tlshdr Record header
3094  * @v rx_data List of received data buffers
3095  * @ret rc Return status code
3096  */
3097 static int tls_new_ciphertext ( struct tls_connection *tls,
3098  struct tls_header *tlshdr,
3099  struct list_head *rx_data ) {
3100  struct tls_cipherspec *cipherspec = &tls->rx.cipherspec.active;
3101  struct tls_cipher_suite *suite = cipherspec->suite;
3102  struct cipher_algorithm *cipher = suite->cipher;
3103  struct digest_algorithm *digest = suite->digest;
3104  size_t len = ntohs ( tlshdr->length );
3105  struct {
3106  uint8_t fixed[suite->fixed_iv_len];
3107  uint8_t record[suite->record_iv_len];
3108  } __attribute__ (( packed )) iv;
3109  struct tls_auth_header authhdr;
3110  uint8_t verify_mac[digest->digestsize];
3111  uint8_t verify_auth[cipher->authsize];
3112  struct io_buffer *first;
3113  struct io_buffer *last;
3114  struct io_buffer *iobuf;
3115  void *mac;
3116  void *auth;
3117  size_t check_len;
3118  int pad_len;
3119  int rc;
3120 
3121  /* Locate first and last data buffers */
3122  assert ( ! list_empty ( rx_data ) );
3123  first = list_first_entry ( rx_data, struct io_buffer, list );
3124  last = list_last_entry ( rx_data, struct io_buffer, list );
3125 
3126  /* Extract initialisation vector */
3127  if ( iob_len ( first ) < sizeof ( iv.record ) ) {
3128  DBGC ( tls, "TLS %p received underlength IV\n", tls );
3129  DBGC_HD ( tls, first->data, iob_len ( first ) );
3130  return -EINVAL_IV;
3131  }
3132  memcpy ( iv.fixed, cipherspec->fixed_iv, sizeof ( iv.fixed ) );
3133  memcpy ( iv.record, first->data, sizeof ( iv.record ) );
3134  iob_pull ( first, sizeof ( iv.record ) );
3135  len -= sizeof ( iv.record );
3136 
3137  /* Extract unencrypted authentication tag */
3138  if ( iob_len ( last ) < cipher->authsize ) {
3139  DBGC ( tls, "TLS %p received underlength authentication tag\n",
3140  tls );
3141  DBGC_HD ( tls, last->data, iob_len ( last ) );
3142  return -EINVAL_MAC;
3143  }
3144  iob_unput ( last, cipher->authsize );
3145  len -= cipher->authsize;
3146  auth = last->tail;
3147 
3148  /* Construct authentication data */
3149  authhdr.seq = cpu_to_be64 ( tls->rx.seq );
3150  authhdr.header.type = tlshdr->type;
3151  authhdr.header.version = tlshdr->version;
3152  authhdr.header.length = htons ( len );
3153 
3154  /* Set initialisation vector */
3155  cipher_setiv ( cipher, cipherspec->cipher_ctx, &iv, sizeof ( iv ) );
3156 
3157  /* Process authentication data, if applicable */
3158  if ( is_auth_cipher ( cipher ) ) {
3159  cipher_decrypt ( cipher, cipherspec->cipher_ctx, &authhdr,
3160  NULL, sizeof ( authhdr ) );
3161  }
3162 
3163  /* Decrypt the received data */
3164  check_len = 0;
3165  list_for_each_entry ( iobuf, &tls->rx.data, list ) {
3166  cipher_decrypt ( cipher, cipherspec->cipher_ctx,
3167  iobuf->data, iobuf->data, iob_len ( iobuf ) );
3168  check_len += iob_len ( iobuf );
3169  }
3170  assert ( check_len == len );
3171 
3172  /* Strip block padding, if applicable */
3173  if ( is_block_cipher ( cipher ) ) {
3174  pad_len = tls_verify_padding ( tls, last );
3175  if ( pad_len < 0 ) {
3176  /* Assume zero padding length to avoid timing attacks */
3177  pad_len = 0;
3178  }
3179  iob_unput ( last, pad_len );
3180  len -= pad_len;
3181  }
3182 
3183  /* Extract decrypted MAC */
3184  if ( iob_len ( last ) < suite->mac_len ) {
3185  DBGC ( tls, "TLS %p received underlength MAC\n", tls );
3186  DBGC_HD ( tls, last->data, iob_len ( last ) );
3187  return -EINVAL_MAC;
3188  }
3189  iob_unput ( last, suite->mac_len );
3190  len -= suite->mac_len;
3191  mac = last->tail;
3192 
3193  /* Dump received data */
3194  DBGC2 ( tls, "Received plaintext data:\n" );
3195  check_len = 0;
3196  list_for_each_entry ( iobuf, rx_data, list ) {
3197  DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
3198  check_len += iob_len ( iobuf );
3199  }
3200  assert ( check_len == len );
3201 
3202  /* Generate MAC */
3203  authhdr.header.length = htons ( len );
3204  if ( suite->mac_len )
3205  tls_hmac_list ( cipherspec, &authhdr, rx_data, verify_mac );
3206 
3207  /* Generate authentication tag */
3208  cipher_auth ( cipher, cipherspec->cipher_ctx, verify_auth );
3209 
3210  /* Verify MAC */
3211  if ( memcmp ( mac, verify_mac, suite->mac_len ) != 0 ) {
3212  DBGC ( tls, "TLS %p failed MAC verification\n", tls );
3213  return -EINVAL_MAC;
3214  }
3215 
3216  /* Verify authentication tag */
3217  if ( memcmp ( auth, verify_auth, cipher->authsize ) != 0 ) {
3218  DBGC ( tls, "TLS %p failed authentication tag verification\n",
3219  tls );
3220  return -EINVAL_MAC;
3221  }
3222 
3223  /* Process plaintext record */
3224  if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
3225  return rc;
3226 
3227  return 0;
3228 }
3229 
3230 /******************************************************************************
3231  *
3232  * Plaintext stream operations
3233  *
3234  ******************************************************************************
3235  */
3236 
3237 /**
3238  * Check flow control window
3239  *
3240  * @v tls TLS connection
3241  * @ret len Length of window
3242  */
3243 static size_t tls_plainstream_window ( struct tls_connection *tls ) {
3244 
3245  /* Block window unless we are ready to accept data */
3246  if ( ! tls_ready ( tls ) )
3247  return 0;
3248 
3249  return xfer_window ( &tls->cipherstream );
3250 }
3251 
3252 /**
3253  * Deliver datagram as raw data
3254  *
3255  * @v tls TLS connection
3256  * @v iobuf I/O buffer
3257  * @v meta Data transfer metadata
3258  * @ret rc Return status code
3259  */
3260 static int tls_plainstream_deliver ( struct tls_connection *tls,
3261  struct io_buffer *iobuf,
3262  struct xfer_metadata *meta __unused ) {
3263  int rc;
3264 
3265  /* Refuse unless we are ready to accept data */
3266  if ( ! tls_ready ( tls ) ) {
3267  rc = -ENOTCONN;
3268  goto done;
3269  }
3270 
3271  if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
3272  iob_len ( iobuf ) ) ) != 0 )
3273  goto done;
3274 
3275  done:
3276  free_iob ( iobuf );
3277  return rc;
3278 }
3279 
3280 /**
3281  * Report job progress
3282  *
3283  * @v tls TLS connection
3284  * @v progress Progress report to fill in
3285  * @ret ongoing_rc Ongoing job status code (if known)
3286  */
3287 static int tls_progress ( struct tls_connection *tls,
3288  struct job_progress *progress ) {
3289 
3290  /* Return cipherstream or validator progress as applicable */
3291  if ( is_pending ( &tls->server.validation ) ) {
3292  return job_progress ( &tls->server.validator, progress );
3293  } else {
3294  return job_progress ( &tls->cipherstream, progress );
3295  }
3296 }
3297 
3298 /** TLS plaintext stream interface operations */
3300  INTF_OP ( xfer_deliver, struct tls_connection *,
3302  INTF_OP ( xfer_window, struct tls_connection *,
3305  INTF_OP ( intf_close, struct tls_connection *, tls_close ),
3306 };
3307 
3308 /** TLS plaintext stream interface descriptor */
3310  INTF_DESC_PASSTHRU ( struct tls_connection, plainstream,
3311  tls_plainstream_ops, cipherstream );
3312 
3313 /******************************************************************************
3314  *
3315  * Ciphertext stream operations
3316  *
3317  ******************************************************************************
3318  */
3319 
3320 /**
3321  * Handle received TLS header
3322  *
3323  * @v tls TLS connection
3324  * @ret rc Returned status code
3325  */
3326 static int tls_newdata_process_header ( struct tls_connection *tls ) {
3327  struct tls_cipherspec *cipherspec = &tls->rx.cipherspec.active;
3328  struct cipher_algorithm *cipher = cipherspec->suite->cipher;
3329  size_t iv_len = cipherspec->suite->record_iv_len;
3330  size_t data_len = ntohs ( tls->rx.header.length );
3331  size_t remaining = data_len;
3332  size_t frag_len;
3333  size_t reserve;
3334  struct io_buffer *iobuf;
3335  struct io_buffer *tmp;
3336  int rc;
3337 
3338  /* Sanity check */
3339  assert ( ( TLS_RX_BUFSIZE % cipher->alignsize ) == 0 );
3340 
3341  /* Calculate alignment reservation at start of first data buffer */
3342  reserve = ( ( -iv_len ) & ( cipher->alignsize - 1 ) );
3343  remaining += reserve;
3344 
3345  /* Allocate data buffers now that we know the length */
3346  assert ( list_empty ( &tls->rx.data ) );
3347  while ( remaining ) {
3348 
3349  /* Calculate fragment length. Ensure that no block is
3350  * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
3351  * allocation length if necessary).
3352  */
3353  frag_len = remaining;
3354  if ( frag_len > TLS_RX_BUFSIZE )
3355  frag_len = TLS_RX_BUFSIZE;
3356  remaining -= frag_len;
3357  if ( remaining < TLS_RX_MIN_BUFSIZE ) {
3358  frag_len += remaining;
3359  remaining = 0;
3360  }
3361 
3362  /* Allocate buffer */
3363  iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
3364  if ( ! iobuf ) {
3365  DBGC ( tls, "TLS %p could not allocate %zd of %zd "
3366  "bytes for receive buffer\n", tls,
3367  remaining, data_len );
3368  rc = -ENOMEM_RX_DATA;
3369  goto err;
3370  }
3371 
3372  /* Ensure tailroom is exactly what we asked for. This
3373  * will result in unaligned I/O buffers when the
3374  * fragment length is unaligned, which can happen only
3375  * before we switch to using a block cipher.
3376  */
3377  iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
3378 
3379  /* Ensure first buffer length will be aligned to a
3380  * multiple of the cipher alignment size after
3381  * stripping the record IV.
3382  */
3383  iob_reserve ( iobuf, reserve );
3384  reserve = 0;
3385 
3386  /* Add I/O buffer to list */
3387  list_add_tail ( &iobuf->list, &tls->rx.data );
3388  }
3389 
3390  /* Move to data state */
3391  tls->rx.state = TLS_RX_DATA;
3392 
3393  return 0;
3394 
3395  err:
3396  list_for_each_entry_safe ( iobuf, tmp, &tls->rx.data, list ) {
3397  list_del ( &iobuf->list );
3398  free_iob ( iobuf );
3399  }
3400  return rc;
3401 }
3402 
3403 /**
3404  * Handle received TLS data payload
3405  *
3406  * @v tls TLS connection
3407  * @ret rc Returned status code
3408  */
3409 static int tls_newdata_process_data ( struct tls_connection *tls ) {
3410  struct io_buffer *iobuf;
3411  int rc;
3412 
3413  /* Move current buffer to end of list */
3414  iobuf = list_first_entry ( &tls->rx.data, struct io_buffer, list );
3415  list_del ( &iobuf->list );
3416  list_add_tail ( &iobuf->list, &tls->rx.data );
3417 
3418  /* Continue receiving data if any space remains */
3419  iobuf = list_first_entry ( &tls->rx.data, struct io_buffer, list );
3420  if ( iob_tailroom ( iobuf ) )
3421  return 0;
3422 
3423  /* Process record */
3424  if ( ( rc = tls_new_ciphertext ( tls, &tls->rx.header,
3425  &tls->rx.data ) ) != 0 )
3426  return rc;
3427 
3428  /* Increment RX sequence number */
3429  tls->rx.seq += 1;
3430 
3431  /* Return to header state */
3432  assert ( list_empty ( &tls->rx.data ) );
3433  tls->rx.state = TLS_RX_HEADER;
3434  iob_unput ( &tls->rx.iobuf, sizeof ( tls->rx.header ) );
3435 
3436  return 0;
3437 }
3438 
3439 /**
3440  * Check flow control window
3441  *
3442  * @v tls TLS connection
3443  * @ret len Length of window
3444  */
3445 static size_t tls_cipherstream_window ( struct tls_connection *tls ) {
3446 
3447  /* Open window until we are ready to accept data */
3448  if ( ! tls_ready ( tls ) )
3449  return -1UL;
3450 
3451  return xfer_window ( &tls->plainstream );
3452 }
3453 
3454 /**
3455  * Receive new ciphertext
3456  *
3457  * @v tls TLS connection
3458  * @v iobuf I/O buffer
3459  * @v meta Data transfer metadat
3460  * @ret rc Return status code
3461  */
3462 static int tls_cipherstream_deliver ( struct tls_connection *tls,
3463  struct io_buffer *iobuf,
3464  struct xfer_metadata *xfer __unused ) {
3465  size_t frag_len;
3466  int ( * process ) ( struct tls_connection *tls );
3467  struct io_buffer *dest;
3468  int rc;
3469 
3470  while ( iob_len ( iobuf ) ) {
3471 
3472  /* Select buffer according to current state */
3473  switch ( tls->rx.state ) {
3474  case TLS_RX_HEADER:
3475  dest = &tls->rx.iobuf;
3477  break;
3478  case TLS_RX_DATA:
3479  dest = list_first_entry ( &tls->rx.data,
3480  struct io_buffer, list );
3481  assert ( dest != NULL );
3483  break;
3484  default:
3485  assert ( 0 );
3486  rc = -EINVAL_RX_STATE;
3487  goto done;
3488  }
3489 
3490  /* Copy data portion to buffer */
3491  frag_len = iob_len ( iobuf );
3492  if ( frag_len > iob_tailroom ( dest ) )
3493  frag_len = iob_tailroom ( dest );
3494  memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
3495  iob_pull ( iobuf, frag_len );
3496 
3497  /* Process data if buffer is now full */
3498  if ( iob_tailroom ( dest ) == 0 ) {
3499  if ( ( rc = process ( tls ) ) != 0 ) {
3500  tls_close ( tls, rc );
3501  goto done;
3502  }
3503  }
3504  }
3505  rc = 0;
3506 
3507  done:
3508  free_iob ( iobuf );
3509  return rc;
3510 }
3511 
3512 /** TLS ciphertext stream interface operations */
3514  INTF_OP ( xfer_deliver, struct tls_connection *,
3516  INTF_OP ( xfer_window, struct tls_connection *,
3519  tls_tx_resume ),
3520  INTF_OP ( intf_close, struct tls_connection *, tls_close ),
3521 };
3522 
3523 /** TLS ciphertext stream interface descriptor */
3525  INTF_DESC_PASSTHRU ( struct tls_connection, cipherstream,
3526  tls_cipherstream_ops, plainstream );
3527 
3528 /******************************************************************************
3529  *
3530  * Certificate validator
3531  *
3532  ******************************************************************************
3533  */
3534 
3535 /**
3536  * Handle certificate validation completion
3537  *
3538  * @v tls TLS connection
3539  * @v rc Reason for completion
3540  */
3541 static void tls_validator_done ( struct tls_connection *tls, int rc ) {
3542  struct tls_session *session = tls->session;
3543  struct x509_certificate *cert;
3544 
3545  /* Mark validation as complete */
3546  pending_put ( &tls->server.validation );
3547 
3548  /* Close validator interface */
3549  intf_restart ( &tls->server.validator, rc );
3550 
3551  /* Check for validation failure */
3552  if ( rc != 0 ) {
3553  DBGC ( tls, "TLS %p certificate validation failed: %s\n",
3554  tls, strerror ( rc ) );
3555  goto err;
3556  }
3557  DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
3558 
3559  /* Extract first certificate */
3560  cert = x509_first ( tls->server.chain );
3561  assert ( cert != NULL );
3562 
3563  /* Verify server name */
3564  if ( ( rc = x509_check_name ( cert, session->name ) ) != 0 ) {
3565  DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
3566  tls, session->name, strerror ( rc ) );
3567  goto err;
3568  }
3569 
3570  /* Extract the now trusted server public key */
3571  memcpy ( &tls->server.key, &cert->subject.public_key.raw,
3572  sizeof ( tls->server.key ) );
3573 
3574  /* Schedule Client Key Exchange, Change Cipher, and Finished */
3577  TLS_TX_FINISHED );
3578  if ( tls->client.chain ) {
3579  tls->tx.pending |= ( TLS_TX_CERTIFICATE |
3581  }
3582  tls_tx_resume ( tls );
3583 
3584  return;
3585 
3586  err:
3587  tls_close ( tls, rc );
3588  return;
3589 }
3590 
3591 /** TLS certificate validator interface operations */
3594 };
3595 
3596 /** TLS certificate validator interface descriptor */
3598  INTF_DESC ( struct tls_connection, server.validator,
3600 
3601 /******************************************************************************
3602  *
3603  * Controlling process
3604  *
3605  ******************************************************************************
3606  */
3607 
3608 /**
3609  * TLS TX state machine
3610  *
3611  * @v tls TLS connection
3612  */
3613 static void tls_tx_step ( struct tls_connection *tls ) {
3614  struct tls_session *session = tls->session;
3615  struct tls_connection *conn;
3616  int rc;
3617 
3618  /* Wait for cipherstream to become ready */
3619  if ( ! xfer_window ( &tls->cipherstream ) )
3620  return;
3621 
3622  /* Send first pending transmission */
3623  if ( tls->tx.pending & TLS_TX_CLIENT_HELLO ) {
3624  /* Serialise server negotiations within a session, to
3625  * provide a consistent view of session IDs and
3626  * session tickets.
3627  */
3628  list_for_each_entry ( conn, &session->conn, list ) {
3629  if ( conn == tls )
3630  break;
3631  if ( is_pending ( &conn->server.negotiation ) )
3632  return;
3633  }
3634  /* Record or generate session ID and associated master secret */
3635  if ( session->id_len ) {
3636  /* Attempt to resume an existing session */
3637  memcpy ( tls->session_id, session->id,
3638  sizeof ( tls->session_id ) );
3639  tls->session_id_len = session->id_len;
3641  sizeof ( tls->master_secret ) );
3642  } else {
3643  /* No existing session: use a random session ID */
3644  assert ( sizeof ( tls->session_id ) ==
3645  sizeof ( tls->client.random ) );
3646  memcpy ( tls->session_id, &tls->client.random,
3647  sizeof ( tls->session_id ) );
3648  tls->session_id_len = sizeof ( tls->session_id );
3649  }
3650  /* Send Client Hello */
3651  if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
3652  DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
3653  tls, strerror ( rc ) );
3654  goto err;
3655  }
3656  tls->tx.pending &= ~TLS_TX_CLIENT_HELLO;
3657  } else if ( tls->tx.pending & TLS_TX_CERTIFICATE ) {
3658  /* Send Certificate */
3659  if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
3660  DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
3661  tls, strerror ( rc ) );
3662  goto err;
3663  }
3664  tls->tx.pending &= ~TLS_TX_CERTIFICATE;
3665  } else if ( tls->tx.pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
3666  /* Send Client Key Exchange */
3667  if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
3668  DBGC ( tls, "TLS %p could not send Client Key "
3669  "Exchange: %s\n", tls, strerror ( rc ) );
3670  goto err;
3671  }
3673  } else if ( tls->tx.pending & TLS_TX_CERTIFICATE_VERIFY ) {
3674  /* Send Certificate Verify */
3675  if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
3676  DBGC ( tls, "TLS %p could not send Certificate "
3677  "Verify: %s\n", tls, strerror ( rc ) );
3678  goto err;
3679  }
3681  } else if ( tls->tx.pending & TLS_TX_CHANGE_CIPHER ) {
3682  /* Send Change Cipher, and then change the cipher in use */
3683  if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
3684  DBGC ( tls, "TLS %p could not send Change Cipher: "
3685  "%s\n", tls, strerror ( rc ) );
3686  goto err;
3687  }
3688  if ( ( rc = tls_change_cipher ( tls,
3689  &tls->tx.cipherspec ) ) != 0 ){
3690  DBGC ( tls, "TLS %p could not activate TX cipher: "
3691  "%s\n", tls, strerror ( rc ) );
3692  goto err;
3693  }
3694  tls->tx.seq = 0;
3695  tls->tx.pending &= ~TLS_TX_CHANGE_CIPHER;
3696  } else if ( tls->tx.pending & TLS_TX_FINISHED ) {
3697  /* Send Finished */
3698  if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
3699  DBGC ( tls, "TLS %p could not send Finished: %s\n",
3700  tls, strerror ( rc ) );
3701  goto err;
3702  }
3703  tls->tx.pending &= ~TLS_TX_FINISHED;
3704  }
3705 
3706  /* Reschedule process if pending transmissions remain,
3707  * otherwise send notification of a window change.
3708  */
3709  if ( tls->tx.pending ) {
3710  tls_tx_resume ( tls );
3711  } else {
3712  xfer_window_changed ( &tls->plainstream );
3713  }
3714 
3715  return;
3716 
3717  err:
3718  tls_close ( tls, rc );
3719 }
3720 
3721 /** TLS TX process descriptor */
3723  PROC_DESC_ONCE ( struct tls_connection, tx.process, tls_tx_step );
3724 
3725 /******************************************************************************
3726  *
3727  * Session management
3728  *
3729  ******************************************************************************
3730  */
3731 
3732 /**
3733  * Find or create session for TLS connection
3734  *
3735  * @v tls TLS connection
3736  * @v name Server name
3737  * @ret rc Return status code
3738  */
3739 static int tls_session ( struct tls_connection *tls, const char *name ) {
3740  struct tls_session *session;
3741  char *name_copy;
3742  int rc;
3743 
3744  /* Find existing matching session, if any */
3745  list_for_each_entry ( session, &tls_sessions, list ) {
3746  if ( ( strcmp ( name, session->name ) == 0 ) &&
3747  ( tls->server.root == session->root ) &&
3748  ( tls->client.key == session->key ) ) {
3749  ref_get ( &session->refcnt );
3750  tls->session = session;
3751  DBGC ( tls, "TLS %p joining session %s\n", tls, name );
3752  return 0;
3753  }
3754  }
3755 
3756  /* Create new session */
3757  session = zalloc ( sizeof ( *session ) + strlen ( name )
3758  + 1 /* NUL */ );
3759  if ( ! session ) {
3760  rc = -ENOMEM;
3761  goto err_alloc;
3762  }
3763  ref_init ( &session->refcnt, free_tls_session );
3764  name_copy = ( ( ( void * ) session ) + sizeof ( *session ) );
3765  strcpy ( name_copy, name );
3766  session->name = name_copy;
3767  session->root = x509_root_get ( tls->server.root );
3768  session->key = privkey_get ( tls->client.key );
3769  INIT_LIST_HEAD ( &session->conn );
3770  list_add ( &session->list, &tls_sessions );
3771 
3772  /* Record session */
3773  tls->session = session;
3774 
3775  DBGC ( tls, "TLS %p created session %s\n", tls, name );
3776  return 0;
3777 
3778  ref_put ( &session->refcnt );
3779  err_alloc:
3780  return rc;
3781 }
3782 
3783 /******************************************************************************
3784  *
3785  * Instantiator
3786  *
3787  ******************************************************************************
3788  */
3789 
3790 /**
3791  * Add TLS on an interface
3792  *
3793  * @v xfer Data transfer interface
3794  * @v name Host name
3795  * @v root Root of trust (or NULL to use default)
3796  * @v key Private key (or NULL to use default)
3797  * @ret rc Return status code
3798  */
3799 int add_tls ( struct interface *xfer, const char *name,
3800  struct x509_root *root, struct private_key *key ) {
3801  struct tls_connection *tls;
3802  int rc;
3803 
3804  /* Allocate and initialise TLS structure */
3805  tls = malloc ( sizeof ( *tls ) );
3806  if ( ! tls ) {
3807  rc = -ENOMEM;
3808  goto err_alloc;
3809  }
3810  memset ( tls, 0, sizeof ( *tls ) );
3811  ref_init ( &tls->refcnt, free_tls );
3812  INIT_LIST_HEAD ( &tls->list );
3813  intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
3815  intf_init ( &tls->server.validator, &tls_validator_desc, &tls->refcnt );
3817  &tls->refcnt );
3818  tls->client.key = privkey_get ( key ? key : &private_key );
3820  tls->version = TLS_VERSION_MAX;
3821  tls_clear_cipher ( tls, &tls->tx.cipherspec.active );
3822  tls_clear_cipher ( tls, &tls->tx.cipherspec.pending );
3823  tls_clear_cipher ( tls, &tls->rx.cipherspec.active );
3824  tls_clear_cipher ( tls, &tls->rx.cipherspec.pending );
3825  tls_clear_handshake ( tls );
3826  tls->client.random.gmt_unix_time = time ( NULL );
3827  iob_populate ( &tls->rx.iobuf, &tls->rx.header, 0,
3828  sizeof ( tls->rx.header ) );
3829  INIT_LIST_HEAD ( &tls->rx.data );
3830  if ( ( rc = tls_generate_random ( tls, &tls->client.random.random,
3831  ( sizeof ( tls->client.random.random ) ) ) ) != 0 ) {
3832  goto err_random;
3833  }
3834  if ( ( rc = tls_session ( tls, name ) ) != 0 )
3835  goto err_session;
3836  list_add_tail ( &tls->list, &tls->session->conn );
3837 
3838  /* Start negotiation */
3839  tls_restart ( tls );
3840 
3841  /* Attach to parent interface, mortalise self, and return */
3842  intf_insert ( xfer, &tls->plainstream, &tls->cipherstream );
3843  ref_put ( &tls->refcnt );
3844  return 0;
3845 
3846  err_session:
3847  err_random:
3848  ref_put ( &tls->refcnt );
3849  err_alloc:
3850  return rc;
3851 }
3852 
3853 /* Drag in objects via add_tls() */
3855 
3856 /* Drag in crypto configuration */
3857 REQUIRE_OBJECT ( config_crypto );
Transport Layer Security Protocol.
#define cpu_to_be16(value)
Definition: byteswap.h:109
struct tls_verify_data verify
Verification data.
Definition: tls.h:447
void * memswap(void *first, void *second, size_t len)
Swap memory regions.
Definition: string.c:153
static void free_tls(struct refcnt *refcnt)
Free TLS connection.
Definition: tls.c:376
static void x509_chain_put(struct x509_chain *chain)
Drop reference to X.509 certificate chain.
Definition: x509.h:299
A process.
Definition: process.h:17
#define iob_pull(iobuf, len)
Definition: iobuf.h:102
static int tls_send_certificate(struct tls_connection *tls)
Transmit Certificate record.
Definition: tls.c:1323
uint8_t id[32]
Session ID.
Definition: tls.h:335
void hmac_init(struct digest_algorithm *digest, void *ctx, const void *key, size_t key_len)
Initialise HMAC.
Definition: hmac.c:57
#define __attribute__(x)
Definition: compiler.h:10
struct tls_header header
Current received record header.
Definition: tls.h:370
An object interface operation.
Definition: interface.h:17
u16 length
Definition: sky2.h:9
#define EPERM_CLIENT_CERT
Definition: tls.c:173
static int is_auth_cipher(struct cipher_algorithm *cipher)
Definition: crypto.h:264
size_t blocksize
Block size.
Definition: crypto.h:60
struct digest_algorithm * digest
Digest algorithm.
Definition: tls.h:270
struct asn1_cursor raw
Raw public key information.
Definition: x509.h:51
uint64_t seq
Sequence number.
Definition: tls.h:144
uint8_t random[32]
Random bytes.
Definition: tls.h:394
#define EINVAL_PADDING
Definition: tls.c:93
struct arbelprm_rc_send_wqe rc
Definition: arbel.h:14
pseudo_bit_t hash[0x00010]
Definition: arbel.h:13
static void tls_tx_resume_all(struct tls_session *session)
Resume TX state machine for all connections within a session.
Definition: tls.c:1090
static void digest_update(struct digest_algorithm *digest, void *ctx, const void *data, size_t len)
Definition: crypto.h:206
const char * name
Definition: ath9k_hw.c:1984
void xfer_window_changed(struct interface *intf)
Report change of flow control window.
Definition: xfer.c:146
unsigned short uint16_t
Definition: stdint.h:11
static int tls_change_cipher(struct tls_connection *tls, struct tls_cipherspec_pair *pair)
Activate next cipher suite.
Definition: tls.c:954
void intf_close(struct interface *intf, int rc)
Close an object interface.
Definition: interface.c:249
An MD5+SHA1 context.
Definition: tls.h:299
uint8_t sha1[SHA1_DIGEST_SIZE]
SHA-1 digest.
Definition: tls.h:314
static void tls_validator_done(struct tls_connection *tls, int rc)
Handle certificate validation completion.
Definition: tls.c:3541
static void privkey_put(struct private_key *key)
Drop reference to private key.
Definition: privkey.h:41
void intf_restart(struct interface *intf, int rc)
Shut down and restart an object interface.
Definition: interface.c:343
struct asn1_cursor key
Public key (within server certificate)
Definition: tls.h:404
static int pubkey_verify(struct pubkey_algorithm *pubkey, const struct asn1_cursor *key, struct digest_algorithm *digest, const void *value, const void *signature, size_t signature_len)
Definition: crypto.h:294
struct tls_cipher_suite tls_cipher_suite_null
Null cipher suite.
Definition: tls.c:822
static int tls_select_cipher(struct tls_connection *tls, unsigned int cipher_suite)
Select next cipher suite.
Definition: tls.c:911
#define iob_put(iobuf, len)
Definition: iobuf.h:120
#define va_end(ap)
Definition: stdarg.h:9
static int elliptic_multiply(struct elliptic_curve *curve, const void *base, const void *scalar, void *result)
Definition: crypto.h:308
#define TLS_NUM_CIPHER_SUITES
Number of supported cipher suites.
Definition: tls.c:830
Data transfer metadata.
Definition: xfer.h:22
void intf_shutdown(struct interface *intf, int rc)
Shut down an object interface.
Definition: interface.c:278
static void tls_tx_resume(struct tls_connection *tls)
Resume TX state machine.
Definition: tls.c:1081
static int tls_new_ciphertext(struct tls_connection *tls, struct tls_header *tlshdr, struct list_head *rx_data)
Receive new ciphertext record.
Definition: tls.c:3097
static int tls_newdata_process_header(struct tls_connection *tls)
Handle received TLS header.
Definition: tls.c:3326
#define TLS_RENEGOTIATION_INFO
Definition: tls.h:139
int xfer_deliver_iob(struct interface *intf, struct io_buffer *iobuf)
Deliver datagram as I/O buffer without metadata.
Definition: xfer.c:255
A TLS cipher specification pair.
Definition: tls.h:252
struct process process
Transmit process.
Definition: tls.h:358
struct x509_chain certstore
Certificate store.
Definition: certstore.c:89
#define max(x, y)
Definition: ath.h:39
struct tls_session * session
Session.
Definition: tls.h:419
static struct tls_named_curve * tls_find_named_curve(unsigned int named_curve)
Identify named curve.
Definition: tls.c:1057
uint8_t master_secret[48]
Master secret.
Definition: tls.h:343
static struct x509_certificate * x509_get(struct x509_certificate *cert)
Get reference to X.509 certificate.
Definition: x509.h:266
struct tls_key_exchange_algorithm * exchange
Key exchange algorithm.
Definition: tls.h:189
struct list_head data
List of received data buffers.
Definition: tls.h:374
uint8_t md5[MD5_DIGEST_SIZE]
MD5 digest.
Definition: tls.h:312
uint8_t record_iv_len
Record initialisation vector length.
Definition: tls.h:205
static unsigned long tls_uint24(const tls24_t *field24)
Extract 24-bit field value.
Definition: tls.c:230
static void tls_restart(struct tls_connection *tls)
Restart negotiation.
Definition: tls.c:1102
#define TLS_NUM_NAMED_CURVES
Number of supported named curves.
Definition: tls.c:1048
struct io_buffer * handshake
Received handshake fragment.
Definition: tls.h:376
int dhe_key(const void *modulus, size_t len, const void *generator, size_t generator_len, const void *partner, size_t partner_len, const void *private, size_t private_len, void *public, void *shared)
Calculate Diffie-Hellman key.
Definition: dhe.c:53
static struct pubkey_algorithm * tls_signature_hash_pubkey(struct tls_signature_hash_id code)
Find TLS signature algorithm.
Definition: tls.c:1009
static int pubkey_encrypt(struct pubkey_algorithm *pubkey, const struct asn1_cursor *key, const void *data, size_t len, void *out)
Definition: crypto.h:275
u8 sig
Definition: CIB_PRM.h:43
struct stp_switch root
Root switch.
Definition: stp.h:26
struct pending_operation negotiation
Security negotiation pending operation.
Definition: tls.h:388
#define list_add(new, head)
Add a new entry to the head of a list.
Definition: list.h:69
uint32_t next
Next descriptor address.
Definition: myson.h:18
uint16_t spec
ENA specification version.
Definition: ena.h:26
struct list_head links
List of links.
Definition: x509.h:204
static struct tls_cipher_suite * tls_find_cipher_suite(unsigned int cipher_suite)
Identify cipher suite.
Definition: tls.c:839
#define EPERM_KEY_EXCHANGE
Definition: tls.c:185
uint32_t first
First block in range.
Definition: pccrr.h:14
#define ref_init(refcnt, free)
Initialise a reference counter.
Definition: refcnt.h:64
Error codes.
struct refcnt refcnt
Reference counter.
Definition: tls.h:416
#define EINVAL_HELLO
Definition: tls.c:65
struct tls_cipherspec_pair cipherspec
Cipher specifications.
Definition: tls.h:364
uint8_t type
Content type.
Definition: tls.h:33
static void tls_verify_handshake(struct tls_connection *tls, void *out)
Calculate handshake verification hash.
Definition: tls.c:806
int x509_check_name(struct x509_certificate *cert, const char *name)
Check X.509 certificate name.
Definition: x509.c:1561
static int rbg_generate(const void *additional, size_t additional_len, int prediction_resist, void *data, size_t len)
Generate bits using RBG.
Definition: rbg.h:36
static int tls_send_client_key_exchange_pubkey(struct tls_connection *tls)
Transmit Client Key Exchange record using public key exchange.
Definition: tls.c:1385
I/O buffers.
static int tls_cipherstream_deliver(struct tls_connection *tls, struct io_buffer *iobuf, struct xfer_metadata *xfer __unused)
Receive new ciphertext.
Definition: tls.c:3462
void free_iob(struct io_buffer *iobuf)
Free I/O buffer.
Definition: iobuf.c:146
struct io_buffer * alloc_iob_raw(size_t len, size_t align, size_t offset)
Allocate I/O buffer with specified alignment and offset.
Definition: iobuf.c:48
static int tls_add_handshake(struct tls_connection *tls, const void *data, size_t len)
Add handshake record to verification hash.
Definition: tls.c:790
static void digest_final(struct digest_algorithm *digest, void *ctx, void *out)
Definition: crypto.h:212
#define ENOTSUP_CURVE
Definition: tls.c:161
uint32_t type
Operating system type.
Definition: ena.h:12
int x509_append_raw(struct x509_chain *chain, const void *data, size_t len)
Append X.509 certificate to X.509 certificate chain.
Definition: x509.c:1660
static void tls_generate_master_secret(struct tls_connection *tls, const void *pre_master_secret, size_t pre_master_secret_len)
Generate master secret.
Definition: tls.c:636
static LIST_HEAD(tls_sessions)
List of TLS session.
size_t alignsize
Alignment size.
Definition: crypto.h:72
#define ENOTSUP_VERSION
Definition: tls.c:157
static struct interface_operation tls_plainstream_ops[]
TLS plaintext stream interface operations.
Definition: tls.c:3299
void pending_put(struct pending_operation *pending)
Mark an operation as no longer pending.
Definition: pending.c:58
#define TLS_CLIENT_HELLO
Definition: tls.h:69
struct x509_root root_certificates
Root certificates.
Definition: rootcert.c:73
struct asn1_algorithm * signature_algorithm
Signature algorithm.
Definition: x509.h:238
const void * data
Start of data.
Definition: asn1.h:22
#define DBGC(...)
Definition: compiler.h:505
void * exchange
Server Key Exchange record (if any)
Definition: tls.h:396
size_t new_session_ticket_len
Length of new session ticket.
Definition: tls.h:429
#define ENOMEM_RX_CONCAT
Definition: tls.c:141
A process descriptor.
Definition: process.h:31
#define TLS_VERSION_TLS_1_2
TLS version 1.2.
Definition: tls.h:47
#define TLS_CERTIFICATE
Definition: tls.h:72
int x509_append(struct x509_chain *chain, struct x509_certificate *cert)
Append X.509 certificate to X.509 certificate chain.
Definition: x509.c:1635
static struct private_key * privkey_get(struct private_key *key)
Get reference to private key.
Definition: privkey.h:30
uint8_t session_id[32]
Session ID.
Definition: tls.h:423
FILE_LICENCE(GPL2_OR_LATER)
struct x509_chain * x509_alloc_chain(void)
Allocate X.509 certificate chain.
Definition: x509.c:1612
static void x509_root_put(struct x509_root *root)
Drop reference to X.509 root certificate list.
Definition: x509.h:403
#define EINVAL_HELLO_DONE
Definition: tls.c:77
uint16_t length
Length of payload.
Definition: tls.h:40
unsigned long long uint64_t
Definition: stdint.h:13
struct io_buffer * xfer_alloc_iob(struct interface *intf, size_t len)
Allocate I/O buffer.
Definition: xfer.c:158
struct eltorito_descriptor_fixed fixed
Fixed portion.
Definition: eltorito.h:13
void alert(unsigned int row, const char *fmt,...)
Show alert message.
Definition: message.c:103
struct pubkey_algorithm pubkey_null
Definition: crypto_null.c:128
#define EPROTO_VERSION
Definition: tls.c:189
#define EIO_ALERT
Definition: tls.c:113
struct tls_key_exchange_algorithm tls_pubkey_exchange_algorithm
Public key exchange algorithm.
Definition: tls.c:1438
uint32_t data_len
Microcode data size (or 0 to indicate 2000 bytes)
Definition: ucode.h:26
static struct digest_algorithm * tls_signature_hash_digest(struct tls_signature_hash_id code)
Find TLS hash algorithm.
Definition: tls.c:1028
static struct interface_operation tls_validator_ops[]
TLS certificate validator interface operations.
Definition: tls.c:3592
#define ENOMEM_CHAIN
Definition: tls.c:125
#define va_copy(dest, src)
Definition: stdarg.h:10
#define ntohs(value)
Definition: byteswap.h:136
#define TLS_SERVER_HELLO_DONE
Definition: tls.h:75
#define PROC_DESC_ONCE(object_type, process, _step)
Define a process descriptor for a process that runs only once.
Definition: process.h:97
static void tls_close(struct tls_connection *tls, int rc)
Finish with TLS connection.
Definition: tls.c:415
#define TLS_CERTIFICATE_REQUEST
Definition: tls.h:74
TLS authentication header.
Definition: tls.h:142
u32 pad[9]
Padding.
Definition: ar9003_mac.h:90
uint8_t mac[ETH_ALEN]
MAC address.
Definition: ena.h:24
static void md5_sha1_final(void *ctx, void *out)
Generate MD5+SHA1 digest.
Definition: tls.c:314
struct golan_eq_context ctx
Definition: CIB_PRM.h:28
A TLS cipher specification.
Definition: tls.h:238
static void iob_populate(struct io_buffer *iobuf, void *data, size_t len, size_t max_len)
Create a temporary I/O buffer.
Definition: iobuf.h:190
#define EINVAL_CERTIFICATE
Definition: tls.c:69
static void free_tls_session(struct refcnt *refcnt)
Free TLS session.
Definition: tls.c:352
const char * name
Algorithm name.
Definition: tls.h:176
struct pubkey_algorithm * pubkey
Public-key encryption algorithm.
Definition: tls.h:191
static void md5_sha1_init(void *ctx)
Initialise MD5+SHA1 algorithm.
Definition: tls.c:287
#define list_last_entry(list, type, member)
Get the container of the last entry in a list.
Definition: list.h:346
void process_del(struct process *process)
Remove process from process list.
Definition: process.c:79
static unsigned int code
Response code.
Definition: hyperv.h:26
#define htonl(value)
Definition: byteswap.h:133
size_t xfer_window(struct interface *intf)
Check flow control window.
Definition: xfer.c:116
u8 iv[16]
Initialization vector.
Definition: wpa.h:60
static void tls_hmac_final(struct tls_cipherspec *cipherspec, void *ctx, void *hmac)
Finalise HMAC.
Definition: tls.c:2867
static struct interface_descriptor tls_cipherstream_desc
TLS ciphertext stream interface descriptor.
Definition: tls.c:3524
A doubly-linked list entry (or list head)
Definition: list.h:18
#define TLS_MAX_FRAGMENT_LENGTH
Definition: tls.h:122
static int tls_send_handshake(struct tls_connection *tls, const void *data, size_t len)
Transmit Handshake record.
Definition: tls.c:1125
Data transfer interfaces.
size_t len
Length of data.
Definition: asn1.h:24
A reference counter.
Definition: refcnt.h:26
static struct asn1_cursor * privkey_cursor(struct private_key *key)
Get private key ASN.1 cursor.
Definition: privkey.h:52
static struct interface_descriptor tls_validator_desc
TLS certificate validator interface descriptor.
Definition: tls.c:3597
#define EINVAL_CHANGE_CIPHER
Definition: tls.c:57
Private key.
#define TLS_NAMED_CURVE
Definition: tls.h:129
struct private_key * key
Private key (if used)
Definition: tls.h:384
#define list_empty(list)
Test whether a list is empty.
Definition: list.h:136
static void tls_hmac_list(struct tls_cipherspec *cipherspec, struct tls_auth_header *authhdr, struct list_head *list, void *hmac)
Calculate HMAC over list of I/O buffers.
Definition: tls.c:2902
unsigned long tmp
Definition: linux_pci.h:63
struct tls_server server
Server state.
Definition: tls.h:456
#define ENOMEM_CONTEXT
Definition: tls.c:117
struct pubkey_algorithm * pubkey
Public-key algorithm (if applicable)
Definition: asn1.h:372
#define cipher_encrypt(cipher, ctx, src, dst, len)
Definition: crypto.h:233
#define list_first_entry(list, type, member)
Get the container of the first entry in a list.
Definition: list.h:333
struct refcnt refcnt
Reference counter.
Definition: tls.h:323
size_t authsize
Authentication tag size.
Definition: crypto.h:74
#define EINVAL_MAC
Definition: tls.c:101
#define list_del(list)
Delete an entry from a list.
Definition: list.h:119
static int tls_send_client_key_exchange_ecdhe(struct tls_connection *tls)
Transmit Client Key Exchange record using ECDHE key exchange.
Definition: tls.c:1664
void * tail
End of data.
Definition: iobuf.h:50
static int tls_new_hello_request(struct tls_connection *tls, const void *data __unused, size_t len __unused)
Receive new Hello Request handshake record.
Definition: tls.c:2025
#define ENOMEM
Not enough space.
Definition: errno.h:534
#define ENOTSUP_NULL
Definition: tls.c:149
#define iob_disown(iobuf)
Disown an I/O buffer.
Definition: iobuf.h:212
#define TLS_NAMED_CURVE_TYPE
TLS named curved type.
Definition: tls.h:219
uint8_t * handshake_ctx
Digest algorithm context used for handshake verification.
Definition: tls.h:443
void * memcpy(void *dest, const void *src, size_t len) __nonnull
Certificate store.
#define va_arg(ap, type)
Definition: stdarg.h:8
static void tls_hmac_update_va(struct digest_algorithm *digest, void *ctx, va_list args)
Update HMAC with a list of ( data, len ) pairs.
Definition: tls.c:476
int(* exchange)(struct tls_connection *tls)
Transmit Client Key Exchange record.
Definition: tls.h:183
u32 version
Driver version.
Definition: ath9k_hw.c:1983
REQUIRE_OBJECT(config_crypto)
#define __unused
Declare a variable or data structure as unused.
Definition: compiler.h:573
static int tls_newdata_process_data(struct tls_connection *tls)
Handle received TLS data payload.
Definition: tls.c:3409
int create_validator(struct interface *job, struct x509_chain *chain, struct x509_root *root)
Instantiate a certificate validator.
Definition: validator.c:759
#define TLS_TYPE_CHANGE_CIPHER
Change cipher content type.
Definition: tls.h:53
#define ENOTSUP_CIPHER
Definition: tls.c:145
size_t id_len
Length of session ID.
Definition: tls.h:337
assert((readw(&hdr->flags) &(GTF_reading|GTF_writing))==0)
#define container_of(ptr, type, field)
Get containing structure.
Definition: stddef.h:35
Certificate validator.
static struct tls_signature_hash_algorithm * tls_signature_hash_algorithm(struct pubkey_algorithm *pubkey, struct digest_algorithm *digest)
Find TLS signature and hash algorithm.
Definition: tls.c:987
An object interface.
Definition: interface.h:124
Keyed-Hashing for Message Authentication.
#define ENOMEM_RX_DATA
Definition: tls.c:137
#define TLS_RX_ALIGN
RX I/O buffer alignment.
Definition: tls.h:478
void * new_session_ticket
New session ticket.
Definition: tls.h:427
struct tls_client client
Client state.
Definition: tls.h:454
static int tls_progress(struct tls_connection *tls, struct job_progress *progress)
Report job progress.
Definition: tls.c:3287
static int tls_send_change_cipher(struct tls_connection *tls)
Transmit Change Cipher record.
Definition: tls.c:1890
void * cipher_ctx
Bulk encryption cipher context.
Definition: tls.h:244
static void tls_tx_step(struct tls_connection *tls)
TLS TX state machine.
Definition: tls.c:3613
#define list_for_each_entry(pos, head, member)
Iterate over entries in a list.
Definition: list.h:431
pseudo_bit_t value[0x00020]
Definition: arbel.h:13
#define TLS_SESSION_TICKET
Definition: tls.h:136
#define DBGC_HDA(...)
Definition: compiler.h:506
static int tls_new_session_ticket(struct tls_connection *tls, const void *data, size_t len)
Receive New Session Ticket handshake record.
Definition: tls.c:2241
#define list_add_tail(new, head)
Add a new entry to the tail of a list.
Definition: list.h:93
struct tls_cipher_suite * suite
Cipher suite.
Definition: tls.h:240
static void tls_hmac_update(struct tls_cipherspec *cipherspec, void *ctx, const void *data, size_t len)
Update HMAC.
Definition: tls.c:2853
#define EINVAL_FINISHED
Definition: tls.c:81
struct digest_algorithm * digest
MAC digest algorithm.
Definition: tls.h:195
static void tls_prf(struct tls_connection *tls, const void *secret, size_t secret_len, void *out, size_t out_len,...)
Generate secure pseudo-random data.
Definition: tls.c:560
struct list_head list
List of connections within the same session.
Definition: tls.h:421
uint32_t gmt_unix_time
GMT Unix time.
Definition: tls.h:293
#define be16_to_cpu(value)
Definition: byteswap.h:115
__be32 out[4]
Definition: CIB_PRM.h:36
u32 link
Link to next descriptor.
Definition: ar9003_mac.h:68
uint8_t fixed_iv_len
Fixed initialisation vector length.
Definition: tls.h:203
A TLS cipher suite.
Definition: tls.h:187
char * strcpy(char *dest, const char *src)
Copy string.
Definition: string.c:346
#define TLS_SERVER_NAME
Definition: tls.h:118
A TLS signature algorithm.
Definition: tls.h:268
static int is_pending(struct pending_operation *pending)
Check if an operation is pending.
Definition: pending.h:24
#define EPERM_VERIFY
Definition: tls.c:169
static int tls_new_alert(struct tls_connection *tls, struct io_buffer *iobuf)
Receive new Alert record.
Definition: tls.c:1983
static struct x509_root * x509_root_get(struct x509_root *root)
Get reference to X.509 root certificate list.
Definition: x509.h:392
size_t ticket_len
Length of session ticket.
Definition: tls.h:341
uint8_t master_secret[48]
Master secret.
Definition: tls.h:439
struct list_head list
List of sessions.
Definition: tls.h:325
static void tls_hmac_init(struct tls_cipherspec *cipherspec, void *ctx, struct tls_auth_header *authhdr)
Initialise HMAC.
Definition: tls.c:2836
#define TLS_ALERT_WARNING
Definition: tls.h:81
#define ENOMEM_TX_CIPHERTEXT
Definition: tls.c:133
static int tls_send_client_key_exchange(struct tls_connection *tls)
Transmit Client Key Exchange record.
Definition: tls.c:1782
static int tls_new_data(struct tls_connection *tls, struct list_head *rx_data)
Receive new data record.
Definition: tls.c:2726
const char * name
Curve name.
Definition: crypto.h:186
struct tls_cipherspec_pair cipherspec
Cipher specifications.
Definition: tls.h:352
#define EINVAL_RX_STATE
Definition: tls.c:97
static int tls_new_change_cipher(struct tls_connection *tls, struct io_buffer *iobuf)
Receive new Change Cipher record.
Definition: tls.c:1948
#define TLS_RX_BUFSIZE
RX I/O buffer size.
Definition: tls.h:467
#define list_for_each_entry_safe(pos, tmp, head, member)
Iterate over entries in a list, safe against deletion of the current entry.
Definition: list.h:458
#define cpu_to_le32(value)
Definition: byteswap.h:107
#define TLS_NAMED_CURVES
TLS named curve table.
Definition: tls.h:230
static struct digest_algorithm md5_sha1_algorithm
Hybrid MD5+SHA1 digest algorithm.
Definition: tls.c:323
RBG mechanism.
struct x509_public_key public_key
Public key information.
Definition: x509.h:65
void process_add(struct process *process)
Add process to process list.
Definition: process.c:59
int meta(WINDOW *, bool)
#define ENOTCONN
The socket is not connected.
Definition: errno.h:569
AES algorithm.
static void digest_init(struct digest_algorithm *digest, void *ctx)
Definition: crypto.h:201
size_t keysize
Key size.
Definition: crypto.h:188
struct io_buffer * iob_concatenate(struct list_head *list)
Concatenate I/O buffers into a single buffer.
Definition: iobuf.c:243
An object interface descriptor.
Definition: interface.h:55
#define TLS_NUM_SIG_HASH_ALGORITHMS
Number of supported signature and hash algorithms.
Definition: tls.c:976
#define TLS_HELLO_REQUEST
Definition: tls.h:68
struct tls_header header
TLS header.
Definition: tls.h:146
#define iob_unput(iobuf, len)
Definition: iobuf.h:135
static void hmac_update(struct digest_algorithm *digest, void *ctx, const void *data, size_t len)
Update HMAC.
Definition: hmac.h:42
int x509_auto_append(struct x509_chain *chain, struct x509_chain *store)
Append X.509 certificates to X.509 certificate chain.
Definition: x509.c:1854
static struct x509_certificate * x509_last(struct x509_chain *chain)
Get last certificate in X.509 certificate chain.
Definition: x509.h:324
static int tls_send_plaintext(struct tls_connection *tls, unsigned int type, const void *data, size_t len)
Send plaintext record.
Definition: tls.c:2926
static size_t hmac_ctxsize(struct digest_algorithm *digest)
Calculate HMAC context size.
Definition: hmac.h:28
char * strerror(int errno)
Retrieve string representation of error number.
Definition: strerror.c:78
uint64_t seq
Sequence number.
Definition: tls.h:354
An X.509 certificate.
Definition: x509.h:215
static void(* free)(struct refcnt *refcnt))
Definition: refcnt.h:54
struct interface cipherstream
Ciphertext stream.
Definition: tls.h:434
struct pending_operation negotiation
Security negotiation pending operation.
Definition: tls.h:410
void * zalloc(size_t size)
Allocate cleared memory.
Definition: malloc.c:624
#define DBGC2_HD(...)
Definition: compiler.h:524
static int tls_new_finished(struct tls_connection *tls, const void *data, size_t len)
Receive new Finished handshake record.
Definition: tls.c:2544
struct x509_subject subject
Subject.
Definition: x509.h:244
uint8_t hash
Hash algorithm.
Definition: tls.h:262
void * ticket
Session ticket.
Definition: tls.h:339
#define ref_get(refcnt)
Get additional reference to object.
Definition: refcnt.h:92
struct digest_algorithm digest_null
Definition: crypto_null.c:48
struct elliptic_curve * curve
Elliptic curve.
Definition: tls.h:224
static size_t iob_len(struct io_buffer *iobuf)
Calculate length of data in an I/O buffer.
Definition: iobuf.h:155
static struct interface_operation tls_cipherstream_ops[]
TLS ciphertext stream interface operations.
Definition: tls.c:3513
Job progress.
Definition: job.h:15
#define INTF_OP(op_type, object_type, op_func)
Define an object interface operation.
Definition: interface.h:32
struct x509_chain * chain
Certificate chain.
Definition: tls.h:402
static int tls_new_server_hello(struct tls_connection *tls, const void *data, size_t len)
Receive new Server Hello handshake record.
Definition: tls.c:2056
#define EINVAL_ALERT
Definition: tls.c:61
#define DBGC_HD(...)
Definition: compiler.h:507
static void cipher_setiv(struct cipher_algorithm *cipher, void *ctx, const void *iv, size_t ivlen)
Definition: crypto.h:223
#define for_each_table_entry(pointer, table)
Iterate through all entries within a linker table.
Definition: tables.h:385
uint8_t mac_len
MAC length.
Definition: tls.h:207
long int random(void)
Generate a pseudo-random number between 0 and 2147483647L or 2147483562?
Definition: random.c:31
static size_t iob_tailroom(struct io_buffer *iobuf)
Calculate available space at end of an I/O buffer.
Definition: iobuf.h:175
int xfer_deliver(struct interface *intf, struct io_buffer *iobuf, struct xfer_metadata *meta)
Deliver datagram.
Definition: xfer.c:194
size_t strlen(const char *src)
Get length of string.
Definition: string.c:243
struct pending_operation validation
Certificate validation pending operation.
Definition: tls.h:408
static int tls_verify_dh_params(struct tls_connection *tls, size_t param_len)
Verify Diffie-Hellman parameter signature.
Definition: tls.c:1450
An RSA digestInfo prefix.
Definition: rsa.h:42
unsigned char uint8_t
Definition: stdint.h:10
uint8_t signature
Signature algorithm.
Definition: tls.h:264
Data transfer interface opening.
#define TLS_ALERT_FATAL
Definition: tls.h:82
#define EPERM_RENEG_VERIFY
Definition: tls.c:181
#define TLS_SIG_HASH_ALGORITHMS
TLS signature hash algorithm table.
Definition: tls.h:282
REQUIRING_SYMBOL(add_tls)
uint16_t hello
Hello time.
Definition: stp.h:38
static void process_init_stopped(struct process *process, struct process_descriptor *desc, struct refcnt *refcnt)
Initialise process without adding to process list.
Definition: process.h:145
X.509 certificates.
unsigned int pending
Pending transmissions.
Definition: tls.h:356
u32 lifetime
For Lifetime-type KDEs, the lifetime in seconds.
Definition: wpa.h:54
struct tls_cipherspec pending
Next cipher specification.
Definition: tls.h:256
size_t ctxsize
Context size.
Definition: crypto.h:54
#define cipher_decrypt(cipher, ctx, src, dst, len)
Definition: crypto.h:243
unsigned int uint32_t
Definition: stdint.h:12
void * malloc(size_t size)
Allocate memory.
Definition: malloc.c:583
static int tls_plainstream_deliver(struct tls_connection *tls, struct io_buffer *iobuf, struct xfer_metadata *meta __unused)
Deliver datagram as raw data.
Definition: tls.c:3260
static int tls_new_certificate_request(struct tls_connection *tls, const void *data __unused, size_t len __unused)
Receive new Certificate Request handshake record.
Definition: tls.c:2444
#define TLS_RX_MIN_BUFSIZE
Minimum RX I/O buffer size.
Definition: tls.h:475
struct tls_rx rx
Receive state.
Definition: tls.h:452
struct cipher_algorithm cipher_null
Definition: crypto_null.c:83
uint8_t unused
Unused.
Definition: librm.h:254
Cryptographic configuration.
Job control interfaces.
struct tls_signature_hash_id code
Numeric code.
Definition: tls.h:274
#define TLS_NEW_SESSION_TICKET
Definition: tls.h:71
uint16_t ext
Extended status.
Definition: ena.h:20
enum tls_rx_state state
State machine current state.
Definition: tls.h:368
#define TLS_VERSION_MAX
Maximum supported TLS version.
Definition: tls.h:50
#define TLS_SERVER_NAME_HOST_NAME
Definition: tls.h:119
uint8_t client[12]
Client verification data.
Definition: tls.h:152
An MD5+SHA1 digest.
Definition: tls.h:310
An X.509 root certificate list.
Definition: x509.h:374
A TLS header.
Definition: tls.h:28
Date and time.
struct tls_tx tx
Transmit state.
Definition: tls.h:450
Pending operations.
long pad_len
Definition: bigint.h:30
#define TLS_TYPE_HANDSHAKE
Handshake content type.
Definition: tls.h:62
RSA public-key cryptography.
A TLS 24-bit integer.
Definition: tls.c:215
static struct interface_descriptor tls_plainstream_desc
TLS plaintext stream interface descriptor.
Definition: tls.c:3309
#define iob_reserve(iobuf, len)
Definition: iobuf.h:67
static int tls_generate_keys(struct tls_connection *tls)
Generate key material.
Definition: tls.c:664
void intf_insert(struct interface *intf, struct interface *upper, struct interface *lower)
Insert a filter interface.
Definition: interface.c:401
#define INIT_LIST_HEAD(list)
Initialise a list head.
Definition: list.h:45
#define INTF_DESC(object_type, intf, operations)
Define an object interface descriptor.
Definition: interface.h:80
const char * x509_name(struct x509_certificate *cert)
Get X.509 certificate display name.
Definition: x509.c:146
static int tls_version(struct tls_connection *tls, unsigned int version)
Check for TLS version.
Definition: tls.c:270
static int tls_send_certificate_verify(struct tls_connection *tls)
Transmit Certificate Verify record.
Definition: tls.c:1810
#define EPERM_RENEG_INSECURE
Definition: tls.c:177
struct digest_algorithm * handshake_digest
Digest algorithm used for handshake verification.
Definition: tls.h:441
uint8_t random[28]
Random data.
Definition: tls.h:295
static int tls_client_hello(struct tls_connection *tls, int(*action)(struct tls_connection *tls, const void *data, size_t len))
Digest or transmit Client Hello record.
Definition: tls.c:1142
uint64_t seq
Sequence number.
Definition: tls.h:366
#define ENOMEM_TX_PLAINTEXT
Definition: tls.c:129
static void tls_hmac(struct tls_cipherspec *cipherspec, struct tls_auth_header *authhdr, const void *data, size_t len, void *hmac)
Calculate HMAC.
Definition: tls.c:2883
struct list_head list
List of which this buffer is a member.
Definition: iobuf.h:40
#define EINVAL_IV
Definition: tls.c:89
static int tls_new_handshake(struct tls_connection *tls, struct io_buffer *iobuf)
Receive new Handshake record.
Definition: tls.c:2621
static int tls_parse_chain(struct tls_connection *tls, const void *data, size_t len)
Parse certificate chain.
Definition: tls.c:2292
A TLS session.
Definition: tls.h:321
size_t ctxsize
Context size.
Definition: crypto.h:22
#define TLS_SERVER_KEY_EXCHANGE
Definition: tls.h:73
static struct process_descriptor tls_process_desc
TLS TX process descriptor.
Definition: tls.c:3722
#define DBGC2(...)
Definition: compiler.h:522
__builtin_va_list va_list
Definition: stdarg.h:6
int strcmp(const char *first, const char *second)
Compare strings.
Definition: string.c:173
size_t digestsize
Digest size.
Definition: crypto.h:26
SHA-1 algorithm.
const char * name
Algorithm name.
Definition: crypto.h:20
uint8_t sha1[SHA1_CTX_SIZE]
SHA-1 context.
Definition: tls.h:303
struct io_buffer iobuf
Current received record header (static I/O buffer)
Definition: tls.h:372
static void x509_put(struct x509_certificate *cert)
Drop reference to X.509 certificate.
Definition: x509.h:277
struct digest_algorithm * handshake
Handshake digest algorithm (for TLSv1.2 and above)
Definition: tls.h:197
void * data
Start of data.
Definition: iobuf.h:48
static struct x509_certificate * x509_first(struct x509_chain *chain)
Get first certificate in X.509 certificate chain.
Definition: x509.h:310
uint16_t low
Low word.
Definition: tls.c:219
Ephemeral Diffie-Hellman key exchange.
struct interface validator
Certificate validator.
Definition: tls.h:406
int job_progress(struct interface *intf, struct job_progress *progress)
Get job progress.
Definition: job.c:43
#define ENOMEM_CERTIFICATE
Definition: tls.c:121
struct x509_chain * chain
Certificate chain (if used)
Definition: tls.h:386
uint16_t version
Protocol version.
Definition: tls.h:38
#define EPERM_ALERT
Definition: tls.c:165
A message digest algorithm.
Definition: crypto.h:18
if(len >=6 *4) __asm__ __volatile__("movsl" if(len >=5 *4) __asm__ __volatile__("movsl" if(len >=4 *4) __asm__ __volatile__("movsl" if(len >=3 *4) __asm__ __volatile__("movsl" if(len >=2 *4) __asm__ __volatile__("movsl" if(len >=1 *4) __asm__ __volatile__("movsl" if((len % 4) >=2) __asm__ __volatile__("movsw" if((len % 2) >=1) __asm__ __volatile__("movsb" return dest
Definition: string.h:150
uint16_t version
Protocol version.
Definition: tls.h:437
#define cpu_to_be64(value)
Definition: byteswap.h:111
uint8_t data[48]
Additional event data.
Definition: ena.h:22
static void tls_clear_handshake(struct tls_connection *tls)
Clear handshake digest algorithm.
Definition: tls.c:749
struct tls_cipherspec active
Current cipher specification.
Definition: tls.h:254
A cipher algorithm.
Definition: crypto.h:50
A private key.
Definition: privkey.h:16
uint8_t server[12]
Server verification data.
Definition: tls.h:154
A TLS key exchange algorithm.
Definition: tls.h:174
struct digest_algorithm * digest
Digest algorithm.
Definition: rsa.h:44
struct x509_root * root
Root of trust.
Definition: tls.h:330
Root certificate store.
A TLS connection.
Definition: tls.h:414
void hmac_final(struct digest_algorithm *digest, void *ctx, void *hmac)
Finalise HMAC.
Definition: hmac.c:87
static void tls_clear_cipher(struct tls_connection *tls, struct tls_cipherspec *cipherspec)
struct private_key * key
Private key.
Definition: tls.h:332
struct tls_client_random random
Random bytes.
Definition: tls.h:382
struct x509_certificate * x509_find_key(struct x509_chain *store, struct private_key *key)
Identify X.509 certificate by corresponding public key.
Definition: x509.c:1821
static void cipher_auth(struct cipher_algorithm *cipher, void *ctx, void *auth)
Definition: crypto.h:249
uint8_t md5[MD5_CTX_SIZE]
MD5 context.
Definition: tls.h:301
#define EINVAL_TICKET
Definition: tls.c:105
#define INTF_DESC_PASSTHRU(object_type, intf, operations, passthru)
Define an object interface descriptor with pass-through interface.
Definition: interface.h:97
static void tls_set_uint24(tls24_t *field24, unsigned long value)
Set 24-bit field value.
Definition: tls.c:241
static int tls_new_record(struct tls_connection *tls, unsigned int type, struct list_head *rx_data)
Receive new record.
Definition: tls.c:2758
struct cipher_algorithm * cipher
Bulk encryption cipher algorithm.
Definition: tls.h:193
struct tls_key_exchange_algorithm tls_ecdhe_exchange_algorithm
Ephemeral Elliptic Curve Diffie-Hellman key exchange algorithm.
Definition: tls.c:1771
struct list_head conn
List of connections.
Definition: tls.h:346
static size_t tls_cipherstream_window(struct tls_connection *tls)
Check flow control window.
Definition: tls.c:3445
int secure_renegotiation
Secure renegotiation flag.
Definition: tls.h:445
A TLS named curve.
Definition: tls.h:222
static int tls_send_finished(struct tls_connection *tls)
Transmit Finished record.
Definition: tls.c:1907
typeof(acpi_finder=acpi_find)
ACPI table finder.
Definition: acpi.c:45
#define EINVAL_KEY_EXCHANGE
Definition: tls.c:109
static int tls_new_certificate(struct tls_connection *tls, const void *data, size_t len)
Receive new Certificate handshake record.
Definition: tls.c:2373
struct pubkey_algorithm * pubkey
Public-key algorithm.
Definition: tls.h:272
static void tls_p_hash_va(struct tls_connection *tls, struct digest_algorithm *digest, const void *secret, size_t secret_len, void *out, size_t out_len, va_list seeds)
Generate secure pseudo-random data using a single hash function.
Definition: tls.c:498
static int tls_session(struct tls_connection *tls, const char *name)
Find or create session for TLS connection.
Definition: tls.c:3739
void * dynamic
Dynamically-allocated storage.
Definition: tls.h:242
uint8_t high
High byte.
Definition: tls.c:217
static int tls_send_client_hello(struct tls_connection *tls)
Transmit Client Hello record.
Definition: tls.c:1312
#define va_start(ap, last)
Definition: stdarg.h:7
static int tls_generate_random(struct tls_connection *tls, void *data, size_t len)
Generate random data.
Definition: tls.c:453
struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix
RSA digestInfo prefix for MD5+SHA1 algorithm.
Definition: tls.c:334
#define EINVAL_CERTIFICATES
Definition: tls.c:73
struct asn1_cursor raw
Raw certificate.
Definition: x509.h:230
#define TLS_MAX_FRAGMENT_LENGTH_4096
Definition: tls.h:126
static size_t pubkey_max_len(struct pubkey_algorithm *pubkey, const struct asn1_cursor *key)
Definition: crypto.h:269
static int tls_ready(struct tls_connection *tls)
Determine if TLS connection is ready for application data.
Definition: tls.c:253
const char * name
Server name.
Definition: tls.h:328
A TLS signature and hash algorithm identifier.
Definition: tls.h:260
static void intf_init(struct interface *intf, struct interface_descriptor *desc, struct refcnt *refcnt)
Initialise an object interface.
Definition: interface.h:203
const char * name
Algorithm name.
Definition: crypto.h:52
#define TLS_CERTIFICATE_VERIFY
Definition: tls.h:76
#define TLS_TYPE_DATA
Application data content type.
Definition: tls.h:65
#define ENOTSUP_SIG_HASH
Definition: tls.c:153
size_t exchange_len
Server Key Exchange record length.
Definition: tls.h:398
static int pubkey_sign(struct pubkey_algorithm *pubkey, const struct asn1_cursor *key, struct digest_algorithm *digest, const void *value, void *signature)
Definition: crypto.h:287
size_t session_id_len
Length of session ID.
Definition: tls.h:425
#define TLS_TYPE_ALERT
Alert content type.
Definition: tls.h:59
static int tls_verify_padding(struct tls_connection *tls, struct io_buffer *iobuf)
Verify block padding.
Definition: tls.c:3062
struct interface plainstream
Plaintext stream.
Definition: tls.h:432
#define TLS_VERSION_MIN
Minimum TLS version.
Definition: crypto.h:13
struct tls_key_exchange_algorithm tls_dhe_exchange_algorithm
Ephemeral Diffie-Hellman key exchange algorithm.
Definition: tls.c:1653
u8 signature
CPU signature.
Definition: CIB_PRM.h:35
MD5 algorithm.
int memcmp(const void *first, const void *second, size_t len)
Compare memory regions.
Definition: string.c:114
SHA-256 algorithm.
uint32_t len
Length.
Definition: ena.h:14
static int tls_set_cipher(struct tls_connection *tls, struct tls_cipherspec *cipherspec, struct tls_cipher_suite *suite)
Set cipher suite.
Definition: tls.c:872
#define NULL
NULL pointer (VOID *)
Definition: Base.h:321
static int tls_select_handshake(struct tls_connection *tls, struct digest_algorithm *digest)
Select handshake digest algorithm.
Definition: tls.c:766
String functions.
#define tls_prf_label(tls, secret, secret_len, out, out_len, label,...)
Generate secure pseudo-random data.
Definition: tls.c:616
An ASN.1 object cursor.
Definition: asn1.h:20
#define TLS_CIPHER_SUITES
TLS cipher suite table.
Definition: tls.h:211
A public key algorithm.
Definition: crypto.h:121
#define htons(value)
Definition: byteswap.h:135
#define TLS_CLIENT_KEY_EXCHANGE
Definition: tls.h:77
size_t(* max_len)(const struct asn1_cursor *key)
Calculate maximum output length.
Definition: crypto.h:129
void pending_get(struct pending_operation *pending)
Mark an operation as pending.
Definition: pending.c:45
struct bofm_section_header done
Definition: bofm_test.c:46
void * fixed_iv
Fixed initialisation vector.
Definition: tls.h:248
#define TLS_SERVER_HELLO
Definition: tls.h:70
union @383 key
Sense key.
Definition: scsi.h:18
static int tls_new_server_hello_done(struct tls_connection *tls, const void *data, size_t len)
Receive new Server Hello Done handshake record.
Definition: tls.c:2508
#define TLS_FINISHED
Definition: tls.h:78
int add_tls(struct interface *xfer, const char *name, struct x509_root *root, struct private_key *key)
Add TLS on an interface.
Definition: tls.c:3799
static void md5_sha1_update(void *ctx, const void *data, size_t len)
Accumulate data with MD5+SHA1 algorithm.
Definition: tls.c:301
#define TLS_SIGNATURE_ALGORITHMS
Definition: tls.h:133
static int tls_new_server_key_exchange(struct tls_connection *tls, const void *data, size_t len)
Receive new Server Key Exchange handshake record.
Definition: tls.c:2413
const char * name
Algorithm name.
Definition: crypto.h:123
struct digest_algorithm md5_algorithm
MD5 algorithm.
Definition: md5.c:286
static int cipher_setkey(struct cipher_algorithm *cipher, void *ctx, const void *key, size_t keylen)
Definition: crypto.h:217
static size_t tls_plainstream_window(struct tls_connection *tls)
Check flow control window.
Definition: tls.c:3243
#define ref_put(refcnt)
Drop reference to object.
Definition: refcnt.h:106
static int tls_send_client_key_exchange_dhe(struct tls_connection *tls)
Transmit Client Key Exchange record using DHE key exchange.
Definition: tls.c:1539
u8 tx[WPA_TKIP_MIC_KEY_LEN]
MIC key for packets to the AP.
Definition: wpa.h:237
uint16_t code
Numeric code (in network-endian order)
Definition: tls.h:199
static int tls_new_unknown(struct tls_connection *tls __unused, struct io_buffer *iobuf)
Receive new unknown record.
Definition: tls.c:2711
struct digest_algorithm sha1_algorithm
SHA-1 algorithm.
Definition: sha1.c:257
void * mac_secret
MAC secret.
Definition: tls.h:246
static int is_block_cipher(struct cipher_algorithm *cipher)
Definition: crypto.h:259
void * memset(void *dest, int character, size_t len) __nonnull
A persistent I/O buffer.
Definition: iobuf.h:33
#define TLS_CHANGE_CIPHER_SPEC
Change cipher spec magic byte.
Definition: tls.h:56
struct x509_root * root
Root of trust.
Definition: tls.h:400
uint8_t key_len
Key length.
Definition: tls.h:201