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