• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * EAP peer state machines (RFC 4137)
3  * Copyright (c) 2004-2019, 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  * This file implements the Peer State Machine as defined in RFC 4137. The used
9  * states and state transitions match mostly with the RFC. However, there are
10  * couple of additional transitions for working around small issues noticed
11  * during testing. These exceptions are explained in comments within the
12  * functions in this file. The method functions, m.func(), are similar to the
13  * ones used in RFC 4137, but some small changes have used here to optimize
14  * operations and to add functionality needed for fast re-authentication
15  * (session resumption).
16  */
17 
18 #include "includes.h"
19 
20 #include "common.h"
21 #include "pcsc_funcs.h"
22 #include "state_machine.h"
23 #include "ext_password.h"
24 #include "crypto/crypto.h"
25 #include "crypto/tls.h"
26 #include "crypto/sha256.h"
27 #include "common/wpa_ctrl.h"
28 #include "eap_common/eap_wsc_common.h"
29 #include "eap_i.h"
30 #include "eap_config.h"
31 
32 #define STATE_MACHINE_DATA struct eap_sm
33 #define STATE_MACHINE_DEBUG_PREFIX "EAP"
34 
35 #define EAP_MAX_AUTH_ROUNDS 100
36 #define EAP_MAX_AUTH_ROUNDS_SHORT 50
37 #define EAP_CLIENT_TIMEOUT_DEFAULT 60
38 
39 
40 static bool eap_sm_allowMethod(struct eap_sm *sm, int vendor,
41 			       enum eap_type method);
42 static struct wpabuf * eap_sm_buildNak(struct eap_sm *sm, int id);
43 static void eap_sm_processIdentity(struct eap_sm *sm,
44 				   const struct wpabuf *req);
45 static void eap_sm_processNotify(struct eap_sm *sm, const struct wpabuf *req);
46 static struct wpabuf * eap_sm_buildNotify(int id);
47 static void eap_sm_parseEapReq(struct eap_sm *sm, const struct wpabuf *req);
48 #ifndef EXT_EAP_TRIM
49 #if defined(CONFIG_CTRL_IFACE) || !defined(CONFIG_NO_STDOUT_DEBUG)
50 static const char * eap_sm_method_state_txt(EapMethodState state);
51 static const char * eap_sm_decision_txt(EapDecision decision);
52 #endif /* CONFIG_CTRL_IFACE || !CONFIG_NO_STDOUT_DEBUG */
53 #endif /* EXT_EAP_TRIM */
54 static void eap_sm_request(struct eap_sm *sm, enum wpa_ctrl_req_type field,
55 			   const char *msg, size_t msglen);
56 
57 
58 
eapol_get_bool(struct eap_sm * sm,enum eapol_bool_var var)59 static bool eapol_get_bool(struct eap_sm *sm, enum eapol_bool_var var)
60 {
61 	return sm->eapol_cb->get_bool(sm->eapol_ctx, var);
62 }
63 
64 
eapol_set_bool(struct eap_sm * sm,enum eapol_bool_var var,bool value)65 static void eapol_set_bool(struct eap_sm *sm, enum eapol_bool_var var,
66 			   bool value)
67 {
68 	sm->eapol_cb->set_bool(sm->eapol_ctx, var, value);
69 }
70 
71 
eapol_get_int(struct eap_sm * sm,enum eapol_int_var var)72 static unsigned int eapol_get_int(struct eap_sm *sm, enum eapol_int_var var)
73 {
74 	return sm->eapol_cb->get_int(sm->eapol_ctx, var);
75 }
76 
77 
eapol_set_int(struct eap_sm * sm,enum eapol_int_var var,unsigned int value)78 static void eapol_set_int(struct eap_sm *sm, enum eapol_int_var var,
79 			  unsigned int value)
80 {
81 	sm->eapol_cb->set_int(sm->eapol_ctx, var, value);
82 }
83 
84 
eapol_get_eapReqData(struct eap_sm * sm)85 static struct wpabuf * eapol_get_eapReqData(struct eap_sm *sm)
86 {
87 	return sm->eapol_cb->get_eapReqData(sm->eapol_ctx);
88 }
89 
90 #ifndef EXT_EAP_TRIM
eap_notify_status(struct eap_sm * sm,const char * status,const char * parameter)91 static void eap_notify_status(struct eap_sm *sm, const char *status,
92 				      const char *parameter)
93 {
94 	wpa_printf(MSG_DEBUG, "EAP: Status notification: %s (param=%s)",
95 		   status, parameter);
96 	if (sm->eapol_cb->notify_status)
97 		sm->eapol_cb->notify_status(sm->eapol_ctx, status, parameter);
98 }
99 
100 
eap_report_error(struct eap_sm * sm,int error_code)101 static void eap_report_error(struct eap_sm *sm, int error_code)
102 {
103 	wpa_printf(MSG_DEBUG, "EAP: Error notification: %d", error_code);
104 	if (sm->eapol_cb->notify_eap_error)
105 		sm->eapol_cb->notify_eap_error(sm->eapol_ctx, error_code);
106 }
107 #endif /* EXT_EAP_TRIM */
108 
eap_sm_free_key(struct eap_sm * sm)109 static void eap_sm_free_key(struct eap_sm *sm)
110 {
111 	if (sm->eapKeyData) {
112 		bin_clear_free(sm->eapKeyData, sm->eapKeyDataLen);
113 		sm->eapKeyData = NULL;
114 	}
115 }
116 
117 
eap_deinit_prev_method(struct eap_sm * sm,const char * txt)118 static void eap_deinit_prev_method(struct eap_sm *sm, const char *txt)
119 {
120 	(void)txt;
121 #ifndef EXT_EAP_TRIM
122 	ext_password_free(sm->ext_pw_buf);
123 	sm->ext_pw_buf = NULL;
124 #endif /* EXT_EAP_TRIM */
125 	if (sm->m == NULL || sm->eap_method_priv == NULL)
126 		return;
127 #ifndef EXT_EAP_TRIM
128 	wpa_printf(MSG_DEBUG, "EAP: deinitialize previously used EAP method "
129 		   "(%d, %s) at %s", sm->selectedMethod, sm->m->name, txt);
130 #endif /* EXT_EAP_TRIM */
131 	sm->m->deinit(sm, sm->eap_method_priv);
132 	sm->eap_method_priv = NULL;
133 	sm->m = NULL;
134 }
135 
136 
137 /**
138  * eap_config_allowed_method - Check whether EAP method is allowed
139  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
140  * @config: EAP configuration
141  * @vendor: Vendor-Id for expanded types or 0 = IETF for legacy types
142  * @method: EAP type
143  * Returns: 1 = allowed EAP method, 0 = not allowed
144  */
eap_config_allowed_method(struct eap_sm * sm,struct eap_peer_config * config,int vendor,u32 method)145 static int eap_config_allowed_method(struct eap_sm *sm,
146 				     struct eap_peer_config *config,
147 				     int vendor, u32 method)
148 {
149 	int i;
150 	struct eap_method_type *m;
151 
152 	if (config == NULL || config->eap_methods == NULL)
153 		return 1;
154 
155 	m = config->eap_methods;
156 	for (i = 0; m[i].vendor != EAP_VENDOR_IETF ||
157 		     m[i].method != EAP_TYPE_NONE; i++) {
158 		if (m[i].vendor == vendor && m[i].method == method)
159 			return 1;
160 	}
161 	return 0;
162 }
163 
164 
165 /**
166  * eap_allowed_method - Check whether EAP method is allowed
167  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
168  * @vendor: Vendor-Id for expanded types or 0 = IETF for legacy types
169  * @method: EAP type
170  * Returns: 1 = allowed EAP method, 0 = not allowed
171  */
eap_allowed_method(struct eap_sm * sm,int vendor,u32 method)172 int eap_allowed_method(struct eap_sm *sm, int vendor, u32 method)
173 {
174 	return eap_config_allowed_method(sm, eap_get_config(sm), vendor,
175 					 method);
176 }
177 
178 
179 #if defined(PCSC_FUNCS) || defined(CONFIG_EAP_PROXY)
eap_sm_append_3gpp_realm(struct eap_sm * sm,char * imsi,size_t max_len,size_t * imsi_len,int mnc_len)180 static int eap_sm_append_3gpp_realm(struct eap_sm *sm, char *imsi,
181 				    size_t max_len, size_t *imsi_len,
182 				    int mnc_len)
183 {
184 	char *pos, mnc[4];
185 
186 	if (*imsi_len + 36 > max_len) {
187 		wpa_printf(MSG_WARNING, "No room for realm in IMSI buffer");
188 		return -1;
189 	}
190 
191 	if (mnc_len != 2 && mnc_len != 3)
192 		mnc_len = 3;
193 
194 	if (mnc_len == 2) {
195 		mnc[0] = '0';
196 		mnc[1] = imsi[3];
197 		mnc[2] = imsi[4];
198 	} else if (mnc_len == 3) {
199 		mnc[0] = imsi[3];
200 		mnc[1] = imsi[4];
201 		mnc[2] = imsi[5];
202 	}
203 	mnc[3] = '\0';
204 
205 	pos = imsi + *imsi_len;
206 	pos += os_snprintf(pos, imsi + max_len - pos,
207 			   "@wlan.mnc%s.mcc%c%c%c.3gppnetwork.org",
208 			   mnc, imsi[0], imsi[1], imsi[2]);
209 	*imsi_len = pos - imsi;
210 
211 	return 0;
212 }
213 #endif /* PCSC_FUNCS || CONFIG_EAP_PROXY */
214 
215 
216 /*
217  * This state initializes state machine variables when the machine is
218  * activated (portEnabled = true). This is also used when re-starting
219  * authentication (eapRestart == true).
220  */
SM_STATE(EAP,INITIALIZE)221 SM_STATE(EAP, INITIALIZE)
222 {
223 	SM_ENTRY(EAP, INITIALIZE);
224 	if (sm->fast_reauth && sm->m && sm->m->has_reauth_data &&
225 	    sm->m->has_reauth_data(sm, sm->eap_method_priv) &&
226 	    !sm->prev_failure &&
227 	    sm->last_config == eap_get_config(sm)) {
228 		wpa_printf(MSG_DEBUG, "EAP: maintaining EAP method data for "
229 			   "fast reauthentication");
230 		sm->m->deinit_for_reauth(sm, sm->eap_method_priv);
231 	} else {
232 		sm->last_config = eap_get_config(sm);
233 #ifndef EXT_EAP_TRIM
234 		eap_deinit_prev_method(sm, "INITIALIZE");
235 #else
236 		eap_deinit_prev_method(sm, NULL);
237 #endif /* EXT_EAP_TRIM */
238 	}
239 	sm->selectedMethod = EAP_TYPE_NONE;
240 	sm->methodState = METHOD_NONE;
241 	sm->allowNotifications = true;
242 	sm->decision = DECISION_FAIL;
243 	sm->ClientTimeout = EAP_CLIENT_TIMEOUT_DEFAULT;
244 	eapol_set_int(sm, EAPOL_idleWhile, sm->ClientTimeout);
245 	eapol_set_bool(sm, EAPOL_eapSuccess, false);
246 	eapol_set_bool(sm, EAPOL_eapFail, false);
247 	eap_sm_free_key(sm);
248 	os_free(sm->eapSessionId);
249 	sm->eapSessionId = NULL;
250 	sm->eapKeyAvailable = false;
251 	eapol_set_bool(sm, EAPOL_eapRestart, false);
252 	sm->lastId = -1; /* new session - make sure this does not match with
253 			  * the first EAP-Packet */
254 	/*
255 	 * RFC 4137 does not reset eapResp and eapNoResp here. However, this
256 	 * seemed to be able to trigger cases where both were set and if EAPOL
257 	 * state machine uses eapNoResp first, it may end up not sending a real
258 	 * reply correctly. This occurred when the workaround in FAIL state set
259 	 * eapNoResp = true.. Maybe that workaround needs to be fixed to do
260 	 * something else(?)
261 	 */
262 	eapol_set_bool(sm, EAPOL_eapResp, false);
263 	eapol_set_bool(sm, EAPOL_eapNoResp, false);
264 	/*
265 	 * RFC 4137 does not reset ignore here, but since it is possible for
266 	 * some method code paths to end up not setting ignore=false, clear the
267 	 * value here to avoid issues if a previous authentication attempt
268 	 * failed with ignore=true being left behind in the last
269 	 * m.check(eapReqData) operation.
270 	 */
271 	sm->ignore = 0;
272 	sm->num_rounds = 0;
273 	sm->num_rounds_short = 0;
274 	sm->prev_failure = 0;
275 	sm->expected_failure = 0;
276 	sm->reauthInit = false;
277 #ifdef CONFIG_ERP
278 	sm->erp_seq = (u32) -1;
279 #endif /* CONFIG_ERP */
280 }
281 
282 
283 /*
284  * This state is reached whenever service from the lower layer is interrupted
285  * or unavailable (portEnabled == false). Immediate transition to INITIALIZE
286  * occurs when the port becomes enabled.
287  */
SM_STATE(EAP,DISABLED)288 SM_STATE(EAP, DISABLED)
289 {
290 	SM_ENTRY(EAP, DISABLED);
291 	sm->num_rounds = 0;
292 	sm->num_rounds_short = 0;
293 	/*
294 	 * RFC 4137 does not describe clearing of idleWhile here, but doing so
295 	 * allows the timer tick to be stopped more quickly when EAP is not in
296 	 * use.
297 	 */
298 	eapol_set_int(sm, EAPOL_idleWhile, 0);
299 }
300 
301 
302 /*
303  * The state machine spends most of its time here, waiting for something to
304  * happen. This state is entered unconditionally from INITIALIZE, DISCARD, and
305  * SEND_RESPONSE states.
306  */
SM_STATE(EAP,IDLE)307 SM_STATE(EAP, IDLE)
308 {
309 	SM_ENTRY(EAP, IDLE);
310 }
311 
312 
313 /*
314  * This state is entered when an EAP packet is received (eapReq == true) to
315  * parse the packet header.
316  */
SM_STATE(EAP,RECEIVED)317 SM_STATE(EAP, RECEIVED)
318 {
319 	const struct wpabuf *eapReqData;
320 
321 	SM_ENTRY(EAP, RECEIVED);
322 	eapReqData = eapol_get_eapReqData(sm);
323 	/* parse rxReq, rxSuccess, rxFailure, reqId, reqMethod */
324 	eap_sm_parseEapReq(sm, eapReqData);
325 	sm->num_rounds++;
326 	if (!eapReqData || wpabuf_len(eapReqData) < 20)
327 		sm->num_rounds_short++;
328 	else
329 		sm->num_rounds_short = 0;
330 }
331 
332 
333 /*
334  * This state is entered when a request for a new type comes in. Either the
335  * correct method is started, or a Nak response is built.
336  */
SM_STATE(EAP,GET_METHOD)337 SM_STATE(EAP, GET_METHOD)
338 {
339 	int reinit;
340 	enum eap_type method;
341 	const struct eap_method *eap_method;
342 
343 	SM_ENTRY(EAP, GET_METHOD);
344 
345 	if (sm->reqMethod == EAP_TYPE_EXPANDED)
346 		method = sm->reqVendorMethod;
347 	else
348 		method = sm->reqMethod;
349 
350 	eap_method = eap_peer_get_eap_method(sm->reqVendor, method);
351 
352 	if (!eap_sm_allowMethod(sm, sm->reqVendor, method)) {
353 #ifndef EXT_EAP_TRIM
354 		wpa_printf(MSG_DEBUG, "EAP: vendor %u method %u not allowed",
355 			   sm->reqVendor, method);
356 		wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_PROPOSED_METHOD
357 			"vendor=%u method=%u -> NAK",
358 			sm->reqVendor, method);
359 		eap_notify_status(sm, "refuse proposed method",
360 				  eap_method ?  eap_method->name : "unknown");
361 #endif /* EXT_EAP_TRIM */
362 		goto nak;
363 	}
364 
365 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_PROPOSED_METHOD
366 		"vendor=%u method=%u", sm->reqVendor, method);
367 #ifndef EXT_EAP_TRIM
368 	eap_notify_status(sm, "accept proposed method",
369 			  eap_method ?  eap_method->name : "unknown");
370 #endif /* EXT_EAP_TRIM */
371 	/*
372 	 * RFC 4137 does not define specific operation for fast
373 	 * re-authentication (session resumption). The design here is to allow
374 	 * the previously used method data to be maintained for
375 	 * re-authentication if the method support session resumption.
376 	 * Otherwise, the previously used method data is freed and a new method
377 	 * is allocated here.
378 	 */
379 	if (sm->fast_reauth &&
380 	    sm->m && sm->m->vendor == sm->reqVendor &&
381 	    sm->m->method == method &&
382 	    sm->m->has_reauth_data &&
383 	    sm->m->has_reauth_data(sm, sm->eap_method_priv)) {
384 #ifndef CONFIG_PRINT_NOUSE
385 		wpa_printf(MSG_DEBUG, "EAP: Using previous method data"
386 			   " for fast re-authentication");
387 #endif /* CONFIG_PRINT_NOUSE */
388 		reinit = 1;
389 	} else {
390 #ifndef EXT_EAP_TRIM
391 		eap_deinit_prev_method(sm, "GET_METHOD");
392 #else
393 		eap_deinit_prev_method(sm, NULL);
394 #endif /* EXT_EAP_TRIM */
395 		reinit = 0;
396 	}
397 
398 	sm->selectedMethod = sm->reqMethod;
399 	if (sm->m == NULL)
400 		sm->m = eap_method;
401 	if (!sm->m) {
402 #ifndef CONFIG_PRINT_NOUSE
403 		wpa_printf(MSG_DEBUG, "EAP: Could not find selected method: "
404 			   "vendor %d method %d",
405 			   sm->reqVendor, method);
406 #endif /* CONFIG_PRINT_NOUSE */
407 		goto nak;
408 	}
409 
410 	sm->ClientTimeout = EAP_CLIENT_TIMEOUT_DEFAULT;
411 #ifndef CONFIG_PRINT_NOUSE
412 	wpa_printf(MSG_DEBUG, "EAP: Initialize selected EAP method: "
413 		   "vendor %u method %u (%s)",
414 		   sm->reqVendor, method, sm->m->name);
415 #endif /* CONFIG_PRINT_NOUSE */
416 	if (reinit) {
417 		sm->eap_method_priv = sm->m->init_for_reauth(
418 			sm, sm->eap_method_priv);
419 	} else {
420 #ifndef EXT_EAP_TRIM
421 		sm->waiting_ext_cert_check = 0;
422 		sm->ext_cert_check = 0;
423 #endif /* EXT_EAP_TRIM */
424 		sm->eap_method_priv = sm->m->init(sm);
425 	}
426 
427 	if (sm->eap_method_priv == NULL) {
428 		struct eap_peer_config *config = eap_get_config(sm);
429 #ifndef CONFIG_PRINT_NOUSE
430 		wpa_msg(sm->msg_ctx, MSG_INFO,
431 			"EAP: Failed to initialize EAP method: vendor %u "
432 			"method %u (%s)",
433 			sm->reqVendor, method, sm->m->name);
434 #endif /* CONFIG_PRINT_NOUSE */
435 		sm->m = NULL;
436 		sm->methodState = METHOD_NONE;
437 		sm->selectedMethod = EAP_TYPE_NONE;
438 		if (sm->reqMethod == EAP_TYPE_TLS && config &&
439 		    (config->pending_req_pin ||
440 		     config->pending_req_passphrase)) {
441 			/*
442 			 * Return without generating Nak in order to allow
443 			 * entering of PIN code or passphrase to retry the
444 			 * current EAP packet.
445 			 */
446 #ifndef CONFIG_PRINT_NOUSE
447 			wpa_printf(MSG_DEBUG, "EAP: Pending PIN/passphrase "
448 				   "request - skip Nak");
449 #endif /* CONFIG_PRINT_NOUSE */
450 			return;
451 		}
452 
453 		goto nak;
454 	}
455 
456 	sm->methodState = METHOD_INIT;
457 #ifndef CONFIG_PRINT_NOUSE
458 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_METHOD
459 		"EAP vendor %u method %u (%s) selected",
460 		sm->reqVendor, method, sm->m->name);
461 #endif /* CONFIG_PRINT_NOUSE */
462 	return;
463 
464 nak:
465 	wpabuf_free(sm->eapRespData);
466 	sm->eapRespData = NULL;
467 	sm->eapRespData = eap_sm_buildNak(sm, sm->reqId);
468 }
469 
470 
471 #ifdef CONFIG_ERP
472 
eap_get_realm(struct eap_sm * sm,struct eap_peer_config * config)473 static char * eap_get_realm(struct eap_sm *sm, struct eap_peer_config *config)
474 {
475 	char *realm;
476 	size_t i, realm_len;
477 
478 	if (!config)
479 		return NULL;
480 
481 	if (config->identity) {
482 		for (i = 0; i < config->identity_len; i++) {
483 			if (config->identity[i] == '@')
484 				break;
485 		}
486 		if (i < config->identity_len) {
487 			realm_len = config->identity_len - i - 1;
488 			realm = os_malloc(realm_len + 1);
489 			if (realm == NULL)
490 				return NULL;
491 			os_memcpy(realm, &config->identity[i + 1], realm_len);
492 			realm[realm_len] = '\0';
493 			return realm;
494 		}
495 	}
496 
497 	if (config->anonymous_identity) {
498 		for (i = 0; i < config->anonymous_identity_len; i++) {
499 			if (config->anonymous_identity[i] == '@')
500 				break;
501 		}
502 		if (i < config->anonymous_identity_len) {
503 			realm_len = config->anonymous_identity_len - i - 1;
504 			realm = os_malloc(realm_len + 1);
505 			if (realm == NULL)
506 				return NULL;
507 			os_memcpy(realm, &config->anonymous_identity[i + 1],
508 				  realm_len);
509 			realm[realm_len] = '\0';
510 			return realm;
511 		}
512 	}
513 
514 #ifdef CONFIG_EAP_PROXY
515 	/* When identity is not provided in the config, build the realm from
516 	 * IMSI for eap_proxy based methods.
517 	 */
518 	if (!config->identity && !config->anonymous_identity &&
519 	    sm->eapol_cb->get_imsi &&
520 	    (eap_config_allowed_method(sm, config, EAP_VENDOR_IETF,
521 				       EAP_TYPE_SIM) ||
522 	     eap_config_allowed_method(sm, config, EAP_VENDOR_IETF,
523 				       EAP_TYPE_AKA) ||
524 	     eap_config_allowed_method(sm, config, EAP_VENDOR_IETF,
525 				       EAP_TYPE_AKA_PRIME))) {
526 		char imsi[100];
527 		size_t imsi_len;
528 		int mnc_len, pos;
529 
530 		wpa_printf(MSG_DEBUG, "EAP: Build realm from IMSI (eap_proxy)");
531 		mnc_len = sm->eapol_cb->get_imsi(sm->eapol_ctx, config->sim_num,
532 						 imsi, &imsi_len);
533 		if (mnc_len < 0)
534 			return NULL;
535 
536 		pos = imsi_len + 1; /* points to the beginning of the realm */
537 		if (eap_sm_append_3gpp_realm(sm, imsi, sizeof(imsi), &imsi_len,
538 					     mnc_len) < 0) {
539 			wpa_printf(MSG_WARNING, "Could not append realm");
540 			return NULL;
541 		}
542 
543 		realm = os_strdup(&imsi[pos]);
544 		if (!realm)
545 			return NULL;
546 
547 		wpa_printf(MSG_DEBUG, "EAP: Generated realm '%s'", realm);
548 		return realm;
549 	}
550 #endif /* CONFIG_EAP_PROXY */
551 
552 	return NULL;
553 }
554 
555 
eap_home_realm(struct eap_sm * sm)556 static char * eap_home_realm(struct eap_sm *sm)
557 {
558 	return eap_get_realm(sm, eap_get_config(sm));
559 }
560 
561 
562 static struct eap_erp_key *
eap_erp_get_key(struct eap_sm * sm,const char * realm)563 eap_erp_get_key(struct eap_sm *sm, const char *realm)
564 {
565 	struct eap_erp_key *erp;
566 
567 	dl_list_for_each(erp, &sm->erp_keys, struct eap_erp_key, list) {
568 		char *pos;
569 
570 		pos = os_strchr(erp->keyname_nai, '@');
571 		if (!pos)
572 			continue;
573 		pos++;
574 		if (os_strcmp(pos, realm) == 0)
575 			return erp;
576 	}
577 
578 	return NULL;
579 }
580 
581 
582 static struct eap_erp_key *
eap_erp_get_key_nai(struct eap_sm * sm,const char * nai)583 eap_erp_get_key_nai(struct eap_sm *sm, const char *nai)
584 {
585 	struct eap_erp_key *erp;
586 
587 	dl_list_for_each(erp, &sm->erp_keys, struct eap_erp_key, list) {
588 		if (os_strcmp(erp->keyname_nai, nai) == 0)
589 			return erp;
590 	}
591 
592 	return NULL;
593 }
594 
595 
eap_peer_erp_free_key(struct eap_erp_key * erp)596 static void eap_peer_erp_free_key(struct eap_erp_key *erp)
597 {
598 	dl_list_del(&erp->list);
599 	bin_clear_free(erp, sizeof(*erp));
600 }
601 
602 
eap_erp_remove_keys_realm(struct eap_sm * sm,const char * realm)603 static void eap_erp_remove_keys_realm(struct eap_sm *sm, const char *realm)
604 {
605 	struct eap_erp_key *erp;
606 
607 	while ((erp = eap_erp_get_key(sm, realm)) != NULL) {
608 		wpa_printf(MSG_DEBUG, "EAP: Delete old ERP key %s",
609 			   erp->keyname_nai);
610 		eap_peer_erp_free_key(erp);
611 	}
612 }
613 
614 
eap_peer_update_erp_next_seq_num(struct eap_sm * sm,u16 next_seq_num)615 int eap_peer_update_erp_next_seq_num(struct eap_sm *sm, u16 next_seq_num)
616 {
617 	struct eap_erp_key *erp;
618 	char *home_realm;
619 
620 	home_realm = eap_home_realm(sm);
621 	if (!home_realm || os_strlen(home_realm) == 0) {
622 		os_free(home_realm);
623 		return -1;
624 	}
625 
626 	erp = eap_erp_get_key(sm, home_realm);
627 	if (!erp) {
628 		wpa_printf(MSG_DEBUG,
629 			   "EAP: Failed to find ERP key for realm: %s",
630 			   home_realm);
631 		os_free(home_realm);
632 		return -1;
633 	}
634 
635 	if ((u32) next_seq_num < erp->next_seq) {
636 		/* Sequence number has wrapped around, clear this ERP
637 		 * info and do a full auth next time.
638 		 */
639 		eap_peer_erp_free_key(erp);
640 	} else {
641 		erp->next_seq = (u32) next_seq_num;
642 	}
643 
644 	os_free(home_realm);
645 	return 0;
646 }
647 
648 
eap_peer_get_erp_info(struct eap_sm * sm,struct eap_peer_config * config,const u8 ** username,size_t * username_len,const u8 ** realm,size_t * realm_len,u16 * erp_next_seq_num,const u8 ** rrk,size_t * rrk_len)649 int eap_peer_get_erp_info(struct eap_sm *sm, struct eap_peer_config *config,
650 			  const u8 **username, size_t *username_len,
651 			  const u8 **realm, size_t *realm_len,
652 			  u16 *erp_next_seq_num, const u8 **rrk,
653 			  size_t *rrk_len)
654 {
655 	struct eap_erp_key *erp;
656 	char *home_realm;
657 	char *pos;
658 
659 	if (config)
660 		home_realm = eap_get_realm(sm, config);
661 	else
662 		home_realm = eap_home_realm(sm);
663 	if (!home_realm || os_strlen(home_realm) == 0) {
664 		os_free(home_realm);
665 		return -1;
666 	}
667 
668 	erp = eap_erp_get_key(sm, home_realm);
669 	os_free(home_realm);
670 	if (!erp)
671 		return -1;
672 
673 	if (erp->next_seq >= 65536)
674 		return -1; /* SEQ has range of 0..65535 */
675 
676 	pos = os_strchr(erp->keyname_nai, '@');
677 	if (!pos)
678 		return -1; /* this cannot really happen */
679 	*username_len = pos - erp->keyname_nai;
680 	*username = (u8 *) erp->keyname_nai;
681 
682 	pos++;
683 	*realm_len = os_strlen(pos);
684 	*realm = (u8 *) pos;
685 
686 	*erp_next_seq_num = (u16) erp->next_seq;
687 
688 	*rrk_len = erp->rRK_len;
689 	*rrk = erp->rRK;
690 
691 	if (*username_len == 0 || *realm_len == 0 || *rrk_len == 0)
692 		return -1;
693 
694 	return 0;
695 }
696 
697 #endif /* CONFIG_ERP */
698 
699 
eap_peer_erp_free_keys(struct eap_sm * sm)700 void eap_peer_erp_free_keys(struct eap_sm *sm)
701 {
702 #ifdef CONFIG_ERP
703 	struct eap_erp_key *erp, *tmp;
704 
705 	dl_list_for_each_safe(erp, tmp, &sm->erp_keys, struct eap_erp_key, list)
706 		eap_peer_erp_free_key(erp);
707 #endif /* CONFIG_ERP */
708 }
709 
710 
711 /* Note: If ext_session and/or ext_emsk are passed to this function, they are
712  * expected to point to allocated memory and those allocations will be freed
713  * unconditionally. */
eap_peer_erp_init(struct eap_sm * sm,u8 * ext_session_id,size_t ext_session_id_len,u8 * ext_emsk,size_t ext_emsk_len)714 void eap_peer_erp_init(struct eap_sm *sm, u8 *ext_session_id,
715 		       size_t ext_session_id_len, u8 *ext_emsk,
716 		       size_t ext_emsk_len)
717 {
718 #ifdef CONFIG_ERP
719 	u8 *emsk = NULL;
720 	size_t emsk_len = 0;
721 	u8 *session_id = NULL;
722 	size_t session_id_len = 0;
723 	u8 EMSKname[EAP_EMSK_NAME_LEN];
724 	u8 len[2], ctx[3];
725 	char *realm;
726 	size_t realm_len, nai_buf_len;
727 	struct eap_erp_key *erp = NULL;
728 	int pos;
729 
730 	realm = eap_home_realm(sm);
731 	if (!realm)
732 		goto fail;
733 	realm_len = os_strlen(realm);
734 	wpa_printf(MSG_DEBUG, "EAP: Realm for ERP keyName-NAI: %s", realm);
735 	eap_erp_remove_keys_realm(sm, realm);
736 
737 	nai_buf_len = 2 * EAP_EMSK_NAME_LEN + 1 + realm_len;
738 	if (nai_buf_len > 253) {
739 		/*
740 		 * keyName-NAI has a maximum length of 253 octet to fit in
741 		 * RADIUS attributes.
742 		 */
743 		wpa_printf(MSG_DEBUG,
744 			   "EAP: Too long realm for ERP keyName-NAI maximum length");
745 		goto fail;
746 	}
747 	nai_buf_len++; /* null termination */
748 	erp = os_zalloc(sizeof(*erp) + nai_buf_len);
749 	if (erp == NULL)
750 		goto fail;
751 
752 	if (ext_emsk) {
753 		emsk = ext_emsk;
754 		emsk_len = ext_emsk_len;
755 	} else {
756 		emsk = sm->m->get_emsk(sm, sm->eap_method_priv, &emsk_len);
757 	}
758 
759 	if (!emsk || emsk_len == 0 || emsk_len > ERP_MAX_KEY_LEN) {
760 		wpa_printf(MSG_DEBUG,
761 			   "EAP: No suitable EMSK available for ERP");
762 		goto fail;
763 	}
764 
765 	wpa_hexdump_key(MSG_DEBUG, "EAP: EMSK", emsk, emsk_len);
766 
767 	if (ext_session_id) {
768 		session_id = ext_session_id;
769 		session_id_len = ext_session_id_len;
770 	} else {
771 		session_id = sm->eapSessionId;
772 		session_id_len = sm->eapSessionIdLen;
773 	}
774 
775 	if (!session_id || session_id_len == 0) {
776 		wpa_printf(MSG_DEBUG,
777 			   "EAP: No suitable session id available for ERP");
778 		goto fail;
779 	}
780 
781 	WPA_PUT_BE16(len, EAP_EMSK_NAME_LEN);
782 	if (hmac_sha256_kdf(session_id, session_id_len, "EMSK", len,
783 			    sizeof(len), EMSKname, EAP_EMSK_NAME_LEN) < 0) {
784 		wpa_printf(MSG_DEBUG, "EAP: Could not derive EMSKname");
785 		goto fail;
786 	}
787 	wpa_hexdump(MSG_DEBUG, "EAP: EMSKname", EMSKname, EAP_EMSK_NAME_LEN);
788 
789 	pos = wpa_snprintf_hex(erp->keyname_nai, nai_buf_len,
790 			       EMSKname, EAP_EMSK_NAME_LEN);
791 	erp->keyname_nai[pos] = '@';
792 	os_memcpy(&erp->keyname_nai[pos + 1], realm, realm_len);
793 
794 	WPA_PUT_BE16(len, emsk_len);
795 	if (hmac_sha256_kdf(emsk, emsk_len,
796 			    "EAP Re-authentication Root Key@ietf.org",
797 			    len, sizeof(len), erp->rRK, emsk_len) < 0) {
798 		wpa_printf(MSG_DEBUG, "EAP: Could not derive rRK for ERP");
799 		goto fail;
800 	}
801 	erp->rRK_len = emsk_len;
802 	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rRK", erp->rRK, erp->rRK_len);
803 
804 	ctx[0] = EAP_ERP_CS_HMAC_SHA256_128;
805 	WPA_PUT_BE16(&ctx[1], erp->rRK_len);
806 	if (hmac_sha256_kdf(erp->rRK, erp->rRK_len,
807 			    "Re-authentication Integrity Key@ietf.org",
808 			    ctx, sizeof(ctx), erp->rIK, erp->rRK_len) < 0) {
809 		wpa_printf(MSG_DEBUG, "EAP: Could not derive rIK for ERP");
810 		goto fail;
811 	}
812 	erp->rIK_len = erp->rRK_len;
813 	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rIK", erp->rIK, erp->rIK_len);
814 
815 	wpa_printf(MSG_DEBUG, "EAP: Stored ERP keys %s", erp->keyname_nai);
816 	dl_list_add(&sm->erp_keys, &erp->list);
817 	erp = NULL;
818 fail:
819 	if (ext_emsk)
820 		bin_clear_free(ext_emsk, ext_emsk_len);
821 	else
822 		bin_clear_free(emsk, emsk_len);
823 	bin_clear_free(ext_session_id, ext_session_id_len);
824 	bin_clear_free(erp, sizeof(*erp));
825 	os_free(realm);
826 #endif /* CONFIG_ERP */
827 }
828 
829 
830 #ifdef CONFIG_ERP
eap_peer_build_erp_reauth_start(struct eap_sm * sm,u8 eap_id)831 struct wpabuf * eap_peer_build_erp_reauth_start(struct eap_sm *sm, u8 eap_id)
832 {
833 	char *realm;
834 	struct eap_erp_key *erp;
835 	struct wpabuf *msg;
836 	u8 hash[SHA256_MAC_LEN];
837 
838 	realm = eap_home_realm(sm);
839 	if (!realm)
840 		return NULL;
841 
842 	erp = eap_erp_get_key(sm, realm);
843 	os_free(realm);
844 	realm = NULL;
845 	if (!erp)
846 		return NULL;
847 
848 	if (erp->next_seq >= 65536)
849 		return NULL; /* SEQ has range of 0..65535 */
850 
851 	/* TODO: check rRK lifetime expiration */
852 
853 	wpa_printf(MSG_DEBUG, "EAP: Valid ERP key found %s (SEQ=%u)",
854 		   erp->keyname_nai, erp->next_seq);
855 
856 	msg = eap_msg_alloc(EAP_VENDOR_IETF,
857 			    (enum eap_type) EAP_ERP_TYPE_REAUTH,
858 			    1 + 2 + 2 + os_strlen(erp->keyname_nai) + 1 + 16,
859 			    EAP_CODE_INITIATE, eap_id);
860 	if (msg == NULL)
861 		return NULL;
862 
863 	wpabuf_put_u8(msg, 0x20); /* Flags: R=0 B=0 L=1 */
864 	wpabuf_put_be16(msg, erp->next_seq);
865 
866 	wpabuf_put_u8(msg, EAP_ERP_TLV_KEYNAME_NAI);
867 	wpabuf_put_u8(msg, os_strlen(erp->keyname_nai));
868 	wpabuf_put_str(msg, erp->keyname_nai);
869 
870 	wpabuf_put_u8(msg, EAP_ERP_CS_HMAC_SHA256_128); /* Cryptosuite */
871 
872 	if (hmac_sha256(erp->rIK, erp->rIK_len,
873 			wpabuf_head(msg), wpabuf_len(msg), hash) < 0) {
874 		wpabuf_free(msg);
875 		return NULL;
876 	}
877 	wpabuf_put_data(msg, hash, 16);
878 
879 	sm->erp_seq = erp->next_seq;
880 	erp->next_seq++;
881 
882 	wpa_hexdump_buf(MSG_DEBUG, "ERP: EAP-Initiate/Re-auth", msg);
883 
884 	return msg;
885 }
886 
887 
eap_peer_erp_reauth_start(struct eap_sm * sm,u8 eap_id)888 static int eap_peer_erp_reauth_start(struct eap_sm *sm, u8 eap_id)
889 {
890 	struct wpabuf *msg;
891 
892 	msg = eap_peer_build_erp_reauth_start(sm, eap_id);
893 	if (!msg)
894 		return -1;
895 
896 	wpa_printf(MSG_DEBUG, "EAP: Sending EAP-Initiate/Re-auth");
897 	wpabuf_free(sm->eapRespData);
898 	sm->eapRespData = msg;
899 	sm->reauthInit = true;
900 	return 0;
901 }
902 #endif /* CONFIG_ERP */
903 
904 
905 /*
906  * The method processing happens here. The request from the authenticator is
907  * processed, and an appropriate response packet is built.
908  */
SM_STATE(EAP,METHOD)909 SM_STATE(EAP, METHOD)
910 {
911 	struct wpabuf *eapReqData;
912 	struct eap_method_ret ret;
913 	int min_len = 1;
914 
915 	SM_ENTRY(EAP, METHOD);
916 	if (sm->m == NULL) {
917 		wpa_printf(MSG_WARNING, "EAP::METHOD - method not selected");
918 		return;
919 	}
920 
921 	eapReqData = eapol_get_eapReqData(sm);
922 	if (sm->m->vendor == EAP_VENDOR_IETF && sm->m->method == EAP_TYPE_LEAP)
923 		min_len = 0; /* LEAP uses EAP-Success without payload */
924 	if (!eap_hdr_len_valid(eapReqData, min_len))
925 		return;
926 
927 	/*
928 	 * Get ignore, methodState, decision, allowNotifications, and
929 	 * eapRespData. RFC 4137 uses three separate method procedure (check,
930 	 * process, and buildResp) in this state. These have been combined into
931 	 * a single function call to m->process() in order to optimize EAP
932 	 * method implementation interface a bit. These procedures are only
933 	 * used from within this METHOD state, so there is no need to keep
934 	 * these as separate C functions.
935 	 *
936 	 * The RFC 4137 procedures return values as follows:
937 	 * ignore = m.check(eapReqData)
938 	 * (methodState, decision, allowNotifications) = m.process(eapReqData)
939 	 * eapRespData = m.buildResp(reqId)
940 	 */
941 	os_memset(&ret, 0, sizeof(ret));
942 	ret.ignore = sm->ignore;
943 	ret.methodState = sm->methodState;
944 	ret.decision = sm->decision;
945 	ret.allowNotifications = sm->allowNotifications;
946 	wpabuf_free(sm->eapRespData);
947 	sm->eapRespData = NULL;
948 	sm->eapRespData = sm->m->process(sm, sm->eap_method_priv, &ret,
949 					 eapReqData);
950 #ifndef EXT_EAP_TRIM
951 	wpa_printf(MSG_DEBUG, "EAP: method process -> ignore=%s "
952 		   "methodState=%s decision=%s eapRespData=%p",
953 		   ret.ignore ? "TRUE" : "FALSE",
954 		   eap_sm_method_state_txt(ret.methodState),
955 		   eap_sm_decision_txt(ret.decision),
956 		   sm->eapRespData);
957 #endif /* EXT_EAP_TRIM */
958 	sm->ignore = ret.ignore;
959 	if (sm->ignore)
960 		return;
961 	sm->methodState = ret.methodState;
962 	sm->decision = ret.decision;
963 	sm->allowNotifications = ret.allowNotifications;
964 
965 	if (sm->m->isKeyAvailable && sm->m->getKey &&
966 	    sm->m->isKeyAvailable(sm, sm->eap_method_priv)) {
967 		eap_sm_free_key(sm);
968 		sm->eapKeyData = sm->m->getKey(sm, sm->eap_method_priv,
969 					       &sm->eapKeyDataLen);
970 		os_free(sm->eapSessionId);
971 		sm->eapSessionId = NULL;
972 		if (sm->m->getSessionId) {
973 			sm->eapSessionId = sm->m->getSessionId(
974 				sm, sm->eap_method_priv,
975 				&sm->eapSessionIdLen);
976 			wpa_hexdump(MSG_DEBUG, "EAP: Session-Id",
977 				    sm->eapSessionId, sm->eapSessionIdLen);
978 		}
979 	}
980 }
981 
982 
983 /*
984  * This state signals the lower layer that a response packet is ready to be
985  * sent.
986  */
SM_STATE(EAP,SEND_RESPONSE)987 SM_STATE(EAP, SEND_RESPONSE)
988 {
989 	SM_ENTRY(EAP, SEND_RESPONSE);
990 	wpabuf_free(sm->lastRespData);
991 	if (sm->eapRespData) {
992 		if (wpabuf_len(sm->eapRespData) >= 20)
993 			sm->num_rounds_short = 0;
994 		if (sm->workaround)
995 			os_memcpy(sm->last_sha1, sm->req_sha1, 20);
996 		sm->lastId = sm->reqId;
997 		sm->lastRespData = wpabuf_dup(sm->eapRespData);
998 		eapol_set_bool(sm, EAPOL_eapResp, true);
999 	} else {
1000 		wpa_printf(MSG_DEBUG, "EAP: No eapRespData available");
1001 		sm->lastRespData = NULL;
1002 	}
1003 	eapol_set_bool(sm, EAPOL_eapReq, false);
1004 	eapol_set_int(sm, EAPOL_idleWhile, sm->ClientTimeout);
1005 	sm->reauthInit = false;
1006 }
1007 
1008 
1009 /*
1010  * This state signals the lower layer that the request was discarded, and no
1011  * response packet will be sent at this time.
1012  */
SM_STATE(EAP,DISCARD)1013 SM_STATE(EAP, DISCARD)
1014 {
1015 	SM_ENTRY(EAP, DISCARD);
1016 	eapol_set_bool(sm, EAPOL_eapReq, false);
1017 	eapol_set_bool(sm, EAPOL_eapNoResp, true);
1018 }
1019 
1020 
1021 /*
1022  * Handles requests for Identity method and builds a response.
1023  */
SM_STATE(EAP,IDENTITY)1024 SM_STATE(EAP, IDENTITY)
1025 {
1026 	const struct wpabuf *eapReqData;
1027 
1028 	SM_ENTRY(EAP, IDENTITY);
1029 	eapReqData = eapol_get_eapReqData(sm);
1030 	if (!eap_hdr_len_valid(eapReqData, 1))
1031 		return;
1032 	eap_sm_processIdentity(sm, eapReqData);
1033 	wpabuf_free(sm->eapRespData);
1034 	sm->eapRespData = NULL;
1035 	sm->eapRespData = eap_sm_buildIdentity(sm, sm->reqId, 0);
1036 }
1037 
1038 
1039 /*
1040  * Handles requests for Notification method and builds a response.
1041  */
SM_STATE(EAP,NOTIFICATION)1042 SM_STATE(EAP, NOTIFICATION)
1043 {
1044 	const struct wpabuf *eapReqData;
1045 
1046 	SM_ENTRY(EAP, NOTIFICATION);
1047 	eapReqData = eapol_get_eapReqData(sm);
1048 	if (!eap_hdr_len_valid(eapReqData, 1))
1049 		return;
1050 	eap_sm_processNotify(sm, eapReqData);
1051 	wpabuf_free(sm->eapRespData);
1052 	sm->eapRespData = NULL;
1053 	sm->eapRespData = eap_sm_buildNotify(sm->reqId);
1054 }
1055 
1056 
1057 /*
1058  * This state retransmits the previous response packet.
1059  */
SM_STATE(EAP,RETRANSMIT)1060 SM_STATE(EAP, RETRANSMIT)
1061 {
1062 	SM_ENTRY(EAP, RETRANSMIT);
1063 	wpabuf_free(sm->eapRespData);
1064 	if (sm->lastRespData)
1065 		sm->eapRespData = wpabuf_dup(sm->lastRespData);
1066 	else
1067 		sm->eapRespData = NULL;
1068 }
1069 
1070 
1071 /*
1072  * This state is entered in case of a successful completion of authentication
1073  * and state machine waits here until port is disabled or EAP authentication is
1074  * restarted.
1075  */
SM_STATE(EAP,SUCCESS)1076 SM_STATE(EAP, SUCCESS)
1077 {
1078 	struct eap_peer_config *config = eap_get_config(sm);
1079 
1080 	SM_ENTRY(EAP, SUCCESS);
1081 	if (sm->eapKeyData != NULL)
1082 		sm->eapKeyAvailable = true;
1083 	eapol_set_bool(sm, EAPOL_eapSuccess, true);
1084 
1085 	/*
1086 	 * RFC 4137 does not clear eapReq here, but this seems to be required
1087 	 * to avoid processing the same request twice when state machine is
1088 	 * initialized.
1089 	 */
1090 	eapol_set_bool(sm, EAPOL_eapReq, false);
1091 
1092 	/*
1093 	 * RFC 4137 does not set eapNoResp here, but this seems to be required
1094 	 * to get EAPOL Supplicant backend state machine into SUCCESS state. In
1095 	 * addition, either eapResp or eapNoResp is required to be set after
1096 	 * processing the received EAP frame.
1097 	 */
1098 	eapol_set_bool(sm, EAPOL_eapNoResp, true);
1099 
1100 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
1101 		"EAP authentication completed successfully");
1102 
1103 	if (!config || !sm->m) {
1104 		/*
1105 		 * This should not happen under normal conditions, but be more
1106 		 * careful here since there was an earlier case where
1107 		 * EAP-Success could end up getting delivered to the state
1108 		 * machine for processing after the state had been cleaned with
1109 		 * a call to eap_invalidate_cached_session() (and also
1110 		 * eapol_sm_notify_config() having been used to clear EAP
1111 		 * configuration in the EAPOL state machine).
1112 		 */
1113 		wpa_printf(MSG_DEBUG,
1114 			   "EAP: State machine not configured - cannot initialize ERP");
1115 		return;
1116 	}
1117 	if (config->erp && sm->m->get_emsk && sm->eapSessionId &&
1118 	    sm->m->isKeyAvailable &&
1119 	    sm->m->isKeyAvailable(sm, sm->eap_method_priv))
1120 		eap_peer_erp_init(sm, NULL, 0, NULL, 0);
1121 }
1122 
1123 
1124 /*
1125  * This state is entered in case of a failure and state machine waits here
1126  * until port is disabled or EAP authentication is restarted.
1127  */
SM_STATE(EAP,FAILURE)1128 SM_STATE(EAP, FAILURE)
1129 {
1130 	SM_ENTRY(EAP, FAILURE);
1131 	eapol_set_bool(sm, EAPOL_eapFail, true);
1132 
1133 	/*
1134 	 * RFC 4137 does not clear eapReq here, but this seems to be required
1135 	 * to avoid processing the same request twice when state machine is
1136 	 * initialized.
1137 	 */
1138 	eapol_set_bool(sm, EAPOL_eapReq, false);
1139 
1140 	/*
1141 	 * RFC 4137 does not set eapNoResp here. However, either eapResp or
1142 	 * eapNoResp is required to be set after processing the received EAP
1143 	 * frame.
1144 	 */
1145 	eapol_set_bool(sm, EAPOL_eapNoResp, true);
1146 
1147 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE
1148 		"EAP authentication failed");
1149 
1150 	sm->prev_failure = 1;
1151 }
1152 
1153 
eap_success_workaround(struct eap_sm * sm,int reqId,int lastId)1154 static int eap_success_workaround(struct eap_sm *sm, int reqId, int lastId)
1155 {
1156 	/*
1157 	 * At least Microsoft IAS and Meetinghouse Aegis seem to be sending
1158 	 * EAP-Success/Failure with lastId + 1 even though RFC 3748 and
1159 	 * RFC 4137 require that reqId == lastId. In addition, it looks like
1160 	 * Ringmaster v2.1.2.0 would be using lastId + 2 in EAP-Success.
1161 	 *
1162 	 * Accept this kind of Id if EAP workarounds are enabled. These are
1163 	 * unauthenticated plaintext messages, so this should have minimal
1164 	 * security implications (bit easier to fake EAP-Success/Failure).
1165 	 */
1166 	if (sm->workaround && (reqId == ((lastId + 1) & 0xff) ||
1167 			       reqId == ((lastId + 2) & 0xff))) {
1168 		wpa_printf(MSG_DEBUG, "EAP: Workaround for unexpected "
1169 			   "identifier field in EAP Success: "
1170 			   "reqId=%d lastId=%d (these are supposed to be "
1171 			   "same)", reqId, lastId);
1172 		return 1;
1173 	}
1174 	wpa_printf(MSG_DEBUG, "EAP: EAP-Success Id mismatch - reqId=%d "
1175 		   "lastId=%d", reqId, lastId);
1176 	return 0;
1177 }
1178 
1179 
1180 /*
1181  * RFC 4137 - Appendix A.1: EAP Peer State Machine - State transitions
1182  */
1183 
eap_peer_sm_step_idle(struct eap_sm * sm)1184 static void eap_peer_sm_step_idle(struct eap_sm *sm)
1185 {
1186 	/*
1187 	 * The first three transitions are from RFC 4137. The last two are
1188 	 * local additions to handle special cases with LEAP and PEAP server
1189 	 * not sending EAP-Success in some cases.
1190 	 */
1191 	if (eapol_get_bool(sm, EAPOL_eapReq))
1192 		SM_ENTER(EAP, RECEIVED);
1193 	else if ((eapol_get_bool(sm, EAPOL_altAccept) &&
1194 		  sm->decision != DECISION_FAIL) ||
1195 		 (eapol_get_int(sm, EAPOL_idleWhile) == 0 &&
1196 		  sm->decision == DECISION_UNCOND_SUCC))
1197 		SM_ENTER(EAP, SUCCESS);
1198 	else if (eapol_get_bool(sm, EAPOL_altReject) ||
1199 		 (eapol_get_int(sm, EAPOL_idleWhile) == 0 &&
1200 		  sm->decision != DECISION_UNCOND_SUCC) ||
1201 		 (eapol_get_bool(sm, EAPOL_altAccept) &&
1202 		  sm->methodState != METHOD_CONT &&
1203 		  sm->decision == DECISION_FAIL))
1204 		SM_ENTER(EAP, FAILURE);
1205 #ifndef EXT_EAP_TRIM
1206 	else if (sm->selectedMethod == EAP_TYPE_LEAP &&
1207 		 sm->leap_done && sm->decision != DECISION_FAIL &&
1208 		 sm->methodState == METHOD_DONE)
1209 		SM_ENTER(EAP, SUCCESS);
1210 	else if (sm->selectedMethod == EAP_TYPE_PEAP &&
1211 		 sm->peap_done && sm->decision != DECISION_FAIL &&
1212 		 sm->methodState == METHOD_DONE)
1213 		SM_ENTER(EAP, SUCCESS);
1214 #endif /* EXT_EAP_TRIM */
1215 }
1216 
1217 
eap_peer_req_is_duplicate(struct eap_sm * sm)1218 static int eap_peer_req_is_duplicate(struct eap_sm *sm)
1219 {
1220 	int duplicate;
1221 
1222 	duplicate = (sm->reqId == sm->lastId) && sm->rxReq;
1223 	if (sm->workaround && duplicate &&
1224 	    os_memcmp(sm->req_sha1, sm->last_sha1, 20) != 0) {
1225 		/*
1226 		 * RFC 4137 uses (reqId == lastId) as the only verification for
1227 		 * duplicate EAP requests. However, this misses cases where the
1228 		 * AS is incorrectly using the same id again; and
1229 		 * unfortunately, such implementations exist. Use SHA1 hash as
1230 		 * an extra verification for the packets being duplicate to
1231 		 * workaround these issues.
1232 		 */
1233 #ifndef CONFIG_PRINT_NOUSE
1234 		wpa_printf(MSG_DEBUG, "EAP: AS used the same Id again, but "
1235 			   "EAP packets were not identical");
1236 		wpa_printf(MSG_DEBUG, "EAP: workaround - assume this is not a "
1237 			   "duplicate packet");
1238 #endif /* CONFIG_PRINT_NOUSE */
1239 		duplicate = 0;
1240 	}
1241 
1242 	return duplicate;
1243 }
1244 
1245 
eap_peer_sm_allow_canned(struct eap_sm * sm)1246 static int eap_peer_sm_allow_canned(struct eap_sm *sm)
1247 {
1248 	struct eap_peer_config *config = eap_get_config(sm);
1249 
1250 	return config && config->phase1 &&
1251 		os_strstr(config->phase1, "allow_canned_success=1");
1252 }
1253 
1254 
eap_peer_sm_step_received(struct eap_sm * sm)1255 static void eap_peer_sm_step_received(struct eap_sm *sm)
1256 {
1257 	int duplicate = eap_peer_req_is_duplicate(sm);
1258 
1259 	/*
1260 	 * Two special cases below for LEAP are local additions to work around
1261 	 * odd LEAP behavior (EAP-Success in the middle of authentication and
1262 	 * then swapped roles). Other transitions are based on RFC 4137.
1263 	 */
1264 	if (sm->rxSuccess && sm->decision != DECISION_FAIL &&
1265 	    (sm->reqId == sm->lastId ||
1266 	     eap_success_workaround(sm, sm->reqId, sm->lastId)))
1267 		SM_ENTER(EAP, SUCCESS);
1268 	else if (sm->workaround && sm->lastId == -1 && sm->rxSuccess &&
1269 		 !sm->rxFailure && !sm->rxReq && eap_peer_sm_allow_canned(sm))
1270 		SM_ENTER(EAP, SUCCESS); /* EAP-Success prior any EAP method */
1271 	else if (sm->workaround && sm->lastId == -1 && sm->rxFailure &&
1272 		 !sm->rxReq && sm->methodState != METHOD_CONT &&
1273 		 eap_peer_sm_allow_canned(sm))
1274 		SM_ENTER(EAP, FAILURE); /* EAP-Failure prior any EAP method */
1275 	else if (sm->workaround && sm->rxSuccess && !sm->rxFailure &&
1276 		 !sm->rxReq && sm->methodState != METHOD_CONT &&
1277 		 eap_peer_sm_allow_canned(sm))
1278 		SM_ENTER(EAP, SUCCESS); /* EAP-Success after Identity */
1279 	else if (sm->methodState != METHOD_CONT &&
1280 		 ((sm->rxFailure &&
1281 		   sm->decision != DECISION_UNCOND_SUCC) ||
1282 		  (sm->rxSuccess && sm->decision == DECISION_FAIL &&
1283 		   (sm->selectedMethod != EAP_TYPE_LEAP ||
1284 		    sm->methodState != METHOD_MAY_CONT))) &&
1285 		 (sm->reqId == sm->lastId ||
1286 		  eap_success_workaround(sm, sm->reqId, sm->lastId)))
1287 		SM_ENTER(EAP, FAILURE);
1288 	else if (sm->rxReq && duplicate)
1289 		SM_ENTER(EAP, RETRANSMIT);
1290 	else if (sm->rxReq && !duplicate &&
1291 		 sm->reqMethod == EAP_TYPE_NOTIFICATION &&
1292 		 sm->allowNotifications)
1293 		SM_ENTER(EAP, NOTIFICATION);
1294 	else if (sm->rxReq && !duplicate &&
1295 		 sm->selectedMethod == EAP_TYPE_NONE &&
1296 		 sm->reqMethod == EAP_TYPE_IDENTITY)
1297 		SM_ENTER(EAP, IDENTITY);
1298 	else if (sm->rxReq && !duplicate &&
1299 		 sm->selectedMethod == EAP_TYPE_NONE &&
1300 		 sm->reqMethod != EAP_TYPE_IDENTITY &&
1301 		 sm->reqMethod != EAP_TYPE_NOTIFICATION)
1302 		SM_ENTER(EAP, GET_METHOD);
1303 	else if (sm->rxReq && !duplicate &&
1304 		 sm->reqMethod == sm->selectedMethod &&
1305 		 sm->methodState != METHOD_DONE)
1306 		SM_ENTER(EAP, METHOD);
1307 #ifndef EXT_EAP_TRIM
1308 	else if (sm->selectedMethod == EAP_TYPE_LEAP &&
1309 		 (sm->rxSuccess || sm->rxResp))
1310 		SM_ENTER(EAP, METHOD);
1311 #endif /* EXT_EAP_TRIM */
1312 	else if (sm->reauthInit)
1313 		SM_ENTER(EAP, SEND_RESPONSE);
1314 	else
1315 		SM_ENTER(EAP, DISCARD);
1316 }
1317 
1318 
eap_peer_sm_step_local(struct eap_sm * sm)1319 static void eap_peer_sm_step_local(struct eap_sm *sm)
1320 {
1321 	switch (sm->EAP_state) {
1322 	case EAP_INITIALIZE:
1323 		SM_ENTER(EAP, IDLE);
1324 		break;
1325 	case EAP_DISABLED:
1326 		if (eapol_get_bool(sm, EAPOL_portEnabled) &&
1327 		    !sm->force_disabled)
1328 			SM_ENTER(EAP, INITIALIZE);
1329 		break;
1330 	case EAP_IDLE:
1331 		eap_peer_sm_step_idle(sm);
1332 		break;
1333 	case EAP_RECEIVED:
1334 		eap_peer_sm_step_received(sm);
1335 		break;
1336 	case EAP_GET_METHOD:
1337 		if (sm->selectedMethod == sm->reqMethod)
1338 			SM_ENTER(EAP, METHOD);
1339 		else
1340 			SM_ENTER(EAP, SEND_RESPONSE);
1341 		break;
1342 	case EAP_METHOD:
1343 		/*
1344 		 * Note: RFC 4137 uses methodState == DONE && decision == FAIL
1345 		 * as the condition. eapRespData == NULL here is used to allow
1346 		 * final EAP method response to be sent without having to change
1347 		 * all methods to either use methodState MAY_CONT or leaving
1348 		 * decision to something else than FAIL in cases where the only
1349 		 * expected response is EAP-Failure.
1350 		 */
1351 		if (sm->ignore)
1352 			SM_ENTER(EAP, DISCARD);
1353 		else if (sm->methodState == METHOD_DONE &&
1354 			 sm->decision == DECISION_FAIL && !sm->eapRespData)
1355 			SM_ENTER(EAP, FAILURE);
1356 		else
1357 			SM_ENTER(EAP, SEND_RESPONSE);
1358 		break;
1359 	case EAP_SEND_RESPONSE:
1360 		SM_ENTER(EAP, IDLE);
1361 		break;
1362 	case EAP_DISCARD:
1363 		SM_ENTER(EAP, IDLE);
1364 		break;
1365 	case EAP_IDENTITY:
1366 		SM_ENTER(EAP, SEND_RESPONSE);
1367 		break;
1368 	case EAP_NOTIFICATION:
1369 		SM_ENTER(EAP, SEND_RESPONSE);
1370 		break;
1371 	case EAP_RETRANSMIT:
1372 		SM_ENTER(EAP, SEND_RESPONSE);
1373 		break;
1374 	case EAP_SUCCESS:
1375 		break;
1376 	case EAP_FAILURE:
1377 		break;
1378 	}
1379 }
1380 
1381 
SM_STEP(EAP)1382 SM_STEP(EAP)
1383 {
1384 	/* Global transitions */
1385 	if (eapol_get_bool(sm, EAPOL_eapRestart) &&
1386 	    eapol_get_bool(sm, EAPOL_portEnabled))
1387 		SM_ENTER_GLOBAL(EAP, INITIALIZE);
1388 	else if (!eapol_get_bool(sm, EAPOL_portEnabled) || sm->force_disabled)
1389 		SM_ENTER_GLOBAL(EAP, DISABLED);
1390 	else if (sm->num_rounds > EAP_MAX_AUTH_ROUNDS) {
1391 		/* RFC 4137 does not place any limit on number of EAP messages
1392 		 * in an authentication session. However, some error cases have
1393 		 * ended up in a state were EAP messages were sent between the
1394 		 * peer and server in a loop (e.g., TLS ACK frame in both
1395 		 * direction). Since this is quite undesired outcome, limit the
1396 		 * total number of EAP round-trips and abort authentication if
1397 		 * this limit is exceeded.
1398 		 */
1399 		if (sm->num_rounds == EAP_MAX_AUTH_ROUNDS + 1) {
1400 #ifndef CONFIG_PRINT_NOUSE
1401 			wpa_msg(sm->msg_ctx, MSG_INFO, "EAP: more than %d "
1402 				"authentication rounds - abort",
1403 				EAP_MAX_AUTH_ROUNDS);
1404 #endif /* CONFIG_PRINT_NOUSE */
1405 			sm->num_rounds++;
1406 			SM_ENTER_GLOBAL(EAP, FAILURE);
1407 		}
1408 	} else if (sm->num_rounds_short > EAP_MAX_AUTH_ROUNDS_SHORT) {
1409 		if (sm->num_rounds_short == EAP_MAX_AUTH_ROUNDS_SHORT + 1) {
1410 			wpa_msg(sm->msg_ctx, MSG_INFO,
1411 				"EAP: more than %d authentication rounds (short) - abort",
1412 				EAP_MAX_AUTH_ROUNDS_SHORT);
1413 			sm->num_rounds_short++;
1414 			SM_ENTER_GLOBAL(EAP, FAILURE);
1415 		}
1416 	} else {
1417 		/* Local transitions */
1418 		eap_peer_sm_step_local(sm);
1419 	}
1420 }
1421 
1422 
eap_sm_allowMethod(struct eap_sm * sm,int vendor,enum eap_type method)1423 static bool eap_sm_allowMethod(struct eap_sm *sm, int vendor,
1424 			       enum eap_type method)
1425 {
1426 	if (!eap_allowed_method(sm, vendor, method)) {
1427 #ifndef CONFIG_PRINT_NOUSE
1428 		wpa_printf(MSG_DEBUG, "EAP: configuration does not allow: "
1429 			   "vendor %u method %u", vendor, method);
1430 #endif /* CONFIG_PRINT_NOUSE */
1431 		return false;
1432 	}
1433 	if (eap_peer_get_eap_method(vendor, method))
1434 		return true;
1435 #ifndef CONFIG_PRINT_NOUSE
1436 	wpa_printf(MSG_DEBUG, "EAP: not included in build: "
1437 		   "vendor %u method %u", vendor, method);
1438 #endif /* CONFIG_PRINT_NOUSE */
1439 	return false;
1440 }
1441 
1442 
eap_sm_build_expanded_nak(struct eap_sm * sm,int id,const struct eap_method * methods,size_t count)1443 static struct wpabuf * eap_sm_build_expanded_nak(
1444 	struct eap_sm *sm, int id, const struct eap_method *methods,
1445 	size_t count)
1446 {
1447 	struct wpabuf *resp;
1448 	int found = 0;
1449 	const struct eap_method *m;
1450 
1451 	wpa_printf(MSG_DEBUG, "EAP: Building expanded EAP-Nak");
1452 
1453 	/* RFC 3748 - 5.3.2: Expanded Nak */
1454 	resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_EXPANDED,
1455 			     8 + 8 * (count + 1), EAP_CODE_RESPONSE, id);
1456 	if (resp == NULL)
1457 		return NULL;
1458 
1459 	wpabuf_put_be24(resp, EAP_VENDOR_IETF);
1460 	wpabuf_put_be32(resp, EAP_TYPE_NAK);
1461 
1462 	for (m = methods; m; m = m->next) {
1463 		if (sm->reqVendor == m->vendor &&
1464 		    sm->reqVendorMethod == m->method)
1465 			continue; /* do not allow the current method again */
1466 		if (eap_allowed_method(sm, m->vendor, m->method)) {
1467 #ifndef CONFIG_PRINT_NOUSE
1468 			wpa_printf(MSG_DEBUG, "EAP: allowed type: "
1469 				   "vendor=%u method=%u",
1470 				   m->vendor, m->method);
1471 #endif /* CONFIG_PRINT_NOUSE */
1472 			wpabuf_put_u8(resp, EAP_TYPE_EXPANDED);
1473 			wpabuf_put_be24(resp, m->vendor);
1474 			wpabuf_put_be32(resp, m->method);
1475 
1476 			found++;
1477 		}
1478 	}
1479 	if (!found) {
1480 #ifndef CONFIG_PRINT_NOUSE
1481 		wpa_printf(MSG_DEBUG, "EAP: no more allowed methods");
1482 #endif /* CONFIG_PRINT_NOUSE */
1483 		wpabuf_put_u8(resp, EAP_TYPE_EXPANDED);
1484 		wpabuf_put_be24(resp, EAP_VENDOR_IETF);
1485 		wpabuf_put_be32(resp, EAP_TYPE_NONE);
1486 	}
1487 
1488 	eap_update_len(resp);
1489 
1490 	return resp;
1491 }
1492 
1493 
eap_sm_buildNak(struct eap_sm * sm,int id)1494 static struct wpabuf * eap_sm_buildNak(struct eap_sm *sm, int id)
1495 {
1496 	struct wpabuf *resp;
1497 	u8 *start;
1498 	int found = 0, expanded_found = 0;
1499 	size_t count;
1500 	const struct eap_method *methods, *m;
1501 
1502 #ifndef CONFIG_PRINT_NOUSE
1503 	wpa_printf(MSG_DEBUG, "EAP: Building EAP-Nak (requested type %u "
1504 		   "vendor=%u method=%u not allowed)", sm->reqMethod,
1505 		   sm->reqVendor, sm->reqVendorMethod);
1506 #endif /* CONFIG_PRINT_NOUSE */
1507 	methods = eap_peer_get_methods(&count);
1508 	if (methods == NULL)
1509 		return NULL;
1510 	if (sm->reqMethod == EAP_TYPE_EXPANDED)
1511 		return eap_sm_build_expanded_nak(sm, id, methods, count);
1512 
1513 	/* RFC 3748 - 5.3.1: Legacy Nak */
1514 	resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_NAK,
1515 			     sizeof(struct eap_hdr) + 1 + count + 1,
1516 			     EAP_CODE_RESPONSE, id);
1517 	if (resp == NULL)
1518 		return NULL;
1519 
1520 	start = wpabuf_put(resp, 0);
1521 	for (m = methods; m; m = m->next) {
1522 		if (m->vendor == EAP_VENDOR_IETF && m->method == sm->reqMethod)
1523 			continue; /* do not allow the current method again */
1524 		if (eap_allowed_method(sm, m->vendor, m->method)) {
1525 			if (m->vendor != EAP_VENDOR_IETF) {
1526 				if (expanded_found)
1527 					continue;
1528 				expanded_found = 1;
1529 				wpabuf_put_u8(resp, EAP_TYPE_EXPANDED);
1530 			} else
1531 				wpabuf_put_u8(resp, m->method);
1532 			found++;
1533 		}
1534 	}
1535 	if (!found)
1536 		wpabuf_put_u8(resp, EAP_TYPE_NONE);
1537 #ifndef CONFIG_PRINT_NOUSE
1538 	wpa_hexdump(MSG_DEBUG, "EAP: allowed methods", start, found);
1539 #endif /* CONFIG_PRINT_NOUSE */
1540 
1541 	eap_update_len(resp);
1542 
1543 	return resp;
1544 }
1545 
1546 
eap_sm_processIdentity(struct eap_sm * sm,const struct wpabuf * req)1547 static void eap_sm_processIdentity(struct eap_sm *sm, const struct wpabuf *req)
1548 {
1549 	const u8 *pos;
1550 	size_t msg_len;
1551 
1552 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_STARTED
1553 		"EAP authentication started");
1554 #ifndef EXT_EAP_TRIM
1555 	eap_notify_status(sm, "started", "");
1556 #endif /* EXT_EAP_TRIM */
1557 	pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY, req,
1558 			       &msg_len);
1559 	if (pos == NULL)
1560 		return;
1561 
1562 	/*
1563 	 * RFC 3748 - 5.1: Identity
1564 	 * Data field may contain a displayable message in UTF-8. If this
1565 	 * includes NUL-character, only the data before that should be
1566 	 * displayed. Some EAP implementasitons may piggy-back additional
1567 	 * options after the NUL.
1568 	 */
1569 	/* TODO: could save displayable message so that it can be shown to the
1570 	 * user in case of interaction is required */
1571 #ifndef CONFIG_PRINT_NOUSE
1572 	wpa_hexdump_ascii(MSG_DEBUG, "EAP: EAP-Request Identity data",
1573 			  pos, msg_len);
1574 #endif /* CONFIG_PRINT_NOUSE */
1575 }
1576 
1577 
1578 #ifdef PCSC_FUNCS
1579 
1580 /*
1581  * Rules for figuring out MNC length based on IMSI for SIM cards that do not
1582  * include MNC length field.
1583  */
mnc_len_from_imsi(const char * imsi)1584 static int mnc_len_from_imsi(const char *imsi)
1585 {
1586 	char mcc_str[4];
1587 	unsigned int mcc;
1588 
1589 	os_memcpy(mcc_str, imsi, 3);
1590 	mcc_str[3] = '\0';
1591 	mcc = atoi(mcc_str);
1592 
1593 	if (mcc == 228)
1594 		return 2; /* Networks in Switzerland use 2-digit MNC */
1595 	if (mcc == 244)
1596 		return 2; /* Networks in Finland use 2-digit MNC */
1597 
1598 	return -1;
1599 }
1600 
1601 
eap_sm_imsi_identity(struct eap_sm * sm,struct eap_peer_config * conf)1602 static int eap_sm_imsi_identity(struct eap_sm *sm,
1603 				struct eap_peer_config *conf)
1604 {
1605 	enum { EAP_SM_SIM, EAP_SM_AKA, EAP_SM_AKA_PRIME } method = EAP_SM_SIM;
1606 	char imsi[100];
1607 	size_t imsi_len;
1608 	struct eap_method_type *m = conf->eap_methods;
1609 	int i, mnc_len;
1610 
1611 	imsi_len = sizeof(imsi);
1612 	if (scard_get_imsi(sm->scard_ctx, imsi, &imsi_len)) {
1613 		wpa_printf(MSG_WARNING, "Failed to get IMSI from SIM");
1614 		return -1;
1615 	}
1616 
1617 	wpa_hexdump_ascii(MSG_DEBUG, "IMSI", (u8 *) imsi, imsi_len);
1618 
1619 	if (imsi_len < 7) {
1620 		wpa_printf(MSG_WARNING, "Too short IMSI for SIM identity");
1621 		return -1;
1622 	}
1623 
1624 	/* MNC (2 or 3 digits) */
1625 	mnc_len = scard_get_mnc_len(sm->scard_ctx);
1626 	if (mnc_len < 0)
1627 		mnc_len = mnc_len_from_imsi(imsi);
1628 	if (mnc_len < 0) {
1629 		wpa_printf(MSG_INFO, "Failed to get MNC length from (U)SIM "
1630 			   "assuming 3");
1631 		mnc_len = 3;
1632 	}
1633 
1634 	if (eap_sm_append_3gpp_realm(sm, imsi, sizeof(imsi), &imsi_len,
1635 				     mnc_len) < 0) {
1636 		wpa_printf(MSG_WARNING, "Could not add realm to SIM identity");
1637 		return -1;
1638 	}
1639 	wpa_hexdump_ascii(MSG_DEBUG, "IMSI + realm", (u8 *) imsi, imsi_len);
1640 
1641 	for (i = 0; m && (m[i].vendor != EAP_VENDOR_IETF ||
1642 			  m[i].method != EAP_TYPE_NONE); i++) {
1643 		if (m[i].vendor == EAP_VENDOR_IETF &&
1644 		    m[i].method == EAP_TYPE_AKA_PRIME) {
1645 			method = EAP_SM_AKA_PRIME;
1646 			break;
1647 		}
1648 
1649 		if (m[i].vendor == EAP_VENDOR_IETF &&
1650 		    m[i].method == EAP_TYPE_AKA) {
1651 			method = EAP_SM_AKA;
1652 			break;
1653 		}
1654 	}
1655 
1656 	os_free(conf->identity);
1657 	conf->identity = os_malloc(1 + imsi_len);
1658 	if (conf->identity == NULL) {
1659 		wpa_printf(MSG_WARNING, "Failed to allocate buffer for "
1660 			   "IMSI-based identity");
1661 		return -1;
1662 	}
1663 
1664 	switch (method) {
1665 	case EAP_SM_SIM:
1666 		conf->identity[0] = '1';
1667 		break;
1668 	case EAP_SM_AKA:
1669 		conf->identity[0] = '0';
1670 		break;
1671 	case EAP_SM_AKA_PRIME:
1672 		conf->identity[0] = '6';
1673 		break;
1674 	}
1675 	os_memcpy(conf->identity + 1, imsi, imsi_len);
1676 	conf->identity_len = 1 + imsi_len;
1677 
1678 	return 0;
1679 }
1680 
1681 
eap_sm_set_scard_pin(struct eap_sm * sm,struct eap_peer_config * conf)1682 static int eap_sm_set_scard_pin(struct eap_sm *sm,
1683 				struct eap_peer_config *conf)
1684 {
1685 	if (scard_set_pin(sm->scard_ctx, conf->cert.pin)) {
1686 		/*
1687 		 * Make sure the same PIN is not tried again in order to avoid
1688 		 * blocking SIM.
1689 		 */
1690 		os_free(conf->cert.pin);
1691 		conf->cert.pin = NULL;
1692 
1693 		wpa_printf(MSG_WARNING, "PIN validation failed");
1694 		eap_sm_request_pin(sm);
1695 		return -1;
1696 	}
1697 	return 0;
1698 }
1699 
1700 
eap_sm_get_scard_identity(struct eap_sm * sm,struct eap_peer_config * conf)1701 static int eap_sm_get_scard_identity(struct eap_sm *sm,
1702 				     struct eap_peer_config *conf)
1703 {
1704 	if (eap_sm_set_scard_pin(sm, conf))
1705 		return -1;
1706 
1707 	return eap_sm_imsi_identity(sm, conf);
1708 }
1709 
1710 #endif /* PCSC_FUNCS */
1711 
1712 
1713 /**
1714  * eap_sm_buildIdentity - Build EAP-Identity/Response for the current network
1715  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
1716  * @id: EAP identifier for the packet
1717  * @encrypted: Whether the packet is for encrypted tunnel (EAP phase 2)
1718  * Returns: Pointer to the allocated EAP-Identity/Response packet or %NULL on
1719  * failure
1720  *
1721  * This function allocates and builds an EAP-Identity/Response packet for the
1722  * current network. The caller is responsible for freeing the returned data.
1723  */
eap_sm_buildIdentity(struct eap_sm * sm,int id,int encrypted)1724 struct wpabuf * eap_sm_buildIdentity(struct eap_sm *sm, int id, int encrypted)
1725 {
1726 	struct eap_peer_config *config = eap_get_config(sm);
1727 	struct wpabuf *resp;
1728 	const u8 *identity;
1729 	size_t identity_len;
1730 
1731 	if (config == NULL) {
1732 #ifndef CONFIG_PRINT_NOUSE
1733 		wpa_printf(MSG_WARNING, "EAP: buildIdentity: configuration "
1734 			   "was not available");
1735 #endif /* CONFIG_PRINT_NOUSE */
1736 		return NULL;
1737 	}
1738 
1739 	if (sm->m && sm->m->get_identity &&
1740 	    (identity = sm->m->get_identity(sm, sm->eap_method_priv,
1741 					    &identity_len)) != NULL) {
1742 #ifndef CONFIG_PRINT_NOUSE
1743 		wpa_hexdump_ascii(MSG_DEBUG, "EAP: using method re-auth "
1744 				  "identity", identity, identity_len);
1745 #endif /* CONFIG_PRINT_NOUSE */
1746 #ifndef EXT_EAP_TRIM
1747 	} else if (!encrypted && config->anonymous_identity) {
1748 		identity = config->anonymous_identity;
1749 		identity_len = config->anonymous_identity_len;
1750 		wpa_hexdump_ascii(MSG_DEBUG, "EAP: using anonymous identity",
1751 				  identity, identity_len);
1752 #endif /* EXT_EAP_TRIM */
1753 	} else if (sm->use_machine_cred) {
1754 		identity = config->machine_identity;
1755 		identity_len = config->machine_identity_len;
1756 		wpa_hexdump_ascii(MSG_DEBUG, "EAP: using machine identity",
1757 				  identity, identity_len);
1758 	} else {
1759 		identity = config->identity;
1760 		identity_len = config->identity_len;
1761 #ifndef CONFIG_PRINT_NOUSE
1762 		wpa_hexdump_ascii(MSG_DEBUG, "EAP: using real identity",
1763 				  identity, identity_len);
1764 #endif /* CONFIG_PRINT_NOUSE */
1765 	}
1766 #ifndef EXT_CODE_CROP
1767 	if (config->pcsc) {
1768 #ifdef PCSC_FUNCS
1769 		if (!identity) {
1770 			if (eap_sm_get_scard_identity(sm, config) < 0)
1771 				return NULL;
1772 			identity = config->identity;
1773 			identity_len = config->identity_len;
1774 			wpa_hexdump_ascii(MSG_DEBUG,
1775 					  "permanent identity from IMSI",
1776 					  identity, identity_len);
1777 		} else if (eap_sm_set_scard_pin(sm, config) < 0) {
1778 			return NULL;
1779 		}
1780 #else /* PCSC_FUNCS */
1781 		return NULL;
1782 #endif /* PCSC_FUNCS */
1783 	} else if (!identity) {
1784 #else
1785 	 if (!identity) {
1786 #endif /* EXT_CODE_CROP */
1787 #ifndef CONFIG_PRINT_NOUSE
1788 		wpa_printf(MSG_WARNING,
1789 			"EAP: buildIdentity: identity configuration was not available");
1790 #endif /* CONFIG_PRINT_NOUSE */
1791 		eap_sm_request_identity(sm);
1792 		return NULL;
1793 	}
1794 
1795 	resp = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_IDENTITY, identity_len,
1796 			     EAP_CODE_RESPONSE, id);
1797 	if (resp == NULL)
1798 		return NULL;
1799 
1800 	wpabuf_put_data(resp, identity, identity_len);
1801 
1802 	return resp;
1803 }
1804 
1805 
1806 static void eap_sm_processNotify(struct eap_sm *sm, const struct wpabuf *req)
1807 {
1808 	const u8 *pos;
1809 	char *msg;
1810 	size_t i, msg_len;
1811 #ifdef CONFIG_NO_WPA_MSG
1812 	(void)sm;
1813 #endif /* CONFIG_NO_WPA_MSG */
1814 
1815 	pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_NOTIFICATION, req,
1816 			       &msg_len);
1817 	if (pos == NULL)
1818 		return;
1819 #ifndef CONFIG_PRINT_NOUSE
1820 	wpa_hexdump_ascii(MSG_DEBUG, "EAP: EAP-Request Notification data",
1821 			  pos, msg_len);
1822 #endif /* CONFIG_PRINT_NOUSE */
1823 
1824 	msg = os_malloc(msg_len + 1);
1825 	if (msg == NULL)
1826 		return;
1827 	for (i = 0; i < msg_len; i++)
1828 		msg[i] = isprint(pos[i]) ? (char) pos[i] : '_';
1829 	msg[msg_len] = '\0';
1830 	wpa_msg(sm->msg_ctx, MSG_INFO, "%s%s",
1831 		WPA_EVENT_EAP_NOTIFICATION, msg);
1832 	os_free(msg);
1833 }
1834 
1835 
1836 static struct wpabuf * eap_sm_buildNotify(int id)
1837 {
1838 #ifndef CONFIG_PRINT_NOUSE
1839 	wpa_printf(MSG_DEBUG, "EAP: Generating EAP-Response Notification");
1840 #endif /* CONFIG_PRINT_NOUSE */
1841 	return eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_NOTIFICATION, 0,
1842 			EAP_CODE_RESPONSE, id);
1843 }
1844 
1845 #ifndef EXT_EAP_TRIM
1846 static void eap_peer_initiate(struct eap_sm *sm, const struct eap_hdr *hdr,
1847 			      size_t len)
1848 {
1849 #ifdef CONFIG_ERP
1850 	const u8 *pos = (const u8 *) (hdr + 1);
1851 	const u8 *end = ((const u8 *) hdr) + len;
1852 	struct erp_tlvs parse;
1853 
1854 	if (len < sizeof(*hdr) + 1) {
1855 		wpa_printf(MSG_DEBUG, "EAP: Ignored too short EAP-Initiate");
1856 		return;
1857 	}
1858 
1859 	if (*pos != EAP_ERP_TYPE_REAUTH_START) {
1860 		wpa_printf(MSG_DEBUG,
1861 			   "EAP: Ignored unexpected EAP-Initiate Type=%u",
1862 			   *pos);
1863 		return;
1864 	}
1865 
1866 	pos++;
1867 	if (pos >= end) {
1868 		wpa_printf(MSG_DEBUG,
1869 			   "EAP: Too short EAP-Initiate/Re-auth-Start");
1870 		return;
1871 	}
1872 	pos++; /* Reserved */
1873 	wpa_hexdump(MSG_DEBUG, "EAP: EAP-Initiate/Re-auth-Start TVs/TLVs",
1874 		    pos, end - pos);
1875 
1876 	if (erp_parse_tlvs(pos, end, &parse, 0) < 0)
1877 		goto invalid;
1878 
1879 	if (parse.domain) {
1880 		wpa_hexdump_ascii(MSG_DEBUG,
1881 				  "EAP: EAP-Initiate/Re-auth-Start - Domain name",
1882 				  parse.domain, parse.domain_len);
1883 		/* TODO: Derivation of domain specific keys for local ER */
1884 	}
1885 
1886 	if (eap_peer_erp_reauth_start(sm, hdr->identifier) == 0)
1887 		return;
1888 
1889 invalid:
1890 #endif /* CONFIG_ERP */
1891 #ifndef CONFIG_PRINT_NOUSE
1892 	wpa_printf(MSG_DEBUG,
1893 		   "EAP: EAP-Initiate/Re-auth-Start - No suitable ERP keys available - try to start full EAP authentication");
1894 #endif /* CONFIG_PRINT_NOUSE */
1895 	eapol_set_bool(sm, EAPOL_eapTriggerStart, true);
1896 }
1897 
1898 
1899 void eap_peer_finish(struct eap_sm *sm, const struct eap_hdr *hdr, size_t len)
1900 {
1901 #ifdef CONFIG_ERP
1902 	const u8 *pos = (const u8 *) (hdr + 1);
1903 	const u8 *end = ((const u8 *) hdr) + len;
1904 	const u8 *start;
1905 	struct erp_tlvs parse;
1906 	u8 flags;
1907 	u16 seq;
1908 	u8 hash[SHA256_MAC_LEN];
1909 	size_t hash_len;
1910 	struct eap_erp_key *erp;
1911 	int max_len;
1912 	char nai[254];
1913 	u8 seed[4];
1914 	int auth_tag_ok = 0;
1915 
1916 	if (len < sizeof(*hdr) + 1) {
1917 		wpa_printf(MSG_DEBUG, "EAP: Ignored too short EAP-Finish");
1918 		return;
1919 	}
1920 
1921 	if (*pos != EAP_ERP_TYPE_REAUTH) {
1922 		wpa_printf(MSG_DEBUG,
1923 			   "EAP: Ignored unexpected EAP-Finish Type=%u", *pos);
1924 		return;
1925 	}
1926 
1927 	if (len < sizeof(*hdr) + 4) {
1928 		wpa_printf(MSG_DEBUG,
1929 			   "EAP: Ignored too short EAP-Finish/Re-auth");
1930 		return;
1931 	}
1932 
1933 	pos++;
1934 	flags = *pos++;
1935 	seq = WPA_GET_BE16(pos);
1936 	pos += 2;
1937 	wpa_printf(MSG_DEBUG, "EAP: Flags=0x%x SEQ=%u", flags, seq);
1938 
1939 	if (seq != sm->erp_seq) {
1940 		wpa_printf(MSG_DEBUG,
1941 			   "EAP: Unexpected EAP-Finish/Re-auth SEQ=%u", seq);
1942 		return;
1943 	}
1944 
1945 	/*
1946 	 * Parse TVs/TLVs. Since we do not yet know the length of the
1947 	 * Authentication Tag, stop parsing if an unknown TV/TLV is seen and
1948 	 * just try to find the keyName-NAI first so that we can check the
1949 	 * Authentication Tag.
1950 	 */
1951 	if (erp_parse_tlvs(pos, end, &parse, 1) < 0)
1952 		return;
1953 
1954 	if (!parse.keyname) {
1955 		wpa_printf(MSG_DEBUG,
1956 			   "EAP: No keyName-NAI in EAP-Finish/Re-auth Packet");
1957 		return;
1958 	}
1959 
1960 	wpa_hexdump_ascii(MSG_DEBUG, "EAP: EAP-Finish/Re-auth - keyName-NAI",
1961 			  parse.keyname, parse.keyname_len);
1962 	if (parse.keyname_len > 253) {
1963 		wpa_printf(MSG_DEBUG,
1964 			   "EAP: Too long keyName-NAI in EAP-Finish/Re-auth");
1965 		return;
1966 	}
1967 	os_memcpy(nai, parse.keyname, parse.keyname_len);
1968 	nai[parse.keyname_len] = '\0';
1969 
1970 	erp = eap_erp_get_key_nai(sm, nai);
1971 	if (!erp) {
1972 		wpa_printf(MSG_DEBUG, "EAP: No matching ERP key found for %s",
1973 			   nai);
1974 		return;
1975 	}
1976 
1977 	/* Is there enough room for Cryptosuite and Authentication Tag? */
1978 	start = parse.keyname + parse.keyname_len;
1979 	max_len = end - start;
1980 	hash_len = 16;
1981 	if (max_len < 1 + (int) hash_len) {
1982 		wpa_printf(MSG_DEBUG,
1983 			   "EAP: Not enough room for Authentication Tag");
1984 		if (flags & 0x80)
1985 			goto no_auth_tag;
1986 		return;
1987 	}
1988 	if (end[-17] != EAP_ERP_CS_HMAC_SHA256_128) {
1989 		wpa_printf(MSG_DEBUG, "EAP: Different Cryptosuite used");
1990 		if (flags & 0x80)
1991 			goto no_auth_tag;
1992 		return;
1993 	}
1994 
1995 	if (hmac_sha256(erp->rIK, erp->rIK_len, (const u8 *) hdr,
1996 			end - ((const u8 *) hdr) - hash_len, hash) < 0)
1997 		return;
1998 	if (os_memcmp(end - hash_len, hash, hash_len) != 0) {
1999 		wpa_printf(MSG_DEBUG,
2000 			   "EAP: Authentication Tag mismatch");
2001 		return;
2002 	}
2003 	auth_tag_ok = 1;
2004 	end -= 1 + hash_len;
2005 
2006 no_auth_tag:
2007 	/*
2008 	 * Parse TVs/TLVs again now that we know the exact part of the buffer
2009 	 * that contains them.
2010 	 */
2011 	wpa_hexdump(MSG_DEBUG, "EAP: EAP-Finish/Re-Auth TVs/TLVs",
2012 		    pos, end - pos);
2013 	if (erp_parse_tlvs(pos, end, &parse, 0) < 0)
2014 		return;
2015 
2016 	if (flags & 0x80 || !auth_tag_ok) {
2017 		wpa_printf(MSG_DEBUG,
2018 			   "EAP: EAP-Finish/Re-auth indicated failure");
2019 		eapol_set_bool(sm, EAPOL_eapFail, true);
2020 		eapol_set_bool(sm, EAPOL_eapReq, false);
2021 		eapol_set_bool(sm, EAPOL_eapNoResp, true);
2022 		wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_FAILURE
2023 			"EAP authentication failed");
2024 		sm->prev_failure = 1;
2025 		wpa_printf(MSG_DEBUG,
2026 			   "EAP: Drop ERP key to try full authentication on next attempt");
2027 		eap_peer_erp_free_key(erp);
2028 		return;
2029 	}
2030 
2031 	eap_sm_free_key(sm);
2032 	sm->eapKeyDataLen = 0;
2033 	sm->eapKeyData = os_malloc(erp->rRK_len);
2034 	if (!sm->eapKeyData)
2035 		return;
2036 	sm->eapKeyDataLen = erp->rRK_len;
2037 
2038 	WPA_PUT_BE16(seed, seq);
2039 	WPA_PUT_BE16(&seed[2], erp->rRK_len);
2040 	if (hmac_sha256_kdf(erp->rRK, erp->rRK_len,
2041 			    "Re-authentication Master Session Key@ietf.org",
2042 			    seed, sizeof(seed),
2043 			    sm->eapKeyData, erp->rRK_len) < 0) {
2044 		wpa_printf(MSG_DEBUG, "EAP: Could not derive rMSK for ERP");
2045 		eap_sm_free_key(sm);
2046 		return;
2047 	}
2048 	wpa_hexdump_key(MSG_DEBUG, "EAP: ERP rMSK",
2049 			sm->eapKeyData, sm->eapKeyDataLen);
2050 	sm->eapKeyAvailable = true;
2051 	eapol_set_bool(sm, EAPOL_eapSuccess, true);
2052 	eapol_set_bool(sm, EAPOL_eapReq, false);
2053 	eapol_set_bool(sm, EAPOL_eapNoResp, true);
2054 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
2055 		"EAP re-authentication completed successfully");
2056 #endif /* CONFIG_ERP */
2057 }
2058 #endif /* EXT_EAP_TRIM */
2059 
2060 static void eap_sm_parseEapReq(struct eap_sm *sm, const struct wpabuf *req)
2061 {
2062 	const struct eap_hdr *hdr;
2063 	size_t plen;
2064 	const u8 *pos;
2065 
2066 	sm->rxReq = sm->rxResp = sm->rxSuccess = sm->rxFailure = false;
2067 	sm->reqId = 0;
2068 	sm->reqMethod = EAP_TYPE_NONE;
2069 	sm->reqVendor = EAP_VENDOR_IETF;
2070 	sm->reqVendorMethod = EAP_TYPE_NONE;
2071 
2072 	if (req == NULL || wpabuf_len(req) < sizeof(*hdr))
2073 		return;
2074 
2075 	hdr = wpabuf_head(req);
2076 	plen = be_to_host16(hdr->length);
2077 	if (plen > wpabuf_len(req)) {
2078 		wpa_printf(MSG_DEBUG, "EAP: Ignored truncated EAP-Packet "
2079 			   "(len=%lu plen=%lu)",
2080 			   (unsigned long) wpabuf_len(req),
2081 			   (unsigned long) plen);
2082 		return;
2083 	}
2084 
2085 	sm->reqId = hdr->identifier;
2086 
2087 	if (sm->workaround) {
2088 		const u8 *addr[1];
2089 		addr[0] = wpabuf_head(req);
2090 		sha1_vector(1, addr, &plen, sm->req_sha1);
2091 	}
2092 
2093 	switch (hdr->code) {
2094 	case EAP_CODE_REQUEST:
2095 		if (plen < sizeof(*hdr) + 1) {
2096 #ifndef CONFIG_PRINT_NOUSE
2097 			wpa_printf(MSG_DEBUG, "EAP: Too short EAP-Request - "
2098 				   "no Type field");
2099 #endif /* CONFIG_PRINT_NOUSE */
2100 			return;
2101 		}
2102 		sm->rxReq = true;
2103 		pos = (const u8 *) (hdr + 1);
2104 		sm->reqMethod = *pos++;
2105 		if (sm->reqMethod == EAP_TYPE_EXPANDED) {
2106 			if (plen < sizeof(*hdr) + 8) {
2107 #ifndef CONFIG_PRINT_NOUSE
2108 				wpa_printf(MSG_DEBUG, "EAP: Ignored truncated "
2109 					   "expanded EAP-Packet (plen=%lu)",
2110 					   (unsigned long) plen);
2111 #endif /* CONFIG_PRINT_NOUSE */
2112 				return;
2113 			}
2114 			sm->reqVendor = WPA_GET_BE24(pos);
2115 			pos += 3;
2116 			sm->reqVendorMethod = WPA_GET_BE32(pos);
2117 		}
2118 #ifndef CONFIG_PRINT_NOUSE
2119 		wpa_printf(MSG_DEBUG, "EAP: Received EAP-Request id=%d "
2120 			   "method=%u vendor=%u vendorMethod=%u",
2121 			   sm->reqId, sm->reqMethod, sm->reqVendor,
2122 			   sm->reqVendorMethod);
2123 #endif /* CONFIG_PRINT_NOUSE */
2124 		break;
2125 	case EAP_CODE_RESPONSE:
2126 #ifndef EXT_EAP_TRIM
2127 		if (sm->selectedMethod == EAP_TYPE_LEAP) {
2128 			/*
2129 			 * LEAP differs from RFC 4137 by using reversed roles
2130 			 * for mutual authentication and because of this, we
2131 			 * need to accept EAP-Response frames if LEAP is used.
2132 			 */
2133 			if (plen < sizeof(*hdr) + 1) {
2134 #ifndef CONFIG_PRINT_NOUSE
2135 				wpa_printf(MSG_DEBUG, "EAP: Too short "
2136 					   "EAP-Response - no Type field");
2137 #endif /* CONFIG_PRINT_NOUSE */
2138 				return;
2139 			}
2140 			sm->rxResp = true;
2141 			pos = (const u8 *) (hdr + 1);
2142 			sm->reqMethod = *pos;
2143 #ifndef CONFIG_PRINT_NOUSE
2144 			wpa_printf(MSG_DEBUG, "EAP: Received EAP-Response for "
2145 				   "LEAP method=%d id=%d",
2146 				   sm->reqMethod, sm->reqId);
2147 #endif /* CONFIG_PRINT_NOUSE */
2148 			break;
2149 		}
2150 #endif /* EXT_EAP_TRIM */
2151 #ifndef CONFIG_PRINT_NOUSE
2152 		wpa_printf(MSG_DEBUG, "EAP: Ignored EAP-Response");
2153 #endif /* CONFIG_PRINT_NOUSE */
2154 		break;
2155 	case EAP_CODE_SUCCESS:
2156 		wpa_printf(MSG_DEBUG, "EAP: Received EAP-Success");
2157 #ifndef EXT_EAP_TRIM
2158 		eap_notify_status(sm, "completion", "success");
2159 #endif /* EXT_EAP_TRIM */
2160 		sm->rxSuccess = true;
2161 		break;
2162 	case EAP_CODE_FAILURE:
2163 		wpa_printf(MSG_DEBUG, "EAP: Received EAP-Failure");
2164 #ifndef EXT_EAP_TRIM
2165 		eap_notify_status(sm, "completion", "failure");
2166 
2167 		/* Get the error code from method */
2168 		if (sm->m && sm->m->get_error_code) {
2169 			int error_code;
2170 
2171 			error_code = sm->m->get_error_code(sm->eap_method_priv);
2172 			if (error_code != NO_EAP_METHOD_ERROR)
2173 				eap_report_error(sm, error_code);
2174 		}
2175 #endif /* EXT_EAP_TRIM */
2176 		sm->rxFailure = true;
2177 		break;
2178 #ifndef EXT_EAP_TRIM
2179 	case EAP_CODE_INITIATE:
2180 		eap_peer_initiate(sm, hdr, plen);
2181 		break;
2182 	case EAP_CODE_FINISH:
2183 		eap_peer_finish(sm, hdr, plen);
2184 		break;
2185 #endif /* EXT_EAP_TRIM */
2186 	default:
2187 #ifndef CONFIG_PRINT_NOUSE
2188 		wpa_printf(MSG_DEBUG, "EAP: Ignored EAP-Packet with unknown "
2189 			   "code %d", hdr->code);
2190 #endif /* CONFIG_PRINT_NOUSE */
2191 		break;
2192 	}
2193 }
2194 
2195 #ifndef EXT_EAP_TRIM
2196 static void eap_peer_sm_tls_event(void *ctx, enum tls_event ev,
2197 				  union tls_event_data *data)
2198 {
2199 	struct eap_sm *sm = ctx;
2200 	char *hash_hex = NULL;
2201 
2202 	switch (ev) {
2203 	case TLS_CERT_CHAIN_SUCCESS:
2204 		eap_notify_status(sm, "remote certificate verification",
2205 				  "success");
2206 		if (sm->ext_cert_check) {
2207 			sm->waiting_ext_cert_check = 1;
2208 			eap_sm_request(sm, WPA_CTRL_REQ_EXT_CERT_CHECK,
2209 				       NULL, 0);
2210 		}
2211 		break;
2212 	case TLS_CERT_CHAIN_FAILURE:
2213 		wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_TLS_CERT_ERROR
2214 			"reason=%d depth=%d subject='%s' err='%s'",
2215 			data->cert_fail.reason,
2216 			data->cert_fail.depth,
2217 			data->cert_fail.subject,
2218 			data->cert_fail.reason_txt);
2219 		eap_notify_status(sm, "remote certificate verification",
2220 				  data->cert_fail.reason_txt);
2221 		break;
2222 	case TLS_PEER_CERTIFICATE:
2223 		if (!sm->eapol_cb->notify_cert)
2224 			break;
2225 
2226 		if (data->peer_cert.hash) {
2227 			size_t len = data->peer_cert.hash_len * 2 + 1;
2228 			hash_hex = os_malloc(len);
2229 			if (hash_hex) {
2230 				wpa_snprintf_hex(hash_hex, len,
2231 						 data->peer_cert.hash,
2232 						 data->peer_cert.hash_len);
2233 			}
2234 		}
2235 
2236 		sm->eapol_cb->notify_cert(sm->eapol_ctx, &data->peer_cert,
2237 					  hash_hex);
2238 		break;
2239 	case TLS_ALERT:
2240 		if (data->alert.is_local)
2241 			eap_notify_status(sm, "local TLS alert",
2242 					  data->alert.description);
2243 		else
2244 			eap_notify_status(sm, "remote TLS alert",
2245 					  data->alert.description);
2246 		break;
2247 	}
2248 
2249 	os_free(hash_hex);
2250 }
2251 #endif /* EXT_EAP_TRIM */
2252 
2253 /**
2254  * eap_peer_sm_init - Allocate and initialize EAP peer state machine
2255  * @eapol_ctx: Context data to be used with eapol_cb calls
2256  * @eapol_cb: Pointer to EAPOL callback functions
2257  * @msg_ctx: Context data for wpa_msg() calls
2258  * @conf: EAP configuration
2259  * Returns: Pointer to the allocated EAP state machine or %NULL on failure
2260  *
2261  * This function allocates and initializes an EAP state machine. In addition,
2262  * this initializes TLS library for the new EAP state machine. eapol_cb pointer
2263  * will be in use until eap_peer_sm_deinit() is used to deinitialize this EAP
2264  * state machine. Consequently, the caller must make sure that this data
2265  * structure remains alive while the EAP state machine is active.
2266  */
2267 struct eap_sm * eap_peer_sm_init(void *eapol_ctx,
2268 				 const struct eapol_callbacks *eapol_cb,
2269 				 void *msg_ctx, struct eap_config *conf)
2270 {
2271 	struct eap_sm *sm;
2272 #ifndef EXT_EAP_TRIM
2273 	struct tls_config tlsconf;
2274 #endif /* EXT_EAP_TRIM */
2275 
2276 	sm = os_zalloc(sizeof(*sm));
2277 	if (sm == NULL)
2278 		return NULL;
2279 	sm->eapol_ctx = eapol_ctx;
2280 	sm->eapol_cb = eapol_cb;
2281 	sm->msg_ctx = msg_ctx;
2282 	sm->ClientTimeout = EAP_CLIENT_TIMEOUT_DEFAULT;
2283 	sm->wps = conf->wps;
2284 #ifdef CONFIG_ERP
2285 	dl_list_init(&sm->erp_keys);
2286 #endif /* CONFIG_ERP */
2287 #ifndef EXT_EAP_TRIM
2288 	os_memset(&tlsconf, 0, sizeof(tlsconf));
2289 	tlsconf.opensc_engine_path = conf->opensc_engine_path;
2290 	tlsconf.pkcs11_engine_path = conf->pkcs11_engine_path;
2291 	tlsconf.pkcs11_module_path = conf->pkcs11_module_path;
2292 	tlsconf.openssl_ciphers = conf->openssl_ciphers;
2293 #ifdef CONFIG_FIPS
2294 	tlsconf.fips_mode = 1;
2295 #endif /* CONFIG_FIPS */
2296 	tlsconf.event_cb = eap_peer_sm_tls_event;
2297 	tlsconf.cb_ctx = sm;
2298 	tlsconf.cert_in_cb = conf->cert_in_cb;
2299 	sm->ssl_ctx = tls_init(&tlsconf);
2300 	if (sm->ssl_ctx == NULL) {
2301 		wpa_printf(MSG_WARNING, "SSL: Failed to initialize TLS "
2302 			   "context.");
2303 		os_free(sm);
2304 		return NULL;
2305 	}
2306 
2307 	sm->ssl_ctx2 = tls_init(&tlsconf);
2308 	if (sm->ssl_ctx2 == NULL) {
2309 		wpa_printf(MSG_INFO, "SSL: Failed to initialize TLS "
2310 			   "context (2).");
2311 		/* Run without separate TLS context within TLS tunnel */
2312 	}
2313 #endif /* EXT_EAP_TRIM */
2314 	return sm;
2315 }
2316 
2317 
2318 /**
2319  * eap_peer_sm_deinit - Deinitialize and free an EAP peer state machine
2320  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2321  *
2322  * This function deinitializes EAP state machine and frees all allocated
2323  * resources.
2324  */
2325 void eap_peer_sm_deinit(struct eap_sm *sm)
2326 {
2327 	if (sm == NULL)
2328 		return;
2329 #ifndef EXT_EAP_TRIM
2330 	eap_deinit_prev_method(sm, "EAP deinit");
2331 #else
2332 	eap_deinit_prev_method(sm, NULL);
2333 #endif /* EXT_EAP_TRIM */
2334 	eap_sm_abort(sm);
2335 #ifndef EXT_EAP_TRIM
2336 	if (sm->ssl_ctx2)
2337 		tls_deinit(sm->ssl_ctx2);
2338 	tls_deinit(sm->ssl_ctx);
2339 #endif /* EXT_EAP_TRIM */
2340 #ifdef CONFIG_ERP
2341 	eap_peer_erp_free_keys(sm);
2342 #endif /* CONFIG_ERP */
2343 	os_free(sm);
2344 }
2345 
2346 
2347 /**
2348  * eap_peer_sm_step - Step EAP peer state machine
2349  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2350  * Returns: 1 if EAP state was changed or 0 if not
2351  *
2352  * This function advances EAP state machine to a new state to match with the
2353  * current variables. This should be called whenever variables used by the EAP
2354  * state machine have changed.
2355  */
2356 int eap_peer_sm_step(struct eap_sm *sm)
2357 {
2358 	int res = 0;
2359 	do {
2360 		sm->changed = false;
2361 		SM_STEP_RUN(EAP);
2362 		if (sm->changed)
2363 			res = 1;
2364 	} while (sm->changed);
2365 	return res;
2366 }
2367 
2368 
2369 /**
2370  * eap_sm_abort - Abort EAP authentication
2371  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2372  *
2373  * Release system resources that have been allocated for the authentication
2374  * session without fully deinitializing the EAP state machine.
2375  */
2376 void eap_sm_abort(struct eap_sm *sm)
2377 {
2378 	wpabuf_free(sm->lastRespData);
2379 	sm->lastRespData = NULL;
2380 	wpabuf_free(sm->eapRespData);
2381 	sm->eapRespData = NULL;
2382 	eap_sm_free_key(sm);
2383 	os_free(sm->eapSessionId);
2384 	sm->eapSessionId = NULL;
2385 
2386 	/* This is not clearly specified in the EAP statemachines draft, but
2387 	 * it seems necessary to make sure that some of the EAPOL variables get
2388 	 * cleared for the next authentication. */
2389 	eapol_set_bool(sm, EAPOL_eapSuccess, false);
2390 }
2391 
2392 #ifndef EXT_EAP_TRIM
2393 #ifdef CONFIG_CTRL_IFACE
2394 static const char * eap_sm_state_txt(int state)
2395 {
2396 	switch (state) {
2397 	case EAP_INITIALIZE:
2398 		return "INITIALIZE";
2399 	case EAP_DISABLED:
2400 		return "DISABLED";
2401 	case EAP_IDLE:
2402 		return "IDLE";
2403 	case EAP_RECEIVED:
2404 		return "RECEIVED";
2405 	case EAP_GET_METHOD:
2406 		return "GET_METHOD";
2407 	case EAP_METHOD:
2408 		return "METHOD";
2409 	case EAP_SEND_RESPONSE:
2410 		return "SEND_RESPONSE";
2411 	case EAP_DISCARD:
2412 		return "DISCARD";
2413 	case EAP_IDENTITY:
2414 		return "IDENTITY";
2415 	case EAP_NOTIFICATION:
2416 		return "NOTIFICATION";
2417 	case EAP_RETRANSMIT:
2418 		return "RETRANSMIT";
2419 	case EAP_SUCCESS:
2420 		return "SUCCESS";
2421 	case EAP_FAILURE:
2422 		return "FAILURE";
2423 	default:
2424 		return "UNKNOWN";
2425 	}
2426 }
2427 #endif /* CONFIG_CTRL_IFACE */
2428 
2429 
2430 #if defined(CONFIG_CTRL_IFACE) || !defined(CONFIG_NO_STDOUT_DEBUG)
2431 static const char * eap_sm_method_state_txt(EapMethodState state)
2432 {
2433 	switch (state) {
2434 	case METHOD_NONE:
2435 		return "NONE";
2436 	case METHOD_INIT:
2437 		return "INIT";
2438 	case METHOD_CONT:
2439 		return "CONT";
2440 	case METHOD_MAY_CONT:
2441 		return "MAY_CONT";
2442 	case METHOD_DONE:
2443 		return "DONE";
2444 	default:
2445 		return "UNKNOWN";
2446 	}
2447 }
2448 
2449 
2450 static const char * eap_sm_decision_txt(EapDecision decision)
2451 {
2452 	switch (decision) {
2453 	case DECISION_FAIL:
2454 		return "FAIL";
2455 	case DECISION_COND_SUCC:
2456 		return "COND_SUCC";
2457 	case DECISION_UNCOND_SUCC:
2458 		return "UNCOND_SUCC";
2459 	default:
2460 		return "UNKNOWN";
2461 	}
2462 }
2463 #endif /* CONFIG_CTRL_IFACE || !CONFIG_NO_STDOUT_DEBUG */
2464 
2465 
2466 #ifdef CONFIG_CTRL_IFACE
2467 
2468 /**
2469  * eap_sm_get_status - Get EAP state machine status
2470  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2471  * @buf: Buffer for status information
2472  * @buflen: Maximum buffer length
2473  * @verbose: Whether to include verbose status information
2474  * Returns: Number of bytes written to buf.
2475  *
2476  * Query EAP state machine for status information. This function fills in a
2477  * text area with current status information from the EAPOL state machine. If
2478  * the buffer (buf) is not large enough, status information will be truncated
2479  * to fit the buffer.
2480  */
2481 int eap_sm_get_status(struct eap_sm *sm, char *buf, size_t buflen, int verbose)
2482 {
2483 	int len, ret;
2484 
2485 	if (sm == NULL)
2486 		return 0;
2487 
2488 	len = os_snprintf(buf, buflen,
2489 			  "EAP state=%s\n",
2490 			  eap_sm_state_txt(sm->EAP_state));
2491 	if (os_snprintf_error(buflen, len))
2492 		return 0;
2493 
2494 	if (sm->selectedMethod != EAP_TYPE_NONE) {
2495 		const char *name;
2496 		if (sm->m) {
2497 			name = sm->m->name;
2498 		} else {
2499 			const struct eap_method *m =
2500 				eap_peer_get_eap_method(EAP_VENDOR_IETF,
2501 							sm->selectedMethod);
2502 			if (m)
2503 				name = m->name;
2504 			else
2505 				name = "?";
2506 		}
2507 		ret = os_snprintf(buf + len, buflen - len,
2508 				  "selectedMethod=%d (EAP-%s)\n",
2509 				  sm->selectedMethod, name);
2510 		if (os_snprintf_error(buflen - len, ret))
2511 			return len;
2512 		len += ret;
2513 
2514 		if (sm->m && sm->m->get_status) {
2515 			len += sm->m->get_status(sm, sm->eap_method_priv,
2516 						 buf + len, buflen - len,
2517 						 verbose);
2518 		}
2519 	}
2520 
2521 	if (verbose) {
2522 		ret = os_snprintf(buf + len, buflen - len,
2523 				  "reqMethod=%d\n"
2524 				  "methodState=%s\n"
2525 				  "decision=%s\n"
2526 				  "ClientTimeout=%d\n",
2527 				  sm->reqMethod,
2528 				  eap_sm_method_state_txt(sm->methodState),
2529 				  eap_sm_decision_txt(sm->decision),
2530 				  sm->ClientTimeout);
2531 		if (os_snprintf_error(buflen - len, ret))
2532 			return len;
2533 		len += ret;
2534 	}
2535 
2536 	return len;
2537 }
2538 #endif /* CONFIG_CTRL_IFACE */
2539 #endif /* EXT_EAP_TRIM */
2540 
2541 static void eap_sm_request(struct eap_sm *sm, enum wpa_ctrl_req_type field,
2542 			   const char *msg, size_t msglen)
2543 {
2544 #if defined(CONFIG_CTRL_IFACE) || !defined(CONFIG_NO_STDOUT_DEBUG)
2545 	struct eap_peer_config *config;
2546 	const char *txt = NULL;
2547 	char *tmp;
2548 
2549 	if (sm == NULL)
2550 		return;
2551 	config = eap_get_config(sm);
2552 	if (config == NULL)
2553 		return;
2554 
2555 	switch (field) {
2556 	case WPA_CTRL_REQ_EAP_IDENTITY:
2557 		config->pending_req_identity++;
2558 		break;
2559 	case WPA_CTRL_REQ_EAP_PASSWORD:
2560 		config->pending_req_password++;
2561 		break;
2562 	case WPA_CTRL_REQ_EAP_NEW_PASSWORD:
2563 		config->pending_req_new_password++;
2564 		break;
2565 	case WPA_CTRL_REQ_EAP_PIN:
2566 		config->pending_req_pin++;
2567 		break;
2568 	case WPA_CTRL_REQ_EAP_OTP:
2569 		if (msg) {
2570 			tmp = os_malloc(msglen + 3);
2571 			if (tmp == NULL)
2572 				return;
2573 			tmp[0] = '[';
2574 			os_memcpy(tmp + 1, msg, msglen);
2575 			tmp[msglen + 1] = ']';
2576 			tmp[msglen + 2] = '\0';
2577 			txt = tmp;
2578 			os_free(config->pending_req_otp);
2579 			config->pending_req_otp = tmp;
2580 			config->pending_req_otp_len = msglen + 3;
2581 		} else {
2582 			if (config->pending_req_otp == NULL)
2583 				return;
2584 			txt = config->pending_req_otp;
2585 		}
2586 		break;
2587 	case WPA_CTRL_REQ_EAP_PASSPHRASE:
2588 		config->pending_req_passphrase++;
2589 		break;
2590 	case WPA_CTRL_REQ_SIM:
2591 		config->pending_req_sim++;
2592 		txt = msg;
2593 		break;
2594 	case WPA_CTRL_REQ_EXT_CERT_CHECK:
2595 		break;
2596 	default:
2597 		return;
2598 	}
2599 
2600 	if (sm->eapol_cb->eap_param_needed)
2601 		sm->eapol_cb->eap_param_needed(sm->eapol_ctx, field, txt);
2602 #endif /* CONFIG_CTRL_IFACE || !CONFIG_NO_STDOUT_DEBUG */
2603 }
2604 
2605 
2606 const char * eap_sm_get_method_name(struct eap_sm *sm)
2607 {
2608 	if (sm->m == NULL)
2609 		return "UNKNOWN";
2610 	return sm->m->name;
2611 }
2612 
2613 
2614 /**
2615  * eap_sm_request_identity - Request identity from user (ctrl_iface)
2616  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2617  *
2618  * EAP methods can call this function to request identity information for the
2619  * current network. This is normally called when the identity is not included
2620  * in the network configuration. The request will be sent to monitor programs
2621  * through the control interface.
2622  */
2623 void eap_sm_request_identity(struct eap_sm *sm)
2624 {
2625 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_IDENTITY, NULL, 0);
2626 }
2627 
2628 
2629 /**
2630  * eap_sm_request_password - Request password from user (ctrl_iface)
2631  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2632  *
2633  * EAP methods can call this function to request password information for the
2634  * current network. This is normally called when the password is not included
2635  * in the network configuration. The request will be sent to monitor programs
2636  * through the control interface.
2637  */
2638 void eap_sm_request_password(struct eap_sm *sm)
2639 {
2640 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_PASSWORD, NULL, 0);
2641 }
2642 
2643 
2644 /**
2645  * eap_sm_request_new_password - Request new password from user (ctrl_iface)
2646  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2647  *
2648  * EAP methods can call this function to request new password information for
2649  * the current network. This is normally called when the EAP method indicates
2650  * that the current password has expired and password change is required. The
2651  * request will be sent to monitor programs through the control interface.
2652  */
2653 void eap_sm_request_new_password(struct eap_sm *sm)
2654 {
2655 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_NEW_PASSWORD, NULL, 0);
2656 }
2657 
2658 
2659 /**
2660  * eap_sm_request_pin - Request SIM or smart card PIN from user (ctrl_iface)
2661  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2662  *
2663  * EAP methods can call this function to request SIM or smart card PIN
2664  * information for the current network. This is normally called when the PIN is
2665  * not included in the network configuration. The request will be sent to
2666  * monitor programs through the control interface.
2667  */
2668 void eap_sm_request_pin(struct eap_sm *sm)
2669 {
2670 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_PIN, NULL, 0);
2671 }
2672 
2673 
2674 /**
2675  * eap_sm_request_otp - Request one time password from user (ctrl_iface)
2676  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2677  * @msg: Message to be displayed to the user when asking for OTP
2678  * @msg_len: Length of the user displayable message
2679  *
2680  * EAP methods can call this function to request open time password (OTP) for
2681  * the current network. The request will be sent to monitor programs through
2682  * the control interface.
2683  */
2684 void eap_sm_request_otp(struct eap_sm *sm, const char *msg, size_t msg_len)
2685 {
2686 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_OTP, msg, msg_len);
2687 }
2688 
2689 
2690 /**
2691  * eap_sm_request_passphrase - Request passphrase from user (ctrl_iface)
2692  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2693  *
2694  * EAP methods can call this function to request passphrase for a private key
2695  * for the current network. This is normally called when the passphrase is not
2696  * included in the network configuration. The request will be sent to monitor
2697  * programs through the control interface.
2698  */
2699 void eap_sm_request_passphrase(struct eap_sm *sm)
2700 {
2701 	eap_sm_request(sm, WPA_CTRL_REQ_EAP_PASSPHRASE, NULL, 0);
2702 }
2703 
2704 
2705 /**
2706  * eap_sm_request_sim - Request external SIM processing
2707  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2708  * @req: EAP method specific request
2709  */
2710 void eap_sm_request_sim(struct eap_sm *sm, const char *req)
2711 {
2712 	eap_sm_request(sm, WPA_CTRL_REQ_SIM, req, os_strlen(req));
2713 }
2714 
2715 
2716 /**
2717  * eap_sm_notify_ctrl_attached - Notification of attached monitor
2718  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2719  *
2720  * Notify EAP state machines that a monitor was attached to the control
2721  * interface to trigger re-sending of pending requests for user input.
2722  */
2723 void eap_sm_notify_ctrl_attached(struct eap_sm *sm)
2724 {
2725 	struct eap_peer_config *config = eap_get_config(sm);
2726 
2727 	if (config == NULL)
2728 		return;
2729 
2730 	/* Re-send any pending requests for user data since a new control
2731 	 * interface was added. This handles cases where the EAP authentication
2732 	 * starts immediately after system startup when the user interface is
2733 	 * not yet running. */
2734 	if (config->pending_req_identity)
2735 		eap_sm_request_identity(sm);
2736 	if (config->pending_req_password)
2737 		eap_sm_request_password(sm);
2738 	if (config->pending_req_new_password)
2739 		eap_sm_request_new_password(sm);
2740 	if (config->pending_req_otp)
2741 		eap_sm_request_otp(sm, NULL, 0);
2742 	if (config->pending_req_pin)
2743 		eap_sm_request_pin(sm);
2744 	if (config->pending_req_passphrase)
2745 		eap_sm_request_passphrase(sm);
2746 }
2747 
2748 
2749 static int eap_allowed_phase2_type(int vendor, int type)
2750 {
2751 	if (vendor == EAP_VENDOR_HOSTAP)
2752 		return 1;
2753 	if (vendor != EAP_VENDOR_IETF)
2754 		return 0;
2755 	return type != EAP_TYPE_PEAP && type != EAP_TYPE_TTLS &&
2756 		type != EAP_TYPE_FAST && type != EAP_TYPE_TEAP;
2757 }
2758 
2759 
2760 /**
2761  * eap_get_phase2_type - Get EAP type for the given EAP phase 2 method name
2762  * @name: EAP method name, e.g., MD5
2763  * @vendor: Buffer for returning EAP Vendor-Id
2764  * Returns: EAP method type or %EAP_TYPE_NONE if not found
2765  *
2766  * This function maps EAP type names into EAP type numbers that are allowed for
2767  * Phase 2, i.e., for tunneled authentication. Phase 2 is used, e.g., with
2768  * EAP-PEAP, EAP-TTLS, and EAP-FAST.
2769  */
2770 u32 eap_get_phase2_type(const char *name, int *vendor)
2771 {
2772 	int v;
2773 	u32 type = eap_peer_get_type(name, &v);
2774 	if (eap_allowed_phase2_type(v, type)) {
2775 		*vendor = v;
2776 		return type;
2777 	}
2778 	*vendor = EAP_VENDOR_IETF;
2779 	return EAP_TYPE_NONE;
2780 }
2781 
2782 
2783 #ifndef EXT_EAP_TRIM
2784 /**
2785  * eap_get_phase2_types - Get list of allowed EAP phase 2 types
2786  * @config: Pointer to a network configuration
2787  * @count: Pointer to a variable to be filled with number of returned EAP types
2788  * Returns: Pointer to allocated type list or %NULL on failure
2789  *
2790  * This function generates an array of allowed EAP phase 2 (tunneled) types for
2791  * the given network configuration.
2792  */
2793 struct eap_method_type * eap_get_phase2_types(struct eap_peer_config *config,
2794 					      size_t *count)
2795 {
2796 	struct eap_method_type *buf;
2797 	u32 method;
2798 	int vendor;
2799 	size_t mcount;
2800 	const struct eap_method *methods, *m;
2801 
2802 	methods = eap_peer_get_methods(&mcount);
2803 	if (methods == NULL)
2804 		return NULL;
2805 	*count = 0;
2806 	buf = os_malloc(mcount * sizeof(struct eap_method_type));
2807 	if (buf == NULL)
2808 		return NULL;
2809 
2810 	for (m = methods; m; m = m->next) {
2811 		vendor = m->vendor;
2812 		method = m->method;
2813 		if (eap_allowed_phase2_type(vendor, method)) {
2814 			if (vendor == EAP_VENDOR_IETF &&
2815 			    method == EAP_TYPE_TLS && config &&
2816 			    !config->phase2_cert.private_key)
2817 				continue;
2818 			buf[*count].vendor = vendor;
2819 			buf[*count].method = method;
2820 			(*count)++;
2821 		}
2822 	}
2823 
2824 	return buf;
2825 }
2826 #endif /* EXT_EAP_TRIM */
2827 
2828 
2829 /**
2830  * eap_set_fast_reauth - Update fast_reauth setting
2831  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2832  * @enabled: 1 = Fast reauthentication is enabled, 0 = Disabled
2833  */
2834 void eap_set_fast_reauth(struct eap_sm *sm, int enabled)
2835 {
2836 	sm->fast_reauth = enabled;
2837 }
2838 
2839 
2840 /**
2841  * eap_set_workaround - Update EAP workarounds setting
2842  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2843  * @workaround: 1 = Enable EAP workarounds, 0 = Disable EAP workarounds
2844  */
2845 void eap_set_workaround(struct eap_sm *sm, unsigned int workaround)
2846 {
2847 	sm->workaround = workaround;
2848 }
2849 
2850 
2851 /**
2852  * eap_get_config - Get current network configuration
2853  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2854  * Returns: Pointer to the current network configuration or %NULL if not found
2855  *
2856  * EAP peer methods should avoid using this function if they can use other
2857  * access functions, like eap_get_config_identity() and
2858  * eap_get_config_password(), that do not require direct access to
2859  * struct eap_peer_config.
2860  */
2861 struct eap_peer_config * eap_get_config(struct eap_sm *sm)
2862 {
2863 	return sm->eapol_cb->get_config(sm->eapol_ctx);
2864 }
2865 
2866 
2867 /**
2868  * eap_get_config_identity - Get identity from the network configuration
2869  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2870  * @len: Buffer for the length of the identity
2871  * Returns: Pointer to the identity or %NULL if not found
2872  */
2873 const u8 * eap_get_config_identity(struct eap_sm *sm, size_t *len)
2874 {
2875 	struct eap_peer_config *config = eap_get_config(sm);
2876 
2877 	if (!config)
2878 		return NULL;
2879 
2880 	if (sm->use_machine_cred) {
2881 		*len = config->machine_identity_len;
2882 		return config->machine_identity;
2883 	}
2884 
2885 	*len = config->identity_len;
2886 	return config->identity;
2887 }
2888 
2889 #ifndef EXT_EAP_TRIM
2890 static int eap_get_ext_password(struct eap_sm *sm,
2891 				struct eap_peer_config *config)
2892 {
2893 	char *name;
2894 	const u8 *password;
2895 	size_t password_len;
2896 
2897 	if (sm->use_machine_cred) {
2898 		password = config->machine_password;
2899 		password_len = config->machine_password_len;
2900 	} else {
2901 		password = config->password;
2902 		password_len = config->password_len;
2903 	}
2904 
2905 	if (!password)
2906 		return -1;
2907 
2908 	name = os_zalloc(password_len + 1);
2909 	if (!name)
2910 		return -1;
2911 	os_memcpy(name, password, password_len);
2912 
2913 	ext_password_free(sm->ext_pw_buf);
2914 	sm->ext_pw_buf = ext_password_get(sm->ext_pw, name);
2915 	os_free(name);
2916 
2917 	return sm->ext_pw_buf == NULL ? -1 : 0;
2918 }
2919 
2920 
2921 /**
2922  * eap_get_config_password - Get password from the network configuration
2923  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2924  * @len: Buffer for the length of the password
2925  * Returns: Pointer to the password or %NULL if not found
2926  */
2927 const u8 * eap_get_config_password(struct eap_sm *sm, size_t *len)
2928 {
2929 	struct eap_peer_config *config = eap_get_config(sm);
2930 
2931 	if (!config)
2932 		return NULL;
2933 
2934 	if ((sm->use_machine_cred &&
2935 	     (config->flags & EAP_CONFIG_FLAGS_EXT_MACHINE_PASSWORD)) ||
2936 	    (!sm->use_machine_cred &&
2937 	     (config->flags & EAP_CONFIG_FLAGS_EXT_PASSWORD))) {
2938 		if (eap_get_ext_password(sm, config) < 0)
2939 			return NULL;
2940 		*len = wpabuf_len(sm->ext_pw_buf);
2941 		return wpabuf_head(sm->ext_pw_buf);
2942 	}
2943 
2944 	if (sm->use_machine_cred) {
2945 		*len = config->machine_password_len;
2946 		return config->machine_password;
2947 	}
2948 
2949 	*len = config->password_len;
2950 	return config->password;
2951 }
2952 
2953 
2954 /**
2955  * eap_get_config_password2 - Get password from the network configuration
2956  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
2957  * @len: Buffer for the length of the password
2958  * @hash: Buffer for returning whether the password is stored as a
2959  * NtPasswordHash instead of plaintext password; can be %NULL if this
2960  * information is not needed
2961  * Returns: Pointer to the password or %NULL if not found
2962  */
2963 const u8 * eap_get_config_password2(struct eap_sm *sm, size_t *len, int *hash)
2964 {
2965 	struct eap_peer_config *config = eap_get_config(sm);
2966 
2967 	if (!config)
2968 		return NULL;
2969 
2970 	if ((sm->use_machine_cred &&
2971 	     (config->flags & EAP_CONFIG_FLAGS_EXT_MACHINE_PASSWORD)) ||
2972 	    (!sm->use_machine_cred &&
2973 	     (config->flags & EAP_CONFIG_FLAGS_EXT_PASSWORD))) {
2974 		if (eap_get_ext_password(sm, config) < 0)
2975 			return NULL;
2976 		if (hash)
2977 			*hash = 0;
2978 		*len = wpabuf_len(sm->ext_pw_buf);
2979 		return wpabuf_head(sm->ext_pw_buf);
2980 	}
2981 
2982 	if (sm->use_machine_cred) {
2983 		*len = config->machine_password_len;
2984 		if (hash)
2985 			*hash = !!(config->flags &
2986 				   EAP_CONFIG_FLAGS_MACHINE_PASSWORD_NTHASH);
2987 		return config->machine_password;
2988 	}
2989 
2990 	*len = config->password_len;
2991 	if (hash)
2992 		*hash = !!(config->flags & EAP_CONFIG_FLAGS_PASSWORD_NTHASH);
2993 	return config->password;
2994 }
2995 
2996 
2997 /**
2998  * eap_get_config_new_password - Get new password from network configuration
2999  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3000  * @len: Buffer for the length of the new password
3001  * Returns: Pointer to the new password or %NULL if not found
3002  */
3003 const u8 * eap_get_config_new_password(struct eap_sm *sm, size_t *len)
3004 {
3005 	struct eap_peer_config *config = eap_get_config(sm);
3006 	if (config == NULL)
3007 		return NULL;
3008 	*len = config->new_password_len;
3009 	return config->new_password;
3010 }
3011 
3012 
3013 /**
3014  * eap_get_config_otp - Get one-time password from the network configuration
3015  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3016  * @len: Buffer for the length of the one-time password
3017  * Returns: Pointer to the one-time password or %NULL if not found
3018  */
3019 const u8 * eap_get_config_otp(struct eap_sm *sm, size_t *len)
3020 {
3021 	struct eap_peer_config *config = eap_get_config(sm);
3022 	if (config == NULL)
3023 		return NULL;
3024 	*len = config->otp_len;
3025 	return config->otp;
3026 }
3027 
3028 
3029 /**
3030  * eap_clear_config_otp - Clear used one-time password
3031  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3032  *
3033  * This function clears a used one-time password (OTP) from the current network
3034  * configuration. This should be called when the OTP has been used and is not
3035  * needed anymore.
3036  */
3037 void eap_clear_config_otp(struct eap_sm *sm)
3038 {
3039 	struct eap_peer_config *config = eap_get_config(sm);
3040 	if (config == NULL)
3041 		return;
3042 	os_memset(config->otp, 0, config->otp_len);
3043 	os_free(config->otp);
3044 	config->otp = NULL;
3045 	config->otp_len = 0;
3046 }
3047 #endif /* EXT_EAP_TRIM */
3048 
3049 /**
3050  * eap_get_config_phase1 - Get phase1 data from the network configuration
3051  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3052  * Returns: Pointer to the phase1 data or %NULL if not found
3053  */
3054 const char * eap_get_config_phase1(struct eap_sm *sm)
3055 {
3056 	struct eap_peer_config *config = eap_get_config(sm);
3057 	if (config == NULL)
3058 		return NULL;
3059 	return config->phase1;
3060 }
3061 
3062 
3063 /**
3064  * eap_get_config_phase2 - Get phase2 data from the network configuration
3065  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3066  * Returns: Pointer to the phase1 data or %NULL if not found
3067  */
3068 const char * eap_get_config_phase2(struct eap_sm *sm)
3069 {
3070 	struct eap_peer_config *config = eap_get_config(sm);
3071 	if (config == NULL)
3072 		return NULL;
3073 	return config->phase2;
3074 }
3075 
3076 
3077 int eap_get_config_fragment_size(struct eap_sm *sm)
3078 {
3079 	struct eap_peer_config *config = eap_get_config(sm);
3080 	if (config == NULL)
3081 		return -1;
3082 	return config->fragment_size;
3083 }
3084 
3085 
3086 /**
3087  * eap_key_available - Get key availability (eapKeyAvailable variable)
3088  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3089  * Returns: 1 if EAP keying material is available, 0 if not
3090  */
3091 int eap_key_available(struct eap_sm *sm)
3092 {
3093 	return sm ? sm->eapKeyAvailable : 0;
3094 }
3095 
3096 
3097 /**
3098  * eap_notify_success - Notify EAP state machine about external success trigger
3099  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3100  *
3101  * This function is called when external event, e.g., successful completion of
3102  * WPA-PSK key handshake, is indicating that EAP state machine should move to
3103  * success state. This is mainly used with security modes that do not use EAP
3104  * state machine (e.g., WPA-PSK).
3105  */
3106 void eap_notify_success(struct eap_sm *sm)
3107 {
3108 	if (sm) {
3109 		sm->decision = DECISION_COND_SUCC;
3110 		sm->EAP_state = EAP_SUCCESS;
3111 	}
3112 }
3113 
3114 
3115 /**
3116  * eap_notify_lower_layer_success - Notification of lower layer success
3117  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3118  *
3119  * Notify EAP state machines that a lower layer has detected a successful
3120  * authentication. This is used to recover from dropped EAP-Success messages.
3121  */
3122 void eap_notify_lower_layer_success(struct eap_sm *sm)
3123 {
3124 	if (sm == NULL)
3125 		return;
3126 
3127 	if (eapol_get_bool(sm, EAPOL_eapSuccess) ||
3128 	    sm->decision == DECISION_FAIL ||
3129 	    (sm->methodState != METHOD_MAY_CONT &&
3130 	     sm->methodState != METHOD_DONE))
3131 		return;
3132 
3133 	if (sm->eapKeyData != NULL)
3134 		sm->eapKeyAvailable = true;
3135 	eapol_set_bool(sm, EAPOL_eapSuccess, true);
3136 	wpa_msg(sm->msg_ctx, MSG_INFO, WPA_EVENT_EAP_SUCCESS
3137 		"EAP authentication completed successfully (based on lower "
3138 		"layer success)");
3139 }
3140 
3141 
3142 /**
3143  * eap_get_eapSessionId - Get Session-Id from EAP state machine
3144  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3145  * @len: Pointer to variable that will be set to number of bytes in the session
3146  * Returns: Pointer to the EAP Session-Id or %NULL on failure
3147  *
3148  * Fetch EAP Session-Id from the EAP state machine. The Session-Id is available
3149  * only after a successful authentication. EAP state machine continues to manage
3150  * the Session-Id and the caller must not change or free the returned data.
3151  */
3152 const u8 * eap_get_eapSessionId(struct eap_sm *sm, size_t *len)
3153 {
3154 	if (sm == NULL || sm->eapSessionId == NULL) {
3155 		*len = 0;
3156 		return NULL;
3157 	}
3158 
3159 	*len = sm->eapSessionIdLen;
3160 	return sm->eapSessionId;
3161 }
3162 
3163 
3164 /**
3165  * eap_get_eapKeyData - Get master session key (MSK) from EAP state machine
3166  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3167  * @len: Pointer to variable that will be set to number of bytes in the key
3168  * Returns: Pointer to the EAP keying data or %NULL on failure
3169  *
3170  * Fetch EAP keying material (MSK, eapKeyData) from the EAP state machine. The
3171  * key is available only after a successful authentication. EAP state machine
3172  * continues to manage the key data and the caller must not change or free the
3173  * returned data.
3174  */
3175 const u8 * eap_get_eapKeyData(struct eap_sm *sm, size_t *len)
3176 {
3177 	if (sm == NULL || sm->eapKeyData == NULL) {
3178 		*len = 0;
3179 		return NULL;
3180 	}
3181 
3182 	*len = sm->eapKeyDataLen;
3183 	return sm->eapKeyData;
3184 }
3185 
3186 
3187 /**
3188  * eap_get_eapKeyData - Get EAP response data
3189  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3190  * Returns: Pointer to the EAP response (eapRespData) or %NULL on failure
3191  *
3192  * Fetch EAP response (eapRespData) from the EAP state machine. This data is
3193  * available when EAP state machine has processed an incoming EAP request. The
3194  * EAP state machine does not maintain a reference to the response after this
3195  * function is called and the caller is responsible for freeing the data.
3196  */
3197 struct wpabuf * eap_get_eapRespData(struct eap_sm *sm)
3198 {
3199 	struct wpabuf *resp;
3200 
3201 	if (sm == NULL || sm->eapRespData == NULL)
3202 		return NULL;
3203 
3204 	resp = sm->eapRespData;
3205 	sm->eapRespData = NULL;
3206 
3207 	return resp;
3208 }
3209 
3210 #ifndef EXT_EAP_TRIM
3211 /**
3212  * eap_sm_register_scard_ctx - Notification of smart card context
3213  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3214  * @ctx: Context data for smart card operations
3215  *
3216  * Notify EAP state machines of context data for smart card operations. This
3217  * context data will be used as a parameter for scard_*() functions.
3218  */
3219 void eap_register_scard_ctx(struct eap_sm *sm, void *ctx)
3220 {
3221 	if (sm)
3222 		sm->scard_ctx = ctx;
3223 }
3224 #endif /* EXT_EAP_TRIM */
3225 
3226 /**
3227  * eap_set_config_blob - Set or add a named configuration blob
3228  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3229  * @blob: New value for the blob
3230  *
3231  * Adds a new configuration blob or replaces the current value of an existing
3232  * blob.
3233  */
3234 void eap_set_config_blob(struct eap_sm *sm, struct wpa_config_blob *blob)
3235 {
3236 #ifndef CONFIG_NO_CONFIG_BLOBS
3237 	sm->eapol_cb->set_config_blob(sm->eapol_ctx, blob);
3238 #endif /* CONFIG_NO_CONFIG_BLOBS */
3239 }
3240 
3241 
3242 /**
3243  * eap_get_config_blob - Get a named configuration blob
3244  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3245  * @name: Name of the blob
3246  * Returns: Pointer to blob data or %NULL if not found
3247  */
3248 const struct wpa_config_blob * eap_get_config_blob(struct eap_sm *sm,
3249 						   const char *name)
3250 {
3251 #ifndef CONFIG_NO_CONFIG_BLOBS
3252 	return sm->eapol_cb->get_config_blob(sm->eapol_ctx, name);
3253 #else /* CONFIG_NO_CONFIG_BLOBS */
3254 	return NULL;
3255 #endif /* CONFIG_NO_CONFIG_BLOBS */
3256 }
3257 
3258 
3259 /**
3260  * eap_set_force_disabled - Set force_disabled flag
3261  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3262  * @disabled: 1 = EAP disabled, 0 = EAP enabled
3263  *
3264  * This function is used to force EAP state machine to be disabled when it is
3265  * not in use (e.g., with WPA-PSK or plaintext connections).
3266  */
3267 void eap_set_force_disabled(struct eap_sm *sm, int disabled)
3268 {
3269 	sm->force_disabled = disabled;
3270 }
3271 
3272 #ifndef EXT_EAP_TRIM
3273 /**
3274  * eap_set_external_sim - Set external_sim flag
3275  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3276  * @external_sim: Whether external SIM/USIM processing is used
3277  */
3278 void eap_set_external_sim(struct eap_sm *sm, int external_sim)
3279 {
3280 	sm->external_sim = external_sim;
3281 }
3282 #endif /* EXT_EAP_TRIM */
3283 
3284  /**
3285  * eap_notify_pending - Notify that EAP method is ready to re-process a request
3286  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3287  *
3288  * An EAP method can perform a pending operation (e.g., to get a response from
3289  * an external process). Once the response is available, this function can be
3290  * used to request EAPOL state machine to retry delivering the previously
3291  * received (and still unanswered) EAP request to EAP state machine.
3292  */
3293 void eap_notify_pending(struct eap_sm *sm)
3294 {
3295 	sm->eapol_cb->notify_pending(sm->eapol_ctx);
3296 }
3297 
3298 
3299 /**
3300  * eap_invalidate_cached_session - Mark cached session data invalid
3301  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3302  */
3303 void eap_invalidate_cached_session(struct eap_sm *sm)
3304 {
3305 	if (sm)
3306 #ifndef EXT_EAP_TRIM
3307 		eap_deinit_prev_method(sm, "invalidate");
3308 #else
3309 		eap_deinit_prev_method(sm, NULL);
3310 #endif /* EXT_EAP_TRIM */
3311 }
3312 
3313 
3314 int eap_is_wps_pbc_enrollee(struct eap_peer_config *conf)
3315 {
3316 	if (conf->identity_len != WSC_ID_ENROLLEE_LEN ||
3317 	    os_memcmp(conf->identity, WSC_ID_ENROLLEE, WSC_ID_ENROLLEE_LEN))
3318 		return 0; /* Not a WPS Enrollee */
3319 
3320 	if (conf->phase1 == NULL || os_strstr(conf->phase1, "pbc=1") == NULL)
3321 		return 0; /* Not using PBC */
3322 
3323 	return 1;
3324 }
3325 
3326 
3327 int eap_is_wps_pin_enrollee(struct eap_peer_config *conf)
3328 {
3329 	if (conf->identity_len != WSC_ID_ENROLLEE_LEN ||
3330 	    os_memcmp(conf->identity, WSC_ID_ENROLLEE, WSC_ID_ENROLLEE_LEN))
3331 		return 0; /* Not a WPS Enrollee */
3332 
3333 	if (conf->phase1 == NULL || os_strstr(conf->phase1, "pin=") == NULL)
3334 		return 0; /* Not using PIN */
3335 
3336 	return 1;
3337 }
3338 
3339 #ifndef EXT_EAP_TRIM
3340 void eap_sm_set_ext_pw_ctx(struct eap_sm *sm, struct ext_password_data *ext)
3341 {
3342 	ext_password_free(sm->ext_pw_buf);
3343 	sm->ext_pw_buf = NULL;
3344 	sm->ext_pw = ext;
3345 }
3346 
3347 
3348 /**
3349  * eap_set_anon_id - Set or add anonymous identity
3350  * @sm: Pointer to EAP state machine allocated with eap_peer_sm_init()
3351  * @id: Anonymous identity (e.g., EAP-SIM pseudonym) or %NULL to clear
3352  * @len: Length of anonymous identity in octets
3353  */
3354 void eap_set_anon_id(struct eap_sm *sm, const u8 *id, size_t len)
3355 {
3356 	if (sm->eapol_cb->set_anon_id)
3357 		sm->eapol_cb->set_anon_id(sm->eapol_ctx, id, len);
3358 }
3359 #endif /* EXT_EAP_TRIM */
3360 
3361 int eap_peer_was_failure_expected(struct eap_sm *sm)
3362 {
3363 	return sm->expected_failure;
3364 }
3365