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