EXT PW: Add framework for supporting external password storage
[mech_eap.git] / wpa_supplicant / eapol_test.c
1 /*
2  * WPA Supplicant - test code
3  * Copyright (c) 2003-2012, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  *
8  * IEEE 802.1X Supplicant test code (to be used in place of wpa_supplicant.c.
9  * Not used in production version.
10  */
11
12 #include "includes.h"
13 #include <assert.h>
14
15 #include "common.h"
16 #include "utils/ext_password.h"
17 #include "config.h"
18 #include "eapol_supp/eapol_supp_sm.h"
19 #include "eap_peer/eap.h"
20 #include "eap_server/eap_methods.h"
21 #include "eloop.h"
22 #include "utils/base64.h"
23 #include "rsn_supp/wpa.h"
24 #include "eap_peer/eap_i.h"
25 #include "wpa_supplicant_i.h"
26 #include "radius/radius.h"
27 #include "radius/radius_client.h"
28 #include "common/wpa_ctrl.h"
29 #include "ctrl_iface.h"
30 #include "pcsc_funcs.h"
31
32
33 extern int wpa_debug_level;
34 extern int wpa_debug_show_keys;
35
36 struct wpa_driver_ops *wpa_drivers[] = { NULL };
37
38
39 struct extra_radius_attr {
40         u8 type;
41         char syntax;
42         char *data;
43         struct extra_radius_attr *next;
44 };
45
46 struct eapol_test_data {
47         struct wpa_supplicant *wpa_s;
48
49         int eapol_test_num_reauths;
50         int no_mppe_keys;
51         int num_mppe_ok, num_mppe_mismatch;
52
53         u8 radius_identifier;
54         struct radius_msg *last_recv_radius;
55         struct in_addr own_ip_addr;
56         struct radius_client_data *radius;
57         struct hostapd_radius_servers *radius_conf;
58
59         u8 *last_eap_radius; /* last received EAP Response from Authentication
60                               * Server */
61         size_t last_eap_radius_len;
62
63         u8 authenticator_pmk[PMK_LEN];
64         size_t authenticator_pmk_len;
65         int radius_access_accept_received;
66         int radius_access_reject_received;
67         int auth_timed_out;
68
69         u8 *eap_identity;
70         size_t eap_identity_len;
71
72         char *connect_info;
73         u8 own_addr[ETH_ALEN];
74         struct extra_radius_attr *extra_attrs;
75
76         FILE *server_cert_file;
77 };
78
79 static struct eapol_test_data eapol_test;
80
81
82 static void send_eap_request_identity(void *eloop_ctx, void *timeout_ctx);
83
84
85 static void hostapd_logger_cb(void *ctx, const u8 *addr, unsigned int module,
86                               int level, const char *txt, size_t len)
87 {
88         if (addr)
89                 wpa_printf(MSG_DEBUG, "STA " MACSTR ": %s\n",
90                            MAC2STR(addr), txt);
91         else
92                 wpa_printf(MSG_DEBUG, "%s", txt);
93 }
94
95
96 static int add_extra_attr(struct radius_msg *msg,
97                           struct extra_radius_attr *attr)
98 {
99         size_t len;
100         char *pos;
101         u32 val;
102         char buf[128];
103
104         switch (attr->syntax) {
105         case 's':
106                 os_snprintf(buf, sizeof(buf), "%s", attr->data);
107                 len = os_strlen(buf);
108                 break;
109         case 'n':
110                 buf[0] = '\0';
111                 len = 1;
112                 break;
113         case 'x':
114                 pos = attr->data;
115                 if (pos[0] == '0' && pos[1] == 'x')
116                         pos += 2;
117                 len = os_strlen(pos);
118                 if ((len & 1) || (len / 2) > sizeof(buf)) {
119                         printf("Invalid extra attribute hexstring\n");
120                         return -1;
121                 }
122                 len /= 2;
123                 if (hexstr2bin(pos, (u8 *) buf, len) < 0) {
124                         printf("Invalid extra attribute hexstring\n");
125                         return -1;
126                 }
127                 break;
128         case 'd':
129                 val = htonl(atoi(attr->data));
130                 os_memcpy(buf, &val, 4);
131                 len = 4;
132                 break;
133         default:
134                 printf("Incorrect extra attribute syntax specification\n");
135                 return -1;
136         }
137
138         if (!radius_msg_add_attr(msg, attr->type, (u8 *) buf, len)) {
139                 printf("Could not add attribute %d\n", attr->type);
140                 return -1;
141         }
142
143         return 0;
144 }
145
146
147 static int add_extra_attrs(struct radius_msg *msg,
148                            struct extra_radius_attr *attrs)
149 {
150         struct extra_radius_attr *p;
151         for (p = attrs; p; p = p->next) {
152                 if (add_extra_attr(msg, p) < 0)
153                         return -1;
154         }
155         return 0;
156 }
157
158
159 static struct extra_radius_attr *
160 find_extra_attr(struct extra_radius_attr *attrs, u8 type)
161 {
162         struct extra_radius_attr *p;
163         for (p = attrs; p; p = p->next) {
164                 if (p->type == type)
165                         return p;
166         }
167         return NULL;
168 }
169
170
171 static void ieee802_1x_encapsulate_radius(struct eapol_test_data *e,
172                                           const u8 *eap, size_t len)
173 {
174         struct radius_msg *msg;
175         char buf[128];
176         const struct eap_hdr *hdr;
177         const u8 *pos;
178
179         wpa_printf(MSG_DEBUG, "Encapsulating EAP message into a RADIUS "
180                    "packet");
181
182         e->radius_identifier = radius_client_get_id(e->radius);
183         msg = radius_msg_new(RADIUS_CODE_ACCESS_REQUEST,
184                              e->radius_identifier);
185         if (msg == NULL) {
186                 printf("Could not create net RADIUS packet\n");
187                 return;
188         }
189
190         radius_msg_make_authenticator(msg, (u8 *) e, sizeof(*e));
191
192         hdr = (const struct eap_hdr *) eap;
193         pos = (const u8 *) (hdr + 1);
194         if (len > sizeof(*hdr) && hdr->code == EAP_CODE_RESPONSE &&
195             pos[0] == EAP_TYPE_IDENTITY) {
196                 pos++;
197                 os_free(e->eap_identity);
198                 e->eap_identity_len = len - sizeof(*hdr) - 1;
199                 e->eap_identity = os_malloc(e->eap_identity_len);
200                 if (e->eap_identity) {
201                         os_memcpy(e->eap_identity, pos, e->eap_identity_len);
202                         wpa_hexdump(MSG_DEBUG, "Learned identity from "
203                                     "EAP-Response-Identity",
204                                     e->eap_identity, e->eap_identity_len);
205                 }
206         }
207
208         if (e->eap_identity &&
209             !radius_msg_add_attr(msg, RADIUS_ATTR_USER_NAME,
210                                  e->eap_identity, e->eap_identity_len)) {
211                 printf("Could not add User-Name\n");
212                 goto fail;
213         }
214
215         if (!find_extra_attr(e->extra_attrs, RADIUS_ATTR_NAS_IP_ADDRESS) &&
216             !radius_msg_add_attr(msg, RADIUS_ATTR_NAS_IP_ADDRESS,
217                                  (u8 *) &e->own_ip_addr, 4)) {
218                 printf("Could not add NAS-IP-Address\n");
219                 goto fail;
220         }
221
222         os_snprintf(buf, sizeof(buf), RADIUS_802_1X_ADDR_FORMAT,
223                     MAC2STR(e->wpa_s->own_addr));
224         if (!find_extra_attr(e->extra_attrs, RADIUS_ATTR_CALLING_STATION_ID)
225             &&
226             !radius_msg_add_attr(msg, RADIUS_ATTR_CALLING_STATION_ID,
227                                  (u8 *) buf, os_strlen(buf))) {
228                 printf("Could not add Calling-Station-Id\n");
229                 goto fail;
230         }
231
232         /* TODO: should probably check MTU from driver config; 2304 is max for
233          * IEEE 802.11, but use 1400 to avoid problems with too large packets
234          */
235         if (!find_extra_attr(e->extra_attrs, RADIUS_ATTR_FRAMED_MTU) &&
236             !radius_msg_add_attr_int32(msg, RADIUS_ATTR_FRAMED_MTU, 1400)) {
237                 printf("Could not add Framed-MTU\n");
238                 goto fail;
239         }
240
241         if (!find_extra_attr(e->extra_attrs, RADIUS_ATTR_NAS_PORT_TYPE) &&
242             !radius_msg_add_attr_int32(msg, RADIUS_ATTR_NAS_PORT_TYPE,
243                                        RADIUS_NAS_PORT_TYPE_IEEE_802_11)) {
244                 printf("Could not add NAS-Port-Type\n");
245                 goto fail;
246         }
247
248         os_snprintf(buf, sizeof(buf), "%s", e->connect_info);
249         if (!find_extra_attr(e->extra_attrs, RADIUS_ATTR_CONNECT_INFO) &&
250             !radius_msg_add_attr(msg, RADIUS_ATTR_CONNECT_INFO,
251                                  (u8 *) buf, os_strlen(buf))) {
252                 printf("Could not add Connect-Info\n");
253                 goto fail;
254         }
255
256         if (add_extra_attrs(msg, e->extra_attrs) < 0)
257                 goto fail;
258
259         if (eap && !radius_msg_add_eap(msg, eap, len)) {
260                 printf("Could not add EAP-Message\n");
261                 goto fail;
262         }
263
264         /* State attribute must be copied if and only if this packet is
265          * Access-Request reply to the previous Access-Challenge */
266         if (e->last_recv_radius &&
267             radius_msg_get_hdr(e->last_recv_radius)->code ==
268             RADIUS_CODE_ACCESS_CHALLENGE) {
269                 int res = radius_msg_copy_attr(msg, e->last_recv_radius,
270                                                RADIUS_ATTR_STATE);
271                 if (res < 0) {
272                         printf("Could not copy State attribute from previous "
273                                "Access-Challenge\n");
274                         goto fail;
275                 }
276                 if (res > 0) {
277                         wpa_printf(MSG_DEBUG, "  Copied RADIUS State "
278                                    "Attribute");
279                 }
280         }
281
282         if (radius_client_send(e->radius, msg, RADIUS_AUTH, e->wpa_s->own_addr)
283             < 0)
284                 goto fail;
285         return;
286
287  fail:
288         radius_msg_free(msg);
289 }
290
291
292 static int eapol_test_eapol_send(void *ctx, int type, const u8 *buf,
293                                  size_t len)
294 {
295         printf("WPA: eapol_test_eapol_send(type=%d len=%lu)\n",
296                type, (unsigned long) len);
297         if (type == IEEE802_1X_TYPE_EAP_PACKET) {
298                 wpa_hexdump(MSG_DEBUG, "TX EAP -> RADIUS", buf, len);
299                 ieee802_1x_encapsulate_radius(&eapol_test, buf, len);
300         }
301         return 0;
302 }
303
304
305 static void eapol_test_set_config_blob(void *ctx,
306                                        struct wpa_config_blob *blob)
307 {
308         struct eapol_test_data *e = ctx;
309         wpa_config_set_blob(e->wpa_s->conf, blob);
310 }
311
312
313 static const struct wpa_config_blob *
314 eapol_test_get_config_blob(void *ctx, const char *name)
315 {
316         struct eapol_test_data *e = ctx;
317         return wpa_config_get_blob(e->wpa_s->conf, name);
318 }
319
320
321 static void eapol_test_eapol_done_cb(void *ctx)
322 {
323         printf("WPA: EAPOL processing complete\n");
324 }
325
326
327 static void eapol_sm_reauth(void *eloop_ctx, void *timeout_ctx)
328 {
329         struct eapol_test_data *e = eloop_ctx;
330         printf("\n\n\n\n\neapol_test: Triggering EAP reauthentication\n\n");
331         e->radius_access_accept_received = 0;
332         send_eap_request_identity(e->wpa_s, NULL);
333 }
334
335
336 static int eapol_test_compare_pmk(struct eapol_test_data *e)
337 {
338         u8 pmk[PMK_LEN];
339         int ret = 1;
340
341         if (eapol_sm_get_key(e->wpa_s->eapol, pmk, PMK_LEN) == 0) {
342                 wpa_hexdump(MSG_DEBUG, "PMK from EAPOL", pmk, PMK_LEN);
343                 if (os_memcmp(pmk, e->authenticator_pmk, PMK_LEN) != 0) {
344                         printf("WARNING: PMK mismatch\n");
345                         wpa_hexdump(MSG_DEBUG, "PMK from AS",
346                                     e->authenticator_pmk, PMK_LEN);
347                 } else if (e->radius_access_accept_received)
348                         ret = 0;
349         } else if (e->authenticator_pmk_len == 16 &&
350                    eapol_sm_get_key(e->wpa_s->eapol, pmk, 16) == 0) {
351                 wpa_hexdump(MSG_DEBUG, "LEAP PMK from EAPOL", pmk, 16);
352                 if (os_memcmp(pmk, e->authenticator_pmk, 16) != 0) {
353                         printf("WARNING: PMK mismatch\n");
354                         wpa_hexdump(MSG_DEBUG, "PMK from AS",
355                                     e->authenticator_pmk, 16);
356                 } else if (e->radius_access_accept_received)
357                         ret = 0;
358         } else if (e->radius_access_accept_received && e->no_mppe_keys) {
359                 /* No keying material expected */
360                 ret = 0;
361         }
362
363         if (ret && !e->no_mppe_keys)
364                 e->num_mppe_mismatch++;
365         else if (!e->no_mppe_keys)
366                 e->num_mppe_ok++;
367
368         return ret;
369 }
370
371
372 static void eapol_sm_cb(struct eapol_sm *eapol, int success, void *ctx)
373 {
374         struct eapol_test_data *e = ctx;
375         printf("eapol_sm_cb: success=%d\n", success);
376         e->eapol_test_num_reauths--;
377         if (e->eapol_test_num_reauths < 0)
378                 eloop_terminate();
379         else {
380                 eapol_test_compare_pmk(e);
381                 eloop_register_timeout(0, 100000, eapol_sm_reauth, e, NULL);
382         }
383 }
384
385
386 static void eapol_test_write_cert(FILE *f, const char *subject,
387                                   const struct wpabuf *cert)
388 {
389         unsigned char *encoded;
390
391         encoded = base64_encode(wpabuf_head(cert), wpabuf_len(cert), NULL);
392         if (encoded == NULL)
393                 return;
394         fprintf(f, "%s\n-----BEGIN CERTIFICATE-----\n%s"
395                 "-----END CERTIFICATE-----\n\n", subject, encoded);
396         os_free(encoded);
397 }
398
399
400 static void eapol_test_cert_cb(void *ctx, int depth, const char *subject,
401                                const char *cert_hash,
402                                const struct wpabuf *cert)
403 {
404         struct eapol_test_data *e = ctx;
405
406         wpa_msg(e->wpa_s, MSG_INFO, WPA_EVENT_EAP_PEER_CERT
407                 "depth=%d subject='%s'%s%s",
408                 depth, subject,
409                 cert_hash ? " hash=" : "",
410                 cert_hash ? cert_hash : "");
411
412         if (cert) {
413                 char *cert_hex;
414                 size_t len = wpabuf_len(cert) * 2 + 1;
415                 cert_hex = os_malloc(len);
416                 if (cert_hex) {
417                         wpa_snprintf_hex(cert_hex, len, wpabuf_head(cert),
418                                          wpabuf_len(cert));
419                         wpa_msg_ctrl(e->wpa_s, MSG_INFO,
420                                      WPA_EVENT_EAP_PEER_CERT
421                                      "depth=%d subject='%s' cert=%s",
422                                      depth, subject, cert_hex);
423                         os_free(cert_hex);
424                 }
425
426                 if (e->server_cert_file)
427                         eapol_test_write_cert(e->server_cert_file,
428                                               subject, cert);
429         }
430 }
431
432
433 static int test_eapol(struct eapol_test_data *e, struct wpa_supplicant *wpa_s,
434                       struct wpa_ssid *ssid)
435 {
436         struct eapol_config eapol_conf;
437         struct eapol_ctx *ctx;
438
439         ctx = os_zalloc(sizeof(*ctx));
440         if (ctx == NULL) {
441                 printf("Failed to allocate EAPOL context.\n");
442                 return -1;
443         }
444         ctx->ctx = e;
445         ctx->msg_ctx = wpa_s;
446         ctx->scard_ctx = wpa_s->scard;
447         ctx->cb = eapol_sm_cb;
448         ctx->cb_ctx = e;
449         ctx->eapol_send_ctx = wpa_s;
450         ctx->preauth = 0;
451         ctx->eapol_done_cb = eapol_test_eapol_done_cb;
452         ctx->eapol_send = eapol_test_eapol_send;
453         ctx->set_config_blob = eapol_test_set_config_blob;
454         ctx->get_config_blob = eapol_test_get_config_blob;
455         ctx->opensc_engine_path = wpa_s->conf->opensc_engine_path;
456         ctx->pkcs11_engine_path = wpa_s->conf->pkcs11_engine_path;
457         ctx->pkcs11_module_path = wpa_s->conf->pkcs11_module_path;
458         ctx->cert_cb = eapol_test_cert_cb;
459         ctx->cert_in_cb = 1;
460
461         wpa_s->eapol = eapol_sm_init(ctx);
462         if (wpa_s->eapol == NULL) {
463                 os_free(ctx);
464                 printf("Failed to initialize EAPOL state machines.\n");
465                 return -1;
466         }
467
468         wpa_s->current_ssid = ssid;
469         os_memset(&eapol_conf, 0, sizeof(eapol_conf));
470         eapol_conf.accept_802_1x_keys = 1;
471         eapol_conf.required_keys = 0;
472         eapol_conf.fast_reauth = wpa_s->conf->fast_reauth;
473         eapol_conf.workaround = ssid->eap_workaround;
474         eapol_sm_notify_config(wpa_s->eapol, &ssid->eap, &eapol_conf);
475         eapol_sm_register_scard_ctx(wpa_s->eapol, wpa_s->scard);
476
477
478         eapol_sm_notify_portValid(wpa_s->eapol, FALSE);
479         /* 802.1X::portControl = Auto */
480         eapol_sm_notify_portEnabled(wpa_s->eapol, TRUE);
481
482         return 0;
483 }
484
485
486 static void test_eapol_clean(struct eapol_test_data *e,
487                              struct wpa_supplicant *wpa_s)
488 {
489         struct extra_radius_attr *p, *prev;
490
491         radius_client_deinit(e->radius);
492         os_free(e->last_eap_radius);
493         radius_msg_free(e->last_recv_radius);
494         e->last_recv_radius = NULL;
495         os_free(e->eap_identity);
496         e->eap_identity = NULL;
497         eapol_sm_deinit(wpa_s->eapol);
498         wpa_s->eapol = NULL;
499         if (e->radius_conf && e->radius_conf->auth_server) {
500                 os_free(e->radius_conf->auth_server->shared_secret);
501                 os_free(e->radius_conf->auth_server);
502         }
503         os_free(e->radius_conf);
504         e->radius_conf = NULL;
505         scard_deinit(wpa_s->scard);
506         if (wpa_s->ctrl_iface) {
507                 wpa_supplicant_ctrl_iface_deinit(wpa_s->ctrl_iface);
508                 wpa_s->ctrl_iface = NULL;
509         }
510
511         ext_password_deinit(wpa_s->ext_pw);
512         wpa_s->ext_pw = NULL;
513
514         wpa_config_free(wpa_s->conf);
515
516         p = e->extra_attrs;
517         while (p) {
518                 prev = p;
519                 p = p->next;
520                 os_free(prev);
521         }
522 }
523
524
525 static void send_eap_request_identity(void *eloop_ctx, void *timeout_ctx)
526 {
527         struct wpa_supplicant *wpa_s = eloop_ctx;
528         u8 buf[100], *pos;
529         struct ieee802_1x_hdr *hdr;
530         struct eap_hdr *eap;
531
532         hdr = (struct ieee802_1x_hdr *) buf;
533         hdr->version = EAPOL_VERSION;
534         hdr->type = IEEE802_1X_TYPE_EAP_PACKET;
535         hdr->length = htons(5);
536
537         eap = (struct eap_hdr *) (hdr + 1);
538         eap->code = EAP_CODE_REQUEST;
539         eap->identifier = 0;
540         eap->length = htons(5);
541         pos = (u8 *) (eap + 1);
542         *pos = EAP_TYPE_IDENTITY;
543
544         printf("Sending fake EAP-Request-Identity\n");
545         eapol_sm_rx_eapol(wpa_s->eapol, wpa_s->bssid, buf,
546                           sizeof(*hdr) + 5);
547 }
548
549
550 static void eapol_test_timeout(void *eloop_ctx, void *timeout_ctx)
551 {
552         struct eapol_test_data *e = eloop_ctx;
553         printf("EAPOL test timed out\n");
554         e->auth_timed_out = 1;
555         eloop_terminate();
556 }
557
558
559 static char *eap_type_text(u8 type)
560 {
561         switch (type) {
562         case EAP_TYPE_IDENTITY: return "Identity";
563         case EAP_TYPE_NOTIFICATION: return "Notification";
564         case EAP_TYPE_NAK: return "Nak";
565         case EAP_TYPE_TLS: return "TLS";
566         case EAP_TYPE_TTLS: return "TTLS";
567         case EAP_TYPE_PEAP: return "PEAP";
568         case EAP_TYPE_SIM: return "SIM";
569         case EAP_TYPE_GTC: return "GTC";
570         case EAP_TYPE_MD5: return "MD5";
571         case EAP_TYPE_OTP: return "OTP";
572         case EAP_TYPE_FAST: return "FAST";
573         case EAP_TYPE_SAKE: return "SAKE";
574         case EAP_TYPE_PSK: return "PSK";
575         default: return "Unknown";
576         }
577 }
578
579
580 static void ieee802_1x_decapsulate_radius(struct eapol_test_data *e)
581 {
582         u8 *eap;
583         size_t len;
584         struct eap_hdr *hdr;
585         int eap_type = -1;
586         char buf[64];
587         struct radius_msg *msg;
588
589         if (e->last_recv_radius == NULL)
590                 return;
591
592         msg = e->last_recv_radius;
593
594         eap = radius_msg_get_eap(msg, &len);
595         if (eap == NULL) {
596                 /* draft-aboba-radius-rfc2869bis-20.txt, Chap. 2.6.3:
597                  * RADIUS server SHOULD NOT send Access-Reject/no EAP-Message
598                  * attribute */
599                 wpa_printf(MSG_DEBUG, "could not extract "
600                                "EAP-Message from RADIUS message");
601                 os_free(e->last_eap_radius);
602                 e->last_eap_radius = NULL;
603                 e->last_eap_radius_len = 0;
604                 return;
605         }
606
607         if (len < sizeof(*hdr)) {
608                 wpa_printf(MSG_DEBUG, "too short EAP packet "
609                                "received from authentication server");
610                 os_free(eap);
611                 return;
612         }
613
614         if (len > sizeof(*hdr))
615                 eap_type = eap[sizeof(*hdr)];
616
617         hdr = (struct eap_hdr *) eap;
618         switch (hdr->code) {
619         case EAP_CODE_REQUEST:
620                 os_snprintf(buf, sizeof(buf), "EAP-Request-%s (%d)",
621                             eap_type >= 0 ? eap_type_text(eap_type) : "??",
622                             eap_type);
623                 break;
624         case EAP_CODE_RESPONSE:
625                 os_snprintf(buf, sizeof(buf), "EAP Response-%s (%d)",
626                             eap_type >= 0 ? eap_type_text(eap_type) : "??",
627                             eap_type);
628                 break;
629         case EAP_CODE_SUCCESS:
630                 os_strlcpy(buf, "EAP Success", sizeof(buf));
631                 /* LEAP uses EAP Success within an authentication, so must not
632                  * stop here with eloop_terminate(); */
633                 break;
634         case EAP_CODE_FAILURE:
635                 os_strlcpy(buf, "EAP Failure", sizeof(buf));
636                 eloop_terminate();
637                 break;
638         default:
639                 os_strlcpy(buf, "unknown EAP code", sizeof(buf));
640                 wpa_hexdump(MSG_DEBUG, "Decapsulated EAP packet", eap, len);
641                 break;
642         }
643         wpa_printf(MSG_DEBUG, "decapsulated EAP packet (code=%d "
644                        "id=%d len=%d) from RADIUS server: %s",
645                       hdr->code, hdr->identifier, ntohs(hdr->length), buf);
646
647         /* sta->eapol_sm->be_auth.idFromServer = hdr->identifier; */
648
649         os_free(e->last_eap_radius);
650         e->last_eap_radius = eap;
651         e->last_eap_radius_len = len;
652
653         {
654                 struct ieee802_1x_hdr *dot1x;
655                 dot1x = os_malloc(sizeof(*dot1x) + len);
656                 assert(dot1x != NULL);
657                 dot1x->version = EAPOL_VERSION;
658                 dot1x->type = IEEE802_1X_TYPE_EAP_PACKET;
659                 dot1x->length = htons(len);
660                 os_memcpy((u8 *) (dot1x + 1), eap, len);
661                 eapol_sm_rx_eapol(e->wpa_s->eapol, e->wpa_s->bssid,
662                                   (u8 *) dot1x, sizeof(*dot1x) + len);
663                 os_free(dot1x);
664         }
665 }
666
667
668 static void ieee802_1x_get_keys(struct eapol_test_data *e,
669                                 struct radius_msg *msg, struct radius_msg *req,
670                                 const u8 *shared_secret,
671                                 size_t shared_secret_len)
672 {
673         struct radius_ms_mppe_keys *keys;
674
675         keys = radius_msg_get_ms_keys(msg, req, shared_secret,
676                                       shared_secret_len);
677         if (keys && keys->send == NULL && keys->recv == NULL) {
678                 os_free(keys);
679                 keys = radius_msg_get_cisco_keys(msg, req, shared_secret,
680                                                  shared_secret_len);
681         }
682
683         if (keys) {
684                 if (keys->send) {
685                         wpa_hexdump(MSG_DEBUG, "MS-MPPE-Send-Key (sign)",
686                                     keys->send, keys->send_len);
687                 }
688                 if (keys->recv) {
689                         wpa_hexdump(MSG_DEBUG, "MS-MPPE-Recv-Key (crypt)",
690                                     keys->recv, keys->recv_len);
691                         e->authenticator_pmk_len =
692                                 keys->recv_len > PMK_LEN ? PMK_LEN :
693                                 keys->recv_len;
694                         os_memcpy(e->authenticator_pmk, keys->recv,
695                                   e->authenticator_pmk_len);
696                         if (e->authenticator_pmk_len == 16 && keys->send &&
697                             keys->send_len == 16) {
698                                 /* MS-CHAP-v2 derives 16 octet keys */
699                                 wpa_printf(MSG_DEBUG, "Use MS-MPPE-Send-Key "
700                                            "to extend PMK to 32 octets");
701                                 os_memcpy(e->authenticator_pmk +
702                                           e->authenticator_pmk_len,
703                                           keys->send, keys->send_len);
704                                 e->authenticator_pmk_len += keys->send_len;
705                         }
706                 }
707
708                 os_free(keys->send);
709                 os_free(keys->recv);
710                 os_free(keys);
711         }
712 }
713
714
715 /* Process the RADIUS frames from Authentication Server */
716 static RadiusRxResult
717 ieee802_1x_receive_auth(struct radius_msg *msg, struct radius_msg *req,
718                         const u8 *shared_secret, size_t shared_secret_len,
719                         void *data)
720 {
721         struct eapol_test_data *e = data;
722         struct radius_hdr *hdr = radius_msg_get_hdr(msg);
723
724         /* RFC 2869, Ch. 5.13: valid Message-Authenticator attribute MUST be
725          * present when packet contains an EAP-Message attribute */
726         if (hdr->code == RADIUS_CODE_ACCESS_REJECT &&
727             radius_msg_get_attr(msg, RADIUS_ATTR_MESSAGE_AUTHENTICATOR, NULL,
728                                 0) < 0 &&
729             radius_msg_get_attr(msg, RADIUS_ATTR_EAP_MESSAGE, NULL, 0) < 0) {
730                 wpa_printf(MSG_DEBUG, "Allowing RADIUS "
731                               "Access-Reject without Message-Authenticator "
732                               "since it does not include EAP-Message\n");
733         } else if (radius_msg_verify(msg, shared_secret, shared_secret_len,
734                                      req, 1)) {
735                 printf("Incoming RADIUS packet did not have correct "
736                        "Message-Authenticator - dropped\n");
737                 return RADIUS_RX_UNKNOWN;
738         }
739
740         if (hdr->code != RADIUS_CODE_ACCESS_ACCEPT &&
741             hdr->code != RADIUS_CODE_ACCESS_REJECT &&
742             hdr->code != RADIUS_CODE_ACCESS_CHALLENGE) {
743                 printf("Unknown RADIUS message code\n");
744                 return RADIUS_RX_UNKNOWN;
745         }
746
747         e->radius_identifier = -1;
748         wpa_printf(MSG_DEBUG, "RADIUS packet matching with station");
749
750         radius_msg_free(e->last_recv_radius);
751         e->last_recv_radius = msg;
752
753         switch (hdr->code) {
754         case RADIUS_CODE_ACCESS_ACCEPT:
755                 e->radius_access_accept_received = 1;
756                 ieee802_1x_get_keys(e, msg, req, shared_secret,
757                                     shared_secret_len);
758                 break;
759         case RADIUS_CODE_ACCESS_REJECT:
760                 e->radius_access_reject_received = 1;
761                 break;
762         }
763
764         ieee802_1x_decapsulate_radius(e);
765
766         if ((hdr->code == RADIUS_CODE_ACCESS_ACCEPT &&
767              e->eapol_test_num_reauths < 0) ||
768             hdr->code == RADIUS_CODE_ACCESS_REJECT) {
769                 eloop_terminate();
770         }
771
772         return RADIUS_RX_QUEUED;
773 }
774
775
776 static void wpa_init_conf(struct eapol_test_data *e,
777                           struct wpa_supplicant *wpa_s, const char *authsrv,
778                           int port, const char *secret,
779                           const char *cli_addr)
780 {
781         struct hostapd_radius_server *as;
782         int res;
783
784         wpa_s->bssid[5] = 1;
785         os_memcpy(wpa_s->own_addr, e->own_addr, ETH_ALEN);
786         e->own_ip_addr.s_addr = htonl((127 << 24) | 1);
787         os_strlcpy(wpa_s->ifname, "test", sizeof(wpa_s->ifname));
788
789         e->radius_conf = os_zalloc(sizeof(struct hostapd_radius_servers));
790         assert(e->radius_conf != NULL);
791         e->radius_conf->num_auth_servers = 1;
792         as = os_zalloc(sizeof(struct hostapd_radius_server));
793         assert(as != NULL);
794 #if defined(CONFIG_NATIVE_WINDOWS) || defined(CONFIG_ANSI_C_EXTRA)
795         {
796                 int a[4];
797                 u8 *pos;
798                 sscanf(authsrv, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]);
799                 pos = (u8 *) &as->addr.u.v4;
800                 *pos++ = a[0];
801                 *pos++ = a[1];
802                 *pos++ = a[2];
803                 *pos++ = a[3];
804         }
805 #else /* CONFIG_NATIVE_WINDOWS or CONFIG_ANSI_C_EXTRA */
806         inet_aton(authsrv, &as->addr.u.v4);
807 #endif /* CONFIG_NATIVE_WINDOWS or CONFIG_ANSI_C_EXTRA */
808         as->addr.af = AF_INET;
809         as->port = port;
810         as->shared_secret = (u8 *) os_strdup(secret);
811         as->shared_secret_len = os_strlen(secret);
812         e->radius_conf->auth_server = as;
813         e->radius_conf->auth_servers = as;
814         e->radius_conf->msg_dumps = 1;
815         if (cli_addr) {
816                 if (hostapd_parse_ip_addr(cli_addr,
817                                           &e->radius_conf->client_addr) == 0)
818                         e->radius_conf->force_client_addr = 1;
819                 else {
820                         wpa_printf(MSG_ERROR, "Invalid IP address '%s'",
821                                    cli_addr);
822                         assert(0);
823                 }
824         }
825
826         e->radius = radius_client_init(wpa_s, e->radius_conf);
827         assert(e->radius != NULL);
828
829         res = radius_client_register(e->radius, RADIUS_AUTH,
830                                      ieee802_1x_receive_auth, e);
831         assert(res == 0);
832 }
833
834
835 static int scard_test(void)
836 {
837         struct scard_data *scard;
838         size_t len;
839         char imsi[20];
840         unsigned char _rand[16];
841 #ifdef PCSC_FUNCS
842         unsigned char sres[4];
843         unsigned char kc[8];
844 #endif /* PCSC_FUNCS */
845 #define num_triplets 5
846         unsigned char rand_[num_triplets][16];
847         unsigned char sres_[num_triplets][4];
848         unsigned char kc_[num_triplets][8];
849         int i, res;
850         size_t j;
851
852 #define AKA_RAND_LEN 16
853 #define AKA_AUTN_LEN 16
854 #define AKA_AUTS_LEN 14
855 #define RES_MAX_LEN 16
856 #define IK_LEN 16
857 #define CK_LEN 16
858         unsigned char aka_rand[AKA_RAND_LEN];
859         unsigned char aka_autn[AKA_AUTN_LEN];
860         unsigned char aka_auts[AKA_AUTS_LEN];
861         unsigned char aka_res[RES_MAX_LEN];
862         size_t aka_res_len;
863         unsigned char aka_ik[IK_LEN];
864         unsigned char aka_ck[CK_LEN];
865
866         scard = scard_init(SCARD_TRY_BOTH, NULL);
867         if (scard == NULL)
868                 return -1;
869         if (scard_set_pin(scard, "1234")) {
870                 wpa_printf(MSG_WARNING, "PIN validation failed");
871                 scard_deinit(scard);
872                 return -1;
873         }
874
875         len = sizeof(imsi);
876         if (scard_get_imsi(scard, imsi, &len))
877                 goto failed;
878         wpa_hexdump_ascii(MSG_DEBUG, "SCARD: IMSI", (u8 *) imsi, len);
879         /* NOTE: Permanent Username: 1 | IMSI */
880
881         wpa_printf(MSG_DEBUG, "SCARD: MNC length %d",
882                    scard_get_mnc_len(scard));
883
884         os_memset(_rand, 0, sizeof(_rand));
885         if (scard_gsm_auth(scard, _rand, sres, kc))
886                 goto failed;
887
888         os_memset(_rand, 0xff, sizeof(_rand));
889         if (scard_gsm_auth(scard, _rand, sres, kc))
890                 goto failed;
891
892         for (i = 0; i < num_triplets; i++) {
893                 os_memset(rand_[i], i, sizeof(rand_[i]));
894                 if (scard_gsm_auth(scard, rand_[i], sres_[i], kc_[i]))
895                         goto failed;
896         }
897
898         for (i = 0; i < num_triplets; i++) {
899                 printf("1");
900                 for (j = 0; j < len; j++)
901                         printf("%c", imsi[j]);
902                 printf(",");
903                 for (j = 0; j < 16; j++)
904                         printf("%02X", rand_[i][j]);
905                 printf(",");
906                 for (j = 0; j < 4; j++)
907                         printf("%02X", sres_[i][j]);
908                 printf(",");
909                 for (j = 0; j < 8; j++)
910                         printf("%02X", kc_[i][j]);
911                 printf("\n");
912         }
913
914         wpa_printf(MSG_DEBUG, "Trying to use UMTS authentication");
915
916         /* seq 39 (0x28) */
917         os_memset(aka_rand, 0xaa, 16);
918         os_memcpy(aka_autn, "\x86\x71\x31\xcb\xa2\xfc\x61\xdf"
919                   "\xa3\xb3\x97\x9d\x07\x32\xa2\x12", 16);
920
921         res = scard_umts_auth(scard, aka_rand, aka_autn, aka_res, &aka_res_len,
922                               aka_ik, aka_ck, aka_auts);
923         if (res == 0) {
924                 wpa_printf(MSG_DEBUG, "UMTS auth completed successfully");
925                 wpa_hexdump(MSG_DEBUG, "RES", aka_res, aka_res_len);
926                 wpa_hexdump(MSG_DEBUG, "IK", aka_ik, IK_LEN);
927                 wpa_hexdump(MSG_DEBUG, "CK", aka_ck, CK_LEN);
928         } else if (res == -2) {
929                 wpa_printf(MSG_DEBUG, "UMTS auth resulted in synchronization "
930                            "failure");
931                 wpa_hexdump(MSG_DEBUG, "AUTS", aka_auts, AKA_AUTS_LEN);
932         } else {
933                 wpa_printf(MSG_DEBUG, "UMTS auth failed");
934         }
935
936 failed:
937         scard_deinit(scard);
938
939         return 0;
940 #undef num_triplets
941 }
942
943
944 static int scard_get_triplets(int argc, char *argv[])
945 {
946         struct scard_data *scard;
947         size_t len;
948         char imsi[20];
949         unsigned char _rand[16];
950         unsigned char sres[4];
951         unsigned char kc[8];
952         int num_triplets;
953         int i;
954         size_t j;
955
956         if (argc < 2 || ((num_triplets = atoi(argv[1])) <= 0)) {
957                 printf("invalid parameters for sim command\n");
958                 return -1;
959         }
960
961         if (argc <= 2 || os_strcmp(argv[2], "debug") != 0) {
962                 /* disable debug output */
963                 wpa_debug_level = 99;
964         }
965
966         scard = scard_init(SCARD_GSM_SIM_ONLY, NULL);
967         if (scard == NULL) {
968                 printf("Failed to open smartcard connection\n");
969                 return -1;
970         }
971         if (scard_set_pin(scard, argv[0])) {
972                 wpa_printf(MSG_WARNING, "PIN validation failed");
973                 scard_deinit(scard);
974                 return -1;
975         }
976
977         len = sizeof(imsi);
978         if (scard_get_imsi(scard, imsi, &len)) {
979                 scard_deinit(scard);
980                 return -1;
981         }
982
983         for (i = 0; i < num_triplets; i++) {
984                 os_memset(_rand, i, sizeof(_rand));
985                 if (scard_gsm_auth(scard, _rand, sres, kc))
986                         break;
987
988                 /* IMSI:Kc:SRES:RAND */
989                 for (j = 0; j < len; j++)
990                         printf("%c", imsi[j]);
991                 printf(":");
992                 for (j = 0; j < 8; j++)
993                         printf("%02X", kc[j]);
994                 printf(":");
995                 for (j = 0; j < 4; j++)
996                         printf("%02X", sres[j]);
997                 printf(":");
998                 for (j = 0; j < 16; j++)
999                         printf("%02X", _rand[j]);
1000                 printf("\n");
1001         }
1002
1003         scard_deinit(scard);
1004
1005         return 0;
1006 }
1007
1008
1009 static void eapol_test_terminate(int sig, void *signal_ctx)
1010 {
1011         struct wpa_supplicant *wpa_s = signal_ctx;
1012         wpa_msg(wpa_s, MSG_INFO, "Signal %d received - terminating", sig);
1013         eloop_terminate();
1014 }
1015
1016
1017 static void usage(void)
1018 {
1019         printf("usage:\n"
1020                "eapol_test [-nWS] -c<conf> [-a<AS IP>] [-p<AS port>] "
1021                "[-s<AS secret>]\\\n"
1022                "           [-r<count>] [-t<timeout>] [-C<Connect-Info>] \\\n"
1023                "           [-M<client MAC address>] [-o<server cert file] \\\n"
1024                "           [-N<attr spec>] \\\n"
1025                "           [-A<client IP>]\n"
1026                "eapol_test scard\n"
1027                "eapol_test sim <PIN> <num triplets> [debug]\n"
1028                "\n");
1029         printf("options:\n"
1030                "  -c<conf> = configuration file\n"
1031                "  -a<AS IP> = IP address of the authentication server, "
1032                "default 127.0.0.1\n"
1033                "  -p<AS port> = UDP port of the authentication server, "
1034                "default 1812\n"
1035                "  -s<AS secret> = shared secret with the authentication "
1036                "server, default 'radius'\n"
1037                "  -A<client IP> = IP address of the client, default: select "
1038                "automatically\n"
1039                "  -r<count> = number of re-authentications\n"
1040                "  -W = wait for a control interface monitor before starting\n"
1041                "  -S = save configuration after authentication\n"
1042                "  -n = no MPPE keys expected\n"
1043                "  -t<timeout> = sets timeout in seconds (default: 30 s)\n"
1044                "  -C<Connect-Info> = RADIUS Connect-Info (default: "
1045                "CONNECT 11Mbps 802.11b)\n"
1046                "  -M<client MAC address> = Set own MAC address "
1047                "(Calling-Station-Id,\n"
1048                "                           default: 02:00:00:00:00:01)\n"
1049                "  -o<server cert file> = Write received server certificate\n"
1050                "                         chain to the specified file\n"
1051                "  -N<attr spec> = send arbitrary attribute specified by:\n"
1052                "                  attr_id:syntax:value or attr_id\n"
1053                "                  attr_id - number id of the attribute\n"
1054                "                  syntax - one of: s, d, x\n"
1055                "                     s = string\n"
1056                "                     d = integer\n"
1057                "                     x = octet string\n"
1058                "                  value - attribute value.\n"
1059                "       When only attr_id is specified, NULL will be used as "
1060                "value.\n"
1061                "       Multiple attributes can be specified by using the "
1062                "option several times.\n");
1063 }
1064
1065
1066 int main(int argc, char *argv[])
1067 {
1068         struct wpa_supplicant wpa_s;
1069         int c, ret = 1, wait_for_monitor = 0, save_config = 0;
1070         char *as_addr = "127.0.0.1";
1071         int as_port = 1812;
1072         char *as_secret = "radius";
1073         char *cli_addr = NULL;
1074         char *conf = NULL;
1075         int timeout = 30;
1076         char *pos;
1077         struct extra_radius_attr *p = NULL, *p1;
1078
1079         if (os_program_init())
1080                 return -1;
1081
1082         hostapd_logger_register_cb(hostapd_logger_cb);
1083
1084         os_memset(&eapol_test, 0, sizeof(eapol_test));
1085         eapol_test.connect_info = "CONNECT 11Mbps 802.11b";
1086         os_memcpy(eapol_test.own_addr, "\x02\x00\x00\x00\x00\x01", ETH_ALEN);
1087
1088         wpa_debug_level = 0;
1089         wpa_debug_show_keys = 1;
1090
1091         for (;;) {
1092                 c = getopt(argc, argv, "a:A:c:C:M:nN:o:p:r:s:St:W");
1093                 if (c < 0)
1094                         break;
1095                 switch (c) {
1096                 case 'a':
1097                         as_addr = optarg;
1098                         break;
1099                 case 'A':
1100                         cli_addr = optarg;
1101                         break;
1102                 case 'c':
1103                         conf = optarg;
1104                         break;
1105                 case 'C':
1106                         eapol_test.connect_info = optarg;
1107                         break;
1108                 case 'M':
1109                         if (hwaddr_aton(optarg, eapol_test.own_addr)) {
1110                                 usage();
1111                                 return -1;
1112                         }
1113                         break;
1114                 case 'n':
1115                         eapol_test.no_mppe_keys++;
1116                         break;
1117                 case 'o':
1118                         if (eapol_test.server_cert_file)
1119                                 fclose(eapol_test.server_cert_file);
1120                         eapol_test.server_cert_file = fopen(optarg, "w");
1121                         if (eapol_test.server_cert_file == NULL) {
1122                                 printf("Could not open '%s' for writing\n",
1123                                        optarg);
1124                                 return -1;
1125                         }
1126                         break;
1127                 case 'p':
1128                         as_port = atoi(optarg);
1129                         break;
1130                 case 'r':
1131                         eapol_test.eapol_test_num_reauths = atoi(optarg);
1132                         break;
1133                 case 's':
1134                         as_secret = optarg;
1135                         break;
1136                 case 'S':
1137                         save_config++;
1138                         break;
1139                 case 't':
1140                         timeout = atoi(optarg);
1141                         break;
1142                 case 'W':
1143                         wait_for_monitor++;
1144                         break;
1145                 case 'N':
1146                         p1 = os_zalloc(sizeof(p1));
1147                         if (p1 == NULL)
1148                                 break;
1149                         if (!p)
1150                                 eapol_test.extra_attrs = p1;
1151                         else
1152                                 p->next = p1;
1153                         p = p1;
1154
1155                         p->type = atoi(optarg);
1156                         pos = os_strchr(optarg, ':');
1157                         if (pos == NULL) {
1158                                 p->syntax = 'n';
1159                                 p->data = NULL;
1160                                 break;
1161                         }
1162
1163                         pos++;
1164                         if (pos[0] == '\0' || pos[1] != ':') {
1165                                 printf("Incorrect format of attribute "
1166                                        "specification\n");
1167                                 break;
1168                         }
1169
1170                         p->syntax = pos[0];
1171                         p->data = pos + 2;
1172                         break;
1173                 default:
1174                         usage();
1175                         return -1;
1176                 }
1177         }
1178
1179         if (argc > optind && os_strcmp(argv[optind], "scard") == 0) {
1180                 return scard_test();
1181         }
1182
1183         if (argc > optind && os_strcmp(argv[optind], "sim") == 0) {
1184                 return scard_get_triplets(argc - optind - 1,
1185                                           &argv[optind + 1]);
1186         }
1187
1188         if (conf == NULL) {
1189                 usage();
1190                 printf("Configuration file is required.\n");
1191                 return -1;
1192         }
1193
1194         if (eap_register_methods()) {
1195                 wpa_printf(MSG_ERROR, "Failed to register EAP methods");
1196                 return -1;
1197         }
1198
1199         if (eloop_init()) {
1200                 wpa_printf(MSG_ERROR, "Failed to initialize event loop");
1201                 return -1;
1202         }
1203
1204         os_memset(&wpa_s, 0, sizeof(wpa_s));
1205         eapol_test.wpa_s = &wpa_s;
1206         wpa_s.conf = wpa_config_read(conf);
1207         if (wpa_s.conf == NULL) {
1208                 printf("Failed to parse configuration file '%s'.\n", conf);
1209                 return -1;
1210         }
1211         if (wpa_s.conf->ssid == NULL) {
1212                 printf("No networks defined.\n");
1213                 return -1;
1214         }
1215
1216         wpa_init_conf(&eapol_test, &wpa_s, as_addr, as_port, as_secret,
1217                       cli_addr);
1218         wpa_s.ctrl_iface = wpa_supplicant_ctrl_iface_init(&wpa_s);
1219         if (wpa_s.ctrl_iface == NULL) {
1220                 printf("Failed to initialize control interface '%s'.\n"
1221                        "You may have another eapol_test process already "
1222                        "running or the file was\n"
1223                        "left by an unclean termination of eapol_test in "
1224                        "which case you will need\n"
1225                        "to manually remove this file before starting "
1226                        "eapol_test again.\n",
1227                        wpa_s.conf->ctrl_interface);
1228                 return -1;
1229         }
1230         if (wpa_supplicant_scard_init(&wpa_s, wpa_s.conf->ssid))
1231                 return -1;
1232
1233         if (test_eapol(&eapol_test, &wpa_s, wpa_s.conf->ssid))
1234                 return -1;
1235
1236         if (wpas_init_ext_pw(&wpa_s) < 0)
1237                 return -1;
1238
1239         if (wait_for_monitor)
1240                 wpa_supplicant_ctrl_iface_wait(wpa_s.ctrl_iface);
1241
1242         eloop_register_timeout(timeout, 0, eapol_test_timeout, &eapol_test,
1243                                NULL);
1244         eloop_register_timeout(0, 0, send_eap_request_identity, &wpa_s, NULL);
1245         eloop_register_signal_terminate(eapol_test_terminate, &wpa_s);
1246         eloop_register_signal_reconfig(eapol_test_terminate, &wpa_s);
1247         eloop_run();
1248
1249         eloop_cancel_timeout(eapol_test_timeout, &eapol_test, NULL);
1250         eloop_cancel_timeout(eapol_sm_reauth, &eapol_test, NULL);
1251
1252         if (eapol_test_compare_pmk(&eapol_test) == 0 ||
1253             eapol_test.no_mppe_keys)
1254                 ret = 0;
1255         if (eapol_test.auth_timed_out)
1256                 ret = -2;
1257         if (eapol_test.radius_access_reject_received)
1258                 ret = -3;
1259
1260         if (save_config)
1261                 wpa_config_write(conf, wpa_s.conf);
1262
1263         test_eapol_clean(&eapol_test, &wpa_s);
1264
1265         eap_peer_unregister_methods();
1266 #ifdef CONFIG_AP
1267         eap_server_unregister_methods();
1268 #endif /* CONFIG_AP */
1269
1270         eloop_destroy();
1271
1272         if (eapol_test.server_cert_file)
1273                 fclose(eapol_test.server_cert_file);
1274
1275         printf("MPPE keys OK: %d  mismatch: %d\n",
1276                eapol_test.num_mppe_ok, eapol_test.num_mppe_mismatch);
1277         if (eapol_test.num_mppe_mismatch)
1278                 ret = -4;
1279         if (ret)
1280                 printf("FAILURE\n");
1281         else
1282                 printf("SUCCESS\n");
1283
1284         os_program_deinit();
1285
1286         return ret;
1287 }