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