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