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