1/*
2 * TLS v1.0/v1.1/v1.2 server (RFC 2246, RFC 4346, RFC 5246)
3 * Copyright (c) 2006-2011, Jouni Malinen <j@w1.fi>
4 *
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
7 */
8
9#include "includes.h"
10
11#include "common.h"
12#include "crypto/sha1.h"
13#include "crypto/tls.h"
14#include "tlsv1_common.h"
15#include "tlsv1_record.h"
16#include "tlsv1_server.h"
17#include "tlsv1_server_i.h"
18
19/* TODO:
20 * Support for a message fragmented across several records (RFC 2246, 6.2.1)
21 */
22
23
24void tlsv1_server_alert(struct tlsv1_server *conn, u8 level, u8 description)
25{
26	conn->alert_level = level;
27	conn->alert_description = description;
28}
29
30
31int tlsv1_server_derive_keys(struct tlsv1_server *conn,
32			     const u8 *pre_master_secret,
33			     size_t pre_master_secret_len)
34{
35	u8 seed[2 * TLS_RANDOM_LEN];
36	u8 key_block[TLS_MAX_KEY_BLOCK_LEN];
37	u8 *pos;
38	size_t key_block_len;
39
40	if (pre_master_secret) {
41		wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: pre_master_secret",
42				pre_master_secret, pre_master_secret_len);
43		os_memcpy(seed, conn->client_random, TLS_RANDOM_LEN);
44		os_memcpy(seed + TLS_RANDOM_LEN, conn->server_random,
45			  TLS_RANDOM_LEN);
46		if (tls_prf(conn->rl.tls_version,
47			    pre_master_secret, pre_master_secret_len,
48			    "master secret", seed, 2 * TLS_RANDOM_LEN,
49			    conn->master_secret, TLS_MASTER_SECRET_LEN)) {
50			wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive "
51				   "master_secret");
52			return -1;
53		}
54		wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: master_secret",
55				conn->master_secret, TLS_MASTER_SECRET_LEN);
56	}
57
58	os_memcpy(seed, conn->server_random, TLS_RANDOM_LEN);
59	os_memcpy(seed + TLS_RANDOM_LEN, conn->client_random, TLS_RANDOM_LEN);
60	key_block_len = 2 * (conn->rl.hash_size + conn->rl.key_material_len +
61			     conn->rl.iv_size);
62	if (tls_prf(conn->rl.tls_version,
63		    conn->master_secret, TLS_MASTER_SECRET_LEN,
64		    "key expansion", seed, 2 * TLS_RANDOM_LEN,
65		    key_block, key_block_len)) {
66		wpa_printf(MSG_DEBUG, "TLSv1: Failed to derive key_block");
67		return -1;
68	}
69	wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: key_block",
70			key_block, key_block_len);
71
72	pos = key_block;
73
74	/* client_write_MAC_secret */
75	os_memcpy(conn->rl.read_mac_secret, pos, conn->rl.hash_size);
76	pos += conn->rl.hash_size;
77	/* server_write_MAC_secret */
78	os_memcpy(conn->rl.write_mac_secret, pos, conn->rl.hash_size);
79	pos += conn->rl.hash_size;
80
81	/* client_write_key */
82	os_memcpy(conn->rl.read_key, pos, conn->rl.key_material_len);
83	pos += conn->rl.key_material_len;
84	/* server_write_key */
85	os_memcpy(conn->rl.write_key, pos, conn->rl.key_material_len);
86	pos += conn->rl.key_material_len;
87
88	/* client_write_IV */
89	os_memcpy(conn->rl.read_iv, pos, conn->rl.iv_size);
90	pos += conn->rl.iv_size;
91	/* server_write_IV */
92	os_memcpy(conn->rl.write_iv, pos, conn->rl.iv_size);
93	pos += conn->rl.iv_size;
94
95	return 0;
96}
97
98
99/**
100 * tlsv1_server_handshake - Process TLS handshake
101 * @conn: TLSv1 server connection data from tlsv1_server_init()
102 * @in_data: Input data from TLS peer
103 * @in_len: Input data length
104 * @out_len: Length of the output buffer.
105 * Returns: Pointer to output data, %NULL on failure
106 */
107u8 * tlsv1_server_handshake(struct tlsv1_server *conn,
108			    const u8 *in_data, size_t in_len,
109			    size_t *out_len)
110{
111	const u8 *pos, *end;
112	u8 *msg = NULL, *in_msg, *in_pos, *in_end, alert, ct;
113	size_t in_msg_len;
114	int used;
115
116	if (in_data == NULL || in_len == 0) {
117		wpa_printf(MSG_DEBUG, "TLSv1: No input data to server");
118		return NULL;
119	}
120
121	pos = in_data;
122	end = in_data + in_len;
123	in_msg = os_malloc(in_len);
124	if (in_msg == NULL)
125		return NULL;
126
127	/* Each received packet may include multiple records */
128	while (pos < end) {
129		in_msg_len = in_len;
130		used = tlsv1_record_receive(&conn->rl, pos, end - pos,
131					    in_msg, &in_msg_len, &alert);
132		if (used < 0) {
133			wpa_printf(MSG_DEBUG, "TLSv1: Processing received "
134				   "record failed");
135			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
136			goto failed;
137		}
138		if (used == 0) {
139			/* need more data */
140			wpa_printf(MSG_DEBUG, "TLSv1: Partial processing not "
141				   "yet supported");
142			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
143			goto failed;
144		}
145		ct = pos[0];
146
147		in_pos = in_msg;
148		in_end = in_msg + in_msg_len;
149
150		/* Each received record may include multiple messages of the
151		 * same ContentType. */
152		while (in_pos < in_end) {
153			in_msg_len = in_end - in_pos;
154			if (tlsv1_server_process_handshake(conn, ct, in_pos,
155							   &in_msg_len) < 0)
156				goto failed;
157			in_pos += in_msg_len;
158		}
159
160		pos += used;
161	}
162
163	os_free(in_msg);
164	in_msg = NULL;
165
166	msg = tlsv1_server_handshake_write(conn, out_len);
167
168failed:
169	os_free(in_msg);
170	if (conn->alert_level) {
171		if (conn->state == FAILED) {
172			/* Avoid alert loops */
173			wpa_printf(MSG_DEBUG, "TLSv1: Drop alert loop");
174			os_free(msg);
175			return NULL;
176		}
177		conn->state = FAILED;
178		os_free(msg);
179		msg = tlsv1_server_send_alert(conn, conn->alert_level,
180					      conn->alert_description,
181					      out_len);
182	}
183
184	return msg;
185}
186
187
188/**
189 * tlsv1_server_encrypt - Encrypt data into TLS tunnel
190 * @conn: TLSv1 server connection data from tlsv1_server_init()
191 * @in_data: Pointer to plaintext data to be encrypted
192 * @in_len: Input buffer length
193 * @out_data: Pointer to output buffer (encrypted TLS data)
194 * @out_len: Maximum out_data length
195 * Returns: Number of bytes written to out_data, -1 on failure
196 *
197 * This function is used after TLS handshake has been completed successfully to
198 * send data in the encrypted tunnel.
199 */
200int tlsv1_server_encrypt(struct tlsv1_server *conn,
201			 const u8 *in_data, size_t in_len,
202			 u8 *out_data, size_t out_len)
203{
204	size_t rlen;
205
206	wpa_hexdump_key(MSG_MSGDUMP, "TLSv1: Plaintext AppData",
207			in_data, in_len);
208
209	if (tlsv1_record_send(&conn->rl, TLS_CONTENT_TYPE_APPLICATION_DATA,
210			      out_data, out_len, in_data, in_len, &rlen) < 0) {
211		wpa_printf(MSG_DEBUG, "TLSv1: Failed to create a record");
212		tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
213				   TLS_ALERT_INTERNAL_ERROR);
214		return -1;
215	}
216
217	return rlen;
218}
219
220
221/**
222 * tlsv1_server_decrypt - Decrypt data from TLS tunnel
223 * @conn: TLSv1 server connection data from tlsv1_server_init()
224 * @in_data: Pointer to input buffer (encrypted TLS data)
225 * @in_len: Input buffer length
226 * @out_data: Pointer to output buffer (decrypted data from TLS tunnel)
227 * @out_len: Maximum out_data length
228 * Returns: Number of bytes written to out_data, -1 on failure
229 *
230 * This function is used after TLS handshake has been completed successfully to
231 * receive data from the encrypted tunnel.
232 */
233int tlsv1_server_decrypt(struct tlsv1_server *conn,
234			 const u8 *in_data, size_t in_len,
235			 u8 *out_data, size_t out_len)
236{
237	const u8 *in_end, *pos;
238	int used;
239	u8 alert, *out_end, *out_pos, ct;
240	size_t olen;
241
242	pos = in_data;
243	in_end = in_data + in_len;
244	out_pos = out_data;
245	out_end = out_data + out_len;
246
247	while (pos < in_end) {
248		ct = pos[0];
249		olen = out_end - out_pos;
250		used = tlsv1_record_receive(&conn->rl, pos, in_end - pos,
251					    out_pos, &olen, &alert);
252		if (used < 0) {
253			wpa_printf(MSG_DEBUG, "TLSv1: Record layer processing "
254				   "failed");
255			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
256			return -1;
257		}
258		if (used == 0) {
259			/* need more data */
260			wpa_printf(MSG_DEBUG, "TLSv1: Partial processing not "
261				   "yet supported");
262			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL, alert);
263			return -1;
264		}
265
266		if (ct == TLS_CONTENT_TYPE_ALERT) {
267			if (olen < 2) {
268				wpa_printf(MSG_DEBUG, "TLSv1: Alert "
269					   "underflow");
270				tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
271						   TLS_ALERT_DECODE_ERROR);
272				return -1;
273			}
274			wpa_printf(MSG_DEBUG, "TLSv1: Received alert %d:%d",
275				   out_pos[0], out_pos[1]);
276			if (out_pos[0] == TLS_ALERT_LEVEL_WARNING) {
277				/* Continue processing */
278				pos += used;
279				continue;
280			}
281
282			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
283					   out_pos[1]);
284			return -1;
285		}
286
287		if (ct != TLS_CONTENT_TYPE_APPLICATION_DATA) {
288			wpa_printf(MSG_DEBUG, "TLSv1: Unexpected content type "
289				   "0x%x", pos[0]);
290			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
291					   TLS_ALERT_UNEXPECTED_MESSAGE);
292			return -1;
293		}
294
295		out_pos += olen;
296		if (out_pos > out_end) {
297			wpa_printf(MSG_DEBUG, "TLSv1: Buffer not large enough "
298				   "for processing the received record");
299			tlsv1_server_alert(conn, TLS_ALERT_LEVEL_FATAL,
300					   TLS_ALERT_INTERNAL_ERROR);
301			return -1;
302		}
303
304		pos += used;
305	}
306
307	return out_pos - out_data;
308}
309
310
311/**
312 * tlsv1_server_global_init - Initialize TLSv1 server
313 * Returns: 0 on success, -1 on failure
314 *
315 * This function must be called before using any other TLSv1 server functions.
316 */
317int tlsv1_server_global_init(void)
318{
319	return crypto_global_init();
320}
321
322
323/**
324 * tlsv1_server_global_deinit - Deinitialize TLSv1 server
325 *
326 * This function can be used to deinitialize the TLSv1 server that was
327 * initialized by calling tlsv1_server_global_init(). No TLSv1 server functions
328 * can be called after this before calling tlsv1_server_global_init() again.
329 */
330void tlsv1_server_global_deinit(void)
331{
332	crypto_global_deinit();
333}
334
335
336/**
337 * tlsv1_server_init - Initialize TLSv1 server connection
338 * @cred: Pointer to server credentials from tlsv1_server_cred_alloc()
339 * Returns: Pointer to TLSv1 server connection data or %NULL on failure
340 */
341struct tlsv1_server * tlsv1_server_init(struct tlsv1_credentials *cred)
342{
343	struct tlsv1_server *conn;
344	size_t count;
345	u16 *suites;
346
347	conn = os_zalloc(sizeof(*conn));
348	if (conn == NULL)
349		return NULL;
350
351	conn->cred = cred;
352
353	conn->state = CLIENT_HELLO;
354
355	if (tls_verify_hash_init(&conn->verify) < 0) {
356		wpa_printf(MSG_DEBUG, "TLSv1: Failed to initialize verify "
357			   "hash");
358		os_free(conn);
359		return NULL;
360	}
361
362	count = 0;
363	suites = conn->cipher_suites;
364	suites[count++] = TLS_RSA_WITH_AES_256_CBC_SHA;
365	suites[count++] = TLS_RSA_WITH_AES_128_CBC_SHA;
366	suites[count++] = TLS_RSA_WITH_3DES_EDE_CBC_SHA;
367	suites[count++] = TLS_RSA_WITH_RC4_128_SHA;
368	suites[count++] = TLS_RSA_WITH_RC4_128_MD5;
369	conn->num_cipher_suites = count;
370
371	return conn;
372}
373
374
375static void tlsv1_server_clear_data(struct tlsv1_server *conn)
376{
377	tlsv1_record_set_cipher_suite(&conn->rl, TLS_NULL_WITH_NULL_NULL);
378	tlsv1_record_change_write_cipher(&conn->rl);
379	tlsv1_record_change_read_cipher(&conn->rl);
380	tls_verify_hash_free(&conn->verify);
381
382	crypto_public_key_free(conn->client_rsa_key);
383	conn->client_rsa_key = NULL;
384
385	os_free(conn->session_ticket);
386	conn->session_ticket = NULL;
387	conn->session_ticket_len = 0;
388	conn->use_session_ticket = 0;
389
390	os_free(conn->dh_secret);
391	conn->dh_secret = NULL;
392	conn->dh_secret_len = 0;
393}
394
395
396/**
397 * tlsv1_server_deinit - Deinitialize TLSv1 server connection
398 * @conn: TLSv1 server connection data from tlsv1_server_init()
399 */
400void tlsv1_server_deinit(struct tlsv1_server *conn)
401{
402	tlsv1_server_clear_data(conn);
403	os_free(conn);
404}
405
406
407/**
408 * tlsv1_server_established - Check whether connection has been established
409 * @conn: TLSv1 server connection data from tlsv1_server_init()
410 * Returns: 1 if connection is established, 0 if not
411 */
412int tlsv1_server_established(struct tlsv1_server *conn)
413{
414	return conn->state == ESTABLISHED;
415}
416
417
418/**
419 * tlsv1_server_prf - Use TLS-PRF to derive keying material
420 * @conn: TLSv1 server connection data from tlsv1_server_init()
421 * @label: Label (e.g., description of the key) for PRF
422 * @server_random_first: seed is 0 = client_random|server_random,
423 * 1 = server_random|client_random
424 * @out: Buffer for output data from TLS-PRF
425 * @out_len: Length of the output buffer
426 * Returns: 0 on success, -1 on failure
427 */
428int tlsv1_server_prf(struct tlsv1_server *conn, const char *label,
429		     int server_random_first, u8 *out, size_t out_len)
430{
431	u8 seed[2 * TLS_RANDOM_LEN];
432
433	if (conn->state != ESTABLISHED)
434		return -1;
435
436	if (server_random_first) {
437		os_memcpy(seed, conn->server_random, TLS_RANDOM_LEN);
438		os_memcpy(seed + TLS_RANDOM_LEN, conn->client_random,
439			  TLS_RANDOM_LEN);
440	} else {
441		os_memcpy(seed, conn->client_random, TLS_RANDOM_LEN);
442		os_memcpy(seed + TLS_RANDOM_LEN, conn->server_random,
443			  TLS_RANDOM_LEN);
444	}
445
446	return tls_prf(conn->rl.tls_version,
447		       conn->master_secret, TLS_MASTER_SECRET_LEN,
448		       label, seed, 2 * TLS_RANDOM_LEN, out, out_len);
449}
450
451
452/**
453 * tlsv1_server_get_cipher - Get current cipher name
454 * @conn: TLSv1 server connection data from tlsv1_server_init()
455 * @buf: Buffer for the cipher name
456 * @buflen: buf size
457 * Returns: 0 on success, -1 on failure
458 *
459 * Get the name of the currently used cipher.
460 */
461int tlsv1_server_get_cipher(struct tlsv1_server *conn, char *buf,
462			    size_t buflen)
463{
464	char *cipher;
465
466	switch (conn->rl.cipher_suite) {
467	case TLS_RSA_WITH_RC4_128_MD5:
468		cipher = "RC4-MD5";
469		break;
470	case TLS_RSA_WITH_RC4_128_SHA:
471		cipher = "RC4-SHA";
472		break;
473	case TLS_RSA_WITH_DES_CBC_SHA:
474		cipher = "DES-CBC-SHA";
475		break;
476	case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
477		cipher = "DES-CBC3-SHA";
478		break;
479	case TLS_DH_anon_WITH_AES_128_CBC_SHA:
480		cipher = "ADH-AES-128-SHA";
481		break;
482	case TLS_RSA_WITH_AES_256_CBC_SHA:
483		cipher = "AES-256-SHA";
484		break;
485	case TLS_RSA_WITH_AES_128_CBC_SHA:
486		cipher = "AES-128-SHA";
487		break;
488	default:
489		return -1;
490	}
491
492	if (os_strlcpy(buf, cipher, buflen) >= buflen)
493		return -1;
494	return 0;
495}
496
497
498/**
499 * tlsv1_server_shutdown - Shutdown TLS connection
500 * @conn: TLSv1 server connection data from tlsv1_server_init()
501 * Returns: 0 on success, -1 on failure
502 */
503int tlsv1_server_shutdown(struct tlsv1_server *conn)
504{
505	conn->state = CLIENT_HELLO;
506
507	if (tls_verify_hash_init(&conn->verify) < 0) {
508		wpa_printf(MSG_DEBUG, "TLSv1: Failed to re-initialize verify "
509			   "hash");
510		return -1;
511	}
512
513	tlsv1_server_clear_data(conn);
514
515	return 0;
516}
517
518
519/**
520 * tlsv1_server_resumed - Was session resumption used
521 * @conn: TLSv1 server connection data from tlsv1_server_init()
522 * Returns: 1 if current session used session resumption, 0 if not
523 */
524int tlsv1_server_resumed(struct tlsv1_server *conn)
525{
526	return 0;
527}
528
529
530/**
531 * tlsv1_server_get_keys - Get master key and random data from TLS connection
532 * @conn: TLSv1 server connection data from tlsv1_server_init()
533 * @keys: Structure of key/random data (filled on success)
534 * Returns: 0 on success, -1 on failure
535 */
536int tlsv1_server_get_keys(struct tlsv1_server *conn, struct tls_keys *keys)
537{
538	os_memset(keys, 0, sizeof(*keys));
539	if (conn->state == CLIENT_HELLO)
540		return -1;
541
542	keys->client_random = conn->client_random;
543	keys->client_random_len = TLS_RANDOM_LEN;
544
545	if (conn->state != SERVER_HELLO) {
546		keys->server_random = conn->server_random;
547		keys->server_random_len = TLS_RANDOM_LEN;
548		keys->master_key = conn->master_secret;
549		keys->master_key_len = TLS_MASTER_SECRET_LEN;
550	}
551
552	return 0;
553}
554
555
556/**
557 * tlsv1_server_get_keyblock_size - Get TLS key_block size
558 * @conn: TLSv1 server connection data from tlsv1_server_init()
559 * Returns: Size of the key_block for the negotiated cipher suite or -1 on
560 * failure
561 */
562int tlsv1_server_get_keyblock_size(struct tlsv1_server *conn)
563{
564	if (conn->state == CLIENT_HELLO || conn->state == SERVER_HELLO)
565		return -1;
566
567	return 2 * (conn->rl.hash_size + conn->rl.key_material_len +
568		    conn->rl.iv_size);
569}
570
571
572/**
573 * tlsv1_server_set_cipher_list - Configure acceptable cipher suites
574 * @conn: TLSv1 server connection data from tlsv1_server_init()
575 * @ciphers: Zero (TLS_CIPHER_NONE) terminated list of allowed ciphers
576 * (TLS_CIPHER_*).
577 * Returns: 0 on success, -1 on failure
578 */
579int tlsv1_server_set_cipher_list(struct tlsv1_server *conn, u8 *ciphers)
580{
581	size_t count;
582	u16 *suites;
583
584	/* TODO: implement proper configuration of cipher suites */
585	if (ciphers[0] == TLS_CIPHER_ANON_DH_AES128_SHA) {
586		count = 0;
587		suites = conn->cipher_suites;
588		suites[count++] = TLS_RSA_WITH_AES_256_CBC_SHA;
589		suites[count++] = TLS_RSA_WITH_AES_128_CBC_SHA;
590		suites[count++] = TLS_RSA_WITH_3DES_EDE_CBC_SHA;
591		suites[count++] = TLS_RSA_WITH_RC4_128_SHA;
592		suites[count++] = TLS_RSA_WITH_RC4_128_MD5;
593		suites[count++] = TLS_DH_anon_WITH_AES_256_CBC_SHA;
594		suites[count++] = TLS_DH_anon_WITH_AES_128_CBC_SHA;
595		suites[count++] = TLS_DH_anon_WITH_3DES_EDE_CBC_SHA;
596		suites[count++] = TLS_DH_anon_WITH_RC4_128_MD5;
597		suites[count++] = TLS_DH_anon_WITH_DES_CBC_SHA;
598		conn->num_cipher_suites = count;
599	}
600
601	return 0;
602}
603
604
605int tlsv1_server_set_verify(struct tlsv1_server *conn, int verify_peer)
606{
607	conn->verify_peer = verify_peer;
608	return 0;
609}
610
611
612void tlsv1_server_set_session_ticket_cb(struct tlsv1_server *conn,
613					tlsv1_server_session_ticket_cb cb,
614					void *ctx)
615{
616	wpa_printf(MSG_DEBUG, "TLSv1: SessionTicket callback set %p (ctx %p)",
617		   cb, ctx);
618	conn->session_ticket_cb = cb;
619	conn->session_ticket_cb_ctx = ctx;
620}
621