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