eap_tls_common.c revision c5ec7f57ead87efa365800228aa0b09a12d9e6c4
1/*
2 * EAP peer: EAP-TLS/PEAP/TTLS/FAST common functions
3 * Copyright (c) 2004-2009, 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 "eap_i.h"
15#include "eap_tls_common.h"
16#include "eap_config.h"
17
18
19static int eap_tls_check_blob(struct eap_sm *sm, const char **name,
20			      const u8 **data, size_t *data_len)
21{
22	const struct wpa_config_blob *blob;
23
24	if (*name == NULL || os_strncmp(*name, "blob://", 7) != 0)
25		return 0;
26
27	blob = eap_get_config_blob(sm, *name + 7);
28	if (blob == NULL) {
29		wpa_printf(MSG_ERROR, "%s: Named configuration blob '%s' not "
30			   "found", __func__, *name + 7);
31		return -1;
32	}
33
34	*name = NULL;
35	*data = blob->data;
36	*data_len = blob->len;
37
38	return 0;
39}
40
41
42static void eap_tls_params_flags(struct tls_connection_params *params,
43				 const char *txt)
44{
45	if (txt == NULL)
46		return;
47	if (os_strstr(txt, "tls_allow_md5=1"))
48		params->flags |= TLS_CONN_ALLOW_SIGN_RSA_MD5;
49	if (os_strstr(txt, "tls_disable_time_checks=1"))
50		params->flags |= TLS_CONN_DISABLE_TIME_CHECKS;
51}
52
53
54static void eap_tls_params_from_conf1(struct tls_connection_params *params,
55				      struct eap_peer_config *config)
56{
57	params->ca_cert = (char *) config->ca_cert;
58	params->ca_path = (char *) config->ca_path;
59	params->client_cert = (char *) config->client_cert;
60	params->private_key = (char *) config->private_key;
61	params->private_key_passwd = (char *) config->private_key_passwd;
62	params->dh_file = (char *) config->dh_file;
63	params->subject_match = (char *) config->subject_match;
64	params->altsubject_match = (char *) config->altsubject_match;
65	params->engine = config->engine;
66	params->engine_id = config->engine_id;
67	params->pin = config->pin;
68	params->key_id = config->key_id;
69	params->cert_id = config->cert_id;
70	params->ca_cert_id = config->ca_cert_id;
71	eap_tls_params_flags(params, config->phase1);
72}
73
74
75static void eap_tls_params_from_conf2(struct tls_connection_params *params,
76				      struct eap_peer_config *config)
77{
78	params->ca_cert = (char *) config->ca_cert2;
79	params->ca_path = (char *) config->ca_path2;
80	params->client_cert = (char *) config->client_cert2;
81	params->private_key = (char *) config->private_key2;
82	params->private_key_passwd = (char *) config->private_key2_passwd;
83	params->dh_file = (char *) config->dh_file2;
84	params->subject_match = (char *) config->subject_match2;
85	params->altsubject_match = (char *) config->altsubject_match2;
86	params->engine = config->engine2;
87	params->engine_id = config->engine2_id;
88	params->pin = config->pin2;
89	params->key_id = config->key2_id;
90	params->cert_id = config->cert2_id;
91	params->ca_cert_id = config->ca_cert2_id;
92	eap_tls_params_flags(params, config->phase2);
93}
94
95
96static int eap_tls_params_from_conf(struct eap_sm *sm,
97				    struct eap_ssl_data *data,
98				    struct tls_connection_params *params,
99				    struct eap_peer_config *config, int phase2)
100{
101	os_memset(params, 0, sizeof(*params));
102	if (phase2) {
103		wpa_printf(MSG_DEBUG, "TLS: using phase2 config options");
104		eap_tls_params_from_conf2(params, config);
105	} else {
106		wpa_printf(MSG_DEBUG, "TLS: using phase1 config options");
107		eap_tls_params_from_conf1(params, config);
108	}
109
110	/*
111	 * Use blob data, if available. Otherwise, leave reference to external
112	 * file as-is.
113	 */
114	if (eap_tls_check_blob(sm, &params->ca_cert, &params->ca_cert_blob,
115			       &params->ca_cert_blob_len) ||
116	    eap_tls_check_blob(sm, &params->client_cert,
117			       &params->client_cert_blob,
118			       &params->client_cert_blob_len) ||
119	    eap_tls_check_blob(sm, &params->private_key,
120			       &params->private_key_blob,
121			       &params->private_key_blob_len) ||
122	    eap_tls_check_blob(sm, &params->dh_file, &params->dh_blob,
123			       &params->dh_blob_len)) {
124		wpa_printf(MSG_INFO, "SSL: Failed to get configuration blobs");
125		return -1;
126	}
127
128	return 0;
129}
130
131
132static int eap_tls_init_connection(struct eap_sm *sm,
133				   struct eap_ssl_data *data,
134				   struct eap_peer_config *config,
135				   struct tls_connection_params *params)
136{
137	int res;
138
139	data->conn = tls_connection_init(sm->ssl_ctx);
140	if (data->conn == NULL) {
141		wpa_printf(MSG_INFO, "SSL: Failed to initialize new TLS "
142			   "connection");
143		return -1;
144	}
145
146	res = tls_connection_set_params(sm->ssl_ctx, data->conn, params);
147	if (res == TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED) {
148		/*
149		 * At this point with the pkcs11 engine the PIN might be wrong.
150		 * We reset the PIN in the configuration to be sure to not use
151		 * it again and the calling function must request a new one.
152		 */
153		os_free(config->pin);
154		config->pin = NULL;
155	} else if (res == TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED) {
156		wpa_printf(MSG_INFO, "TLS: Failed to load private key");
157		/*
158		 * We do not know exactly but maybe the PIN was wrong,
159		 * so ask for a new one.
160		 */
161		os_free(config->pin);
162		config->pin = NULL;
163		eap_sm_request_pin(sm);
164		sm->ignore = TRUE;
165		tls_connection_deinit(sm->ssl_ctx, data->conn);
166		data->conn = NULL;
167		return -1;
168	} else if (res) {
169		wpa_printf(MSG_INFO, "TLS: Failed to set TLS connection "
170			   "parameters");
171		tls_connection_deinit(sm->ssl_ctx, data->conn);
172		data->conn = NULL;
173		return -1;
174	}
175
176	return 0;
177}
178
179
180/**
181 * eap_peer_tls_ssl_init - Initialize shared TLS functionality
182 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
183 * @data: Data for TLS processing
184 * @config: Pointer to the network configuration
185 * Returns: 0 on success, -1 on failure
186 *
187 * This function is used to initialize shared TLS functionality for EAP-TLS,
188 * EAP-PEAP, EAP-TTLS, and EAP-FAST.
189 */
190int eap_peer_tls_ssl_init(struct eap_sm *sm, struct eap_ssl_data *data,
191			  struct eap_peer_config *config)
192{
193	struct tls_connection_params params;
194
195	if (config == NULL)
196		return -1;
197
198	data->eap = sm;
199	data->phase2 = sm->init_phase2;
200	if (eap_tls_params_from_conf(sm, data, &params, config, data->phase2) <
201	    0)
202		return -1;
203
204	if (eap_tls_init_connection(sm, data, config, &params) < 0)
205		return -1;
206
207	data->tls_out_limit = config->fragment_size;
208	if (data->phase2) {
209		/* Limit the fragment size in the inner TLS authentication
210		 * since the outer authentication with EAP-PEAP does not yet
211		 * support fragmentation */
212		if (data->tls_out_limit > 100)
213			data->tls_out_limit -= 100;
214	}
215
216	if (config->phase1 &&
217	    os_strstr(config->phase1, "include_tls_length=1")) {
218		wpa_printf(MSG_DEBUG, "TLS: Include TLS Message Length in "
219			   "unfragmented packets");
220		data->include_tls_length = 1;
221	}
222
223	return 0;
224}
225
226
227/**
228 * eap_peer_tls_ssl_deinit - Deinitialize shared TLS functionality
229 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
230 * @data: Data for TLS processing
231 *
232 * This function deinitializes shared TLS functionality that was initialized
233 * with eap_peer_tls_ssl_init().
234 */
235void eap_peer_tls_ssl_deinit(struct eap_sm *sm, struct eap_ssl_data *data)
236{
237	tls_connection_deinit(sm->ssl_ctx, data->conn);
238	eap_peer_tls_reset_input(data);
239	eap_peer_tls_reset_output(data);
240}
241
242
243/**
244 * eap_peer_tls_derive_key - Derive a key based on TLS session data
245 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
246 * @data: Data for TLS processing
247 * @label: Label string for deriving the keys, e.g., "client EAP encryption"
248 * @len: Length of the key material to generate (usually 64 for MSK)
249 * Returns: Pointer to allocated key on success or %NULL on failure
250 *
251 * This function uses TLS-PRF to generate pseudo-random data based on the TLS
252 * session data (client/server random and master key). Each key type may use a
253 * different label to bind the key usage into the generated material.
254 *
255 * The caller is responsible for freeing the returned buffer.
256 */
257u8 * eap_peer_tls_derive_key(struct eap_sm *sm, struct eap_ssl_data *data,
258			     const char *label, size_t len)
259{
260	struct tls_keys keys;
261	u8 *rnd = NULL, *out;
262
263	out = os_malloc(len);
264	if (out == NULL)
265		return NULL;
266
267	/* First, try to use TLS library function for PRF, if available. */
268	if (tls_connection_prf(sm->ssl_ctx, data->conn, label, 0, out, len) ==
269	    0)
270		return out;
271
272	/*
273	 * TLS library did not support key generation, so get the needed TLS
274	 * session parameters and use an internal implementation of TLS PRF to
275	 * derive the key.
276	 */
277	if (tls_connection_get_keys(sm->ssl_ctx, data->conn, &keys))
278		goto fail;
279
280	if (keys.client_random == NULL || keys.server_random == NULL ||
281	    keys.master_key == NULL)
282		goto fail;
283
284	rnd = os_malloc(keys.client_random_len + keys.server_random_len);
285	if (rnd == NULL)
286		goto fail;
287	os_memcpy(rnd, keys.client_random, keys.client_random_len);
288	os_memcpy(rnd + keys.client_random_len, keys.server_random,
289		  keys.server_random_len);
290
291	if (tls_prf_sha1_md5(keys.master_key, keys.master_key_len,
292			     label, rnd, keys.client_random_len +
293			     keys.server_random_len, out, len))
294		goto fail;
295
296	os_free(rnd);
297	return out;
298
299fail:
300	os_free(out);
301	os_free(rnd);
302	return NULL;
303}
304
305
306/**
307 * eap_peer_tls_reassemble_fragment - Reassemble a received fragment
308 * @data: Data for TLS processing
309 * @in_data: Next incoming TLS segment
310 * Returns: 0 on success, 1 if more data is needed for the full message, or
311 * -1 on error
312 */
313static int eap_peer_tls_reassemble_fragment(struct eap_ssl_data *data,
314					    const struct wpabuf *in_data)
315{
316	size_t tls_in_len, in_len;
317
318	tls_in_len = data->tls_in ? wpabuf_len(data->tls_in) : 0;
319	in_len = in_data ? wpabuf_len(in_data) : 0;
320
321	if (tls_in_len + in_len == 0) {
322		/* No message data received?! */
323		wpa_printf(MSG_WARNING, "SSL: Invalid reassembly state: "
324			   "tls_in_left=%lu tls_in_len=%lu in_len=%lu",
325			   (unsigned long) data->tls_in_left,
326			   (unsigned long) tls_in_len,
327			   (unsigned long) in_len);
328		eap_peer_tls_reset_input(data);
329		return -1;
330	}
331
332	if (tls_in_len + in_len > 65536) {
333		/*
334		 * Limit length to avoid rogue servers from causing large
335		 * memory allocations.
336		 */
337		wpa_printf(MSG_INFO, "SSL: Too long TLS fragment (size over "
338			   "64 kB)");
339		eap_peer_tls_reset_input(data);
340		return -1;
341	}
342
343	if (in_len > data->tls_in_left) {
344		/* Sender is doing something odd - reject message */
345		wpa_printf(MSG_INFO, "SSL: more data than TLS message length "
346			   "indicated");
347		eap_peer_tls_reset_input(data);
348		return -1;
349	}
350
351	if (wpabuf_resize(&data->tls_in, in_len) < 0) {
352		wpa_printf(MSG_INFO, "SSL: Could not allocate memory for TLS "
353			   "data");
354		eap_peer_tls_reset_input(data);
355		return -1;
356	}
357	if (in_data)
358		wpabuf_put_buf(data->tls_in, in_data);
359	data->tls_in_left -= in_len;
360
361	if (data->tls_in_left > 0) {
362		wpa_printf(MSG_DEBUG, "SSL: Need %lu bytes more input "
363			   "data", (unsigned long) data->tls_in_left);
364		return 1;
365	}
366
367	return 0;
368}
369
370
371/**
372 * eap_peer_tls_data_reassemble - Reassemble TLS data
373 * @data: Data for TLS processing
374 * @in_data: Next incoming TLS segment
375 * @need_more_input: Variable for returning whether more input data is needed
376 * to reassemble this TLS packet
377 * Returns: Pointer to output data, %NULL on error or when more data is needed
378 * for the full message (in which case, *need_more_input is also set to 1).
379 *
380 * This function reassembles TLS fragments. Caller must not free the returned
381 * data buffer since an internal pointer to it is maintained.
382 */
383static const struct wpabuf * eap_peer_tls_data_reassemble(
384	struct eap_ssl_data *data, const struct wpabuf *in_data,
385	int *need_more_input)
386{
387	*need_more_input = 0;
388
389	if (data->tls_in_left > wpabuf_len(in_data) || data->tls_in) {
390		/* Message has fragments */
391		int res = eap_peer_tls_reassemble_fragment(data, in_data);
392		if (res) {
393			if (res == 1)
394				*need_more_input = 1;
395			return NULL;
396		}
397
398		/* Message is now fully reassembled. */
399	} else {
400		/* No fragments in this message, so just make a copy of it. */
401		data->tls_in_left = 0;
402		data->tls_in = wpabuf_dup(in_data);
403		if (data->tls_in == NULL)
404			return NULL;
405	}
406
407	return data->tls_in;
408}
409
410
411/**
412 * eap_tls_process_input - Process incoming TLS message
413 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
414 * @data: Data for TLS processing
415 * @in_data: Message received from the server
416 * @in_len: Length of in_data
417 * @out_data: Buffer for returning a pointer to application data (if available)
418 * Returns: 0 on success, 1 if more input data is needed, 2 if application data
419 * is available, -1 on failure
420 */
421static int eap_tls_process_input(struct eap_sm *sm, struct eap_ssl_data *data,
422				 const u8 *in_data, size_t in_len,
423				 struct wpabuf **out_data)
424{
425	const struct wpabuf *msg;
426	int need_more_input;
427	struct wpabuf *appl_data;
428	struct wpabuf buf;
429
430	wpabuf_set(&buf, in_data, in_len);
431	msg = eap_peer_tls_data_reassemble(data, &buf, &need_more_input);
432	if (msg == NULL)
433		return need_more_input ? 1 : -1;
434
435	/* Full TLS message reassembled - continue handshake processing */
436	if (data->tls_out) {
437		/* This should not happen.. */
438		wpa_printf(MSG_INFO, "SSL: eap_tls_process_input - pending "
439			   "tls_out data even though tls_out_len = 0");
440		wpabuf_free(data->tls_out);
441		WPA_ASSERT(data->tls_out == NULL);
442	}
443	appl_data = NULL;
444	data->tls_out = tls_connection_handshake(sm->ssl_ctx, data->conn,
445						 msg, &appl_data);
446
447	eap_peer_tls_reset_input(data);
448
449	if (appl_data &&
450	    tls_connection_established(sm->ssl_ctx, data->conn) &&
451	    !tls_connection_get_failed(sm->ssl_ctx, data->conn)) {
452		wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application data",
453				    appl_data);
454		*out_data = appl_data;
455		return 2;
456	}
457
458	wpabuf_free(appl_data);
459
460	return 0;
461}
462
463
464/**
465 * eap_tls_process_output - Process outgoing TLS message
466 * @data: Data for TLS processing
467 * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
468 * @peap_version: Version number for EAP-PEAP/TTLS
469 * @id: EAP identifier for the response
470 * @ret: Return value to use on success
471 * @out_data: Buffer for returning the allocated output buffer
472 * Returns: ret (0 or 1) on success, -1 on failure
473 */
474static int eap_tls_process_output(struct eap_ssl_data *data, EapType eap_type,
475				  int peap_version, u8 id, int ret,
476				  struct wpabuf **out_data)
477{
478	size_t len;
479	u8 *flags;
480	int more_fragments, length_included;
481
482	if (data->tls_out == NULL)
483		return -1;
484	len = wpabuf_len(data->tls_out) - data->tls_out_pos;
485	wpa_printf(MSG_DEBUG, "SSL: %lu bytes left to be sent out (of total "
486		   "%lu bytes)",
487		   (unsigned long) len,
488		   (unsigned long) wpabuf_len(data->tls_out));
489
490	/*
491	 * Limit outgoing message to the configured maximum size. Fragment
492	 * message if needed.
493	 */
494	if (len > data->tls_out_limit) {
495		more_fragments = 1;
496		len = data->tls_out_limit;
497		wpa_printf(MSG_DEBUG, "SSL: sending %lu bytes, more fragments "
498			   "will follow", (unsigned long) len);
499	} else
500		more_fragments = 0;
501
502	length_included = data->tls_out_pos == 0 &&
503		(wpabuf_len(data->tls_out) > data->tls_out_limit ||
504		 data->include_tls_length);
505	if (!length_included &&
506	    eap_type == EAP_TYPE_PEAP && peap_version == 0 &&
507	    !tls_connection_established(data->eap->ssl_ctx, data->conn)) {
508		/*
509		 * Windows Server 2008 NPS really wants to have the TLS Message
510		 * length included in phase 0 even for unfragmented frames or
511		 * it will get very confused with Compound MAC calculation and
512		 * Outer TLVs.
513		 */
514		length_included = 1;
515	}
516
517	*out_data = eap_msg_alloc(EAP_VENDOR_IETF, eap_type,
518				  1 + length_included * 4 + len,
519				  EAP_CODE_RESPONSE, id);
520	if (*out_data == NULL)
521		return -1;
522
523	flags = wpabuf_put(*out_data, 1);
524	*flags = peap_version;
525	if (more_fragments)
526		*flags |= EAP_TLS_FLAGS_MORE_FRAGMENTS;
527	if (length_included) {
528		*flags |= EAP_TLS_FLAGS_LENGTH_INCLUDED;
529		wpabuf_put_be32(*out_data, wpabuf_len(data->tls_out));
530	}
531
532	wpabuf_put_data(*out_data,
533			wpabuf_head_u8(data->tls_out) + data->tls_out_pos,
534			len);
535	data->tls_out_pos += len;
536
537	if (!more_fragments)
538		eap_peer_tls_reset_output(data);
539
540	return ret;
541}
542
543
544/**
545 * eap_peer_tls_process_helper - Process TLS handshake message
546 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
547 * @data: Data for TLS processing
548 * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
549 * @peap_version: Version number for EAP-PEAP/TTLS
550 * @id: EAP identifier for the response
551 * @in_data: Message received from the server
552 * @in_len: Length of in_data
553 * @out_data: Buffer for returning a pointer to the response message
554 * Returns: 0 on success, 1 if more input data is needed, 2 if application data
555 * is available, or -1 on failure
556 *
557 * This function can be used to process TLS handshake messages. It reassembles
558 * the received fragments and uses a TLS library to process the messages. The
559 * response data from the TLS library is fragmented to suitable output messages
560 * that the caller can send out.
561 *
562 * out_data is used to return the response message if the return value of this
563 * function is 0, 2, or -1. In case of failure, the message is likely a TLS
564 * alarm message. The caller is responsible for freeing the allocated buffer if
565 * *out_data is not %NULL.
566 *
567 * This function is called for each received TLS message during the TLS
568 * handshake after eap_peer_tls_process_init() call and possible processing of
569 * TLS Flags field. Once the handshake has been completed, i.e., when
570 * tls_connection_established() returns 1, EAP method specific decrypting of
571 * the tunneled data is used.
572 */
573int eap_peer_tls_process_helper(struct eap_sm *sm, struct eap_ssl_data *data,
574				EapType eap_type, int peap_version,
575				u8 id, const u8 *in_data, size_t in_len,
576				struct wpabuf **out_data)
577{
578	int ret = 0;
579
580	*out_data = NULL;
581
582	if (data->tls_out && wpabuf_len(data->tls_out) > 0 && in_len > 0) {
583		wpa_printf(MSG_DEBUG, "SSL: Received non-ACK when output "
584			   "fragments are waiting to be sent out");
585		return -1;
586	}
587
588	if (data->tls_out == NULL || wpabuf_len(data->tls_out) == 0) {
589		/*
590		 * No more data to send out - expect to receive more data from
591		 * the AS.
592		 */
593		int res = eap_tls_process_input(sm, data, in_data, in_len,
594						out_data);
595		if (res) {
596			/*
597			 * Input processing failed (res = -1) or more data is
598			 * needed (res = 1).
599			 */
600			return res;
601		}
602
603		/*
604		 * The incoming message has been reassembled and processed. The
605		 * response was allocated into data->tls_out buffer.
606		 */
607	}
608
609	if (data->tls_out == NULL) {
610		/*
611		 * No outgoing fragments remaining from the previous message
612		 * and no new message generated. This indicates an error in TLS
613		 * processing.
614		 */
615		eap_peer_tls_reset_output(data);
616		return -1;
617	}
618
619	if (tls_connection_get_failed(sm->ssl_ctx, data->conn)) {
620		/* TLS processing has failed - return error */
621		wpa_printf(MSG_DEBUG, "SSL: Failed - tls_out available to "
622			   "report error");
623		ret = -1;
624		/* TODO: clean pin if engine used? */
625	}
626
627	if (data->tls_out == NULL || wpabuf_len(data->tls_out) == 0) {
628		/*
629		 * TLS negotiation should now be complete since all other cases
630		 * needing more data should have been caught above based on
631		 * the TLS Message Length field.
632		 */
633		wpa_printf(MSG_DEBUG, "SSL: No data to be sent out");
634		wpabuf_free(data->tls_out);
635		data->tls_out = NULL;
636		return 1;
637	}
638
639	/* Send the pending message (in fragments, if needed). */
640	return eap_tls_process_output(data, eap_type, peap_version, id, ret,
641				      out_data);
642}
643
644
645/**
646 * eap_peer_tls_build_ack - Build a TLS ACK frame
647 * @id: EAP identifier for the response
648 * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
649 * @peap_version: Version number for EAP-PEAP/TTLS
650 * Returns: Pointer to the allocated ACK frame or %NULL on failure
651 */
652struct wpabuf * eap_peer_tls_build_ack(u8 id, EapType eap_type,
653				       int peap_version)
654{
655	struct wpabuf *resp;
656
657	resp = eap_msg_alloc(EAP_VENDOR_IETF, eap_type, 1, EAP_CODE_RESPONSE,
658			     id);
659	if (resp == NULL)
660		return NULL;
661	wpa_printf(MSG_DEBUG, "SSL: Building ACK (type=%d id=%d ver=%d)",
662		   (int) eap_type, id, peap_version);
663	wpabuf_put_u8(resp, peap_version); /* Flags */
664	return resp;
665}
666
667
668/**
669 * eap_peer_tls_reauth_init - Re-initialize shared TLS for session resumption
670 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
671 * @data: Data for TLS processing
672 * Returns: 0 on success, -1 on failure
673 */
674int eap_peer_tls_reauth_init(struct eap_sm *sm, struct eap_ssl_data *data)
675{
676	eap_peer_tls_reset_input(data);
677	eap_peer_tls_reset_output(data);
678	return tls_connection_shutdown(sm->ssl_ctx, data->conn);
679}
680
681
682/**
683 * eap_peer_tls_status - Get TLS status
684 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
685 * @data: Data for TLS processing
686 * @buf: Buffer for status information
687 * @buflen: Maximum buffer length
688 * @verbose: Whether to include verbose status information
689 * Returns: Number of bytes written to buf.
690 */
691int eap_peer_tls_status(struct eap_sm *sm, struct eap_ssl_data *data,
692			char *buf, size_t buflen, int verbose)
693{
694	char name[128];
695	int len = 0, ret;
696
697	if (tls_get_cipher(sm->ssl_ctx, data->conn, name, sizeof(name)) == 0) {
698		ret = os_snprintf(buf + len, buflen - len,
699				  "EAP TLS cipher=%s\n", name);
700		if (ret < 0 || (size_t) ret >= buflen - len)
701			return len;
702		len += ret;
703	}
704
705	return len;
706}
707
708
709/**
710 * eap_peer_tls_process_init - Initial validation/processing of EAP requests
711 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
712 * @data: Data for TLS processing
713 * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
714 * @ret: Return values from EAP request validation and processing
715 * @reqData: EAP request to be processed (eapReqData)
716 * @len: Buffer for returning length of the remaining payload
717 * @flags: Buffer for returning TLS flags
718 * Returns: Pointer to payload after TLS flags and length or %NULL on failure
719 *
720 * This function validates the EAP header and processes the optional TLS
721 * Message Length field. If this is the first fragment of a TLS message, the
722 * TLS reassembly code is initialized to receive the indicated number of bytes.
723 *
724 * EAP-TLS, EAP-PEAP, EAP-TTLS, and EAP-FAST methods are expected to use this
725 * function as the first step in processing received messages. They will need
726 * to process the flags (apart from Message Length Included) that are returned
727 * through the flags pointer and the message payload that will be returned (and
728 * the length is returned through the len pointer). Return values (ret) are set
729 * for continuation of EAP method processing. The caller is responsible for
730 * setting these to indicate completion (either success or failure) based on
731 * the authentication result.
732 */
733const u8 * eap_peer_tls_process_init(struct eap_sm *sm,
734				     struct eap_ssl_data *data,
735				     EapType eap_type,
736				     struct eap_method_ret *ret,
737				     const struct wpabuf *reqData,
738				     size_t *len, u8 *flags)
739{
740	const u8 *pos;
741	size_t left;
742	unsigned int tls_msg_len;
743
744	if (tls_get_errors(sm->ssl_ctx)) {
745		wpa_printf(MSG_INFO, "SSL: TLS errors detected");
746		ret->ignore = TRUE;
747		return NULL;
748	}
749
750	pos = eap_hdr_validate(EAP_VENDOR_IETF, eap_type, reqData, &left);
751	if (pos == NULL) {
752		ret->ignore = TRUE;
753		return NULL;
754	}
755	if (left == 0) {
756		wpa_printf(MSG_DEBUG, "SSL: Invalid TLS message: no Flags "
757			   "octet included");
758		if (!sm->workaround) {
759			ret->ignore = TRUE;
760			return NULL;
761		}
762
763		wpa_printf(MSG_DEBUG, "SSL: Workaround - assume no Flags "
764			   "indicates ACK frame");
765		*flags = 0;
766	} else {
767		*flags = *pos++;
768		left--;
769	}
770	wpa_printf(MSG_DEBUG, "SSL: Received packet(len=%lu) - "
771		   "Flags 0x%02x", (unsigned long) wpabuf_len(reqData),
772		   *flags);
773	if (*flags & EAP_TLS_FLAGS_LENGTH_INCLUDED) {
774		if (left < 4) {
775			wpa_printf(MSG_INFO, "SSL: Short frame with TLS "
776				   "length");
777			ret->ignore = TRUE;
778			return NULL;
779		}
780		tls_msg_len = WPA_GET_BE32(pos);
781		wpa_printf(MSG_DEBUG, "SSL: TLS Message Length: %d",
782			   tls_msg_len);
783		if (data->tls_in_left == 0) {
784			data->tls_in_total = tls_msg_len;
785			data->tls_in_left = tls_msg_len;
786			wpabuf_free(data->tls_in);
787			data->tls_in = NULL;
788		}
789		pos += 4;
790		left -= 4;
791	}
792
793	ret->ignore = FALSE;
794	ret->methodState = METHOD_MAY_CONT;
795	ret->decision = DECISION_FAIL;
796	ret->allowNotifications = TRUE;
797
798	*len = left;
799	return pos;
800}
801
802
803/**
804 * eap_peer_tls_reset_input - Reset input buffers
805 * @data: Data for TLS processing
806 *
807 * This function frees any allocated memory for input buffers and resets input
808 * state.
809 */
810void eap_peer_tls_reset_input(struct eap_ssl_data *data)
811{
812	data->tls_in_left = data->tls_in_total = 0;
813	wpabuf_free(data->tls_in);
814	data->tls_in = NULL;
815}
816
817
818/**
819 * eap_peer_tls_reset_output - Reset output buffers
820 * @data: Data for TLS processing
821 *
822 * This function frees any allocated memory for output buffers and resets
823 * output state.
824 */
825void eap_peer_tls_reset_output(struct eap_ssl_data *data)
826{
827	data->tls_out_pos = 0;
828	wpabuf_free(data->tls_out);
829	data->tls_out = NULL;
830}
831
832
833/**
834 * eap_peer_tls_decrypt - Decrypt received phase 2 TLS message
835 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
836 * @data: Data for TLS processing
837 * @in_data: Message received from the server
838 * @in_decrypted: Buffer for returning a pointer to the decrypted message
839 * Returns: 0 on success, 1 if more input data is needed, or -1 on failure
840 */
841int eap_peer_tls_decrypt(struct eap_sm *sm, struct eap_ssl_data *data,
842			 const struct wpabuf *in_data,
843			 struct wpabuf **in_decrypted)
844{
845	const struct wpabuf *msg;
846	int need_more_input;
847
848	msg = eap_peer_tls_data_reassemble(data, in_data, &need_more_input);
849	if (msg == NULL)
850		return need_more_input ? 1 : -1;
851
852	*in_decrypted = tls_connection_decrypt(sm->ssl_ctx, data->conn, msg);
853	eap_peer_tls_reset_input(data);
854	if (*in_decrypted == NULL) {
855		wpa_printf(MSG_INFO, "SSL: Failed to decrypt Phase 2 data");
856		return -1;
857	}
858	return 0;
859}
860
861
862/**
863 * eap_peer_tls_encrypt - Encrypt phase 2 TLS message
864 * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
865 * @data: Data for TLS processing
866 * @eap_type: EAP type (EAP_TYPE_TLS, EAP_TYPE_PEAP, ...)
867 * @peap_version: Version number for EAP-PEAP/TTLS
868 * @id: EAP identifier for the response
869 * @in_data: Plaintext phase 2 data to encrypt or %NULL to continue fragments
870 * @out_data: Buffer for returning a pointer to the encrypted response message
871 * Returns: 0 on success, -1 on failure
872 */
873int eap_peer_tls_encrypt(struct eap_sm *sm, struct eap_ssl_data *data,
874			 EapType eap_type, int peap_version, u8 id,
875			 const struct wpabuf *in_data,
876			 struct wpabuf **out_data)
877{
878	if (in_data) {
879		eap_peer_tls_reset_output(data);
880		data->tls_out = tls_connection_encrypt(sm->ssl_ctx, data->conn,
881						       in_data);
882		if (data->tls_out == NULL) {
883			wpa_printf(MSG_INFO, "SSL: Failed to encrypt Phase 2 "
884				   "data (in_len=%lu)",
885				   (unsigned long) wpabuf_len(in_data));
886			eap_peer_tls_reset_output(data);
887			return -1;
888		}
889	}
890
891	return eap_tls_process_output(data, eap_type, peap_version, id, 0,
892				      out_data);
893}
894
895
896/**
897 * eap_peer_select_phase2_methods - Select phase 2 EAP method
898 * @config: Pointer to the network configuration
899 * @prefix: 'phase2' configuration prefix, e.g., "auth="
900 * @types: Buffer for returning allocated list of allowed EAP methods
901 * @num_types: Buffer for returning number of allocated EAP methods
902 * Returns: 0 on success, -1 on failure
903 *
904 * This function is used to parse EAP method list and select allowed methods
905 * for Phase2 authentication.
906 */
907int eap_peer_select_phase2_methods(struct eap_peer_config *config,
908				   const char *prefix,
909				   struct eap_method_type **types,
910				   size_t *num_types)
911{
912	char *start, *pos, *buf;
913	struct eap_method_type *methods = NULL, *_methods;
914	u8 method;
915	size_t num_methods = 0, prefix_len;
916
917	if (config == NULL || config->phase2 == NULL)
918		goto get_defaults;
919
920	start = buf = os_strdup(config->phase2);
921	if (buf == NULL)
922		return -1;
923
924	prefix_len = os_strlen(prefix);
925
926	while (start && *start != '\0') {
927		int vendor;
928		pos = os_strstr(start, prefix);
929		if (pos == NULL)
930			break;
931		if (start != pos && *(pos - 1) != ' ') {
932			start = pos + prefix_len;
933			continue;
934		}
935
936		start = pos + prefix_len;
937		pos = os_strchr(start, ' ');
938		if (pos)
939			*pos++ = '\0';
940		method = eap_get_phase2_type(start, &vendor);
941		if (vendor == EAP_VENDOR_IETF && method == EAP_TYPE_NONE) {
942			wpa_printf(MSG_ERROR, "TLS: Unsupported Phase2 EAP "
943				   "method '%s'", start);
944		} else {
945			num_methods++;
946			_methods = os_realloc(methods,
947					      num_methods * sizeof(*methods));
948			if (_methods == NULL) {
949				os_free(methods);
950				os_free(buf);
951				return -1;
952			}
953			methods = _methods;
954			methods[num_methods - 1].vendor = vendor;
955			methods[num_methods - 1].method = method;
956		}
957
958		start = pos;
959	}
960
961	os_free(buf);
962
963get_defaults:
964	if (methods == NULL)
965		methods = eap_get_phase2_types(config, &num_methods);
966
967	if (methods == NULL) {
968		wpa_printf(MSG_ERROR, "TLS: No Phase2 EAP methods available");
969		return -1;
970	}
971	wpa_hexdump(MSG_DEBUG, "TLS: Phase2 EAP types",
972		    (u8 *) methods,
973		    num_methods * sizeof(struct eap_method_type));
974
975	*types = methods;
976	*num_types = num_methods;
977
978	return 0;
979}
980
981
982/**
983 * eap_peer_tls_phase2_nak - Generate EAP-Nak for Phase 2
984 * @types: Buffer for returning allocated list of allowed EAP methods
985 * @num_types: Buffer for returning number of allocated EAP methods
986 * @hdr: EAP-Request header (and the following EAP type octet)
987 * @resp: Buffer for returning the EAP-Nak message
988 * Returns: 0 on success, -1 on failure
989 */
990int eap_peer_tls_phase2_nak(struct eap_method_type *types, size_t num_types,
991			    struct eap_hdr *hdr, struct wpabuf **resp)
992{
993	u8 *pos = (u8 *) (hdr + 1);
994	size_t i;
995
996	/* TODO: add support for expanded Nak */
997	wpa_printf(MSG_DEBUG, "TLS: Phase 2 Request: Nak type=%d", *pos);
998	wpa_hexdump(MSG_DEBUG, "TLS: Allowed Phase2 EAP types",
999		    (u8 *) types, num_types * sizeof(struct eap_method_type));
1000	*resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_NAK, num_types,
1001			      EAP_CODE_RESPONSE, hdr->identifier);
1002	if (*resp == NULL)
1003		return -1;
1004
1005	for (i = 0; i < num_types; i++) {
1006		if (types[i].vendor == EAP_VENDOR_IETF &&
1007		    types[i].method < 256)
1008			wpabuf_put_u8(*resp, types[i].method);
1009	}
1010
1011	eap_update_len(*resp);
1012
1013	return 0;
1014}
1015