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