tlsv1_client_write.c revision 1f69aa52ea2e0a73ac502565df8c666ee49cab6a
1/*
2 * TLSv1 client - write handshake message
3 * Copyright (c) 2006-2011, Jouni Malinen <j@w1.fi>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *
9 * Alternatively, this software may be distributed under the terms of BSD
10 * license.
11 *
12 * See README and COPYING for more details.
13 */
14
15#include "includes.h"
16
17#include "common.h"
18#include "crypto/md5.h"
19#include "crypto/sha1.h"
20#include "crypto/sha256.h"
21#include "crypto/tls.h"
22#include "crypto/random.h"
23#include "x509v3.h"
24#include "tlsv1_common.h"
25#include "tlsv1_record.h"
26#include "tlsv1_client.h"
27#include "tlsv1_client_i.h"
28
29
30static size_t tls_client_cert_chain_der_len(struct tlsv1_client *conn)
31{
32	size_t len = 0;
33	struct x509_certificate *cert;
34
35	if (conn->cred == NULL)
36		return 0;
37
38	cert = conn->cred->cert;
39	while (cert) {
40		len += 3 + cert->cert_len;
41		if (x509_certificate_self_signed(cert))
42			break;
43		cert = x509_certificate_get_subject(conn->cred->trusted_certs,
44						    &cert->issuer);
45	}
46
47	return len;
48}
49
50
51u8 * tls_send_client_hello(struct tlsv1_client *conn, size_t *out_len)
52{
53	u8 *hello, *end, *pos, *hs_length, *hs_start, *rhdr;
54	struct os_time now;
55	size_t len, i;
56
57	wpa_printf(MSG_DEBUG, "TLSv1: Send ClientHello");
58	*out_len = 0;
59
60	os_get_time(&now);
61	WPA_PUT_BE32(conn->client_random, now.sec);
62	if (random_get_bytes(conn->client_random + 4, TLS_RANDOM_LEN - 4)) {
63		wpa_printf(MSG_ERROR, "TLSv1: Could not generate "
64			   "client_random");
65		return NULL;
66	}
67	wpa_hexdump(MSG_MSGDUMP, "TLSv1: client_random",
68		    conn->client_random, TLS_RANDOM_LEN);
69
70	len = 100 + conn->num_cipher_suites * 2 + conn->client_hello_ext_len;
71	hello = os_malloc(len);
72	if (hello == NULL)
73		return NULL;
74	end = hello + len;
75
76	rhdr = hello;
77	pos = rhdr + TLS_RECORD_HEADER_LEN;
78
79	/* opaque fragment[TLSPlaintext.length] */
80
81	/* Handshake */
82	hs_start = pos;
83	/* HandshakeType msg_type */
84	*pos++ = TLS_HANDSHAKE_TYPE_CLIENT_HELLO;
85	/* uint24 length (to be filled) */
86	hs_length = pos;
87	pos += 3;
88	/* body - ClientHello */
89	/* ProtocolVersion client_version */
90	WPA_PUT_BE16(pos, TLS_VERSION);
91	pos += 2;
92	/* Random random: uint32 gmt_unix_time, opaque random_bytes */
93	os_memcpy(pos, conn->client_random, TLS_RANDOM_LEN);
94	pos += TLS_RANDOM_LEN;
95	/* SessionID session_id */
96	*pos++ = conn->session_id_len;
97	os_memcpy(pos, conn->session_id, conn->session_id_len);
98	pos += conn->session_id_len;
99	/* CipherSuite cipher_suites<2..2^16-1> */
100	WPA_PUT_BE16(pos, 2 * conn->num_cipher_suites);
101	pos += 2;
102	for (i = 0; i < conn->num_cipher_suites; i++) {
103		WPA_PUT_BE16(pos, conn->cipher_suites[i]);
104		pos += 2;
105	}
106	/* CompressionMethod compression_methods<1..2^8-1> */
107	*pos++ = 1;
108	*pos++ = TLS_COMPRESSION_NULL;
109
110	if (conn->client_hello_ext) {
111		os_memcpy(pos, conn->client_hello_ext,
112			  conn->client_hello_ext_len);
113		pos += conn->client_hello_ext_len;
114	}
115
116	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
117	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
118
119	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
120			      rhdr, end - rhdr, hs_start, pos - hs_start,
121			      out_len) < 0) {
122		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create TLS record");
123		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
124			  TLS_ALERT_INTERNAL_ERROR);
125		os_free(hello);
126		return NULL;
127	}
128
129	conn->state = SERVER_HELLO;
130
131	return hello;
132}
133
134
135static int tls_write_client_certificate(struct tlsv1_client *conn,
136					u8 **msgpos, u8 *end)
137{
138	u8 *pos, *rhdr, *hs_start, *hs_length, *cert_start;
139	size_t rlen;
140	struct x509_certificate *cert;
141
142	pos = *msgpos;
143
144	wpa_printf(MSG_DEBUG, "TLSv1: Send Certificate");
145	rhdr = pos;
146	pos += TLS_RECORD_HEADER_LEN;
147
148	/* opaque fragment[TLSPlaintext.length] */
149
150	/* Handshake */
151	hs_start = pos;
152	/* HandshakeType msg_type */
153	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE;
154	/* uint24 length (to be filled) */
155	hs_length = pos;
156	pos += 3;
157	/* body - Certificate */
158	/* uint24 length (to be filled) */
159	cert_start = pos;
160	pos += 3;
161	cert = conn->cred ? conn->cred->cert : NULL;
162	while (cert) {
163		if (pos + 3 + cert->cert_len > end) {
164			wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space "
165				   "for Certificate (cert_len=%lu left=%lu)",
166				   (unsigned long) cert->cert_len,
167				   (unsigned long) (end - pos));
168			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
169				  TLS_ALERT_INTERNAL_ERROR);
170			return -1;
171		}
172		WPA_PUT_BE24(pos, cert->cert_len);
173		pos += 3;
174		os_memcpy(pos, cert->cert_start, cert->cert_len);
175		pos += cert->cert_len;
176
177		if (x509_certificate_self_signed(cert))
178			break;
179		cert = x509_certificate_get_subject(conn->cred->trusted_certs,
180						    &cert->issuer);
181	}
182	if (conn->cred == NULL || cert == conn->cred->cert || cert == NULL) {
183		/*
184		 * Client was not configured with all the needed certificates
185		 * to form a full certificate chain. The server may fail to
186		 * validate the chain unless it is configured with all the
187		 * missing CA certificates.
188		 */
189		wpa_printf(MSG_DEBUG, "TLSv1: Full client certificate chain "
190			   "not configured - validation may fail");
191	}
192	WPA_PUT_BE24(cert_start, pos - cert_start - 3);
193
194	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
195
196	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
197			      rhdr, end - rhdr, hs_start, pos - hs_start,
198			      &rlen) < 0) {
199		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
200		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
201			  TLS_ALERT_INTERNAL_ERROR);
202		return -1;
203	}
204	pos = rhdr + rlen;
205
206	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
207
208	*msgpos = pos;
209
210	return 0;
211}
212
213
214static int tlsv1_key_x_anon_dh(struct tlsv1_client *conn, u8 **pos, u8 *end)
215{
216	/* ClientDiffieHellmanPublic */
217	u8 *csecret, *csecret_start, *dh_yc, *shared;
218	size_t csecret_len, dh_yc_len, shared_len;
219
220	csecret_len = conn->dh_p_len;
221	csecret = os_malloc(csecret_len);
222	if (csecret == NULL) {
223		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate "
224			   "memory for Yc (Diffie-Hellman)");
225		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
226			  TLS_ALERT_INTERNAL_ERROR);
227		return -1;
228	}
229	if (random_get_bytes(csecret, csecret_len)) {
230		wpa_printf(MSG_DEBUG, "TLSv1: Failed to get random "
231			   "data for Diffie-Hellman");
232		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
233			  TLS_ALERT_INTERNAL_ERROR);
234		os_free(csecret);
235		return -1;
236	}
237
238	if (os_memcmp(csecret, conn->dh_p, csecret_len) > 0)
239		csecret[0] = 0; /* make sure Yc < p */
240
241	csecret_start = csecret;
242	while (csecret_len > 1 && *csecret_start == 0) {
243		csecret_start++;
244		csecret_len--;
245	}
246	wpa_hexdump_key(MSG_DEBUG, "TLSv1: DH client's secret value",
247			csecret_start, csecret_len);
248
249	/* Yc = g^csecret mod p */
250	dh_yc_len = conn->dh_p_len;
251	dh_yc = os_malloc(dh_yc_len);
252	if (dh_yc == NULL) {
253		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate "
254			   "memory for Diffie-Hellman");
255		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
256			  TLS_ALERT_INTERNAL_ERROR);
257		os_free(csecret);
258		return -1;
259	}
260	if (crypto_mod_exp(conn->dh_g, conn->dh_g_len,
261			   csecret_start, csecret_len,
262			   conn->dh_p, conn->dh_p_len,
263			   dh_yc, &dh_yc_len)) {
264		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
265			  TLS_ALERT_INTERNAL_ERROR);
266		os_free(csecret);
267		os_free(dh_yc);
268		return -1;
269	}
270
271	wpa_hexdump(MSG_DEBUG, "TLSv1: DH Yc (client's public value)",
272		    dh_yc, dh_yc_len);
273
274	WPA_PUT_BE16(*pos, dh_yc_len);
275	*pos += 2;
276	if (*pos + dh_yc_len > end) {
277		wpa_printf(MSG_DEBUG, "TLSv1: Not enough room in the "
278			   "message buffer for Yc");
279		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
280			  TLS_ALERT_INTERNAL_ERROR);
281		os_free(csecret);
282		os_free(dh_yc);
283		return -1;
284	}
285	os_memcpy(*pos, dh_yc, dh_yc_len);
286	*pos += dh_yc_len;
287	os_free(dh_yc);
288
289	shared_len = conn->dh_p_len;
290	shared = os_malloc(shared_len);
291	if (shared == NULL) {
292		wpa_printf(MSG_DEBUG, "TLSv1: Could not allocate memory for "
293			   "DH");
294		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
295			  TLS_ALERT_INTERNAL_ERROR);
296		os_free(csecret);
297		return -1;
298	}
299
300	/* shared = Ys^csecret mod p */
301	if (crypto_mod_exp(conn->dh_ys, conn->dh_ys_len,
302			   csecret_start, csecret_len,
303			   conn->dh_p, conn->dh_p_len,
304			   shared, &shared_len)) {
305		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
306			  TLS_ALERT_INTERNAL_ERROR);
307		os_free(csecret);
308		os_free(shared);
309		return -1;
310	}
311	wpa_hexdump_key(MSG_DEBUG, "TLSv1: Shared secret from DH key exchange",
312			shared, shared_len);
313
314	os_memset(csecret_start, 0, csecret_len);
315	os_free(csecret);
316	if (tls_derive_keys(conn, shared, shared_len)) {
317		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive keys");
318		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
319			  TLS_ALERT_INTERNAL_ERROR);
320		os_free(shared);
321		return -1;
322	}
323	os_memset(shared, 0, shared_len);
324	os_free(shared);
325	tlsv1_client_free_dh(conn);
326	return 0;
327}
328
329
330static int tlsv1_key_x_rsa(struct tlsv1_client *conn, u8 **pos, u8 *end)
331{
332	u8 pre_master_secret[TLS_PRE_MASTER_SECRET_LEN];
333	size_t clen;
334	int res;
335
336	if (tls_derive_pre_master_secret(pre_master_secret) < 0 ||
337	    tls_derive_keys(conn, pre_master_secret,
338			    TLS_PRE_MASTER_SECRET_LEN)) {
339		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive keys");
340		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
341			  TLS_ALERT_INTERNAL_ERROR);
342		return -1;
343	}
344
345	/* EncryptedPreMasterSecret */
346	if (conn->server_rsa_key == NULL) {
347		wpa_printf(MSG_DEBUG, "TLSv1: No server RSA key to "
348			   "use for encrypting pre-master secret");
349		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
350			  TLS_ALERT_INTERNAL_ERROR);
351		return -1;
352	}
353
354	/* RSA encrypted value is encoded with PKCS #1 v1.5 block type 2. */
355	*pos += 2;
356	clen = end - *pos;
357	res = crypto_public_key_encrypt_pkcs1_v15(
358		conn->server_rsa_key,
359		pre_master_secret, TLS_PRE_MASTER_SECRET_LEN,
360		*pos, &clen);
361	os_memset(pre_master_secret, 0, TLS_PRE_MASTER_SECRET_LEN);
362	if (res < 0) {
363		wpa_printf(MSG_DEBUG, "TLSv1: RSA encryption failed");
364		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
365			  TLS_ALERT_INTERNAL_ERROR);
366		return -1;
367	}
368	WPA_PUT_BE16(*pos - 2, clen);
369	wpa_hexdump(MSG_MSGDUMP, "TLSv1: Encrypted pre_master_secret",
370		    *pos, clen);
371	*pos += clen;
372
373	return 0;
374}
375
376
377static int tls_write_client_key_exchange(struct tlsv1_client *conn,
378					 u8 **msgpos, u8 *end)
379{
380	u8 *pos, *rhdr, *hs_start, *hs_length;
381	size_t rlen;
382	tls_key_exchange keyx;
383	const struct tls_cipher_suite *suite;
384
385	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
386	if (suite == NULL)
387		keyx = TLS_KEY_X_NULL;
388	else
389		keyx = suite->key_exchange;
390
391	pos = *msgpos;
392
393	wpa_printf(MSG_DEBUG, "TLSv1: Send ClientKeyExchange");
394
395	rhdr = pos;
396	pos += TLS_RECORD_HEADER_LEN;
397
398	/* opaque fragment[TLSPlaintext.length] */
399
400	/* Handshake */
401	hs_start = pos;
402	/* HandshakeType msg_type */
403	*pos++ = TLS_HANDSHAKE_TYPE_CLIENT_KEY_EXCHANGE;
404	/* uint24 length (to be filled) */
405	hs_length = pos;
406	pos += 3;
407	/* body - ClientKeyExchange */
408	if (keyx == TLS_KEY_X_DH_anon) {
409		if (tlsv1_key_x_anon_dh(conn, &pos, end) < 0)
410			return -1;
411	} else {
412		if (tlsv1_key_x_rsa(conn, &pos, end) < 0)
413			return -1;
414	}
415
416	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
417
418	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
419			      rhdr, end - rhdr, hs_start, pos - hs_start,
420			      &rlen) < 0) {
421		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
422		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
423			  TLS_ALERT_INTERNAL_ERROR);
424		return -1;
425	}
426	pos = rhdr + rlen;
427	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
428
429	*msgpos = pos;
430
431	return 0;
432}
433
434
435static int tls_write_client_certificate_verify(struct tlsv1_client *conn,
436					       u8 **msgpos, u8 *end)
437{
438	u8 *pos, *rhdr, *hs_start, *hs_length, *signed_start;
439	size_t rlen, hlen, clen;
440	u8 hash[100], *hpos;
441	enum { SIGN_ALG_RSA, SIGN_ALG_DSA } alg = SIGN_ALG_RSA;
442
443	pos = *msgpos;
444
445	wpa_printf(MSG_DEBUG, "TLSv1: Send CertificateVerify");
446	rhdr = pos;
447	pos += TLS_RECORD_HEADER_LEN;
448
449	/* Handshake */
450	hs_start = pos;
451	/* HandshakeType msg_type */
452	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY;
453	/* uint24 length (to be filled) */
454	hs_length = pos;
455	pos += 3;
456
457	/*
458	 * RFC 2246: 7.4.3 and 7.4.8:
459	 * Signature signature
460	 *
461	 * RSA:
462	 * digitally-signed struct {
463	 *     opaque md5_hash[16];
464	 *     opaque sha_hash[20];
465	 * };
466	 *
467	 * DSA:
468	 * digitally-signed struct {
469	 *     opaque sha_hash[20];
470	 * };
471	 *
472	 * The hash values are calculated over all handshake messages sent or
473	 * received starting at ClientHello up to, but not including, this
474	 * CertificateVerify message, including the type and length fields of
475	 * the handshake messages.
476	 */
477
478	hpos = hash;
479
480#ifdef CONFIG_TLSV12
481	if (conn->rl.tls_version == TLS_VERSION_1_2) {
482		hlen = SHA256_MAC_LEN;
483		if (conn->verify.sha256_cert == NULL ||
484		    crypto_hash_finish(conn->verify.sha256_cert, hpos, &hlen) <
485		    0) {
486			conn->verify.sha256_cert = NULL;
487			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
488				  TLS_ALERT_INTERNAL_ERROR);
489			return -1;
490		}
491		conn->verify.sha256_cert = NULL;
492
493		/*
494		 * RFC 3447, A.2.4 RSASSA-PKCS1-v1_5
495		 *
496		 * DigestInfo ::= SEQUENCE {
497		 *   digestAlgorithm DigestAlgorithm,
498		 *   digest OCTET STRING
499		 * }
500		 *
501		 * SHA-256 OID: sha256WithRSAEncryption ::= {pkcs-1 11}
502		 *
503		 * DER encoded DigestInfo for SHA256 per RFC 3447:
504		 * 30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20 ||
505		 * H
506		 */
507		os_memmove(hash + 19, hash, hlen);
508		hlen += 19;
509		os_memcpy(hash, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65"
510			  "\x03\x04\x02\x01\x05\x00\x04\x20", 19);
511	} else {
512#endif /* CONFIG_TLSV12 */
513
514	if (alg == SIGN_ALG_RSA) {
515		hlen = MD5_MAC_LEN;
516		if (conn->verify.md5_cert == NULL ||
517		    crypto_hash_finish(conn->verify.md5_cert, hpos, &hlen) < 0)
518		{
519			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
520				  TLS_ALERT_INTERNAL_ERROR);
521			conn->verify.md5_cert = NULL;
522			crypto_hash_finish(conn->verify.sha1_cert, NULL, NULL);
523			conn->verify.sha1_cert = NULL;
524			return -1;
525		}
526		hpos += MD5_MAC_LEN;
527	} else
528		crypto_hash_finish(conn->verify.md5_cert, NULL, NULL);
529
530	conn->verify.md5_cert = NULL;
531	hlen = SHA1_MAC_LEN;
532	if (conn->verify.sha1_cert == NULL ||
533	    crypto_hash_finish(conn->verify.sha1_cert, hpos, &hlen) < 0) {
534		conn->verify.sha1_cert = NULL;
535		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
536			  TLS_ALERT_INTERNAL_ERROR);
537		return -1;
538	}
539	conn->verify.sha1_cert = NULL;
540
541	if (alg == SIGN_ALG_RSA)
542		hlen += MD5_MAC_LEN;
543
544#ifdef CONFIG_TLSV12
545	}
546#endif /* CONFIG_TLSV12 */
547
548	wpa_hexdump(MSG_MSGDUMP, "TLSv1: CertificateVerify hash", hash, hlen);
549
550#ifdef CONFIG_TLSV12
551	if (conn->rl.tls_version >= TLS_VERSION_1_2) {
552		/*
553		 * RFC 5246, 4.7:
554		 * TLS v1.2 adds explicit indication of the used signature and
555		 * hash algorithms.
556		 *
557		 * struct {
558		 *   HashAlgorithm hash;
559		 *   SignatureAlgorithm signature;
560		 * } SignatureAndHashAlgorithm;
561		 */
562		*pos++ = TLS_HASH_ALG_SHA256;
563		*pos++ = TLS_SIGN_ALG_RSA;
564	}
565#endif /* CONFIG_TLSV12 */
566
567	/*
568	 * RFC 2246, 4.7:
569	 * In digital signing, one-way hash functions are used as input for a
570	 * signing algorithm. A digitally-signed element is encoded as an
571	 * opaque vector <0..2^16-1>, where the length is specified by the
572	 * signing algorithm and key.
573	 *
574	 * In RSA signing, a 36-byte structure of two hashes (one SHA and one
575	 * MD5) is signed (encrypted with the private key). It is encoded with
576	 * PKCS #1 block type 0 or type 1 as described in [PKCS1].
577	 */
578	signed_start = pos; /* length to be filled */
579	pos += 2;
580	clen = end - pos;
581	if (conn->cred == NULL ||
582	    crypto_private_key_sign_pkcs1(conn->cred->key, hash, hlen,
583					  pos, &clen) < 0) {
584		wpa_printf(MSG_DEBUG, "TLSv1: Failed to sign hash (PKCS #1)");
585		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
586			  TLS_ALERT_INTERNAL_ERROR);
587		return -1;
588	}
589	WPA_PUT_BE16(signed_start, clen);
590
591	pos += clen;
592
593	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
594
595	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
596			      rhdr, end - rhdr, hs_start, pos - hs_start,
597			      &rlen) < 0) {
598		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
599		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
600			  TLS_ALERT_INTERNAL_ERROR);
601		return -1;
602	}
603	pos = rhdr + rlen;
604
605	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
606
607	*msgpos = pos;
608
609	return 0;
610}
611
612
613static int tls_write_client_change_cipher_spec(struct tlsv1_client *conn,
614					       u8 **msgpos, u8 *end)
615{
616	size_t rlen;
617	u8 payload[1];
618
619	wpa_printf(MSG_DEBUG, "TLSv1: Send ChangeCipherSpec");
620
621	payload[0] = TLS_CHANGE_CIPHER_SPEC;
622
623	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC,
624			      *msgpos, end - *msgpos, payload, sizeof(payload),
625			      &rlen) < 0) {
626		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
627		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
628			  TLS_ALERT_INTERNAL_ERROR);
629		return -1;
630	}
631
632	if (tlsv1_record_change_write_cipher(&conn->rl) < 0) {
633		wpa_printf(MSG_DEBUG, "TLSv1: Failed to set write cipher for "
634			   "record layer");
635		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
636			  TLS_ALERT_INTERNAL_ERROR);
637		return -1;
638	}
639
640	*msgpos += rlen;
641
642	return 0;
643}
644
645
646static int tls_write_client_finished(struct tlsv1_client *conn,
647				     u8 **msgpos, u8 *end)
648{
649	u8 *pos, *hs_start;
650	size_t rlen, hlen;
651	u8 verify_data[1 + 3 + TLS_VERIFY_DATA_LEN];
652	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN];
653
654	wpa_printf(MSG_DEBUG, "TLSv1: Send Finished");
655
656	/* Encrypted Handshake Message: Finished */
657
658#ifdef CONFIG_TLSV12
659	if (conn->rl.tls_version >= TLS_VERSION_1_2) {
660		hlen = SHA256_MAC_LEN;
661		if (conn->verify.sha256_client == NULL ||
662		    crypto_hash_finish(conn->verify.sha256_client, hash, &hlen)
663		    < 0) {
664			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
665				  TLS_ALERT_INTERNAL_ERROR);
666			conn->verify.sha256_client = NULL;
667			return -1;
668		}
669		conn->verify.sha256_client = NULL;
670	} else {
671#endif /* CONFIG_TLSV12 */
672
673	hlen = MD5_MAC_LEN;
674	if (conn->verify.md5_client == NULL ||
675	    crypto_hash_finish(conn->verify.md5_client, hash, &hlen) < 0) {
676		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
677			  TLS_ALERT_INTERNAL_ERROR);
678		conn->verify.md5_client = NULL;
679		crypto_hash_finish(conn->verify.sha1_client, NULL, NULL);
680		conn->verify.sha1_client = NULL;
681		return -1;
682	}
683	conn->verify.md5_client = NULL;
684	hlen = SHA1_MAC_LEN;
685	if (conn->verify.sha1_client == NULL ||
686	    crypto_hash_finish(conn->verify.sha1_client, hash + MD5_MAC_LEN,
687			       &hlen) < 0) {
688		conn->verify.sha1_client = NULL;
689		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
690			  TLS_ALERT_INTERNAL_ERROR);
691		return -1;
692	}
693	conn->verify.sha1_client = NULL;
694	hlen = MD5_MAC_LEN + SHA1_MAC_LEN;
695
696#ifdef CONFIG_TLSV12
697	}
698#endif /* CONFIG_TLSV12 */
699
700	if (tls_prf(conn->rl.tls_version,
701		    conn->master_secret, TLS_MASTER_SECRET_LEN,
702		    "client finished", hash, hlen,
703		    verify_data + 1 + 3, TLS_VERIFY_DATA_LEN)) {
704		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate verify_data");
705		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
706			  TLS_ALERT_INTERNAL_ERROR);
707		return -1;
708	}
709	wpa_hexdump_key(MSG_DEBUG, "TLSv1: verify_data (client)",
710			verify_data + 1 + 3, TLS_VERIFY_DATA_LEN);
711
712	/* Handshake */
713	pos = hs_start = verify_data;
714	/* HandshakeType msg_type */
715	*pos++ = TLS_HANDSHAKE_TYPE_FINISHED;
716	/* uint24 length */
717	WPA_PUT_BE24(pos, TLS_VERIFY_DATA_LEN);
718	pos += 3;
719	pos += TLS_VERIFY_DATA_LEN; /* verify_data already in place */
720	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
721
722	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
723			      *msgpos, end - *msgpos, hs_start, pos - hs_start,
724			      &rlen) < 0) {
725		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
726		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
727			  TLS_ALERT_INTERNAL_ERROR);
728		return -1;
729	}
730
731	*msgpos += rlen;
732
733	return 0;
734}
735
736
737static u8 * tls_send_client_key_exchange(struct tlsv1_client *conn,
738					 size_t *out_len)
739{
740	u8 *msg, *end, *pos;
741	size_t msglen;
742
743	*out_len = 0;
744
745	msglen = 2000;
746	if (conn->certificate_requested)
747		msglen += tls_client_cert_chain_der_len(conn);
748
749	msg = os_malloc(msglen);
750	if (msg == NULL)
751		return NULL;
752
753	pos = msg;
754	end = msg + msglen;
755
756	if (conn->certificate_requested) {
757		if (tls_write_client_certificate(conn, &pos, end) < 0) {
758			os_free(msg);
759			return NULL;
760		}
761	}
762
763	if (tls_write_client_key_exchange(conn, &pos, end) < 0 ||
764	    (conn->certificate_requested && conn->cred && conn->cred->key &&
765	     tls_write_client_certificate_verify(conn, &pos, end) < 0) ||
766	    tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
767	    tls_write_client_finished(conn, &pos, end) < 0) {
768		os_free(msg);
769		return NULL;
770	}
771
772	*out_len = pos - msg;
773
774	conn->state = SERVER_CHANGE_CIPHER_SPEC;
775
776	return msg;
777}
778
779
780static u8 * tls_send_change_cipher_spec(struct tlsv1_client *conn,
781					size_t *out_len)
782{
783	u8 *msg, *end, *pos;
784
785	*out_len = 0;
786
787	msg = os_malloc(1000);
788	if (msg == NULL)
789		return NULL;
790
791	pos = msg;
792	end = msg + 1000;
793
794	if (tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
795	    tls_write_client_finished(conn, &pos, end) < 0) {
796		os_free(msg);
797		return NULL;
798	}
799
800	*out_len = pos - msg;
801
802	wpa_printf(MSG_DEBUG, "TLSv1: Session resumption completed "
803		   "successfully");
804	conn->state = ESTABLISHED;
805
806	return msg;
807}
808
809
810u8 * tlsv1_client_handshake_write(struct tlsv1_client *conn, size_t *out_len,
811				  int no_appl_data)
812{
813	switch (conn->state) {
814	case CLIENT_KEY_EXCHANGE:
815		return tls_send_client_key_exchange(conn, out_len);
816	case CHANGE_CIPHER_SPEC:
817		return tls_send_change_cipher_spec(conn, out_len);
818	case ACK_FINISHED:
819		wpa_printf(MSG_DEBUG, "TLSv1: Handshake completed "
820			   "successfully");
821		conn->state = ESTABLISHED;
822		*out_len = 0;
823		if (no_appl_data) {
824			/* Need to return something to get final TLS ACK. */
825			return os_malloc(1);
826		}
827		return NULL;
828	default:
829		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected state %d while "
830			   "generating reply", conn->state);
831		return NULL;
832	}
833}
834
835
836u8 * tlsv1_client_send_alert(struct tlsv1_client *conn, u8 level,
837			     u8 description, size_t *out_len)
838{
839	u8 *alert, *pos, *length;
840
841	wpa_printf(MSG_DEBUG, "TLSv1: Send Alert(%d:%d)", level, description);
842	*out_len = 0;
843
844	alert = os_malloc(10);
845	if (alert == NULL)
846		return NULL;
847
848	pos = alert;
849
850	/* TLSPlaintext */
851	/* ContentType type */
852	*pos++ = TLS_CONTENT_TYPE_ALERT;
853	/* ProtocolVersion version */
854	WPA_PUT_BE16(pos, conn->rl.tls_version ? conn->rl.tls_version :
855		     TLS_VERSION);
856	pos += 2;
857	/* uint16 length (to be filled) */
858	length = pos;
859	pos += 2;
860	/* opaque fragment[TLSPlaintext.length] */
861
862	/* Alert */
863	/* AlertLevel level */
864	*pos++ = level;
865	/* AlertDescription description */
866	*pos++ = description;
867
868	WPA_PUT_BE16(length, pos - length - 2);
869	*out_len = pos - alert;
870
871	return alert;
872}
873