1 /*
2  * TLSv1 client - write handshake message
3  * Copyright (c) 2006-2014, 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_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 || keyx == TLS_KEY_X_DHE_RSA) {
403 		if (tlsv1_key_x_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 
436 	pos = *msgpos;
437 
438 	wpa_printf(MSG_DEBUG, "TLSv1: Send CertificateVerify");
439 	rhdr = pos;
440 	pos += TLS_RECORD_HEADER_LEN;
441 
442 	/* Handshake */
443 	hs_start = pos;
444 	/* HandshakeType msg_type */
445 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE_VERIFY;
446 	/* uint24 length (to be filled) */
447 	hs_length = pos;
448 	pos += 3;
449 
450 	/*
451 	 * RFC 2246: 7.4.3 and 7.4.8:
452 	 * Signature signature
453 	 *
454 	 * RSA:
455 	 * digitally-signed struct {
456 	 *     opaque md5_hash[16];
457 	 *     opaque sha_hash[20];
458 	 * };
459 	 *
460 	 * DSA:
461 	 * digitally-signed struct {
462 	 *     opaque sha_hash[20];
463 	 * };
464 	 *
465 	 * The hash values are calculated over all handshake messages sent or
466 	 * received starting at ClientHello up to, but not including, this
467 	 * CertificateVerify message, including the type and length fields of
468 	 * the handshake messages.
469 	 */
470 
471 	hpos = hash;
472 
473 #ifdef CONFIG_TLSV12
474 	if (conn->rl.tls_version == TLS_VERSION_1_2) {
475 		hlen = SHA256_MAC_LEN;
476 		if (conn->verify.sha256_cert == NULL ||
477 		    crypto_hash_finish(conn->verify.sha256_cert, hpos, &hlen) <
478 		    0) {
479 			conn->verify.sha256_cert = NULL;
480 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
481 				  TLS_ALERT_INTERNAL_ERROR);
482 			return -1;
483 		}
484 		conn->verify.sha256_cert = NULL;
485 
486 		/*
487 		 * RFC 3447, A.2.4 RSASSA-PKCS1-v1_5
488 		 *
489 		 * DigestInfo ::= SEQUENCE {
490 		 *   digestAlgorithm DigestAlgorithm,
491 		 *   digest OCTET STRING
492 		 * }
493 		 *
494 		 * SHA-256 OID: sha256WithRSAEncryption ::= {pkcs-1 11}
495 		 *
496 		 * DER encoded DigestInfo for SHA256 per RFC 3447:
497 		 * 30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00 04 20 ||
498 		 * H
499 		 */
500 		os_memmove(hash + 19, hash, hlen);
501 		hlen += 19;
502 		os_memcpy(hash, "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65"
503 			  "\x03\x04\x02\x01\x05\x00\x04\x20", 19);
504 	} else {
505 #endif /* CONFIG_TLSV12 */
506 
507 	hlen = MD5_MAC_LEN;
508 	if (conn->verify.md5_cert == NULL ||
509 	    crypto_hash_finish(conn->verify.md5_cert, hpos, &hlen) < 0) {
510 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
511 			  TLS_ALERT_INTERNAL_ERROR);
512 		conn->verify.md5_cert = NULL;
513 		crypto_hash_finish(conn->verify.sha1_cert, NULL, NULL);
514 		conn->verify.sha1_cert = NULL;
515 		return -1;
516 	}
517 	hpos += MD5_MAC_LEN;
518 
519 	conn->verify.md5_cert = NULL;
520 	hlen = SHA1_MAC_LEN;
521 	if (conn->verify.sha1_cert == NULL ||
522 	    crypto_hash_finish(conn->verify.sha1_cert, hpos, &hlen) < 0) {
523 		conn->verify.sha1_cert = NULL;
524 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
525 			  TLS_ALERT_INTERNAL_ERROR);
526 		return -1;
527 	}
528 	conn->verify.sha1_cert = NULL;
529 
530 	hlen += MD5_MAC_LEN;
531 
532 #ifdef CONFIG_TLSV12
533 	}
534 #endif /* CONFIG_TLSV12 */
535 
536 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: CertificateVerify hash", hash, hlen);
537 
538 #ifdef CONFIG_TLSV12
539 	if (conn->rl.tls_version >= TLS_VERSION_1_2) {
540 		/*
541 		 * RFC 5246, 4.7:
542 		 * TLS v1.2 adds explicit indication of the used signature and
543 		 * hash algorithms.
544 		 *
545 		 * struct {
546 		 *   HashAlgorithm hash;
547 		 *   SignatureAlgorithm signature;
548 		 * } SignatureAndHashAlgorithm;
549 		 */
550 		*pos++ = TLS_HASH_ALG_SHA256;
551 		*pos++ = TLS_SIGN_ALG_RSA;
552 	}
553 #endif /* CONFIG_TLSV12 */
554 
555 	/*
556 	 * RFC 2246, 4.7:
557 	 * In digital signing, one-way hash functions are used as input for a
558 	 * signing algorithm. A digitally-signed element is encoded as an
559 	 * opaque vector <0..2^16-1>, where the length is specified by the
560 	 * signing algorithm and key.
561 	 *
562 	 * In RSA signing, a 36-byte structure of two hashes (one SHA and one
563 	 * MD5) is signed (encrypted with the private key). It is encoded with
564 	 * PKCS #1 block type 0 or type 1 as described in [PKCS1].
565 	 */
566 	signed_start = pos; /* length to be filled */
567 	pos += 2;
568 	clen = end - pos;
569 	if (conn->cred == NULL ||
570 	    crypto_private_key_sign_pkcs1(conn->cred->key, hash, hlen,
571 					  pos, &clen) < 0) {
572 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to sign hash (PKCS #1)");
573 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
574 			  TLS_ALERT_INTERNAL_ERROR);
575 		return -1;
576 	}
577 	WPA_PUT_BE16(signed_start, clen);
578 
579 	pos += clen;
580 
581 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
582 
583 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
584 			      rhdr, end - rhdr, hs_start, pos - hs_start,
585 			      &rlen) < 0) {
586 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
587 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
588 			  TLS_ALERT_INTERNAL_ERROR);
589 		return -1;
590 	}
591 	pos = rhdr + rlen;
592 
593 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
594 
595 	*msgpos = pos;
596 
597 	return 0;
598 }
599 
600 
601 static int tls_write_client_change_cipher_spec(struct tlsv1_client *conn,
602 					       u8 **msgpos, u8 *end)
603 {
604 	size_t rlen;
605 	u8 payload[1];
606 
607 	wpa_printf(MSG_DEBUG, "TLSv1: Send ChangeCipherSpec");
608 
609 	payload[0] = TLS_CHANGE_CIPHER_SPEC;
610 
611 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC,
612 			      *msgpos, end - *msgpos, payload, sizeof(payload),
613 			      &rlen) < 0) {
614 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
615 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
616 			  TLS_ALERT_INTERNAL_ERROR);
617 		return -1;
618 	}
619 
620 	if (tlsv1_record_change_write_cipher(&conn->rl) < 0) {
621 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to set write cipher for "
622 			   "record layer");
623 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
624 			  TLS_ALERT_INTERNAL_ERROR);
625 		return -1;
626 	}
627 
628 	*msgpos += rlen;
629 
630 	return 0;
631 }
632 
633 
634 static int tls_write_client_finished(struct tlsv1_client *conn,
635 				     u8 **msgpos, u8 *end)
636 {
637 	u8 *pos, *hs_start;
638 	size_t rlen, hlen;
639 	u8 verify_data[1 + 3 + TLS_VERIFY_DATA_LEN];
640 	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN];
641 
642 	wpa_printf(MSG_DEBUG, "TLSv1: Send Finished");
643 
644 	/* Encrypted Handshake Message: Finished */
645 
646 #ifdef CONFIG_TLSV12
647 	if (conn->rl.tls_version >= TLS_VERSION_1_2) {
648 		hlen = SHA256_MAC_LEN;
649 		if (conn->verify.sha256_client == NULL ||
650 		    crypto_hash_finish(conn->verify.sha256_client, hash, &hlen)
651 		    < 0) {
652 			tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
653 				  TLS_ALERT_INTERNAL_ERROR);
654 			conn->verify.sha256_client = NULL;
655 			return -1;
656 		}
657 		conn->verify.sha256_client = NULL;
658 	} else {
659 #endif /* CONFIG_TLSV12 */
660 
661 	hlen = MD5_MAC_LEN;
662 	if (conn->verify.md5_client == NULL ||
663 	    crypto_hash_finish(conn->verify.md5_client, hash, &hlen) < 0) {
664 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
665 			  TLS_ALERT_INTERNAL_ERROR);
666 		conn->verify.md5_client = NULL;
667 		crypto_hash_finish(conn->verify.sha1_client, NULL, NULL);
668 		conn->verify.sha1_client = NULL;
669 		return -1;
670 	}
671 	conn->verify.md5_client = NULL;
672 	hlen = SHA1_MAC_LEN;
673 	if (conn->verify.sha1_client == NULL ||
674 	    crypto_hash_finish(conn->verify.sha1_client, hash + MD5_MAC_LEN,
675 			       &hlen) < 0) {
676 		conn->verify.sha1_client = NULL;
677 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
678 			  TLS_ALERT_INTERNAL_ERROR);
679 		return -1;
680 	}
681 	conn->verify.sha1_client = NULL;
682 	hlen = MD5_MAC_LEN + SHA1_MAC_LEN;
683 
684 #ifdef CONFIG_TLSV12
685 	}
686 #endif /* CONFIG_TLSV12 */
687 
688 	if (tls_prf(conn->rl.tls_version,
689 		    conn->master_secret, TLS_MASTER_SECRET_LEN,
690 		    "client finished", hash, hlen,
691 		    verify_data + 1 + 3, TLS_VERIFY_DATA_LEN)) {
692 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate verify_data");
693 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
694 			  TLS_ALERT_INTERNAL_ERROR);
695 		return -1;
696 	}
697 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: verify_data (client)",
698 			verify_data + 1 + 3, TLS_VERIFY_DATA_LEN);
699 
700 	/* Handshake */
701 	pos = hs_start = verify_data;
702 	/* HandshakeType msg_type */
703 	*pos++ = TLS_HANDSHAKE_TYPE_FINISHED;
704 	/* uint24 length */
705 	WPA_PUT_BE24(pos, TLS_VERIFY_DATA_LEN);
706 	pos += 3;
707 	pos += TLS_VERIFY_DATA_LEN; /* verify_data already in place */
708 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
709 
710 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
711 			      *msgpos, end - *msgpos, hs_start, pos - hs_start,
712 			      &rlen) < 0) {
713 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
714 		tls_alert(conn, TLS_ALERT_LEVEL_FATAL,
715 			  TLS_ALERT_INTERNAL_ERROR);
716 		return -1;
717 	}
718 
719 	*msgpos += rlen;
720 
721 	return 0;
722 }
723 
724 
725 static u8 * tls_send_client_key_exchange(struct tlsv1_client *conn,
726 					 size_t *out_len)
727 {
728 	u8 *msg, *end, *pos;
729 	size_t msglen;
730 
731 	*out_len = 0;
732 
733 	msglen = 2000;
734 	if (conn->certificate_requested)
735 		msglen += tls_client_cert_chain_der_len(conn);
736 
737 	msg = os_malloc(msglen);
738 	if (msg == NULL)
739 		return NULL;
740 
741 	pos = msg;
742 	end = msg + msglen;
743 
744 	if (conn->certificate_requested) {
745 		if (tls_write_client_certificate(conn, &pos, end) < 0) {
746 			os_free(msg);
747 			return NULL;
748 		}
749 	}
750 
751 	if (tls_write_client_key_exchange(conn, &pos, end) < 0 ||
752 	    (conn->certificate_requested && conn->cred && conn->cred->key &&
753 	     tls_write_client_certificate_verify(conn, &pos, end) < 0) ||
754 	    tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
755 	    tls_write_client_finished(conn, &pos, end) < 0) {
756 		os_free(msg);
757 		return NULL;
758 	}
759 
760 	*out_len = pos - msg;
761 
762 	conn->state = SERVER_CHANGE_CIPHER_SPEC;
763 
764 	return msg;
765 }
766 
767 
768 static u8 * tls_send_change_cipher_spec(struct tlsv1_client *conn,
769 					size_t *out_len)
770 {
771 	u8 *msg, *end, *pos;
772 
773 	*out_len = 0;
774 
775 	msg = os_malloc(1000);
776 	if (msg == NULL)
777 		return NULL;
778 
779 	pos = msg;
780 	end = msg + 1000;
781 
782 	if (tls_write_client_change_cipher_spec(conn, &pos, end) < 0 ||
783 	    tls_write_client_finished(conn, &pos, end) < 0) {
784 		os_free(msg);
785 		return NULL;
786 	}
787 
788 	*out_len = pos - msg;
789 
790 	wpa_printf(MSG_DEBUG, "TLSv1: Session resumption completed "
791 		   "successfully");
792 	conn->state = ESTABLISHED;
793 
794 	return msg;
795 }
796 
797 
798 u8 * tlsv1_client_handshake_write(struct tlsv1_client *conn, size_t *out_len,
799 				  int no_appl_data)
800 {
801 	switch (conn->state) {
802 	case CLIENT_KEY_EXCHANGE:
803 		return tls_send_client_key_exchange(conn, out_len);
804 	case CHANGE_CIPHER_SPEC:
805 		return tls_send_change_cipher_spec(conn, out_len);
806 	case ACK_FINISHED:
807 		wpa_printf(MSG_DEBUG, "TLSv1: Handshake completed "
808 			   "successfully");
809 		conn->state = ESTABLISHED;
810 		*out_len = 0;
811 		if (no_appl_data) {
812 			/* Need to return something to get final TLS ACK. */
813 			return os_malloc(1);
814 		}
815 		return NULL;
816 	default:
817 		wpa_printf(MSG_DEBUG, "TLSv1: Unexpected state %d while "
818 			   "generating reply", conn->state);
819 		return NULL;
820 	}
821 }
822 
823 
824 u8 * tlsv1_client_send_alert(struct tlsv1_client *conn, u8 level,
825 			     u8 description, size_t *out_len)
826 {
827 	u8 *alert, *pos, *length;
828 
829 	wpa_printf(MSG_DEBUG, "TLSv1: Send Alert(%d:%d)", level, description);
830 	*out_len = 0;
831 
832 	alert = os_malloc(10);
833 	if (alert == NULL)
834 		return NULL;
835 
836 	pos = alert;
837 
838 	/* TLSPlaintext */
839 	/* ContentType type */
840 	*pos++ = TLS_CONTENT_TYPE_ALERT;
841 	/* ProtocolVersion version */
842 	WPA_PUT_BE16(pos, conn->rl.tls_version ? conn->rl.tls_version :
843 		     TLS_VERSION);
844 	pos += 2;
845 	/* uint16 length (to be filled) */
846 	length = pos;
847 	pos += 2;
848 	/* opaque fragment[TLSPlaintext.length] */
849 
850 	/* Alert */
851 	/* AlertLevel level */
852 	*pos++ = level;
853 	/* AlertDescription description */
854 	*pos++ = description;
855 
856 	WPA_PUT_BE16(length, pos - length - 2);
857 	*out_len = pos - alert;
858 
859 	return alert;
860 }
861