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