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