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