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