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