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