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