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