EAP-FAST: Add peer identity into EAP-FAST PAC-Opaque
[mech_eap.git] / src / eap_server / eap_fast.c
1 /*
2  * EAP-FAST server (RFC 4851)
3  * Copyright (c) 2004-2008, 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
15 #include "includes.h"
16
17 #include "common.h"
18 #include "aes_wrap.h"
19 #include "sha1.h"
20 #include "eap_i.h"
21 #include "eap_tls_common.h"
22 #include "tls.h"
23 #include "eap_common/eap_tlv_common.h"
24 #include "eap_common/eap_fast_common.h"
25
26
27 static void eap_fast_reset(struct eap_sm *sm, void *priv);
28
29
30 /* Private PAC-Opaque TLV types */
31 #define PAC_OPAQUE_TYPE_PAD 0
32 #define PAC_OPAQUE_TYPE_KEY 1
33 #define PAC_OPAQUE_TYPE_LIFETIME 2
34 #define PAC_OPAQUE_TYPE_IDENTITY 3
35
36 /* PAC-Key lifetime in seconds (hard limit) */
37 #define PAC_KEY_LIFETIME (7 * 24 * 60 * 60)
38
39 /*
40  * PAC-Key refresh time in seconds (soft limit on remaining hard limit). The
41  * server will generate a new PAC-Key when this number of seconds (or fewer)
42  * of the lifetime.
43  */
44 #define PAC_KEY_REFRESH_TIME (1 * 24 * 60 * 60)
45
46
47 struct eap_fast_data {
48         struct eap_ssl_data ssl;
49         enum {
50                 START, PHASE1, PHASE2_START, PHASE2_ID, PHASE2_METHOD,
51                 CRYPTO_BINDING, REQUEST_PAC, SUCCESS, FAILURE
52         } state;
53
54         int fast_version;
55         const struct eap_method *phase2_method;
56         void *phase2_priv;
57         int force_version;
58         int peer_version;
59
60         u8 crypto_binding_nonce[32];
61         int final_result;
62
63         struct eap_fast_key_block_provisioning *key_block_p;
64
65         u8 simck[EAP_FAST_SIMCK_LEN];
66         u8 cmk[20];
67         int simck_idx;
68
69         u8 pac_opaque_encr[16];
70         char *srv_id;
71
72         int anon_provisioning;
73         int send_new_pac; /* server triggered re-keying of Tunnel PAC */
74         struct wpabuf *pending_phase2_resp;
75         u8 *identity; /* from PAC-Opaque */
76         size_t identity_len;
77 };
78
79
80 static const char * eap_fast_state_txt(int state)
81 {
82         switch (state) {
83         case START:
84                 return "START";
85         case PHASE1:
86                 return "PHASE1";
87         case PHASE2_START:
88                 return "PHASE2_START";
89         case PHASE2_ID:
90                 return "PHASE2_ID";
91         case PHASE2_METHOD:
92                 return "PHASE2_METHOD";
93         case CRYPTO_BINDING:
94                 return "CRYPTO_BINDING";
95         case REQUEST_PAC:
96                 return "REQUEST_PAC";
97         case SUCCESS:
98                 return "SUCCESS";
99         case FAILURE:
100                 return "FAILURE";
101         default:
102                 return "Unknown?!";
103         }
104 }
105
106
107 static void eap_fast_state(struct eap_fast_data *data, int state)
108 {
109         wpa_printf(MSG_DEBUG, "EAP-FAST: %s -> %s",
110                    eap_fast_state_txt(data->state),
111                    eap_fast_state_txt(state));
112         data->state = state;
113 }
114
115
116 static EapType eap_fast_req_failure(struct eap_sm *sm,
117                                     struct eap_fast_data *data)
118 {
119         /* TODO: send Result TLV(FAILURE) */
120         eap_fast_state(data, FAILURE);
121         return EAP_TYPE_NONE;
122 }
123
124
125 static int eap_fast_session_ticket_cb(void *ctx, const u8 *ticket, size_t len,
126                                       const u8 *client_random,
127                                       const u8 *server_random,
128                                       u8 *master_secret)
129 {
130         struct eap_fast_data *data = ctx;
131 #define TLS_RANDOM_LEN 32
132 #define TLS_MASTER_SECRET_LEN 48
133         u8 seed[2 * TLS_RANDOM_LEN];
134         const u8 *pac_opaque;
135         size_t pac_opaque_len;
136         u8 *buf, *pos, *end, *pac_key = NULL;
137         os_time_t lifetime = 0;
138         struct os_time now;
139         u8 *identity = NULL;
140         size_t identity_len = 0;
141
142         wpa_printf(MSG_DEBUG, "EAP-FAST: SessionTicket callback");
143         wpa_hexdump(MSG_DEBUG, "EAP-FAST: SessionTicket (PAC-Opaque)",
144                     ticket, len);
145         wpa_hexdump(MSG_DEBUG, "EAP-FAST: client_random",
146                     client_random, TLS_RANDOM_LEN);
147         wpa_hexdump(MSG_DEBUG, "EAP-FAST: server_random",
148                     server_random, TLS_RANDOM_LEN);
149
150         if (len < 4 || WPA_GET_BE16(ticket) != PAC_TYPE_PAC_OPAQUE) {
151                 wpa_printf(MSG_DEBUG, "EAP-FAST: Ignore invalid "
152                            "SessionTicket");
153                 return 0;
154         }
155
156         pac_opaque_len = WPA_GET_BE16(ticket + 2);
157         pac_opaque = ticket + 4;
158         if (pac_opaque_len < 8 || pac_opaque_len % 8 ||
159             pac_opaque_len > len - 4) {
160                 wpa_printf(MSG_DEBUG, "EAP-FAST: Ignore invalid PAC-Opaque "
161                            "(len=%lu left=%lu)",
162                            (unsigned long) pac_opaque_len,
163                            (unsigned long) len);
164                 return 0;
165         }
166         wpa_hexdump(MSG_DEBUG, "EAP-FAST: Received PAC-Opaque",
167                     pac_opaque, pac_opaque_len);
168
169         buf = os_malloc(pac_opaque_len - 8);
170         if (buf == NULL) {
171                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to allocate memory "
172                            "for decrypting PAC-Opaque");
173                 return 0;
174         }
175
176         if (aes_unwrap(data->pac_opaque_encr, (pac_opaque_len - 8) / 8,
177                        pac_opaque, buf) < 0) {
178                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to decrypt "
179                            "PAC-Opaque");
180                 os_free(buf);
181                 /*
182                  * This may have been caused by server changing the PAC-Opaque
183                  * encryption key, so just ignore this PAC-Opaque instead of
184                  * failing the authentication completely. Provisioning can now
185                  * be used to provision a new PAC.
186                  */
187                 return 0;
188         }
189
190         end = buf + pac_opaque_len - 8;
191         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Decrypted PAC-Opaque",
192                         buf, end - buf);
193
194         pos = buf;
195         while (pos + 1 < end) {
196                 if (pos + 2 + pos[1] > end)
197                         break;
198
199                 switch (*pos) {
200                 case PAC_OPAQUE_TYPE_PAD:
201                         pos = end;
202                         break;
203                 case PAC_OPAQUE_TYPE_KEY:
204                         if (pos[1] != EAP_FAST_PAC_KEY_LEN) {
205                                 wpa_printf(MSG_DEBUG, "EAP-FAST: Invalid "
206                                            "PAC-Key length %d", pos[1]);
207                                 os_free(buf);
208                                 return -1;
209                         }
210                         pac_key = pos + 2;
211                         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: PAC-Key from "
212                                         "decrypted PAC-Opaque",
213                                         pac_key, EAP_FAST_PAC_KEY_LEN);
214                         break;
215                 case PAC_OPAQUE_TYPE_LIFETIME:
216                         if (pos[1] != 4) {
217                                 wpa_printf(MSG_DEBUG, "EAP-FAST: Invalid "
218                                            "PAC-Key lifetime length %d",
219                                            pos[1]);
220                                 os_free(buf);
221                                 return -1;
222                         }
223                         lifetime = WPA_GET_BE32(pos + 2);
224                         break;
225                 case PAC_OPAQUE_TYPE_IDENTITY:
226                         identity = pos + 2;
227                         identity_len = pos[1];
228                         break;
229                 }
230
231                 pos += 2 + pos[1];
232         }
233
234         if (pac_key == NULL) {
235                 wpa_printf(MSG_DEBUG, "EAP-FAST: No PAC-Key included in "
236                            "PAC-Opaque");
237                 os_free(buf);
238                 return -1;
239         }
240
241         if (identity) {
242                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-FAST: Identity from "
243                                   "PAC-Opaque", identity, identity_len);
244                 os_free(data->identity);
245                 data->identity = os_malloc(identity_len);
246                 if (data->identity) {
247                         os_memcpy(data->identity, identity, identity_len);
248                         data->identity_len = identity_len;
249                 }
250         }
251
252         if (os_get_time(&now) < 0 || lifetime <= 0 || now.sec > lifetime) {
253                 wpa_printf(MSG_DEBUG, "EAP-FAST: PAC-Key not valid anymore "
254                            "(lifetime=%ld now=%ld)", lifetime, now.sec);
255                 os_free(buf);
256                 return 0;
257         }
258
259         if (lifetime - now.sec < PAC_KEY_REFRESH_TIME)
260                 data->send_new_pac = 1;
261
262         /*
263          * RFC 4851, Section 5.1:
264          * master_secret = T-PRF(PAC-Key, "PAC to master secret label hash", 
265          *                       server_random + client_random, 48)
266          */
267         os_memcpy(seed, server_random, TLS_RANDOM_LEN);
268         os_memcpy(seed + TLS_RANDOM_LEN, client_random, TLS_RANDOM_LEN);
269         sha1_t_prf(pac_key, EAP_FAST_PAC_KEY_LEN,
270                    "PAC to master secret label hash",
271                    seed, sizeof(seed), master_secret, TLS_MASTER_SECRET_LEN);
272
273         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: master_secret",
274                         master_secret, TLS_MASTER_SECRET_LEN);
275
276         os_free(buf);
277
278         return 1;
279 }
280
281
282 static u8 * eap_fast_derive_key(struct eap_sm *sm, struct eap_ssl_data *data,
283                                 char *label, size_t len)
284 {
285         struct tls_keys keys;
286         u8 *rnd = NULL, *out;
287         int block_size;
288
289         block_size = tls_connection_get_keyblock_size(sm->ssl_ctx, data->conn);
290         if (block_size < 0)
291                 return NULL;
292
293         out = os_malloc(block_size + len);
294         if (out == NULL)
295                 return NULL;
296
297         if (tls_connection_prf(sm->ssl_ctx, data->conn, label, 1, out,
298                                block_size + len) == 0) {
299                 os_memmove(out, out + block_size, len);
300                 return out;
301         }
302
303         if (tls_connection_get_keys(sm->ssl_ctx, data->conn, &keys))
304                 goto fail;
305
306         rnd = os_malloc(keys.client_random_len + keys.server_random_len);
307         if (rnd == NULL)
308                 goto fail;
309
310         os_memcpy(rnd, keys.server_random, keys.server_random_len);
311         os_memcpy(rnd + keys.server_random_len, keys.client_random,
312                   keys.client_random_len);
313
314         wpa_hexdump_key(MSG_MSGDUMP, "EAP-FAST: master_secret for key "
315                         "expansion", keys.master_key, keys.master_key_len);
316         if (tls_prf(keys.master_key, keys.master_key_len,
317                     label, rnd, keys.client_random_len +
318                     keys.server_random_len, out, block_size + len))
319                 goto fail;
320         os_free(rnd);
321         os_memmove(out, out + block_size, len);
322         return out;
323
324 fail:
325         os_free(rnd);
326         os_free(out);
327         return NULL;
328 }
329
330
331 static void eap_fast_derive_key_auth(struct eap_sm *sm,
332                                      struct eap_fast_data *data)
333 {
334         u8 *sks;
335
336         /* RFC 4851, Section 5.1:
337          * Extra key material after TLS key_block: session_key_seed[40]
338          */
339
340         sks = eap_fast_derive_key(sm, &data->ssl, "key expansion",
341                                   EAP_FAST_SKS_LEN);
342         if (sks == NULL) {
343                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to derive "
344                            "session_key_seed");
345                 return;
346         }
347
348         /*
349          * RFC 4851, Section 5.2:
350          * S-IMCK[0] = session_key_seed
351          */
352         wpa_hexdump_key(MSG_DEBUG,
353                         "EAP-FAST: session_key_seed (SKS = S-IMCK[0])",
354                         sks, EAP_FAST_SKS_LEN);
355         data->simck_idx = 0;
356         os_memcpy(data->simck, sks, EAP_FAST_SIMCK_LEN);
357         os_free(sks);
358 }
359
360
361 static void eap_fast_derive_key_provisioning(struct eap_sm *sm,
362                                              struct eap_fast_data *data)
363 {
364         os_free(data->key_block_p);
365         data->key_block_p = (struct eap_fast_key_block_provisioning *)
366                 eap_fast_derive_key(sm, &data->ssl, "key expansion",
367                                     sizeof(*data->key_block_p));
368         if (data->key_block_p == NULL) {
369                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to derive key block");
370                 return;
371         }
372         /*
373          * RFC 4851, Section 5.2:
374          * S-IMCK[0] = session_key_seed
375          */
376         wpa_hexdump_key(MSG_DEBUG,
377                         "EAP-FAST: session_key_seed (SKS = S-IMCK[0])",
378                         data->key_block_p->session_key_seed,
379                         sizeof(data->key_block_p->session_key_seed));
380         data->simck_idx = 0;
381         os_memcpy(data->simck, data->key_block_p->session_key_seed,
382                   EAP_FAST_SIMCK_LEN);
383         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: server_challenge",
384                         data->key_block_p->server_challenge,
385                         sizeof(data->key_block_p->server_challenge));
386         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: client_challenge",
387                         data->key_block_p->client_challenge,
388                         sizeof(data->key_block_p->client_challenge));
389 }
390
391
392 static int eap_fast_get_phase2_key(struct eap_sm *sm,
393                                    struct eap_fast_data *data,
394                                    u8 *isk, size_t isk_len)
395 {
396         u8 *key;
397         size_t key_len;
398
399         os_memset(isk, 0, isk_len);
400
401         if (data->phase2_method == NULL || data->phase2_priv == NULL) {
402                 wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 method not "
403                            "available");
404                 return -1;
405         }
406
407         if (data->phase2_method->getKey == NULL)
408                 return 0;
409
410         if ((key = data->phase2_method->getKey(sm, data->phase2_priv,
411                                                &key_len)) == NULL) {
412                 wpa_printf(MSG_DEBUG, "EAP-FAST: Could not get key material "
413                            "from Phase 2");
414                 return -1;
415         }
416
417         if (key_len > isk_len)
418                 key_len = isk_len;
419         os_memcpy(isk, key, key_len);
420         os_free(key);
421
422         return 0;
423 }
424
425
426 static int eap_fast_update_icmk(struct eap_sm *sm, struct eap_fast_data *data)
427 {
428         u8 isk[32], imck[60];
429
430         wpa_printf(MSG_DEBUG, "EAP-FAST: Deriving ICMK[%d] (S-IMCK and CMK)",
431                    data->simck_idx + 1);
432
433         /*
434          * RFC 4851, Section 5.2:
435          * IMCK[j] = T-PRF(S-IMCK[j-1], "Inner Methods Compound Keys",
436          *                 MSK[j], 60)
437          * S-IMCK[j] = first 40 octets of IMCK[j]
438          * CMK[j] = last 20 octets of IMCK[j]
439          */
440
441         if (eap_fast_get_phase2_key(sm, data, isk, sizeof(isk)) < 0)
442                 return -1;
443         wpa_hexdump_key(MSG_MSGDUMP, "EAP-FAST: ISK[j]", isk, sizeof(isk));
444         sha1_t_prf(data->simck, EAP_FAST_SIMCK_LEN,
445                    "Inner Methods Compound Keys",
446                    isk, sizeof(isk), imck, sizeof(imck));
447         data->simck_idx++;
448         os_memcpy(data->simck, imck, EAP_FAST_SIMCK_LEN);
449         wpa_hexdump_key(MSG_MSGDUMP, "EAP-FAST: S-IMCK[j]",
450                         data->simck, EAP_FAST_SIMCK_LEN);
451         os_memcpy(data->cmk, imck + EAP_FAST_SIMCK_LEN, 20);
452         wpa_hexdump_key(MSG_MSGDUMP, "EAP-FAST: CMK[j]", data->cmk, 20);
453
454         return 0;
455 }
456
457
458 static void * eap_fast_init(struct eap_sm *sm)
459 {
460         struct eap_fast_data *data;
461         u8 ciphers[5] = {
462                 TLS_CIPHER_ANON_DH_AES128_SHA,
463                 TLS_CIPHER_AES128_SHA,
464                 TLS_CIPHER_RSA_DHE_AES128_SHA,
465                 TLS_CIPHER_RC4_SHA,
466                 TLS_CIPHER_NONE
467         };
468
469         data = os_zalloc(sizeof(*data));
470         if (data == NULL)
471                 return NULL;
472         data->fast_version = EAP_FAST_VERSION;
473         data->force_version = -1;
474         if (sm->user && sm->user->force_version >= 0) {
475                 data->force_version = sm->user->force_version;
476                 wpa_printf(MSG_DEBUG, "EAP-FAST: forcing version %d",
477                            data->force_version);
478                 data->fast_version = data->force_version;
479         }
480         data->state = START;
481
482         if (eap_server_tls_ssl_init(sm, &data->ssl, 0)) {
483                 wpa_printf(MSG_INFO, "EAP-FAST: Failed to initialize SSL.");
484                 eap_fast_reset(sm, data);
485                 return NULL;
486         }
487
488         if (tls_connection_set_cipher_list(sm->ssl_ctx, data->ssl.conn,
489                                            ciphers) < 0) {
490                 wpa_printf(MSG_INFO, "EAP-FAST: Failed to set TLS cipher "
491                            "suites");
492                 eap_fast_reset(sm, data);
493                 return NULL;
494         }
495
496         if (tls_connection_set_session_ticket_cb(sm->ssl_ctx, data->ssl.conn,
497                                                  eap_fast_session_ticket_cb,
498                                                  data) < 0) {
499                 wpa_printf(MSG_INFO, "EAP-FAST: Failed to set SessionTicket "
500                            "callback");
501                 eap_fast_reset(sm, data);
502                 return NULL;
503         }
504
505         if (sm->pac_opaque_encr_key == NULL) {
506                 wpa_printf(MSG_INFO, "EAP-FAST: No PAC-Opaque encryption key "
507                            "configured");
508                 eap_fast_reset(sm, data);
509                 return NULL;
510         }
511         os_memcpy(data->pac_opaque_encr, sm->pac_opaque_encr_key,
512                   sizeof(data->pac_opaque_encr));
513
514         if (sm->eap_fast_a_id == NULL) {
515                 wpa_printf(MSG_INFO, "EAP-FAST: No A-ID configured");
516                 eap_fast_reset(sm, data);
517                 return NULL;
518         }
519         data->srv_id = os_strdup(sm->eap_fast_a_id);
520         if (data->srv_id == NULL) {
521                 eap_fast_reset(sm, data);
522                 return NULL;
523         }
524
525         return data;
526 }
527
528
529 static void eap_fast_reset(struct eap_sm *sm, void *priv)
530 {
531         struct eap_fast_data *data = priv;
532         if (data == NULL)
533                 return;
534         if (data->phase2_priv && data->phase2_method)
535                 data->phase2_method->reset(sm, data->phase2_priv);
536         eap_server_tls_ssl_deinit(sm, &data->ssl);
537         os_free(data->srv_id);
538         os_free(data->key_block_p);
539         wpabuf_free(data->pending_phase2_resp);
540         os_free(data->identity);
541         os_free(data);
542 }
543
544
545 static struct wpabuf * eap_fast_build_start(struct eap_sm *sm,
546                                             struct eap_fast_data *data, u8 id)
547 {
548         struct wpabuf *req;
549         struct pac_tlv_hdr *a_id;
550         size_t srv_id_len = os_strlen(data->srv_id);
551
552         req = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_FAST,
553                             1 + sizeof(*a_id) + srv_id_len,
554                             EAP_CODE_REQUEST, id);
555         if (req == NULL) {
556                 wpa_printf(MSG_ERROR, "EAP-FAST: Failed to allocate memory for"
557                            " request");
558                 eap_fast_state(data, FAILURE);
559                 return NULL;
560         }
561
562         wpabuf_put_u8(req, EAP_TLS_FLAGS_START | data->fast_version);
563         a_id = wpabuf_put(req, sizeof(*a_id));
564         a_id->type = host_to_be16(PAC_TYPE_A_ID);
565         a_id->len = host_to_be16(srv_id_len);
566         wpabuf_put_data(req, data->srv_id, srv_id_len);
567
568         eap_fast_state(data, PHASE1);
569
570         return req;
571 }
572
573
574 static int eap_fast_phase1_done(struct eap_sm *sm, struct eap_fast_data *data)
575 {
576         char cipher[64];
577
578         wpa_printf(MSG_DEBUG, "EAP-FAST: Phase1 done, starting Phase2");
579
580         if (tls_get_cipher(sm->ssl_ctx, data->ssl.conn, cipher, sizeof(cipher))
581             < 0) {
582                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to get cipher "
583                            "information");
584                 eap_fast_state(data, FAILURE);
585                 return -1;
586         }
587         data->anon_provisioning = os_strstr(cipher, "ADH") != NULL;
588                     
589         if (data->anon_provisioning) {
590                 wpa_printf(MSG_DEBUG, "EAP-FAST: Anonymous provisioning");
591                 eap_fast_derive_key_provisioning(sm, data);
592         } else
593                 eap_fast_derive_key_auth(sm, data);
594
595         eap_fast_state(data, PHASE2_START);
596
597         return 0;
598 }
599
600
601 static struct wpabuf * eap_fast_build_req(struct eap_sm *sm,
602                                           struct eap_fast_data *data, u8 id)
603 {
604         int res;
605         struct wpabuf *req;
606
607         res = eap_server_tls_buildReq_helper(sm, &data->ssl, EAP_TYPE_FAST,
608                                              data->fast_version, id, &req);
609
610         if (tls_connection_established(sm->ssl_ctx, data->ssl.conn)) {
611                 if (eap_fast_phase1_done(sm, data) < 0) {
612                         os_free(req);
613                         return NULL;
614                 }
615         }
616
617         if (res == 1)
618                 return eap_server_tls_build_ack(id, EAP_TYPE_FAST,
619                                                 data->fast_version);
620         return req;
621 }
622
623
624 static struct wpabuf * eap_fast_encrypt(struct eap_sm *sm,
625                                         struct eap_fast_data *data,
626                                         u8 id, u8 *plain, size_t plain_len)
627 {
628         int res;
629         struct wpabuf *buf;
630
631         /* TODO: add support for fragmentation, if needed. This will need to
632          * add TLS Message Length field, if the frame is fragmented. */
633         buf = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_FAST,
634                             1 + data->ssl.tls_out_limit,
635                             EAP_CODE_REQUEST, id);
636         if (buf == NULL)
637                 return NULL;
638
639         wpabuf_put_u8(buf, data->fast_version);
640
641         res = tls_connection_encrypt(sm->ssl_ctx, data->ssl.conn,
642                                      plain, plain_len, wpabuf_put(buf, 0),
643                                      data->ssl.tls_out_limit);
644         if (res < 0) {
645                 wpa_printf(MSG_INFO, "EAP-FAST: Failed to encrypt Phase 2 "
646                            "data");
647                 wpabuf_free(buf);
648                 return NULL;
649         }
650
651         wpabuf_put(buf, res);
652         eap_update_len(buf);
653
654         return buf;
655 }
656
657
658 static struct wpabuf * eap_fast_tlv_eap_payload(struct wpabuf *buf)
659 {
660         struct wpabuf *e;
661         struct eap_tlv_hdr *tlv;
662
663         if (buf == NULL)
664                 return NULL;
665
666         /* Encapsulate EAP packet in EAP-Payload TLV */
667         wpa_printf(MSG_DEBUG, "EAP-FAST: Add EAP-Payload TLV");
668         e = wpabuf_alloc(sizeof(*tlv) + wpabuf_len(buf));
669         if (e == NULL) {
670                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to allocate memory "
671                            "for TLV encapsulation");
672                 wpabuf_free(buf);
673                 return NULL;
674         }
675         tlv = wpabuf_put(e, sizeof(*tlv));
676         tlv->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
677                                      EAP_TLV_EAP_PAYLOAD_TLV);
678         tlv->length = host_to_be16(wpabuf_len(buf));
679         wpabuf_put_buf(e, buf);
680         wpabuf_free(buf);
681         return e;
682 }
683
684
685 static struct wpabuf * eap_fast_build_phase2_req(struct eap_sm *sm,
686                                                  struct eap_fast_data *data,
687                                                  u8 id)
688 {
689         struct wpabuf *req;
690
691         if (data->phase2_priv == NULL) {
692                 wpa_printf(MSG_DEBUG, "EAP-FAST: Phase 2 method not "
693                            "initialized");
694                 return NULL;
695         }
696         req = data->phase2_method->buildReq(sm, data->phase2_priv, id);
697         if (req == NULL)
698                 return NULL;
699
700         wpa_hexdump_buf_key(MSG_MSGDUMP, "EAP-FAST: Phase 2 EAP-Request", req);
701         return eap_fast_tlv_eap_payload(req);
702 }
703
704
705 static struct wpabuf * eap_fast_build_crypto_binding(
706         struct eap_sm *sm, struct eap_fast_data *data)
707 {
708         struct wpabuf *buf;
709         struct eap_tlv_result_tlv *result;
710         struct eap_tlv_crypto_binding__tlv *binding;
711         int type;
712
713         buf = wpabuf_alloc(sizeof(*result) + sizeof(*binding));
714         if (buf == NULL)
715                 return NULL;
716
717         if (data->send_new_pac || data->anon_provisioning) {
718                 type = EAP_TLV_INTERMEDIATE_RESULT_TLV;
719                 data->final_result = 0;
720         } else {
721                 type = EAP_TLV_RESULT_TLV;
722                 data->final_result = 1;
723         }
724
725         /* Result TLV */
726         wpa_printf(MSG_DEBUG, "EAP-FAST: Add Result TLV (status=SUCCESS)");
727         result = wpabuf_put(buf, sizeof(*result));
728         result->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY | type);
729         result->length = host_to_be16(2);
730         result->status = host_to_be16(EAP_TLV_RESULT_SUCCESS);
731
732         /* Crypto-Binding TLV */
733         binding = wpabuf_put(buf, sizeof(*binding));
734         binding->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
735                                          EAP_TLV_CRYPTO_BINDING_TLV);
736         binding->length = host_to_be16(sizeof(*binding) -
737                                        sizeof(struct eap_tlv_hdr));
738         binding->version = EAP_FAST_VERSION;
739         binding->received_version = data->peer_version;
740         binding->subtype = EAP_TLV_CRYPTO_BINDING_SUBTYPE_REQUEST;
741         if (os_get_random(binding->nonce, sizeof(binding->nonce)) < 0) {
742                 wpabuf_free(buf);
743                 return NULL;
744         }
745
746         /*
747          * RFC 4851, Section 4.2.8:
748          * The nonce in a request MUST have its least significant bit set to 0.
749          */
750         binding->nonce[sizeof(binding->nonce) - 1] &= ~0x01;
751
752         os_memcpy(data->crypto_binding_nonce, binding->nonce,
753                   sizeof(binding->nonce));
754
755         /*
756          * RFC 4851, Section 5.3:
757          * CMK = CMK[j]
758          * Compound-MAC = HMAC-SHA1( CMK, Crypto-Binding TLV )
759          */
760
761         hmac_sha1(data->cmk, 20, (u8 *) binding, sizeof(*binding),
762                   binding->compound_mac);
763
764         wpa_printf(MSG_DEBUG, "EAP-FAST: Add Crypto-Binding TLV: Version %d "
765                    "Received Version %d SubType %d",
766                    binding->version, binding->received_version,
767                    binding->subtype);
768         wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: NONCE",
769                     binding->nonce, sizeof(binding->nonce));
770         wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Compound MAC",
771                     binding->compound_mac, sizeof(binding->compound_mac));
772
773         return buf;
774 }
775
776
777 static struct wpabuf * eap_fast_build_pac(struct eap_sm *sm,
778                                           struct eap_fast_data *data)
779 {
780         u8 pac_key[EAP_FAST_PAC_KEY_LEN];
781         u8 *pac_buf, *pac_opaque;
782         struct wpabuf *buf;
783         u8 *pos;
784         size_t buf_len, srv_id_len, pac_len;
785         struct eap_tlv_hdr *pac_tlv;
786         struct pac_tlv_hdr *hdr, *pac_info;
787         struct eap_tlv_result_tlv *result;
788         struct os_time now;
789
790         if (os_get_random(pac_key, EAP_FAST_PAC_KEY_LEN) < 0 ||
791             os_get_time(&now) < 0)
792                 return NULL;
793         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Generated PAC-Key",
794                         pac_key, EAP_FAST_PAC_KEY_LEN);
795
796         pac_len = (2 + EAP_FAST_PAC_KEY_LEN) + (2 + 4) +
797                 (2 + sm->identity_len) + 8;
798         pac_buf = os_malloc(pac_len);
799         if (pac_buf == NULL)
800                 return NULL;
801
802         srv_id_len = os_strlen(data->srv_id);
803
804         pos = pac_buf;
805         *pos++ = PAC_OPAQUE_TYPE_KEY;
806         *pos++ = EAP_FAST_PAC_KEY_LEN;
807         os_memcpy(pos, pac_key, EAP_FAST_PAC_KEY_LEN);
808         pos += EAP_FAST_PAC_KEY_LEN;
809
810         *pos++ = PAC_OPAQUE_TYPE_LIFETIME;
811         *pos++ = 4;
812         WPA_PUT_BE32(pos, now.sec + PAC_KEY_LIFETIME);
813         pos += 4;
814
815         if (sm->identity) {
816                 *pos++ = PAC_OPAQUE_TYPE_IDENTITY;
817                 *pos++ = sm->identity_len;
818                 os_memcpy(pos, sm->identity, sm->identity_len);
819                 pos += sm->identity_len;
820         }
821
822         pac_len = pos - pac_buf;
823         if (pac_len % 8) {
824                 *pos++ = PAC_OPAQUE_TYPE_PAD;
825                 pac_len++;
826         }
827
828         pac_opaque = os_malloc(pac_len + 8);
829         if (pac_opaque == NULL) {
830                 os_free(pac_buf);
831                 return NULL;
832         }
833         if (aes_wrap(data->pac_opaque_encr, pac_len / 8, pac_buf,
834                      pac_opaque) < 0) {
835                 os_free(pac_buf);
836                 os_free(pac_opaque);
837                 return NULL;
838         }
839         os_free(pac_buf);
840
841         pac_len += 8;
842         wpa_hexdump(MSG_DEBUG, "EAP-FAST: PAC-Opaque",
843                     pac_opaque, pac_len);
844
845         buf_len = sizeof(*pac_tlv) +
846                 sizeof(*hdr) + EAP_FAST_PAC_KEY_LEN +
847                 sizeof(*hdr) + pac_len +
848                 2 * srv_id_len + 100 + sizeof(*result);
849         buf = wpabuf_alloc(buf_len);
850         if (buf == NULL) {
851                 os_free(pac_opaque);
852                 return NULL;
853         }
854
855         /* PAC TLV */
856         wpa_printf(MSG_DEBUG, "EAP-FAST: Add PAC TLV");
857         pac_tlv = wpabuf_put(buf, sizeof(*pac_tlv));
858         pac_tlv->tlv_type = host_to_be16(EAP_TLV_TYPE_MANDATORY |
859                                          EAP_TLV_PAC_TLV);
860
861         /* PAC-Key */
862         hdr = wpabuf_put(buf, sizeof(*hdr));
863         hdr->type = host_to_be16(PAC_TYPE_PAC_KEY);
864         hdr->len = host_to_be16(EAP_FAST_PAC_KEY_LEN);
865         wpabuf_put_data(buf, pac_key, EAP_FAST_PAC_KEY_LEN);
866
867         /* PAC-Opaque */
868         hdr = wpabuf_put(buf, sizeof(*hdr));
869         hdr->type = host_to_be16(PAC_TYPE_PAC_OPAQUE);
870         hdr->len = host_to_be16(pac_len);
871         wpabuf_put_data(buf, pac_opaque, pac_len);
872         os_free(pac_opaque);
873
874         /* PAC-Info */
875         pac_info = wpabuf_put(buf, sizeof(*pac_info));
876         pac_info->type = host_to_be16(PAC_TYPE_PAC_INFO);
877
878         /* PAC-Lifetime (inside PAC-Info) */
879         hdr = wpabuf_put(buf, sizeof(*hdr));
880         hdr->type = host_to_be16(PAC_TYPE_CRED_LIFETIME);
881         hdr->len = host_to_be16(4);
882         wpabuf_put_be32(buf, now.sec + PAC_KEY_LIFETIME);
883
884         /* A-ID (inside PAC-Info) */
885         hdr = wpabuf_put(buf, sizeof(*hdr));
886         hdr->type = host_to_be16(PAC_TYPE_A_ID);
887         hdr->len = host_to_be16(srv_id_len);
888         wpabuf_put_data(buf, data->srv_id, srv_id_len);
889         
890         /* Note: headers may be misaligned after A-ID */
891
892         /* A-ID-Info (inside PAC-Info) */
893         hdr = wpabuf_put(buf, sizeof(*hdr));
894         WPA_PUT_BE16((u8 *) &hdr->type, PAC_TYPE_A_ID_INFO);
895         WPA_PUT_BE16((u8 *) &hdr->len, srv_id_len);
896         wpabuf_put_data(buf, data->srv_id, srv_id_len);
897
898         /* PAC-Type (inside PAC-Info) */
899         hdr = wpabuf_put(buf, sizeof(*hdr));
900         WPA_PUT_BE16((u8 *) &hdr->type, PAC_TYPE_PAC_TYPE);
901         WPA_PUT_BE16((u8 *) &hdr->len, 2);
902         wpabuf_put_be16(buf, PAC_TYPE_TUNNEL_PAC);
903
904         /* Update PAC-Info and PAC TLV Length fields */
905         pos = wpabuf_put(buf, 0);
906         pac_info->len = host_to_be16(pos - (u8 *) (pac_info + 1));
907         pac_tlv->length = host_to_be16(pos - (u8 *) (pac_tlv + 1));
908
909         /* Result TLV */
910         wpa_printf(MSG_DEBUG, "EAP-FAST: Add Result TLV (status=SUCCESS)");
911         result = wpabuf_put(buf, sizeof(*result));
912         WPA_PUT_BE16((u8 *) &result->tlv_type,
913                      EAP_TLV_TYPE_MANDATORY | EAP_TLV_RESULT_TLV);
914         WPA_PUT_BE16((u8 *) &result->length, 2);
915         WPA_PUT_BE16((u8 *) &result->status, EAP_TLV_RESULT_SUCCESS);
916
917         return buf;
918 }
919
920
921 static struct wpabuf * eap_fast_buildReq(struct eap_sm *sm, void *priv, u8 id)
922 {
923         struct eap_fast_data *data = priv;
924         struct wpabuf *req;
925         struct wpabuf *encr;
926
927         if (data->state == START)
928                 return eap_fast_build_start(sm, data, id);
929
930         if (data->state == PHASE1)
931                 return eap_fast_build_req(sm, data, id);
932
933         switch (data->state) {
934         case PHASE2_ID:
935         case PHASE2_METHOD:
936                 req = eap_fast_build_phase2_req(sm, data, id);
937                 break;
938         case CRYPTO_BINDING:
939                 req = eap_fast_build_crypto_binding(sm, data);
940                 break;
941         case REQUEST_PAC:
942                 req = eap_fast_build_pac(sm, data);
943                 break;
944         default:
945                 wpa_printf(MSG_DEBUG, "EAP-FAST: %s - unexpected state %d",
946                            __func__, data->state);
947                 return NULL;
948         }
949
950         if (req == NULL)
951                 return NULL;
952
953         wpa_hexdump_buf_key(MSG_DEBUG, "EAP-FAST: Encrypting Phase 2 TLVs",
954                             req);
955         encr = eap_fast_encrypt(sm, data, id, wpabuf_mhead(req),
956                                 wpabuf_len(req));
957         wpabuf_free(req);
958
959         return encr;
960 }
961
962
963 static Boolean eap_fast_check(struct eap_sm *sm, void *priv,
964                               struct wpabuf *respData)
965 {
966         const u8 *pos;
967         size_t len;
968
969         pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_FAST, respData, &len);
970         if (pos == NULL || len < 1) {
971                 wpa_printf(MSG_INFO, "EAP-FAST: Invalid frame");
972                 return TRUE;
973         }
974
975         return FALSE;
976 }
977
978
979 static int eap_fast_phase2_init(struct eap_sm *sm, struct eap_fast_data *data,
980                                 EapType eap_type)
981 {
982         if (data->phase2_priv && data->phase2_method) {
983                 data->phase2_method->reset(sm, data->phase2_priv);
984                 data->phase2_method = NULL;
985                 data->phase2_priv = NULL;
986         }
987         data->phase2_method = eap_server_get_eap_method(EAP_VENDOR_IETF,
988                                                         eap_type);
989         if (!data->phase2_method)
990                 return -1;
991
992         if (data->key_block_p) {
993                 sm->auth_challenge = data->key_block_p->server_challenge;
994                 sm->peer_challenge = data->key_block_p->client_challenge;
995         }
996         sm->init_phase2 = 1;
997         data->phase2_priv = data->phase2_method->init(sm);
998         sm->init_phase2 = 0;
999         sm->auth_challenge = NULL;
1000         sm->peer_challenge = NULL;
1001
1002         return data->phase2_priv == NULL ? -1 : 0;
1003 }
1004
1005
1006 static void eap_fast_process_phase2_response(struct eap_sm *sm,
1007                                              struct eap_fast_data *data,
1008                                              u8 *in_data, size_t in_len)
1009 {
1010         u8 next_type = EAP_TYPE_NONE;
1011         struct eap_hdr *hdr;
1012         u8 *pos;
1013         size_t left;
1014         struct wpabuf buf;
1015         const struct eap_method *m = data->phase2_method;
1016         void *priv = data->phase2_priv;
1017
1018         if (priv == NULL) {
1019                 wpa_printf(MSG_DEBUG, "EAP-FAST: %s - Phase2 not "
1020                            "initialized?!", __func__);
1021                 return;
1022         }
1023
1024         hdr = (struct eap_hdr *) in_data;
1025         pos = (u8 *) (hdr + 1);
1026
1027         if (in_len > sizeof(*hdr) && *pos == EAP_TYPE_NAK) {
1028                 left = in_len - sizeof(*hdr);
1029                 wpa_hexdump(MSG_DEBUG, "EAP-FAST: Phase2 type Nak'ed; "
1030                             "allowed types", pos + 1, left - 1);
1031                 eap_sm_process_nak(sm, pos + 1, left - 1);
1032                 if (sm->user && sm->user_eap_method_index < EAP_MAX_METHODS &&
1033                     sm->user->methods[sm->user_eap_method_index].method !=
1034                     EAP_TYPE_NONE) {
1035                         next_type = sm->user->methods[
1036                                 sm->user_eap_method_index++].method;
1037                         wpa_printf(MSG_DEBUG, "EAP-FAST: try EAP type %d",
1038                                    next_type);
1039                 } else {
1040                         next_type = eap_fast_req_failure(sm, data);
1041                 }
1042                 eap_fast_phase2_init(sm, data, next_type);
1043                 return;
1044         }
1045
1046         wpabuf_set(&buf, in_data, in_len);
1047
1048         if (m->check(sm, priv, &buf)) {
1049                 wpa_printf(MSG_DEBUG, "EAP-FAST: Phase2 check() asked to "
1050                            "ignore the packet");
1051                 next_type = eap_fast_req_failure(sm, data);
1052                 return;
1053         }
1054
1055         m->process(sm, priv, &buf);
1056
1057         if (!m->isDone(sm, priv))
1058                 return;
1059
1060         if (!m->isSuccess(sm, priv)) {
1061                 wpa_printf(MSG_DEBUG, "EAP-FAST: Phase2 method failed");
1062                 next_type = eap_fast_req_failure(sm, data);
1063                 eap_fast_phase2_init(sm, data, next_type);
1064                 return;
1065         }
1066
1067         switch (data->state) {
1068         case PHASE2_ID:
1069                 if (eap_user_get(sm, sm->identity, sm->identity_len, 1) != 0) {
1070                         wpa_hexdump_ascii(MSG_DEBUG, "EAP-FAST: Phase2 "
1071                                           "Identity not found in the user "
1072                                           "database",
1073                                           sm->identity, sm->identity_len);
1074                         next_type = eap_fast_req_failure(sm, data);
1075                         break;
1076                 }
1077
1078                 eap_fast_state(data, PHASE2_METHOD);
1079                 if (data->anon_provisioning) {
1080                         /*
1081                          * Only EAP-MSCHAPv2 is allowed for anonymous
1082                          * provisioning.
1083                          */
1084                         next_type = EAP_TYPE_MSCHAPV2;
1085                         sm->user_eap_method_index = 0;
1086                 } else {
1087                         next_type = sm->user->methods[0].method;
1088                         sm->user_eap_method_index = 1;
1089                 }
1090                 wpa_printf(MSG_DEBUG, "EAP-FAST: try EAP type %d", next_type);
1091                 break;
1092         case PHASE2_METHOD:
1093                 eap_fast_update_icmk(sm, data);
1094                 eap_fast_state(data, CRYPTO_BINDING);
1095                 next_type = EAP_TYPE_NONE;
1096                 break;
1097         case FAILURE:
1098                 break;
1099         default:
1100                 wpa_printf(MSG_DEBUG, "EAP-FAST: %s - unexpected state %d",
1101                            __func__, data->state);
1102                 break;
1103         }
1104
1105         eap_fast_phase2_init(sm, data, next_type);
1106 }
1107
1108
1109 static void eap_fast_process_phase2_eap(struct eap_sm *sm,
1110                                         struct eap_fast_data *data,
1111                                         u8 *in_data, size_t in_len)
1112 {
1113         struct eap_hdr *hdr;
1114         size_t len;
1115
1116         hdr = (struct eap_hdr *) in_data;
1117         if (in_len < (int) sizeof(*hdr)) {
1118                 wpa_printf(MSG_INFO, "EAP-FAST: Too short Phase 2 "
1119                            "EAP frame (len=%d)", in_len);
1120                 eap_fast_req_failure(sm, data);
1121                 return;
1122         }
1123         len = be_to_host16(hdr->length);
1124         if (len > in_len) {
1125                 wpa_printf(MSG_INFO, "EAP-FAST: Length mismatch in "
1126                            "Phase 2 EAP frame (len=%d hdr->length=%d)",
1127                            in_len, len);
1128                 eap_fast_req_failure(sm, data);
1129                 return;
1130         }
1131         wpa_printf(MSG_DEBUG, "EAP-FAST: Received Phase 2: code=%d "
1132                    "identifier=%d length=%d", hdr->code, hdr->identifier, len);
1133         switch (hdr->code) {
1134         case EAP_CODE_RESPONSE:
1135                 eap_fast_process_phase2_response(sm, data, (u8 *) hdr, len);
1136                 break;
1137         default:
1138                 wpa_printf(MSG_INFO, "EAP-FAST: Unexpected code=%d in "
1139                            "Phase 2 EAP header", hdr->code);
1140                 break;
1141         }
1142 }
1143
1144
1145 struct eap_fast_tlv_parse {
1146         u8 *eap_payload_tlv;
1147         size_t eap_payload_tlv_len;
1148         struct eap_tlv_crypto_binding__tlv *crypto_binding;
1149         size_t crypto_binding_len;
1150         int iresult;
1151         int result;
1152         int request_action;
1153         u8 *pac;
1154         size_t pac_len;
1155 };
1156
1157
1158 static int eap_fast_parse_tlv(struct eap_fast_tlv_parse *tlv,
1159                               int tlv_type, u8 *pos, int len)
1160 {
1161         switch (tlv_type) {
1162         case EAP_TLV_EAP_PAYLOAD_TLV:
1163                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: EAP-Payload TLV",
1164                             pos, len);
1165                 if (tlv->eap_payload_tlv) {
1166                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1167                                    "EAP-Payload TLV in the message");
1168                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1169                         return -2;
1170                 }
1171                 tlv->eap_payload_tlv = pos;
1172                 tlv->eap_payload_tlv_len = len;
1173                 break;
1174         case EAP_TLV_RESULT_TLV:
1175                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Result TLV", pos, len);
1176                 if (tlv->result) {
1177                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1178                                    "Result TLV in the message");
1179                         tlv->result = EAP_TLV_RESULT_FAILURE;
1180                         return -2;
1181                 }
1182                 if (len < 2) {
1183                         wpa_printf(MSG_DEBUG, "EAP-FAST: Too short "
1184                                    "Result TLV");
1185                         tlv->result = EAP_TLV_RESULT_FAILURE;
1186                         break;
1187                 }
1188                 tlv->result = WPA_GET_BE16(pos);
1189                 if (tlv->result != EAP_TLV_RESULT_SUCCESS &&
1190                     tlv->result != EAP_TLV_RESULT_FAILURE) {
1191                         wpa_printf(MSG_DEBUG, "EAP-FAST: Unknown Result %d",
1192                                    tlv->result);
1193                         tlv->result = EAP_TLV_RESULT_FAILURE;
1194                 }
1195                 wpa_printf(MSG_DEBUG, "EAP-FAST: Result: %s",
1196                            tlv->result == EAP_TLV_RESULT_SUCCESS ?
1197                            "Success" : "Failure");
1198                 break;
1199         case EAP_TLV_INTERMEDIATE_RESULT_TLV:
1200                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Intermediate Result TLV",
1201                             pos, len);
1202                 if (len < 2) {
1203                         wpa_printf(MSG_DEBUG, "EAP-FAST: Too short "
1204                                    "Intermediate-Result TLV");
1205                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1206                         break;
1207                 }
1208                 if (tlv->iresult) {
1209                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1210                                    "Intermediate-Result TLV in the message");
1211                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1212                         return -2;
1213                 }
1214                 tlv->iresult = WPA_GET_BE16(pos);
1215                 if (tlv->iresult != EAP_TLV_RESULT_SUCCESS &&
1216                     tlv->iresult != EAP_TLV_RESULT_FAILURE) {
1217                         wpa_printf(MSG_DEBUG, "EAP-FAST: Unknown Intermediate "
1218                                    "Result %d", tlv->iresult);
1219                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1220                 }
1221                 wpa_printf(MSG_DEBUG, "EAP-FAST: Intermediate Result: %s",
1222                            tlv->iresult == EAP_TLV_RESULT_SUCCESS ?
1223                            "Success" : "Failure");
1224                 break;
1225         case EAP_TLV_CRYPTO_BINDING_TLV:
1226                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Crypto-Binding TLV",
1227                             pos, len);
1228                 if (tlv->crypto_binding) {
1229                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1230                                    "Crypto-Binding TLV in the message");
1231                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1232                         return -2;
1233                 }
1234                 tlv->crypto_binding_len = sizeof(struct eap_tlv_hdr) + len;
1235                 if (tlv->crypto_binding_len < sizeof(*tlv->crypto_binding)) {
1236                         wpa_printf(MSG_DEBUG, "EAP-FAST: Too short "
1237                                    "Crypto-Binding TLV");
1238                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1239                         return -2;
1240                 }
1241                 tlv->crypto_binding = (struct eap_tlv_crypto_binding__tlv *)
1242                         (pos - sizeof(struct eap_tlv_hdr));
1243                 break;
1244         case EAP_TLV_REQUEST_ACTION_TLV:
1245                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Request-Action TLV",
1246                             pos, len);
1247                 if (tlv->request_action) {
1248                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1249                                    "Request-Action TLV in the message");
1250                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1251                         return -2;
1252                 }
1253                 if (len < 2) {
1254                         wpa_printf(MSG_DEBUG, "EAP-FAST: Too short "
1255                                    "Request-Action TLV");
1256                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1257                         break;
1258                 }
1259                 tlv->request_action = WPA_GET_BE16(pos);
1260                 wpa_printf(MSG_DEBUG, "EAP-FAST: Request-Action: %d",
1261                            tlv->request_action);
1262                 break;
1263         case EAP_TLV_PAC_TLV:
1264                 wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: PAC TLV", pos, len);
1265                 if (tlv->pac) {
1266                         wpa_printf(MSG_DEBUG, "EAP-FAST: More than one "
1267                                    "PAC TLV in the message");
1268                         tlv->iresult = EAP_TLV_RESULT_FAILURE;
1269                         return -2;
1270                 }
1271                 tlv->pac = pos;
1272                 tlv->pac_len = len;
1273                 break;
1274         default:
1275                 /* Unknown TLV */
1276                 return -1;
1277         }
1278
1279         return 0;
1280 }
1281
1282
1283 static int eap_fast_parse_tlvs(u8 *data, size_t data_len,
1284                                struct eap_fast_tlv_parse *tlv)
1285 {
1286         int mandatory, tlv_type, len, res;
1287         u8 *pos, *end;
1288
1289         os_memset(tlv, 0, sizeof(*tlv));
1290
1291         pos = data;
1292         end = data + data_len;
1293         while (pos + 4 < end) {
1294                 mandatory = pos[0] & 0x80;
1295                 tlv_type = WPA_GET_BE16(pos) & 0x3fff;
1296                 pos += 2;
1297                 len = WPA_GET_BE16(pos);
1298                 pos += 2;
1299                 if (pos + len > end) {
1300                         wpa_printf(MSG_INFO, "EAP-FAST: TLV overflow");
1301                         return -1;
1302                 }
1303                 wpa_printf(MSG_DEBUG, "EAP-FAST: Received Phase 2: "
1304                            "TLV type %d length %d%s",
1305                            tlv_type, len, mandatory ? " (mandatory)" : "");
1306
1307                 res = eap_fast_parse_tlv(tlv, tlv_type, pos, len);
1308                 if (res == -2)
1309                         break;
1310                 if (res < 0) {
1311                         if (mandatory) {
1312                                 wpa_printf(MSG_DEBUG, "EAP-FAST: Nak unknown "
1313                                            "mandatory TLV type %d", tlv_type);
1314                                 /* TODO: generate Nak TLV */
1315                                 break;
1316                         } else {
1317                                 wpa_printf(MSG_DEBUG, "EAP-FAST: Ignored "
1318                                            "unknown optional TLV type %d",
1319                                            tlv_type);
1320                         }
1321                 }
1322
1323                 pos += len;
1324         }
1325
1326         return 0;
1327 }
1328
1329
1330 static int eap_fast_validate_crypto_binding(
1331         struct eap_fast_data *data, struct eap_tlv_crypto_binding__tlv *b,
1332         size_t bind_len)
1333 {
1334         u8 cmac[20];
1335
1336         wpa_printf(MSG_DEBUG, "EAP-FAST: Reply Crypto-Binding TLV: "
1337                    "Version %d Received Version %d SubType %d",
1338                    b->version, b->received_version, b->subtype);
1339         wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: NONCE",
1340                     b->nonce, sizeof(b->nonce));
1341         wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Compound MAC",
1342                     b->compound_mac, sizeof(b->compound_mac));
1343
1344         if (b->version != EAP_FAST_VERSION ||
1345             b->received_version != EAP_FAST_VERSION) {
1346                 wpa_printf(MSG_DEBUG, "EAP-FAST: Unexpected version "
1347                            "in Crypto-Binding: version %d "
1348                            "received_version %d", b->version,
1349                            b->received_version);
1350                 return -1;
1351         }
1352
1353         if (b->subtype != EAP_TLV_CRYPTO_BINDING_SUBTYPE_RESPONSE) {
1354                 wpa_printf(MSG_DEBUG, "EAP-FAST: Unexpected subtype in "
1355                            "Crypto-Binding: %d", b->subtype);
1356                 return -1;
1357         }
1358
1359         if (os_memcmp(data->crypto_binding_nonce, b->nonce, 31) != 0 ||
1360             (data->crypto_binding_nonce[31] | 1) != b->nonce[31]) {
1361                 wpa_printf(MSG_DEBUG, "EAP-FAST: Invalid nonce in "
1362                            "Crypto-Binding");
1363                 return -1;
1364         }
1365
1366         os_memcpy(cmac, b->compound_mac, sizeof(cmac));
1367         os_memset(b->compound_mac, 0, sizeof(cmac));
1368         wpa_hexdump(MSG_MSGDUMP, "EAP-FAST: Crypto-Binding TLV for "
1369                     "Compound MAC calculation",
1370                     (u8 *) b, bind_len);
1371         hmac_sha1(data->cmk, 20, (u8 *) b, bind_len, b->compound_mac);
1372         if (os_memcmp(cmac, b->compound_mac, sizeof(cmac)) != 0) {
1373                 wpa_hexdump(MSG_MSGDUMP,
1374                             "EAP-FAST: Calculated Compound MAC",
1375                             b->compound_mac, sizeof(cmac));
1376                 wpa_printf(MSG_INFO, "EAP-FAST: Compound MAC did not "
1377                            "match");
1378                 return -1;
1379         }
1380
1381         return 0;
1382 }
1383
1384
1385 static int eap_fast_pac_type(u8 *pac, size_t len, u16 type)
1386 {
1387         struct eap_tlv_pac_type_tlv *tlv;
1388
1389         if (pac == NULL || len != sizeof(*tlv))
1390                 return 0;
1391
1392         tlv = (struct eap_tlv_pac_type_tlv *) pac;
1393
1394         return be_to_host16(tlv->tlv_type) == PAC_TYPE_PAC_TYPE &&
1395                 be_to_host16(tlv->length) == 2 &&
1396                 be_to_host16(tlv->pac_type) == type;
1397 }
1398
1399
1400 static void eap_fast_process_phase2_tlvs(struct eap_sm *sm,
1401                                          struct eap_fast_data *data,
1402                                          u8 *in_data, size_t in_len)
1403 {
1404         struct eap_fast_tlv_parse tlv;
1405         int check_crypto_binding = data->state == CRYPTO_BINDING;
1406
1407         if (eap_fast_parse_tlvs(in_data, in_len, &tlv) < 0) {
1408                 wpa_printf(MSG_DEBUG, "EAP-FAST: Failed to parse received "
1409                            "Phase 2 TLVs");
1410                 return;
1411         }
1412
1413         if (tlv.result == EAP_TLV_RESULT_FAILURE) {
1414                 wpa_printf(MSG_DEBUG, "EAP-FAST: Result TLV indicated "
1415                            "failure");
1416                 eap_fast_state(data, FAILURE);
1417                 return;
1418         }
1419
1420         if (data->state == REQUEST_PAC) {
1421                 u16 type, len, res;
1422                 if (tlv.pac == NULL || tlv.pac_len < 6) {
1423                         wpa_printf(MSG_DEBUG, "EAP-FAST: No PAC "
1424                                    "Acknowledgement received");
1425                         eap_fast_state(data, FAILURE);
1426                         return;
1427                 }
1428
1429                 type = WPA_GET_BE16(tlv.pac);
1430                 len = WPA_GET_BE16(tlv.pac + 2);
1431                 res = WPA_GET_BE16(tlv.pac + 4);
1432
1433                 if (type != PAC_TYPE_PAC_ACKNOWLEDGEMENT || len != 2 ||
1434                     res != EAP_TLV_RESULT_SUCCESS) {
1435                         wpa_printf(MSG_DEBUG, "EAP-FAST: PAC TLV did not "
1436                                    "contain acknowledgement");
1437                         eap_fast_state(data, FAILURE);
1438                         return;
1439                 }
1440
1441                 wpa_printf(MSG_DEBUG, "EAP-FAST: PAC-Acknowledgement received "
1442                            "- PAC provisioning succeeded");
1443                 eap_fast_state(data, data->anon_provisioning ?
1444                                FAILURE : SUCCESS);
1445                 return;
1446         }
1447
1448         if (tlv.eap_payload_tlv) {
1449                 eap_fast_process_phase2_eap(sm, data, tlv.eap_payload_tlv,
1450                                             tlv.eap_payload_tlv_len);
1451         }
1452
1453         if (check_crypto_binding) {
1454                 if (tlv.crypto_binding == NULL) {
1455                         wpa_printf(MSG_DEBUG, "EAP-FAST: No Crypto-Binding "
1456                                    "TLV received");
1457                         eap_fast_state(data, FAILURE);
1458                         return;
1459                 }
1460
1461                 if (data->final_result &&
1462                     tlv.result != EAP_TLV_RESULT_SUCCESS) {
1463                         wpa_printf(MSG_DEBUG, "EAP-FAST: Crypto-Binding TLV "
1464                                    "without Success Result");
1465                         eap_fast_state(data, FAILURE);
1466                         return;
1467                 }
1468
1469                 if (!data->final_result &&
1470                     tlv.iresult != EAP_TLV_RESULT_SUCCESS) {
1471                         wpa_printf(MSG_DEBUG, "EAP-FAST: Crypto-Binding TLV "
1472                                    "without intermediate Success Result");
1473                         eap_fast_state(data, FAILURE);
1474                         return;
1475                 }
1476
1477                 if (eap_fast_validate_crypto_binding(data, tlv.crypto_binding,
1478                                                      tlv.crypto_binding_len)) {
1479                         eap_fast_state(data, FAILURE);
1480                         return;
1481                 }
1482
1483                 wpa_printf(MSG_DEBUG, "EAP-FAST: Valid Crypto-Binding TLV "
1484                            "received - authentication completed successfully");
1485
1486                 if (data->anon_provisioning ||
1487                     (tlv.request_action == EAP_TLV_ACTION_PROCESS_TLV &&
1488                      eap_fast_pac_type(tlv.pac, tlv.pac_len,
1489                                        PAC_TYPE_TUNNEL_PAC))) {
1490                         wpa_printf(MSG_DEBUG, "EAP-FAST: Requested a new "
1491                                    "Tunnel PAC");
1492                         eap_fast_state(data, REQUEST_PAC);
1493                 } else if (data->send_new_pac) {
1494                         wpa_printf(MSG_DEBUG, "EAP-FAST: Server triggered "
1495                                    "re-keying of Tunnel PAC");
1496                         eap_fast_state(data, REQUEST_PAC);
1497                 } else
1498                         eap_fast_state(data, SUCCESS);
1499         }
1500 }
1501
1502
1503 static void eap_fast_process_phase2(struct eap_sm *sm,
1504                                     struct eap_fast_data *data,
1505                                     const u8 *in_data, size_t in_len)
1506 {
1507         u8 *in_decrypted;
1508         int len_decrypted, res;
1509         size_t buf_len;
1510
1511         wpa_printf(MSG_DEBUG, "EAP-FAST: Received %lu bytes encrypted data for"
1512                    " Phase 2", (unsigned long) in_len);
1513
1514         if (data->pending_phase2_resp) {
1515                 wpa_printf(MSG_DEBUG, "EAP-PEAP: Pending Phase 2 response - "
1516                            "skip decryption and use old data");
1517                 eap_fast_process_phase2_tlvs(
1518                         sm, data, wpabuf_mhead(data->pending_phase2_resp),
1519                         wpabuf_len(data->pending_phase2_resp));
1520                 wpabuf_free(data->pending_phase2_resp);
1521                 data->pending_phase2_resp = NULL;
1522                 return;
1523         }
1524
1525         /* FIX: get rid of const -> non-const typecast */
1526         res = eap_server_tls_data_reassemble(sm, &data->ssl, (u8 **) &in_data,
1527                                              &in_len);
1528         if (res < 0 || res == 1)
1529                 return;
1530
1531         buf_len = in_len;
1532         if (data->ssl.tls_in_total > buf_len)
1533                 buf_len = data->ssl.tls_in_total;
1534         in_decrypted = os_malloc(buf_len);
1535         if (in_decrypted == NULL) {
1536                 os_free(data->ssl.tls_in);
1537                 data->ssl.tls_in = NULL;
1538                 data->ssl.tls_in_len = 0;
1539                 wpa_printf(MSG_WARNING, "EAP-FAST: Failed to allocate memory "
1540                            "for decryption");
1541                 return;
1542         }
1543
1544         len_decrypted = tls_connection_decrypt(sm->ssl_ctx, data->ssl.conn,
1545                                                in_data, in_len,
1546                                                in_decrypted, buf_len);
1547         os_free(data->ssl.tls_in);
1548         data->ssl.tls_in = NULL;
1549         data->ssl.tls_in_len = 0;
1550         if (len_decrypted < 0) {
1551                 wpa_printf(MSG_INFO, "EAP-FAST: Failed to decrypt Phase 2 "
1552                            "data");
1553                 os_free(in_decrypted);
1554                 eap_fast_state(data, FAILURE);
1555                 return;
1556         }
1557
1558         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Decrypted Phase 2 TLVs",
1559                         in_decrypted, len_decrypted);
1560
1561         eap_fast_process_phase2_tlvs(sm, data, in_decrypted, len_decrypted);
1562
1563         if (sm->method_pending == METHOD_PENDING_WAIT) {
1564                 wpa_printf(MSG_DEBUG, "EAP-FAST: Phase2 method is in "
1565                            "pending wait state - save decrypted response");
1566                 wpabuf_free(data->pending_phase2_resp);
1567                 data->pending_phase2_resp = wpabuf_alloc_copy(in_decrypted,
1568                                                               len_decrypted);
1569         }
1570
1571         os_free(in_decrypted);
1572 }
1573
1574
1575 static void eap_fast_process(struct eap_sm *sm, void *priv,
1576                              struct wpabuf *respData)
1577 {
1578         struct eap_fast_data *data = priv;
1579         const u8 *pos;
1580         u8 flags;
1581         size_t left;
1582         unsigned int tls_msg_len;
1583         int peer_version;
1584         u8 next_type;
1585
1586         pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_FAST, respData,
1587                                &left);
1588         if (pos == NULL || left < 1)
1589                 return;
1590         flags = *pos++;
1591         left--;
1592         wpa_printf(MSG_DEBUG, "EAP-FAST: Received packet(len=%lu) - "
1593                    "Flags 0x%02x", (unsigned long) wpabuf_len(respData),
1594                    flags);
1595         data->peer_version = peer_version = flags & EAP_PEAP_VERSION_MASK;
1596         if (data->force_version >= 0 && peer_version != data->force_version) {
1597                 wpa_printf(MSG_INFO, "EAP-FAST: peer did not select the forced"
1598                            " version (forced=%d peer=%d) - reject",
1599                            data->force_version, peer_version);
1600                 eap_fast_state(data, FAILURE);
1601                 return;
1602         }
1603         if (peer_version < data->fast_version) {
1604                 wpa_printf(MSG_DEBUG, "EAP-FAST: peer ver=%d, own ver=%d; "
1605                            "use version %d",
1606                            peer_version, data->fast_version, peer_version);
1607                 data->fast_version = peer_version;
1608         }
1609         if (flags & EAP_TLS_FLAGS_LENGTH_INCLUDED) {
1610                 if (left < 4) {
1611                         wpa_printf(MSG_INFO, "EAP-FAST: Short frame with TLS "
1612                                    "length");
1613                         eap_fast_state(data, FAILURE);
1614                         return;
1615                 }
1616                 tls_msg_len = WPA_GET_BE32(pos);
1617                 wpa_printf(MSG_DEBUG, "EAP-FAST: TLS Message Length: %d",
1618                            tls_msg_len);
1619                 if (data->ssl.tls_in_left == 0) {
1620                         data->ssl.tls_in_total = tls_msg_len;
1621                         data->ssl.tls_in_left = tls_msg_len;
1622                         os_free(data->ssl.tls_in);
1623                         data->ssl.tls_in = NULL;
1624                         data->ssl.tls_in_len = 0;
1625                 }
1626                 pos += 4;
1627                 left -= 4;
1628         }
1629
1630         switch (data->state) {
1631         case PHASE1:
1632                 if (eap_server_tls_process_helper(sm, &data->ssl, pos, left) <
1633                     0) {
1634                         wpa_printf(MSG_INFO, "EAP-FAST: TLS processing "
1635                                    "failed");
1636                         eap_fast_state(data, FAILURE);
1637                 }
1638
1639                 if (!tls_connection_established(sm->ssl_ctx, data->ssl.conn) ||
1640                     data->ssl.tls_out_len > 0)
1641                         break;
1642
1643                 /*
1644                  * Phase 1 was completed with the received message (e.g., when
1645                  * using abbreviated handshake), so Phase 2 can be started
1646                  * immediately without having to send through an empty message
1647                  * to the peer.
1648                  */
1649
1650                 if (eap_fast_phase1_done(sm, data) < 0)
1651                         break;
1652
1653                 /* fall through to PHASE2_START */
1654         case PHASE2_START:
1655                 if (data->identity) {
1656                         os_free(sm->identity);
1657                         sm->identity = data->identity;
1658                         data->identity = NULL;
1659                         sm->identity_len = data->identity_len;
1660                         data->identity_len = 0;
1661                         if (eap_user_get(sm, sm->identity, sm->identity_len, 1)
1662                             != 0) {
1663                                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-FAST: "
1664                                                   "Phase2 Identity not found "
1665                                                   "in the user database",
1666                                                   sm->identity,
1667                                                   sm->identity_len);
1668                                 next_type = eap_fast_req_failure(sm, data);
1669                         } else {
1670                                 wpa_printf(MSG_DEBUG, "EAP-FAST: Identity "
1671                                            "already known - skip Phase 2 "
1672                                            "Identity Request");
1673                                 next_type = sm->user->methods[0].method;
1674                                 sm->user_eap_method_index = 1;
1675                         }
1676
1677                         eap_fast_state(data, PHASE2_METHOD);
1678                 } else {
1679                         eap_fast_state(data, PHASE2_ID);
1680                         next_type = EAP_TYPE_IDENTITY;
1681                 }
1682
1683                 eap_fast_phase2_init(sm, data, next_type);
1684                 break;
1685         case PHASE2_ID:
1686         case PHASE2_METHOD:
1687         case CRYPTO_BINDING:
1688         case REQUEST_PAC:
1689                 eap_fast_process_phase2(sm, data, pos, left);
1690                 break;
1691         default:
1692                 wpa_printf(MSG_DEBUG, "EAP-FAST: Unexpected state %d in %s",
1693                            data->state, __func__);
1694                 break;
1695         }
1696
1697         if (tls_connection_get_write_alerts(sm->ssl_ctx, data->ssl.conn) > 1) {
1698                 wpa_printf(MSG_INFO, "EAP-FAST: Locally detected fatal error "
1699                            "in TLS processing");
1700                 eap_fast_state(data, FAILURE);
1701         }
1702 }
1703
1704
1705 static Boolean eap_fast_isDone(struct eap_sm *sm, void *priv)
1706 {
1707         struct eap_fast_data *data = priv;
1708         return data->state == SUCCESS || data->state == FAILURE;
1709 }
1710
1711
1712 static u8 * eap_fast_getKey(struct eap_sm *sm, void *priv, size_t *len)
1713 {
1714         struct eap_fast_data *data = priv;
1715         u8 *eapKeyData;
1716
1717         if (data->state != SUCCESS)
1718                 return NULL;
1719
1720         /*
1721          * RFC 4851, Section 5.4: EAP Master Session Key Genreration
1722          * MSK = T-PRF(S-IMCK[j], "Session Key Generating Function", 64)
1723          */
1724
1725         eapKeyData = os_malloc(EAP_FAST_KEY_LEN);
1726         if (eapKeyData == NULL)
1727                 return NULL;
1728
1729         sha1_t_prf(data->simck, EAP_FAST_SIMCK_LEN,
1730                    "Session Key Generating Function", (u8 *) "", 0,
1731                    eapKeyData, EAP_FAST_KEY_LEN);
1732         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Derived key (MSK)",
1733                         eapKeyData, EAP_FAST_KEY_LEN);
1734         *len = EAP_FAST_KEY_LEN;
1735
1736         return eapKeyData;
1737 }
1738
1739
1740 static u8 * eap_fast_get_emsk(struct eap_sm *sm, void *priv, size_t *len)
1741 {
1742         struct eap_fast_data *data = priv;
1743         u8 *eapKeyData;
1744
1745         if (data->state != SUCCESS)
1746                 return NULL;
1747
1748         /*
1749          * RFC 4851, Section 5.4: EAP Master Session Key Genreration
1750          * EMSK = T-PRF(S-IMCK[j],
1751          *        "Extended Session Key Generating Function", 64)
1752          */
1753
1754         eapKeyData = os_malloc(EAP_EMSK_LEN);
1755         if (eapKeyData == NULL)
1756                 return NULL;
1757
1758         sha1_t_prf(data->simck, EAP_FAST_SIMCK_LEN,
1759                    "Extended Session Key Generating Function",
1760                    (u8 *) "", 0, eapKeyData, EAP_EMSK_LEN);
1761         wpa_hexdump_key(MSG_DEBUG, "EAP-FAST: Derived key (EMSK)",
1762                         eapKeyData, EAP_EMSK_LEN);
1763
1764         *len = EAP_EMSK_LEN;
1765
1766         return eapKeyData;
1767 }
1768
1769
1770 static Boolean eap_fast_isSuccess(struct eap_sm *sm, void *priv)
1771 {
1772         struct eap_fast_data *data = priv;
1773         return data->state == SUCCESS;
1774 }
1775
1776
1777 int eap_server_fast_register(void)
1778 {
1779         struct eap_method *eap;
1780         int ret;
1781
1782         eap = eap_server_method_alloc(EAP_SERVER_METHOD_INTERFACE_VERSION,
1783                                       EAP_VENDOR_IETF, EAP_TYPE_FAST, "FAST");
1784         if (eap == NULL)
1785                 return -1;
1786
1787         eap->init = eap_fast_init;
1788         eap->reset = eap_fast_reset;
1789         eap->buildReq = eap_fast_buildReq;
1790         eap->check = eap_fast_check;
1791         eap->process = eap_fast_process;
1792         eap->isDone = eap_fast_isDone;
1793         eap->getKey = eap_fast_getKey;
1794         eap->get_emsk = eap_fast_get_emsk;
1795         eap->isSuccess = eap_fast_isSuccess;
1796
1797         ret = eap_server_method_register(eap);
1798         if (ret)
1799                 eap_server_method_free(eap);
1800         return ret;
1801 }