xref: /freebsd/contrib/wpa/src/tls/tlsv1_server_write.c (revision fa50a3552d1e759e1bb65e54cb0b7e863bcf54d5)
1 /*
2  * TLSv1 server - 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_server.h"
21 #include "tlsv1_server_i.h"
22 
23 
24 static size_t tls_server_cert_chain_der_len(struct tlsv1_server *conn)
25 {
26 	size_t len = 0;
27 	struct x509_certificate *cert;
28 
29 	cert = conn->cred->cert;
30 	while (cert) {
31 		len += 3 + cert->cert_len;
32 		if (x509_certificate_self_signed(cert))
33 			break;
34 		cert = x509_certificate_get_subject(conn->cred->trusted_certs,
35 						    &cert->issuer);
36 	}
37 
38 	return len;
39 }
40 
41 
42 static int tls_write_server_hello(struct tlsv1_server *conn,
43 				  u8 **msgpos, u8 *end)
44 {
45 	u8 *pos, *rhdr, *hs_start, *hs_length, *ext_start;
46 	struct os_time now;
47 	size_t rlen;
48 
49 	pos = *msgpos;
50 
51 	tlsv1_server_log(conn, "Send ServerHello");
52 	rhdr = pos;
53 	pos += TLS_RECORD_HEADER_LEN;
54 
55 	os_get_time(&now);
56 	WPA_PUT_BE32(conn->server_random, now.sec);
57 	if (random_get_bytes(conn->server_random + 4, TLS_RANDOM_LEN - 4)) {
58 		wpa_printf(MSG_ERROR, "TLSv1: Could not generate "
59 			   "server_random");
60 		return -1;
61 	}
62 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: server_random",
63 		    conn->server_random, TLS_RANDOM_LEN);
64 
65 	conn->session_id_len = TLS_SESSION_ID_MAX_LEN;
66 	if (random_get_bytes(conn->session_id, conn->session_id_len)) {
67 		wpa_printf(MSG_ERROR, "TLSv1: Could not generate "
68 			   "session_id");
69 		return -1;
70 	}
71 	wpa_hexdump(MSG_MSGDUMP, "TLSv1: session_id",
72 		    conn->session_id, conn->session_id_len);
73 
74 	/* opaque fragment[TLSPlaintext.length] */
75 
76 	/* Handshake */
77 	hs_start = pos;
78 	/* HandshakeType msg_type */
79 	*pos++ = TLS_HANDSHAKE_TYPE_SERVER_HELLO;
80 	/* uint24 length (to be filled) */
81 	hs_length = pos;
82 	pos += 3;
83 	/* body - ServerHello */
84 	/* ProtocolVersion server_version */
85 	WPA_PUT_BE16(pos, conn->rl.tls_version);
86 	pos += 2;
87 	/* Random random: uint32 gmt_unix_time, opaque random_bytes */
88 	os_memcpy(pos, conn->server_random, TLS_RANDOM_LEN);
89 	pos += TLS_RANDOM_LEN;
90 	/* SessionID session_id */
91 	*pos++ = conn->session_id_len;
92 	os_memcpy(pos, conn->session_id, conn->session_id_len);
93 	pos += conn->session_id_len;
94 	/* CipherSuite cipher_suite */
95 	WPA_PUT_BE16(pos, conn->cipher_suite);
96 	pos += 2;
97 	/* CompressionMethod compression_method */
98 	*pos++ = TLS_COMPRESSION_NULL;
99 
100 	/* Extension */
101 	ext_start = pos;
102 	pos += 2;
103 
104 	if (conn->status_request) {
105 		/* Add a status_request extension with empty extension_data */
106 		/* ExtensionsType extension_type = status_request(5) */
107 		WPA_PUT_BE16(pos, TLS_EXT_STATUS_REQUEST);
108 		pos += 2;
109 		/* opaque extension_data<0..2^16-1> length */
110 		WPA_PUT_BE16(pos, 0);
111 		pos += 2;
112 	}
113 
114 	if (conn->status_request_v2) {
115 		/*
116 		  Add a status_request_v2 extension with empty extension_data
117 		*/
118 		/* ExtensionsType extension_type = status_request_v2(17) */
119 		WPA_PUT_BE16(pos, TLS_EXT_STATUS_REQUEST_V2);
120 		pos += 2;
121 		/* opaque extension_data<0..2^16-1> length */
122 		WPA_PUT_BE16(pos, 0);
123 		pos += 2;
124 	}
125 
126 	if (conn->session_ticket && conn->session_ticket_cb) {
127 		int res = conn->session_ticket_cb(
128 			conn->session_ticket_cb_ctx,
129 			conn->session_ticket, conn->session_ticket_len,
130 			conn->client_random, conn->server_random,
131 			conn->master_secret);
132 		if (res < 0) {
133 			tlsv1_server_log(conn, "SessionTicket callback indicated failure");
134 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
135 					   TLS_ALERT_HANDSHAKE_FAILURE);
136 			return -1;
137 		}
138 		conn->use_session_ticket = res;
139 
140 		if (conn->use_session_ticket) {
141 			if (tlsv1_server_derive_keys(conn, NULL, 0) < 0) {
142 				wpa_printf(MSG_DEBUG, "TLSv1: Failed to "
143 					   "derive keys");
144 				tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
145 						   TLS_ALERT_INTERNAL_ERROR);
146 				return -1;
147 			}
148 		}
149 
150 		/*
151 		 * RFC 4507 specifies that server would include an empty
152 		 * SessionTicket extension in ServerHello and a
153 		 * NewSessionTicket message after the ServerHello. However,
154 		 * EAP-FAST (RFC 4851), i.e., the only user of SessionTicket
155 		 * extension at the moment, does not use such extensions.
156 		 *
157 		 * TODO: Add support for configuring RFC 4507 behavior and make
158 		 * EAP-FAST disable it.
159 		 */
160 	}
161 
162 	if (pos == ext_start + 2)
163 		pos -= 2; /* no extensions */
164 	else
165 		WPA_PUT_BE16(ext_start, pos - ext_start - 2);
166 
167 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
168 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
169 
170 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
171 			      rhdr, end - rhdr, hs_start, pos - hs_start,
172 			      &rlen) < 0) {
173 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create TLS record");
174 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
175 				   TLS_ALERT_INTERNAL_ERROR);
176 		return -1;
177 	}
178 	pos = rhdr + rlen;
179 
180 	*msgpos = pos;
181 
182 	return 0;
183 }
184 
185 
186 static int tls_write_server_certificate(struct tlsv1_server *conn,
187 					u8 **msgpos, u8 *end)
188 {
189 	u8 *pos, *rhdr, *hs_start, *hs_length, *cert_start;
190 	size_t rlen;
191 	struct x509_certificate *cert;
192 	const struct tls_cipher_suite *suite;
193 
194 	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
195 	if (suite && suite->key_exchange == TLS_KEY_X_DH_anon) {
196 		wpa_printf(MSG_DEBUG, "TLSv1: Do not send Certificate when "
197 			   "using anonymous DH");
198 		return 0;
199 	}
200 
201 	pos = *msgpos;
202 	if (TLS_RECORD_HEADER_LEN + 1 + 3 + 3 > end - pos) {
203 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
204 				   TLS_ALERT_INTERNAL_ERROR);
205 		return -1;
206 	}
207 
208 	tlsv1_server_log(conn, "Send Certificate");
209 	rhdr = pos;
210 	pos += TLS_RECORD_HEADER_LEN;
211 
212 	/* opaque fragment[TLSPlaintext.length] */
213 
214 	/* Handshake */
215 	hs_start = pos;
216 	/* HandshakeType msg_type */
217 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE;
218 	/* uint24 length (to be filled) */
219 	hs_length = pos;
220 	pos += 3;
221 	/* body - Certificate */
222 	/* uint24 length (to be filled) */
223 	cert_start = pos;
224 	pos += 3;
225 	cert = conn->cred->cert;
226 	while (cert) {
227 		if (3 + cert->cert_len > (size_t) (end - pos)) {
228 			wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space "
229 				   "for Certificate (cert_len=%lu left=%lu)",
230 				   (unsigned long) cert->cert_len,
231 				   (unsigned long) (end - pos));
232 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
233 					   TLS_ALERT_INTERNAL_ERROR);
234 			return -1;
235 		}
236 		WPA_PUT_BE24(pos, cert->cert_len);
237 		pos += 3;
238 		os_memcpy(pos, cert->cert_start, cert->cert_len);
239 		pos += cert->cert_len;
240 
241 		if (x509_certificate_self_signed(cert))
242 			break;
243 		cert = x509_certificate_get_subject(conn->cred->trusted_certs,
244 						    &cert->issuer);
245 	}
246 	if (cert == conn->cred->cert || cert == NULL) {
247 		/*
248 		 * Server was not configured with all the needed certificates
249 		 * to form a full certificate chain. The client may fail to
250 		 * validate the chain unless it is configured with all the
251 		 * missing CA certificates.
252 		 */
253 		wpa_printf(MSG_DEBUG, "TLSv1: Full server certificate chain "
254 			   "not configured - validation may fail");
255 	}
256 	WPA_PUT_BE24(cert_start, pos - cert_start - 3);
257 
258 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
259 
260 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
261 			      rhdr, end - rhdr, hs_start, pos - hs_start,
262 			      &rlen) < 0) {
263 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
264 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
265 				   TLS_ALERT_INTERNAL_ERROR);
266 		return -1;
267 	}
268 	pos = rhdr + rlen;
269 
270 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
271 
272 	*msgpos = pos;
273 
274 	return 0;
275 }
276 
277 
278 static int tls_write_server_certificate_status(struct tlsv1_server *conn,
279 					       u8 **msgpos, u8 *end,
280 					       int ocsp_multi,
281 					       char *ocsp_resp,
282 					       size_t ocsp_resp_len)
283 {
284 	u8 *pos, *rhdr, *hs_start, *hs_length;
285 	size_t rlen;
286 
287 	if (!ocsp_resp) {
288 		 /*
289 		  * Client did not request certificate status or there is no
290 		  * matching response cached.
291 		  */
292 		return 0;
293 	}
294 
295 	pos = *msgpos;
296 	if (TLS_RECORD_HEADER_LEN + 1 + 3 + 1 + 3 + ocsp_resp_len >
297 	    (unsigned int) (end - pos)) {
298 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
299 				   TLS_ALERT_INTERNAL_ERROR);
300 		return -1;
301 	}
302 
303 	tlsv1_server_log(conn, "Send CertificateStatus (multi=%d)", ocsp_multi);
304 	rhdr = pos;
305 	pos += TLS_RECORD_HEADER_LEN;
306 
307 	/* opaque fragment[TLSPlaintext.length] */
308 
309 	/* Handshake */
310 	hs_start = pos;
311 	/* HandshakeType msg_type */
312 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE_STATUS;
313 	/* uint24 length (to be filled) */
314 	hs_length = pos;
315 	pos += 3;
316 
317 	/* body - CertificateStatus
318 	 *
319 	 * struct {
320 	 *     CertificateStatusType status_type;
321 	 *     select (status_type) {
322 	 *         case ocsp: OCSPResponse;
323 	 *         case ocsp_multi: OCSPResponseList;
324 	 *     } response;
325 	 * } CertificateStatus;
326 	 *
327 	 * opaque OCSPResponse<1..2^24-1>;
328 	 *
329 	 * struct {
330 	 *   OCSPResponse ocsp_response_list<1..2^24-1>;
331 	 * } OCSPResponseList;
332 	 */
333 
334 	/* CertificateStatusType status_type */
335 	if (ocsp_multi)
336 		*pos++ = 2; /* ocsp_multi(2) */
337 	else
338 		*pos++ = 1; /* ocsp(1) */
339 	/* uint24 length of OCSPResponse */
340 	WPA_PUT_BE24(pos, ocsp_resp_len);
341 	pos += 3;
342 	os_memcpy(pos, ocsp_resp, ocsp_resp_len);
343 	pos += ocsp_resp_len;
344 
345 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
346 
347 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
348 			      rhdr, end - rhdr, hs_start, pos - hs_start,
349 			      &rlen) < 0) {
350 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
351 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
352 				   TLS_ALERT_INTERNAL_ERROR);
353 		return -1;
354 	}
355 	pos = rhdr + rlen;
356 
357 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
358 
359 	*msgpos = pos;
360 
361 	return 0;
362 }
363 
364 
365 static int tls_write_server_key_exchange(struct tlsv1_server *conn,
366 					 u8 **msgpos, u8 *end)
367 {
368 	tls_key_exchange keyx;
369 	const struct tls_cipher_suite *suite;
370 	u8 *pos, *rhdr, *hs_start, *hs_length, *server_params;
371 	size_t rlen;
372 	u8 *dh_ys;
373 	size_t dh_ys_len;
374 	const u8 *dh_p;
375 	size_t dh_p_len;
376 
377 	suite = tls_get_cipher_suite(conn->rl.cipher_suite);
378 	if (suite == NULL)
379 		keyx = TLS_KEY_X_NULL;
380 	else
381 		keyx = suite->key_exchange;
382 
383 	if (!tls_server_key_exchange_allowed(conn->rl.cipher_suite)) {
384 		wpa_printf(MSG_DEBUG, "TLSv1: No ServerKeyExchange needed");
385 		return 0;
386 	}
387 
388 	if (keyx != TLS_KEY_X_DH_anon && keyx != TLS_KEY_X_DHE_RSA) {
389 		wpa_printf(MSG_DEBUG, "TLSv1: ServerKeyExchange not yet "
390 			   "supported with key exchange type %d", keyx);
391 		return -1;
392 	}
393 
394 	if (conn->cred == NULL || conn->cred->dh_p == NULL ||
395 	    conn->cred->dh_g == NULL) {
396 		wpa_printf(MSG_DEBUG, "TLSv1: No DH parameters available for "
397 			   "ServerKeyExhcange");
398 		return -1;
399 	}
400 
401 	tlsv1_server_get_dh_p(conn, &dh_p, &dh_p_len);
402 
403 	os_free(conn->dh_secret);
404 	conn->dh_secret_len = dh_p_len;
405 	conn->dh_secret = os_malloc(conn->dh_secret_len);
406 	if (conn->dh_secret == NULL) {
407 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate "
408 			   "memory for secret (Diffie-Hellman)");
409 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
410 				   TLS_ALERT_INTERNAL_ERROR);
411 		return -1;
412 	}
413 	if (random_get_bytes(conn->dh_secret, conn->dh_secret_len)) {
414 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to get random "
415 			   "data for Diffie-Hellman");
416 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
417 				   TLS_ALERT_INTERNAL_ERROR);
418 		os_free(conn->dh_secret);
419 		conn->dh_secret = NULL;
420 		return -1;
421 	}
422 
423 	if (os_memcmp(conn->dh_secret, dh_p, conn->dh_secret_len) > 0)
424 		conn->dh_secret[0] = 0; /* make sure secret < p */
425 
426 	pos = conn->dh_secret;
427 	while (pos + 1 < conn->dh_secret + conn->dh_secret_len && *pos == 0)
428 		pos++;
429 	if (pos != conn->dh_secret) {
430 		os_memmove(conn->dh_secret, pos,
431 			   conn->dh_secret_len - (pos - conn->dh_secret));
432 		conn->dh_secret_len -= pos - conn->dh_secret;
433 	}
434 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: DH server's secret value",
435 			conn->dh_secret, conn->dh_secret_len);
436 
437 	/* Ys = g^secret mod p */
438 	dh_ys_len = dh_p_len;
439 	dh_ys = os_malloc(dh_ys_len);
440 	if (dh_ys == NULL) {
441 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to allocate memory for "
442 			   "Diffie-Hellman");
443 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
444 				   TLS_ALERT_INTERNAL_ERROR);
445 		return -1;
446 	}
447 	if (crypto_mod_exp(conn->cred->dh_g, conn->cred->dh_g_len,
448 			   conn->dh_secret, conn->dh_secret_len,
449 			   dh_p, dh_p_len, dh_ys, &dh_ys_len)) {
450 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
451 				   TLS_ALERT_INTERNAL_ERROR);
452 		os_free(dh_ys);
453 		return -1;
454 	}
455 
456 	wpa_hexdump(MSG_DEBUG, "TLSv1: DH Ys (server's public value)",
457 		    dh_ys, dh_ys_len);
458 
459 	/*
460 	 * struct {
461 	 *    select (KeyExchangeAlgorithm) {
462 	 *       case diffie_hellman:
463 	 *          ServerDHParams params;
464 	 *          Signature signed_params;
465 	 *       case rsa:
466 	 *          ServerRSAParams params;
467 	 *          Signature signed_params;
468 	 *    };
469 	 * } ServerKeyExchange;
470 	 *
471 	 * struct {
472 	 *    opaque dh_p<1..2^16-1>;
473 	 *    opaque dh_g<1..2^16-1>;
474 	 *    opaque dh_Ys<1..2^16-1>;
475 	 * } ServerDHParams;
476 	 */
477 
478 	pos = *msgpos;
479 
480 	tlsv1_server_log(conn, "Send ServerKeyExchange");
481 	rhdr = pos;
482 	pos += TLS_RECORD_HEADER_LEN;
483 
484 	/* opaque fragment[TLSPlaintext.length] */
485 
486 	/* Handshake */
487 	hs_start = pos;
488 	/* HandshakeType msg_type */
489 	*pos++ = TLS_HANDSHAKE_TYPE_SERVER_KEY_EXCHANGE;
490 	/* uint24 length (to be filled) */
491 	hs_length = pos;
492 	pos += 3;
493 
494 	/* body - ServerDHParams */
495 	server_params = pos;
496 	/* dh_p */
497 	if (2 + dh_p_len > (size_t) (end - pos)) {
498 		wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space for "
499 			   "dh_p");
500 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
501 				   TLS_ALERT_INTERNAL_ERROR);
502 		os_free(dh_ys);
503 		return -1;
504 	}
505 	WPA_PUT_BE16(pos, dh_p_len);
506 	pos += 2;
507 	os_memcpy(pos, dh_p, dh_p_len);
508 	pos += dh_p_len;
509 
510 	/* dh_g */
511 	if (2 + conn->cred->dh_g_len > (size_t) (end - pos)) {
512 		wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space for "
513 			   "dh_g");
514 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
515 				   TLS_ALERT_INTERNAL_ERROR);
516 		os_free(dh_ys);
517 		return -1;
518 	}
519 	WPA_PUT_BE16(pos, conn->cred->dh_g_len);
520 	pos += 2;
521 	os_memcpy(pos, conn->cred->dh_g, conn->cred->dh_g_len);
522 	pos += conn->cred->dh_g_len;
523 
524 	/* dh_Ys */
525 	if (2 + dh_ys_len > (size_t) (end - pos)) {
526 		wpa_printf(MSG_DEBUG, "TLSv1: Not enough buffer space for "
527 			   "dh_Ys");
528 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
529 				   TLS_ALERT_INTERNAL_ERROR);
530 		os_free(dh_ys);
531 		return -1;
532 	}
533 	WPA_PUT_BE16(pos, dh_ys_len);
534 	pos += 2;
535 	os_memcpy(pos, dh_ys, dh_ys_len);
536 	pos += dh_ys_len;
537 	os_free(dh_ys);
538 
539 	/*
540 	 * select (SignatureAlgorithm)
541 	 * {   case anonymous: struct { };
542 	 *     case rsa:
543 	 *         digitally-signed struct {
544 	 *             opaque md5_hash[16];
545 	 *             opaque sha_hash[20];
546 	 *         };
547 	 *     case dsa:
548 	 *         digitally-signed struct {
549 	 *             opaque sha_hash[20];
550 	 *         };
551 	 * } Signature;
552 	 *
553 	 * md5_hash
554 	 *     MD5(ClientHello.random + ServerHello.random + ServerParams);
555 	 *
556 	 * sha_hash
557 	 *     SHA(ClientHello.random + ServerHello.random + ServerParams);
558 	 */
559 
560 	if (keyx == TLS_KEY_X_DHE_RSA) {
561 		u8 hash[100];
562 		u8 *signed_start;
563 		size_t clen;
564 		int hlen;
565 
566 		if (conn->rl.tls_version >= TLS_VERSION_1_2) {
567 #ifdef CONFIG_TLSV12
568 			hlen = tlsv12_key_x_server_params_hash(
569 				conn->rl.tls_version, TLS_HASH_ALG_SHA256,
570 				conn->client_random,
571 				conn->server_random, server_params,
572 				pos - server_params, hash + 19);
573 
574 			/*
575 			 * RFC 5246, 4.7:
576 			 * TLS v1.2 adds explicit indication of the used
577 			 * signature and hash algorithms.
578 			 *
579 			 * struct {
580 			 *   HashAlgorithm hash;
581 			 *   SignatureAlgorithm signature;
582 			 * } SignatureAndHashAlgorithm;
583 			 */
584 			if (hlen < 0 || end - pos < 2) {
585 				tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
586 						   TLS_ALERT_INTERNAL_ERROR);
587 				return -1;
588 			}
589 			*pos++ = TLS_HASH_ALG_SHA256;
590 			*pos++ = TLS_SIGN_ALG_RSA;
591 
592 			/*
593 			 * RFC 3447, A.2.4 RSASSA-PKCS1-v1_5
594 			 *
595 			 * DigestInfo ::= SEQUENCE {
596 			 *   digestAlgorithm DigestAlgorithm,
597 			 *   digest OCTET STRING
598 			 * }
599 			 *
600 			 * SHA-256 OID: sha256WithRSAEncryption ::= {pkcs-1 11}
601 			 *
602 			 * DER encoded DigestInfo for SHA256 per RFC 3447:
603 			 * 30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00
604 			 * 04 20 || H
605 			 */
606 			hlen += 19;
607 			os_memcpy(hash,
608 				  "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65"
609 				  "\x03\x04\x02\x01\x05\x00\x04\x20", 19);
610 
611 #else /* CONFIG_TLSV12 */
612 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
613 					   TLS_ALERT_INTERNAL_ERROR);
614 			return -1;
615 #endif /* CONFIG_TLSV12 */
616 		} else {
617 			hlen = tls_key_x_server_params_hash(
618 				conn->rl.tls_version, conn->client_random,
619 				conn->server_random, server_params,
620 				pos - server_params, hash);
621 		}
622 
623 		if (hlen < 0) {
624 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
625 					   TLS_ALERT_INTERNAL_ERROR);
626 			return -1;
627 		}
628 
629 		wpa_hexdump(MSG_MSGDUMP, "TLS: ServerKeyExchange signed_params hash",
630 			    hash, hlen);
631 #ifdef CONFIG_TESTING_OPTIONS
632 		if (conn->test_flags & TLS_BREAK_SRV_KEY_X_HASH) {
633 			tlsv1_server_log(conn, "TESTING: Break ServerKeyExchange signed params hash");
634 			hash[hlen - 1] ^= 0x80;
635 		}
636 #endif /* CONFIG_TESTING_OPTIONS */
637 
638 		/*
639 		 * RFC 2246, 4.7:
640 		 * In digital signing, one-way hash functions are used as input
641 		 * for a signing algorithm. A digitally-signed element is
642 		 * encoded as an opaque vector <0..2^16-1>, where the length is
643 		 * specified by the signing algorithm and key.
644 		 *
645 		 * In RSA signing, a 36-byte structure of two hashes (one SHA
646 		 * and one MD5) is signed (encrypted with the private key). It
647 		 * is encoded with PKCS #1 block type 0 or type 1 as described
648 		 * in [PKCS1].
649 		 */
650 		signed_start = pos; /* length to be filled */
651 		pos += 2;
652 		clen = end - pos;
653 		if (conn->cred == NULL ||
654 		    crypto_private_key_sign_pkcs1(conn->cred->key, hash, hlen,
655 						  pos, &clen) < 0) {
656 			wpa_printf(MSG_DEBUG, "TLSv1: Failed to sign hash (PKCS #1)");
657 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
658 					   TLS_ALERT_INTERNAL_ERROR);
659 			return -1;
660 		}
661 		WPA_PUT_BE16(signed_start, clen);
662 #ifdef CONFIG_TESTING_OPTIONS
663 		if (conn->test_flags & TLS_BREAK_SRV_KEY_X_SIGNATURE) {
664 			tlsv1_server_log(conn, "TESTING: Break ServerKeyExchange signed params signature");
665 			pos[clen - 1] ^= 0x80;
666 		}
667 #endif /* CONFIG_TESTING_OPTIONS */
668 
669 		pos += clen;
670 	}
671 
672 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
673 
674 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
675 			      rhdr, end - rhdr, hs_start, pos - hs_start,
676 			      &rlen) < 0) {
677 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
678 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
679 				   TLS_ALERT_INTERNAL_ERROR);
680 		return -1;
681 	}
682 	pos = rhdr + rlen;
683 
684 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
685 
686 	*msgpos = pos;
687 
688 	return 0;
689 }
690 
691 
692 static int tls_write_server_certificate_request(struct tlsv1_server *conn,
693 						u8 **msgpos, u8 *end)
694 {
695 	u8 *pos, *rhdr, *hs_start, *hs_length;
696 	size_t rlen;
697 
698 	if (!conn->verify_peer) {
699 		wpa_printf(MSG_DEBUG, "TLSv1: No CertificateRequest needed");
700 		return 0;
701 	}
702 
703 	pos = *msgpos;
704 
705 	tlsv1_server_log(conn, "Send CertificateRequest");
706 	rhdr = pos;
707 	pos += TLS_RECORD_HEADER_LEN;
708 
709 	/* opaque fragment[TLSPlaintext.length] */
710 
711 	/* Handshake */
712 	hs_start = pos;
713 	/* HandshakeType msg_type */
714 	*pos++ = TLS_HANDSHAKE_TYPE_CERTIFICATE_REQUEST;
715 	/* uint24 length (to be filled) */
716 	hs_length = pos;
717 	pos += 3;
718 	/* body - CertificateRequest */
719 
720 	/*
721 	 * enum {
722 	 *   rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
723 	 *   (255)
724 	 * } ClientCertificateType;
725 	 * ClientCertificateType certificate_types<1..2^8-1>
726 	 */
727 	*pos++ = 1;
728 	*pos++ = 1; /* rsa_sign */
729 
730 	/*
731 	 * opaque DistinguishedName<1..2^16-1>
732 	 * DistinguishedName certificate_authorities<3..2^16-1>
733 	 */
734 	/* TODO: add support for listing DNs for trusted CAs */
735 	WPA_PUT_BE16(pos, 0);
736 	pos += 2;
737 
738 	WPA_PUT_BE24(hs_length, pos - hs_length - 3);
739 
740 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
741 			      rhdr, end - rhdr, hs_start, pos - hs_start,
742 			      &rlen) < 0) {
743 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
744 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
745 				   TLS_ALERT_INTERNAL_ERROR);
746 		return -1;
747 	}
748 	pos = rhdr + rlen;
749 
750 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
751 
752 	*msgpos = pos;
753 
754 	return 0;
755 }
756 
757 
758 static int tls_write_server_hello_done(struct tlsv1_server *conn,
759 				       u8 **msgpos, u8 *end)
760 {
761 	u8 *pos;
762 	size_t rlen;
763 	u8 payload[4];
764 
765 	tlsv1_server_log(conn, "Send ServerHelloDone");
766 
767 	/* opaque fragment[TLSPlaintext.length] */
768 
769 	/* Handshake */
770 	pos = payload;
771 	/* HandshakeType msg_type */
772 	*pos++ = TLS_HANDSHAKE_TYPE_SERVER_HELLO_DONE;
773 	/* uint24 length */
774 	WPA_PUT_BE24(pos, 0);
775 	pos += 3;
776 	/* body - ServerHelloDone (empty) */
777 
778 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
779 			      *msgpos, end - *msgpos, payload, pos - payload,
780 			      &rlen) < 0) {
781 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate a record");
782 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
783 				   TLS_ALERT_INTERNAL_ERROR);
784 		return -1;
785 	}
786 
787 	tls_verify_hash_add(&conn->verify, payload, pos - payload);
788 
789 	*msgpos += rlen;
790 
791 	return 0;
792 }
793 
794 
795 static int tls_write_server_change_cipher_spec(struct tlsv1_server *conn,
796 					       u8 **msgpos, u8 *end)
797 {
798 	size_t rlen;
799 	u8 payload[1];
800 
801 	tlsv1_server_log(conn, "Send ChangeCipherSpec");
802 
803 	payload[0] = TLS_CHANGE_CIPHER_SPEC;
804 
805 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_CHANGE_CIPHER_SPEC,
806 			      *msgpos, end - *msgpos, payload, sizeof(payload),
807 			      &rlen) < 0) {
808 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
809 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
810 				   TLS_ALERT_INTERNAL_ERROR);
811 		return -1;
812 	}
813 
814 	if (tlsv1_record_change_write_cipher(&conn->rl) < 0) {
815 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to set write cipher for "
816 			   "record layer");
817 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
818 				   TLS_ALERT_INTERNAL_ERROR);
819 		return -1;
820 	}
821 
822 	*msgpos += rlen;
823 
824 	return 0;
825 }
826 
827 
828 static int tls_write_server_finished(struct tlsv1_server *conn,
829 				     u8 **msgpos, u8 *end)
830 {
831 	u8 *pos, *hs_start;
832 	size_t rlen, hlen;
833 	u8 verify_data[1 + 3 + TLS_VERIFY_DATA_LEN];
834 	u8 hash[MD5_MAC_LEN + SHA1_MAC_LEN];
835 
836 	pos = *msgpos;
837 
838 	tlsv1_server_log(conn, "Send Finished");
839 
840 	/* Encrypted Handshake Message: Finished */
841 
842 #ifdef CONFIG_TLSV12
843 	if (conn->rl.tls_version >= TLS_VERSION_1_2) {
844 		hlen = SHA256_MAC_LEN;
845 		if (conn->verify.sha256_server == NULL ||
846 		    crypto_hash_finish(conn->verify.sha256_server, hash, &hlen)
847 		    < 0) {
848 			conn->verify.sha256_server = NULL;
849 			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
850 					   TLS_ALERT_INTERNAL_ERROR);
851 			return -1;
852 		}
853 		conn->verify.sha256_server = NULL;
854 	} else {
855 #endif /* CONFIG_TLSV12 */
856 
857 	hlen = MD5_MAC_LEN;
858 	if (conn->verify.md5_server == NULL ||
859 	    crypto_hash_finish(conn->verify.md5_server, hash, &hlen) < 0) {
860 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
861 				   TLS_ALERT_INTERNAL_ERROR);
862 		conn->verify.md5_server = NULL;
863 		crypto_hash_finish(conn->verify.sha1_server, NULL, NULL);
864 		conn->verify.sha1_server = NULL;
865 		return -1;
866 	}
867 	conn->verify.md5_server = NULL;
868 	hlen = SHA1_MAC_LEN;
869 	if (conn->verify.sha1_server == NULL ||
870 	    crypto_hash_finish(conn->verify.sha1_server, hash + MD5_MAC_LEN,
871 			       &hlen) < 0) {
872 		conn->verify.sha1_server = NULL;
873 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
874 				   TLS_ALERT_INTERNAL_ERROR);
875 		return -1;
876 	}
877 	conn->verify.sha1_server = NULL;
878 	hlen = MD5_MAC_LEN + SHA1_MAC_LEN;
879 
880 #ifdef CONFIG_TLSV12
881 	}
882 #endif /* CONFIG_TLSV12 */
883 
884 	if (tls_prf(conn->rl.tls_version,
885 		    conn->master_secret, TLS_MASTER_SECRET_LEN,
886 		    "server finished", hash, hlen,
887 		    verify_data + 1 + 3, TLS_VERIFY_DATA_LEN)) {
888 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to generate verify_data");
889 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
890 				   TLS_ALERT_INTERNAL_ERROR);
891 		return -1;
892 	}
893 	wpa_hexdump_key(MSG_DEBUG, "TLSv1: verify_data (server)",
894 			verify_data + 1 + 3, TLS_VERIFY_DATA_LEN);
895 #ifdef CONFIG_TESTING_OPTIONS
896 	if (conn->test_flags & TLS_BREAK_VERIFY_DATA) {
897 		tlsv1_server_log(conn, "TESTING: Break verify_data (server)");
898 		verify_data[1 + 3 + 1] ^= 0x80;
899 	}
900 #endif /* CONFIG_TESTING_OPTIONS */
901 
902 	/* Handshake */
903 	pos = hs_start = verify_data;
904 	/* HandshakeType msg_type */
905 	*pos++ = TLS_HANDSHAKE_TYPE_FINISHED;
906 	/* uint24 length */
907 	WPA_PUT_BE24(pos, TLS_VERIFY_DATA_LEN);
908 	pos += 3;
909 	pos += TLS_VERIFY_DATA_LEN;
910 	tls_verify_hash_add(&conn->verify, hs_start, pos - hs_start);
911 
912 	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_HANDSHAKE,
913 			      *msgpos, end - *msgpos, hs_start, pos - hs_start,
914 			      &rlen) < 0) {
915 		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
916 		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
917 				   TLS_ALERT_INTERNAL_ERROR);
918 		return -1;
919 	}
920 
921 	*msgpos += rlen;
922 
923 	return 0;
924 }
925 
926 
927 static u8 * tls_send_server_hello(struct tlsv1_server *conn, size_t *out_len)
928 {
929 	u8 *msg, *end, *pos;
930 	size_t msglen;
931 	int ocsp_multi = 0;
932 	char *ocsp_resp = NULL;
933 	size_t ocsp_resp_len = 0;
934 
935 	*out_len = 0;
936 
937 	if (conn->status_request_multi &&
938 	    conn->cred->ocsp_stapling_response_multi) {
939 		ocsp_resp = os_readfile(
940 			conn->cred->ocsp_stapling_response_multi,
941 			&ocsp_resp_len);
942 		ocsp_multi = 1;
943 	} else if ((conn->status_request || conn->status_request_v2) &&
944 		   conn->cred->ocsp_stapling_response) {
945 		ocsp_resp = os_readfile(conn->cred->ocsp_stapling_response,
946 					&ocsp_resp_len);
947 	}
948 	if (!ocsp_resp)
949 		ocsp_resp_len = 0;
950 
951 	msglen = 1000 + tls_server_cert_chain_der_len(conn) + ocsp_resp_len;
952 
953 	msg = os_malloc(msglen);
954 	if (msg == NULL) {
955 		os_free(ocsp_resp);
956 		return NULL;
957 	}
958 
959 	pos = msg;
960 	end = msg + msglen;
961 
962 	if (tls_write_server_hello(conn, &pos, end) < 0) {
963 		os_free(msg);
964 		os_free(ocsp_resp);
965 		return NULL;
966 	}
967 
968 	if (conn->use_session_ticket) {
969 		os_free(ocsp_resp);
970 
971 		/* Abbreviated handshake using session ticket; RFC 4507 */
972 		if (tls_write_server_change_cipher_spec(conn, &pos, end) < 0 ||
973 		    tls_write_server_finished(conn, &pos, end) < 0) {
974 			os_free(msg);
975 			return NULL;
976 		}
977 
978 		*out_len = pos - msg;
979 
980 		conn->state = CHANGE_CIPHER_SPEC;
981 
982 		return msg;
983 	}
984 
985 	/* Full handshake */
986 	if (tls_write_server_certificate(conn, &pos, end) < 0 ||
987 	    tls_write_server_certificate_status(conn, &pos, end, ocsp_multi,
988 						ocsp_resp, ocsp_resp_len) < 0 ||
989 	    tls_write_server_key_exchange(conn, &pos, end) < 0 ||
990 	    tls_write_server_certificate_request(conn, &pos, end) < 0 ||
991 	    tls_write_server_hello_done(conn, &pos, end) < 0) {
992 		os_free(msg);
993 		os_free(ocsp_resp);
994 		return NULL;
995 	}
996 	os_free(ocsp_resp);
997 
998 	*out_len = pos - msg;
999 
1000 	conn->state = CLIENT_CERTIFICATE;
1001 
1002 	return msg;
1003 }
1004 
1005 
1006 static u8 * tls_send_change_cipher_spec(struct tlsv1_server *conn,
1007 					size_t *out_len)
1008 {
1009 	u8 *msg, *end, *pos;
1010 
1011 	*out_len = 0;
1012 
1013 	msg = os_malloc(1000);
1014 	if (msg == NULL)
1015 		return NULL;
1016 
1017 	pos = msg;
1018 	end = msg + 1000;
1019 
1020 	if (tls_write_server_change_cipher_spec(conn, &pos, end) < 0 ||
1021 	    tls_write_server_finished(conn, &pos, end) < 0) {
1022 		os_free(msg);
1023 		return NULL;
1024 	}
1025 
1026 	*out_len = pos - msg;
1027 
1028 	tlsv1_server_log(conn, "Handshake completed successfully");
1029 	conn->state = ESTABLISHED;
1030 
1031 	return msg;
1032 }
1033 
1034 
1035 u8 * tlsv1_server_handshake_write(struct tlsv1_server *conn, size_t *out_len)
1036 {
1037 	switch (conn->state) {
1038 	case SERVER_HELLO:
1039 		return tls_send_server_hello(conn, out_len);
1040 	case SERVER_CHANGE_CIPHER_SPEC:
1041 		return tls_send_change_cipher_spec(conn, out_len);
1042 	default:
1043 		if (conn->state == ESTABLISHED && conn->use_session_ticket) {
1044 			/* Abbreviated handshake was already completed. */
1045 			return NULL;
1046 		}
1047 		tlsv1_server_log(conn, "Unexpected state %d while generating reply",
1048 				 conn->state);
1049 		return NULL;
1050 	}
1051 }
1052 
1053 
1054 u8 * tlsv1_server_send_alert(struct tlsv1_server *conn, u8 level,
1055 			     u8 description, size_t *out_len)
1056 {
1057 	u8 *alert, *pos, *length;
1058 
1059 	tlsv1_server_log(conn, "Send Alert(%d:%d)", level, description);
1060 	*out_len = 0;
1061 
1062 	alert = os_malloc(10);
1063 	if (alert == NULL)
1064 		return NULL;
1065 
1066 	pos = alert;
1067 
1068 	/* TLSPlaintext */
1069 	/* ContentType type */
1070 	*pos++ = TLS_CONTENT_TYPE_ALERT;
1071 	/* ProtocolVersion version */
1072 	WPA_PUT_BE16(pos, conn->rl.tls_version ? conn->rl.tls_version :
1073 		     TLS_VERSION);
1074 	pos += 2;
1075 	/* uint16 length (to be filled) */
1076 	length = pos;
1077 	pos += 2;
1078 	/* opaque fragment[TLSPlaintext.length] */
1079 
1080 	/* Alert */
1081 	/* AlertLevel level */
1082 	*pos++ = level;
1083 	/* AlertDescription description */
1084 	*pos++ = description;
1085 
1086 	WPA_PUT_BE16(length, pos - length - 2);
1087 	*out_len = pos - alert;
1088 
1089 	return alert;
1090 }
1091