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