Fix bug in eap_ttls_avp_encapsulate() when >248 bytes are encapsulated.
[mech_eap.git] / libeap / src / eap_peer / eap_ttls.c
1 /*
2  * EAP peer method: EAP-TTLS (RFC 5281)
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 "crypto/ms_funcs.h"
19 #include "crypto/sha1.h"
20 #include "crypto/tls.h"
21 #include "eap_common/chap.h"
22 #include "eap_common/eap_ttls.h"
23 #include "mschapv2.h"
24 #include "eap_i.h"
25 #include "eap_tls_common.h"
26 #include "eap_config.h"
27
28
29 /* Maximum supported TTLS version
30  * 0 = RFC 5281
31  * 1 = draft-funk-eap-ttls-v1-00.txt
32  */
33 #ifndef EAP_TTLS_VERSION
34 #define EAP_TTLS_VERSION 0 /* TTLSv1 implementation is not yet complete */
35 #endif /* EAP_TTLS_VERSION */
36
37
38 #define MSCHAPV2_KEY_LEN 16
39 #define MSCHAPV2_NT_RESPONSE_LEN 24
40
41
42 static void eap_ttls_deinit(struct eap_sm *sm, void *priv);
43
44
45 struct eap_ttls_data {
46         struct eap_ssl_data ssl;
47         int ssl_initialized;
48
49         int ttls_version, force_ttls_version;
50
51         const struct eap_method *phase2_method;
52         void *phase2_priv;
53         int phase2_success;
54         int phase2_start;
55
56         enum phase2_types {
57                 EAP_TTLS_PHASE2_EAP,
58                 EAP_TTLS_PHASE2_MSCHAPV2,
59                 EAP_TTLS_PHASE2_MSCHAP,
60                 EAP_TTLS_PHASE2_PAP,
61                 EAP_TTLS_PHASE2_CHAP
62         } phase2_type;
63         struct eap_method_type phase2_eap_type;
64         struct eap_method_type *phase2_eap_types;
65         size_t num_phase2_eap_types;
66
67         u8 auth_response[MSCHAPV2_AUTH_RESPONSE_LEN];
68         int auth_response_valid;
69         u8 master_key[MSCHAPV2_MASTER_KEY_LEN]; /* MSCHAPv2 master key */
70         u8 ident;
71         int resuming; /* starting a resumed session */
72         int reauth; /* reauthentication */
73         u8 *key_data;
74
75         struct wpabuf *pending_phase2_req;
76         int chbind_req_sent; /* channel binding request was sent */
77 #ifdef EAP_TNC
78         int ready_for_tnc;
79         int tnc_started;
80 #endif /* EAP_TNC */
81 };
82
83
84 /* draft-ietf-emu-chbind-13 section 5.3 */
85
86 #ifdef _MSC_VER
87 #pragma pack(push, 1)
88 #endif /* _MSC_VER */
89
90 struct chbind_hdr {
91         u16 len;
92         u8 nsid;
93 };
94
95 #ifdef _MSC_VER
96 #pragma pack(pop)
97 #endif /* _MSC_VER */
98
99
100
101 static void * eap_ttls_init(struct eap_sm *sm)
102 {
103         struct eap_ttls_data *data;
104         struct eap_peer_config *config = eap_get_config(sm);
105         char *selected;
106
107         data = os_zalloc(sizeof(*data));
108         if (data == NULL)
109                 return NULL;
110         data->ttls_version = EAP_TTLS_VERSION;
111         data->force_ttls_version = -1;
112         selected = "EAP";
113         data->phase2_type = EAP_TTLS_PHASE2_EAP;
114
115 #if EAP_TTLS_VERSION > 0
116         if (config && config->phase1) {
117                 const char *pos = os_strstr(config->phase1, "ttlsver=");
118                 if (pos) {
119                         data->force_ttls_version = atoi(pos + 8);
120                         data->ttls_version = data->force_ttls_version;
121                         wpa_printf(MSG_DEBUG, "EAP-TTLS: Forced TTLS version "
122                                    "%d", data->force_ttls_version);
123                 }
124         }
125 #endif /* EAP_TTLS_VERSION */
126
127         if (config && config->phase2) {
128                 if (os_strstr(config->phase2, "autheap=")) {
129                         selected = "EAP";
130                         data->phase2_type = EAP_TTLS_PHASE2_EAP;
131                 } else if (os_strstr(config->phase2, "auth=MSCHAPV2")) {
132                         selected = "MSCHAPV2";
133                         data->phase2_type = EAP_TTLS_PHASE2_MSCHAPV2;
134                 } else if (os_strstr(config->phase2, "auth=MSCHAP")) {
135                         selected = "MSCHAP";
136                         data->phase2_type = EAP_TTLS_PHASE2_MSCHAP;
137                 } else if (os_strstr(config->phase2, "auth=PAP")) {
138                         selected = "PAP";
139                         data->phase2_type = EAP_TTLS_PHASE2_PAP;
140                 } else if (os_strstr(config->phase2, "auth=CHAP")) {
141                         selected = "CHAP";
142                         data->phase2_type = EAP_TTLS_PHASE2_CHAP;
143                 }
144         }
145         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase2 type: %s", selected);
146
147         if (data->phase2_type == EAP_TTLS_PHASE2_EAP) {
148                 if (eap_peer_select_phase2_methods(config, "autheap=",
149                                                    &data->phase2_eap_types,
150                                                    &data->num_phase2_eap_types)
151                     < 0) {
152                         eap_ttls_deinit(sm, data);
153                         return NULL;
154                 }
155
156                 data->phase2_eap_type.vendor = EAP_VENDOR_IETF;
157                 data->phase2_eap_type.method = EAP_TYPE_NONE;
158         }
159
160 #if EAP_TTLS_VERSION > 0
161         if (!(tls_capabilities(sm->ssl_ctx) & TLS_CAPABILITY_IA) &&
162             data->ttls_version > 0) {
163                 if (data->force_ttls_version > 0) {
164                         wpa_printf(MSG_INFO, "EAP-TTLS: Forced TTLSv%d and "
165                                    "TLS library does not support TLS/IA.",
166                                    data->force_ttls_version);
167                         eap_ttls_deinit(sm, data);
168                         return NULL;
169                 }
170                 data->ttls_version = 0;
171         }
172 #endif /* EAP_TTLS_VERSION */
173
174         return data;
175 }
176
177
178 static void eap_ttls_phase2_eap_deinit(struct eap_sm *sm,
179                                        struct eap_ttls_data *data)
180 {
181         if (data->phase2_priv && data->phase2_method) {
182                 data->phase2_method->deinit(sm, data->phase2_priv);
183                 data->phase2_method = NULL;
184                 data->phase2_priv = NULL;
185         }
186 }
187
188
189 static void eap_ttls_deinit(struct eap_sm *sm, void *priv)
190 {
191         struct eap_ttls_data *data = priv;
192         if (data == NULL)
193                 return;
194         eap_ttls_phase2_eap_deinit(sm, data);
195         os_free(data->phase2_eap_types);
196         if (data->ssl_initialized)
197                 eap_peer_tls_ssl_deinit(sm, &data->ssl);
198         os_free(data->key_data);
199         wpabuf_free(data->pending_phase2_req);
200         os_free(data);
201 }
202
203
204 static u8 * eap_ttls_avp_hdr(u8 *avphdr, u32 avp_code, u32 vendor_id,
205                              int mandatory, size_t len)
206 {
207         struct ttls_avp_vendor *avp;
208         u8 flags;
209         size_t hdrlen;
210
211         avp = (struct ttls_avp_vendor *) avphdr;
212         flags = mandatory ? AVP_FLAGS_MANDATORY : 0;
213         if (vendor_id) {
214                 flags |= AVP_FLAGS_VENDOR;
215                 hdrlen = sizeof(*avp);
216                 avp->vendor_id = host_to_be32(vendor_id);
217         } else {
218                 hdrlen = sizeof(struct ttls_avp);
219         }
220
221         avp->avp_code = host_to_be32(avp_code);
222         avp->avp_length = host_to_be32((flags << 24) | (hdrlen + len));
223
224         return avphdr + hdrlen;
225 }
226
227
228 static u8 * eap_ttls_avp_add(u8 *start, u8 *avphdr, u32 avp_code,
229                              u32 vendor_id, int mandatory,
230                              const u8 *data, size_t len)
231 {
232         u8 *pos;
233         pos = eap_ttls_avp_hdr(avphdr, avp_code, vendor_id, mandatory, len);
234         os_memcpy(pos, data, len);
235         pos += len;
236         AVP_PAD(start, pos);
237         return pos;
238 }
239
240
241 static int eap_ttls_avp_encapsulate(struct wpabuf **resp, u32 avp_code,
242                                     int mandatory)
243 {
244         struct wpabuf *msg;
245         u8 *avp, *pos;
246
247         msg = wpabuf_alloc(sizeof(struct ttls_avp) + wpabuf_len(*resp) + 4);
248         if (msg == NULL) {
249                 wpabuf_free(*resp);
250                 *resp = NULL;
251                 return -1;
252         }
253
254         avp = wpabuf_mhead(msg);
255         pos = eap_ttls_avp_hdr(avp, avp_code, 0, mandatory, wpabuf_len(*resp));
256         os_memcpy(pos, wpabuf_head(*resp), wpabuf_len(*resp));
257         pos += wpabuf_len(*resp);
258         AVP_PAD(avp, pos);
259         wpabuf_free(*resp);
260         wpabuf_put(msg, pos - avp);
261         *resp = msg;
262         return 0;
263 }
264
265 /* chop up resp into multiple vsa's as necessary*/
266 static int eap_ttls_avp_vsa_encapsulate(struct wpabuf **resp, u32 vendor,
267                                         u8 attr, int mandatory)
268 {
269         struct wpabuf *msg;
270         u8 *avp, *pos, *src;
271         size_t size = wpabuf_len(*resp);
272         size_t num_msgs = 1 + (size / 248);
273         size_t msg_wrapper_size = sizeof(struct ttls_avp_vendor) + 4;
274         size_t allocated_total = num_msgs * (4 + msg_wrapper_size) + size;
275
276         msg = wpabuf_alloc(allocated_total);
277         if (msg == NULL) {
278                 wpabuf_free(*resp);
279                 *resp = NULL;
280                 return -1;
281         }
282         src = wpabuf_mhead(*resp);
283         avp = wpabuf_mhead(msg);
284         while (size > 0) {
285                 int avp_size = size > 248 ? 248 : size;
286                 size -= avp_size;
287                 pos = eap_ttls_avp_hdr(avp, attr, vendor, mandatory,
288                                        avp_size);
289                 os_memcpy(pos, src, avp_size);
290                 pos += avp_size;
291                 src += avp_size;
292                 AVP_PAD(avp, pos);
293                 wpabuf_put(msg, pos - avp);
294                 avp = pos;
295         }
296         /* check avp-wpabuf_mhead(msg) < allocated_total */
297         wpabuf_free(*resp);
298         *resp = msg;
299         return 0;
300 }
301
302 #if EAP_TTLS_VERSION > 0
303 static int eap_ttls_ia_permute_inner_secret(struct eap_sm *sm,
304                                             struct eap_ttls_data *data,
305                                             const u8 *key, size_t key_len)
306 {
307         u8 *buf;
308         size_t buf_len;
309         int ret;
310
311         if (key) {
312                 buf_len = 2 + key_len;
313                 buf = os_malloc(buf_len);
314                 if (buf == NULL)
315                         return -1;
316                 WPA_PUT_BE16(buf, key_len);
317                 os_memcpy(buf + 2, key, key_len);
318         } else {
319                 buf = NULL;
320                 buf_len = 0;
321         }
322
323         wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Session keys for TLS/IA inner "
324                         "secret permutation", buf, buf_len);
325         ret = tls_connection_ia_permute_inner_secret(sm->ssl_ctx,
326                                                      data->ssl.conn,
327                                                      buf, buf_len);
328         os_free(buf);
329
330         return ret;
331 }
332 #endif /* EAP_TTLS_VERSION */
333
334
335 static int eap_ttls_v0_derive_key(struct eap_sm *sm,
336                                   struct eap_ttls_data *data)
337 {
338         os_free(data->key_data);
339         data->key_data = eap_peer_tls_derive_key(sm, &data->ssl,
340                                                  "ttls keying material",
341                                                  EAP_TLS_KEY_LEN);
342         if (!data->key_data) {
343                 wpa_printf(MSG_INFO, "EAP-TTLS: Failed to derive key");
344                 return -1;
345         }
346
347         wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Derived key",
348                         data->key_data, EAP_TLS_KEY_LEN);
349
350         return 0;
351 }
352
353
354 #if EAP_TTLS_VERSION > 0
355 static int eap_ttls_v1_derive_key(struct eap_sm *sm,
356                                   struct eap_ttls_data *data)
357 {
358         struct tls_keys keys;
359         u8 *rnd;
360
361         os_free(data->key_data);
362         data->key_data = NULL;
363
364         os_memset(&keys, 0, sizeof(keys));
365         if (tls_connection_get_keys(sm->ssl_ctx, data->ssl.conn, &keys) ||
366             keys.client_random == NULL || keys.server_random == NULL ||
367             keys.inner_secret == NULL) {
368                 wpa_printf(MSG_INFO, "EAP-TTLS: Could not get inner secret, "
369                            "client random, or server random to derive keying "
370                            "material");
371                 return -1;
372         }
373
374         rnd = os_malloc(keys.client_random_len + keys.server_random_len);
375         data->key_data = os_malloc(EAP_TLS_KEY_LEN);
376         if (rnd == NULL || data->key_data == NULL) {
377                 wpa_printf(MSG_INFO, "EAP-TTLS: No memory for key derivation");
378                 os_free(rnd);
379                 os_free(data->key_data);
380                 data->key_data = NULL;
381                 return -1;
382         }
383         os_memcpy(rnd, keys.client_random, keys.client_random_len);
384         os_memcpy(rnd + keys.client_random_len, keys.server_random,
385                   keys.server_random_len);
386
387         if (tls_prf(keys.inner_secret, keys.inner_secret_len,
388                     "ttls v1 keying material", rnd, keys.client_random_len +
389                     keys.server_random_len, data->key_data, EAP_TLS_KEY_LEN)) {
390                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Failed to derive key");
391                 os_free(rnd);
392                 os_free(data->key_data);
393                 data->key_data = NULL;
394                 return -1;
395         }
396
397         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: client/server random",
398                     rnd, keys.client_random_len + keys.server_random_len);
399         wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: TLS/IA inner secret",
400                         keys.inner_secret, keys.inner_secret_len);
401
402         os_free(rnd);
403
404         wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Derived key",
405                         data->key_data, EAP_TLS_KEY_LEN);
406
407         return 0;
408 }
409 #endif /* EAP_TTLS_VERSION */
410
411
412 static u8 * eap_ttls_implicit_challenge(struct eap_sm *sm,
413                                         struct eap_ttls_data *data, size_t len)
414 {
415 #if EAP_TTLS_VERSION > 0
416         struct tls_keys keys;
417         u8 *challenge, *rnd;
418 #endif /* EAP_TTLS_VERSION */
419
420         if (data->ttls_version == 0) {
421                 return eap_peer_tls_derive_key(sm, &data->ssl,
422                                                "ttls challenge", len);
423         }
424
425 #if EAP_TTLS_VERSION > 0
426
427         os_memset(&keys, 0, sizeof(keys));
428         if (tls_connection_get_keys(sm->ssl_ctx, data->ssl.conn, &keys) ||
429             keys.client_random == NULL || keys.server_random == NULL ||
430             keys.inner_secret == NULL) {
431                 wpa_printf(MSG_INFO, "EAP-TTLS: Could not get inner secret, "
432                            "client random, or server random to derive "
433                            "implicit challenge");
434                 return NULL;
435         }
436
437         rnd = os_malloc(keys.client_random_len + keys.server_random_len);
438         challenge = os_malloc(len);
439         if (rnd == NULL || challenge == NULL) {
440                 wpa_printf(MSG_INFO, "EAP-TTLS: No memory for implicit "
441                            "challenge derivation");
442                 os_free(rnd);
443                 os_free(challenge);
444                 return NULL;
445         }
446         os_memcpy(rnd, keys.server_random, keys.server_random_len);
447         os_memcpy(rnd + keys.server_random_len, keys.client_random,
448                   keys.client_random_len);
449
450         if (tls_prf(keys.inner_secret, keys.inner_secret_len,
451                     "inner application challenge", rnd,
452                     keys.client_random_len + keys.server_random_len,
453                     challenge, len)) {
454                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Failed to derive implicit "
455                            "challenge");
456                 os_free(rnd);
457                 os_free(challenge);
458                 return NULL;
459         }
460
461         os_free(rnd);
462
463         wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: Derived implicit challenge",
464                         challenge, len);
465
466         return challenge;
467
468 #else /* EAP_TTLS_VERSION */
469
470         return NULL;
471
472 #endif /* EAP_TTLS_VERSION */
473 }
474
475
476 static void eap_ttlsv1_phase2_eap_finish(struct eap_sm *sm,
477                                          struct eap_ttls_data *data,
478                                          struct eap_method_ret *ret)
479 {
480 #if EAP_TTLS_VERSION > 0
481         if (data->ttls_version > 0) {
482                 const struct eap_method *m = data->phase2_method;
483                 void *priv = data->phase2_priv;
484
485                 /* TTLSv1 requires TLS/IA FinalPhaseFinished */
486                 if (ret->decision == DECISION_UNCOND_SUCC)
487                         ret->decision = DECISION_COND_SUCC;
488                 ret->methodState = METHOD_CONT;
489
490                 if (ret->decision == DECISION_COND_SUCC &&
491                     m->isKeyAvailable && m->getKey &&
492                     m->isKeyAvailable(sm, priv)) {
493                         u8 *key;
494                         size_t key_len;
495                         key = m->getKey(sm, priv, &key_len);
496                         if (key) {
497                                 eap_ttls_ia_permute_inner_secret(
498                                         sm, data, key, key_len);
499                                 os_free(key);
500                         }
501                 }
502         }
503 #endif /* EAP_TTLS_VERSION */
504 }
505
506
507 static void eap_ttls_phase2_select_eap_method(struct eap_ttls_data *data,
508                                               u8 method)
509 {
510         size_t i;
511         for (i = 0; i < data->num_phase2_eap_types; i++) {
512                 if (data->phase2_eap_types[i].vendor != EAP_VENDOR_IETF ||
513                     data->phase2_eap_types[i].method != method)
514                         continue;
515
516                 data->phase2_eap_type.vendor =
517                         data->phase2_eap_types[i].vendor;
518                 data->phase2_eap_type.method =
519                         data->phase2_eap_types[i].method;
520                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Selected "
521                            "Phase 2 EAP vendor %d method %d",
522                            data->phase2_eap_type.vendor,
523                            data->phase2_eap_type.method);
524                 break;
525         }
526 }
527
528
529 static int eap_ttls_phase2_eap_process(struct eap_sm *sm,
530                                        struct eap_ttls_data *data,
531                                        struct eap_method_ret *ret,
532                                        struct eap_hdr *hdr, size_t len,
533                                        struct wpabuf **resp)
534 {
535         struct wpabuf msg;
536         struct eap_method_ret iret;
537
538         os_memset(&iret, 0, sizeof(iret));
539         wpabuf_set(&msg, hdr, len);
540         *resp = data->phase2_method->process(sm, data->phase2_priv, &iret,
541                                              &msg);
542         if ((iret.methodState == METHOD_DONE ||
543              iret.methodState == METHOD_MAY_CONT) &&
544             (iret.decision == DECISION_UNCOND_SUCC ||
545              iret.decision == DECISION_COND_SUCC ||
546              iret.decision == DECISION_FAIL)) {
547                 ret->methodState = iret.methodState;
548                 ret->decision = iret.decision;
549         }
550         eap_ttlsv1_phase2_eap_finish(sm, data, ret);
551
552         return 0;
553 }
554
555
556 static int eap_ttls_phase2_request_eap_method(struct eap_sm *sm,
557                                               struct eap_ttls_data *data,
558                                               struct eap_method_ret *ret,
559                                               struct eap_hdr *hdr, size_t len,
560                                               u8 method, struct wpabuf **resp)
561 {
562 #ifdef EAP_TNC
563         if (data->tnc_started && data->phase2_method &&
564             data->phase2_priv && method == EAP_TYPE_TNC &&
565             data->phase2_eap_type.method == EAP_TYPE_TNC)
566                 return eap_ttls_phase2_eap_process(sm, data, ret, hdr, len,
567                                                    resp);
568
569         if (data->ready_for_tnc && !data->tnc_started &&
570             method == EAP_TYPE_TNC) {
571                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Start TNC after completed "
572                            "EAP method");
573                 data->tnc_started = 1;
574         }
575
576         if (data->tnc_started) {
577                 if (data->phase2_eap_type.vendor != EAP_VENDOR_IETF ||
578                     data->phase2_eap_type.method == EAP_TYPE_TNC) {
579                         wpa_printf(MSG_DEBUG, "EAP-TTLS: Unexpected EAP "
580                                    "type %d for TNC", method);
581                         return -1;
582                 }
583
584                 data->phase2_eap_type.vendor = EAP_VENDOR_IETF;
585                 data->phase2_eap_type.method = method;
586                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Selected "
587                            "Phase 2 EAP vendor %d method %d (TNC)",
588                            data->phase2_eap_type.vendor,
589                            data->phase2_eap_type.method);
590
591                 if (data->phase2_type == EAP_TTLS_PHASE2_EAP)
592                         eap_ttls_phase2_eap_deinit(sm, data);
593         }
594 #endif /* EAP_TNC */
595
596         if (data->phase2_eap_type.vendor == EAP_VENDOR_IETF &&
597             data->phase2_eap_type.method == EAP_TYPE_NONE)
598                 eap_ttls_phase2_select_eap_method(data, method);
599
600         if (method != data->phase2_eap_type.method || method == EAP_TYPE_NONE)
601         {
602                 if (eap_peer_tls_phase2_nak(data->phase2_eap_types,
603                                             data->num_phase2_eap_types,
604                                             hdr, resp))
605                         return -1;
606                 return 0;
607         }
608
609         if (data->phase2_priv == NULL) {
610                 data->phase2_method = eap_peer_get_eap_method(
611                         EAP_VENDOR_IETF, method);
612                 if (data->phase2_method) {
613                         sm->init_phase2 = 1;
614                         data->phase2_priv = data->phase2_method->init(sm);
615                         sm->init_phase2 = 0;
616                 }
617         }
618         if (data->phase2_priv == NULL || data->phase2_method == NULL) {
619                 wpa_printf(MSG_INFO, "EAP-TTLS: failed to initialize "
620                            "Phase 2 EAP method %d", method);
621                 return -1;
622         }
623
624         return eap_ttls_phase2_eap_process(sm, data, ret, hdr, len, resp);
625 }
626
627
628 static int eap_ttls_phase2_request_eap(struct eap_sm *sm,
629                                        struct eap_ttls_data *data,
630                                        struct eap_method_ret *ret,
631                                        struct eap_hdr *hdr,
632                                        struct wpabuf **resp)
633 {
634         size_t len = be_to_host16(hdr->length);
635         u8 *pos;
636         struct eap_peer_config *config = eap_get_config(sm);
637
638         if (len <= sizeof(struct eap_hdr)) {
639                 wpa_printf(MSG_INFO, "EAP-TTLS: too short "
640                            "Phase 2 request (len=%lu)", (unsigned long) len);
641                 return -1;
642         }
643         pos = (u8 *) (hdr + 1);
644         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 EAP Request: type=%d", *pos);
645         switch (*pos) {
646         case EAP_TYPE_IDENTITY:
647                 *resp = eap_sm_buildIdentity(sm, hdr->identifier, 1);
648                 break;
649         default:
650                 if (eap_ttls_phase2_request_eap_method(sm, data, ret, hdr, len,
651                                                        *pos, resp) < 0)
652                         return -1;
653                 break;
654         }
655
656         if (*resp == NULL &&
657             (config->pending_req_identity || config->pending_req_password ||
658              config->pending_req_otp)) {
659                 return 0;
660         }
661
662         if (*resp == NULL)
663                 return -1;
664
665         wpa_hexdump_buf(MSG_DEBUG, "EAP-TTLS: AVP encapsulate EAP Response",
666                         *resp);
667         return eap_ttls_avp_encapsulate(resp, RADIUS_ATTR_EAP_MESSAGE, 1);
668 }
669
670
671 static void eap_ttlsv1_permute_inner(struct eap_sm *sm,
672                                      struct eap_ttls_data *data)
673 {
674 #if EAP_TTLS_VERSION > 0
675         u8 session_key[2 * MSCHAPV2_KEY_LEN];
676
677         if (data->ttls_version == 0)
678                 return;
679
680         get_asymetric_start_key(data->master_key, session_key,
681                                 MSCHAPV2_KEY_LEN, 0, 0);
682         get_asymetric_start_key(data->master_key,
683                                 session_key + MSCHAPV2_KEY_LEN,
684                                 MSCHAPV2_KEY_LEN, 1, 0);
685         eap_ttls_ia_permute_inner_secret(sm, data, session_key,
686                                          sizeof(session_key));
687 #endif /* EAP_TTLS_VERSION */
688 }
689
690
691 static int eap_ttls_phase2_request_mschapv2(struct eap_sm *sm,
692                                             struct eap_ttls_data *data,
693                                             struct eap_method_ret *ret,
694                                             struct wpabuf **resp)
695 {
696         struct wpabuf *msg;
697         u8 *buf, *pos, *challenge, *peer_challenge;
698         const u8 *identity, *password;
699         size_t identity_len, password_len;
700         int pwhash;
701
702         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 MSCHAPV2 Request");
703
704         identity = eap_get_config_identity(sm, &identity_len);
705         password = eap_get_config_password2(sm, &password_len, &pwhash);
706         if (identity == NULL || password == NULL)
707                 return -1;
708
709         msg = wpabuf_alloc(identity_len + 1000);
710         if (msg == NULL) {
711                 wpa_printf(MSG_ERROR,
712                            "EAP-TTLS/MSCHAPV2: Failed to allocate memory");
713                 return -1;
714         }
715         pos = buf = wpabuf_mhead(msg);
716
717         /* User-Name */
718         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1,
719                                identity, identity_len);
720
721         /* MS-CHAP-Challenge */
722         challenge = eap_ttls_implicit_challenge(
723                 sm, data, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN + 1);
724         if (challenge == NULL) {
725                 wpabuf_free(msg);
726                 wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to derive "
727                            "implicit challenge");
728                 return -1;
729         }
730         peer_challenge = challenge + 1 + EAP_TTLS_MSCHAPV2_CHALLENGE_LEN;
731
732         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_MS_CHAP_CHALLENGE,
733                                RADIUS_VENDOR_ID_MICROSOFT, 1,
734                                challenge, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN);
735
736         /* MS-CHAP2-Response */
737         pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_MS_CHAP2_RESPONSE,
738                                RADIUS_VENDOR_ID_MICROSOFT, 1,
739                                EAP_TTLS_MSCHAPV2_RESPONSE_LEN);
740         data->ident = challenge[EAP_TTLS_MSCHAPV2_CHALLENGE_LEN];
741         *pos++ = data->ident;
742         *pos++ = 0; /* Flags */
743         os_memcpy(pos, peer_challenge, EAP_TTLS_MSCHAPV2_CHALLENGE_LEN);
744         pos += EAP_TTLS_MSCHAPV2_CHALLENGE_LEN;
745         os_memset(pos, 0, 8); /* Reserved, must be zero */
746         pos += 8;
747         if (mschapv2_derive_response(identity, identity_len, password,
748                                      password_len, pwhash, challenge,
749                                      peer_challenge, pos, data->auth_response,
750                                      data->master_key)) {
751                 wpabuf_free(msg);
752                 wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAPV2: Failed to derive "
753                            "response");
754                 return -1;
755         }
756         data->auth_response_valid = 1;
757
758         eap_ttlsv1_permute_inner(sm, data);
759
760         pos += 24;
761         os_free(challenge);
762         AVP_PAD(buf, pos);
763
764         wpabuf_put(msg, pos - buf);
765         *resp = msg;
766
767         if (sm->workaround && data->ttls_version == 0) {
768                 /* At least FreeRADIUS seems to be terminating
769                  * EAP-TTLS/MSHCAPV2 without the expected MS-CHAP-v2 Success
770                  * packet. */
771                 wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAPV2: EAP workaround - "
772                            "allow success without tunneled response");
773                 ret->methodState = METHOD_MAY_CONT;
774                 ret->decision = DECISION_COND_SUCC;
775         }
776
777         return 0;
778 }
779
780
781 static int eap_ttls_phase2_request_mschap(struct eap_sm *sm,
782                                           struct eap_ttls_data *data,
783                                           struct eap_method_ret *ret,
784                                           struct wpabuf **resp)
785 {
786         struct wpabuf *msg;
787         u8 *buf, *pos, *challenge;
788         const u8 *identity, *password;
789         size_t identity_len, password_len;
790         int pwhash;
791
792         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 MSCHAP Request");
793
794         identity = eap_get_config_identity(sm, &identity_len);
795         password = eap_get_config_password2(sm, &password_len, &pwhash);
796         if (identity == NULL || password == NULL)
797                 return -1;
798
799         msg = wpabuf_alloc(identity_len + 1000);
800         if (msg == NULL) {
801                 wpa_printf(MSG_ERROR,
802                            "EAP-TTLS/MSCHAP: Failed to allocate memory");
803                 return -1;
804         }
805         pos = buf = wpabuf_mhead(msg);
806
807         /* User-Name */
808         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1,
809                                identity, identity_len);
810
811         /* MS-CHAP-Challenge */
812         challenge = eap_ttls_implicit_challenge(
813                 sm, data, EAP_TTLS_MSCHAP_CHALLENGE_LEN + 1);
814         if (challenge == NULL) {
815                 wpabuf_free(msg);
816                 wpa_printf(MSG_ERROR, "EAP-TTLS/MSCHAP: Failed to derive "
817                            "implicit challenge");
818                 return -1;
819         }
820
821         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_MS_CHAP_CHALLENGE,
822                                RADIUS_VENDOR_ID_MICROSOFT, 1,
823                                challenge, EAP_TTLS_MSCHAP_CHALLENGE_LEN);
824
825         /* MS-CHAP-Response */
826         pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_MS_CHAP_RESPONSE,
827                                RADIUS_VENDOR_ID_MICROSOFT, 1,
828                                EAP_TTLS_MSCHAP_RESPONSE_LEN);
829         data->ident = challenge[EAP_TTLS_MSCHAP_CHALLENGE_LEN];
830         *pos++ = data->ident;
831         *pos++ = 1; /* Flags: Use NT style passwords */
832         os_memset(pos, 0, 24); /* LM-Response */
833         pos += 24;
834         if (pwhash) {
835                 challenge_response(challenge, password, pos); /* NT-Response */
836                 wpa_hexdump_key(MSG_DEBUG, "EAP-TTLS: MSCHAP password hash",
837                                 password, 16);
838         } else {
839                 nt_challenge_response(challenge, password, password_len,
840                                       pos); /* NT-Response */
841                 wpa_hexdump_ascii_key(MSG_DEBUG, "EAP-TTLS: MSCHAP password",
842                                       password, password_len);
843         }
844         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: MSCHAP implicit challenge",
845                     challenge, EAP_TTLS_MSCHAP_CHALLENGE_LEN);
846         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: MSCHAP response", pos, 24);
847         pos += 24;
848         os_free(challenge);
849         AVP_PAD(buf, pos);
850
851         wpabuf_put(msg, pos - buf);
852         *resp = msg;
853
854         if (data->ttls_version > 0) {
855                 /* EAP-TTLSv1 uses TLS/IA FinalPhaseFinished to report success,
856                  * so do not allow connection to be terminated yet. */
857                 ret->methodState = METHOD_CONT;
858                 ret->decision = DECISION_COND_SUCC;
859         } else {
860                 /* EAP-TTLS/MSCHAP does not provide tunneled success
861                  * notification, so assume that Phase2 succeeds. */
862                 ret->methodState = METHOD_DONE;
863                 ret->decision = DECISION_COND_SUCC;
864         }
865
866         return 0;
867 }
868
869
870 static int eap_ttls_phase2_request_pap(struct eap_sm *sm,
871                                        struct eap_ttls_data *data,
872                                        struct eap_method_ret *ret,
873                                        struct wpabuf **resp)
874 {
875         struct wpabuf *msg;
876         u8 *buf, *pos;
877         size_t pad;
878         const u8 *identity, *password;
879         size_t identity_len, password_len;
880
881         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 PAP Request");
882
883         identity = eap_get_config_identity(sm, &identity_len);
884         password = eap_get_config_password(sm, &password_len);
885         if (identity == NULL || password == NULL)
886                 return -1;
887
888         msg = wpabuf_alloc(identity_len + password_len + 100);
889         if (msg == NULL) {
890                 wpa_printf(MSG_ERROR,
891                            "EAP-TTLS/PAP: Failed to allocate memory");
892                 return -1;
893         }
894         pos = buf = wpabuf_mhead(msg);
895
896         /* User-Name */
897         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1,
898                                identity, identity_len);
899
900         /* User-Password; in RADIUS, this is encrypted, but EAP-TTLS encrypts
901          * the data, so no separate encryption is used in the AVP itself.
902          * However, the password is padded to obfuscate its length. */
903         pad = password_len == 0 ? 16 : (16 - (password_len & 15)) & 15;
904         pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_USER_PASSWORD, 0, 1,
905                                password_len + pad);
906         os_memcpy(pos, password, password_len);
907         pos += password_len;
908         os_memset(pos, 0, pad);
909         pos += pad;
910         AVP_PAD(buf, pos);
911
912         wpabuf_put(msg, pos - buf);
913         *resp = msg;
914
915         if (data->ttls_version > 0) {
916                 /* EAP-TTLSv1 uses TLS/IA FinalPhaseFinished to report success,
917                  * so do not allow connection to be terminated yet. */
918                 ret->methodState = METHOD_CONT;
919                 ret->decision = DECISION_COND_SUCC;
920         } else {
921                 /* EAP-TTLS/PAP does not provide tunneled success notification,
922                  * so assume that Phase2 succeeds. */
923                 ret->methodState = METHOD_DONE;
924                 ret->decision = DECISION_COND_SUCC;
925         }
926
927         return 0;
928 }
929
930
931 static int eap_ttls_phase2_request_chap(struct eap_sm *sm,
932                                         struct eap_ttls_data *data,
933                                         struct eap_method_ret *ret,
934                                         struct wpabuf **resp)
935 {
936         struct wpabuf *msg;
937         u8 *buf, *pos, *challenge;
938         const u8 *identity, *password;
939         size_t identity_len, password_len;
940
941         wpa_printf(MSG_DEBUG, "EAP-TTLS: Phase 2 CHAP Request");
942
943         identity = eap_get_config_identity(sm, &identity_len);
944         password = eap_get_config_password(sm, &password_len);
945         if (identity == NULL || password == NULL)
946                 return -1;
947
948         msg = wpabuf_alloc(identity_len + 1000);
949         if (msg == NULL) {
950                 wpa_printf(MSG_ERROR,
951                            "EAP-TTLS/CHAP: Failed to allocate memory");
952                 return -1;
953         }
954         pos = buf = wpabuf_mhead(msg);
955
956         /* User-Name */
957         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_USER_NAME, 0, 1,
958                                identity, identity_len);
959
960         /* CHAP-Challenge */
961         challenge = eap_ttls_implicit_challenge(
962                 sm, data, EAP_TTLS_CHAP_CHALLENGE_LEN + 1);
963         if (challenge == NULL) {
964                 wpabuf_free(msg);
965                 wpa_printf(MSG_ERROR, "EAP-TTLS/CHAP: Failed to derive "
966                            "implicit challenge");
967                 return -1;
968         }
969
970         pos = eap_ttls_avp_add(buf, pos, RADIUS_ATTR_CHAP_CHALLENGE, 0, 1,
971                                challenge, EAP_TTLS_CHAP_CHALLENGE_LEN);
972
973         /* CHAP-Password */
974         pos = eap_ttls_avp_hdr(pos, RADIUS_ATTR_CHAP_PASSWORD, 0, 1,
975                                1 + EAP_TTLS_CHAP_PASSWORD_LEN);
976         data->ident = challenge[EAP_TTLS_CHAP_CHALLENGE_LEN];
977         *pos++ = data->ident;
978
979         /* MD5(Ident + Password + Challenge) */
980         chap_md5(data->ident, password, password_len, challenge,
981                  EAP_TTLS_CHAP_CHALLENGE_LEN, pos);
982
983         wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: CHAP username",
984                           identity, identity_len);
985         wpa_hexdump_ascii_key(MSG_DEBUG, "EAP-TTLS: CHAP password",
986                               password, password_len);
987         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: CHAP implicit challenge",
988                     challenge, EAP_TTLS_CHAP_CHALLENGE_LEN);
989         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: CHAP password",
990                     pos, EAP_TTLS_CHAP_PASSWORD_LEN);
991         pos += EAP_TTLS_CHAP_PASSWORD_LEN;
992         os_free(challenge);
993         AVP_PAD(buf, pos);
994
995         wpabuf_put(msg, pos - buf);
996         *resp = msg;
997
998         if (data->ttls_version > 0) {
999                 /* EAP-TTLSv1 uses TLS/IA FinalPhaseFinished to report success,
1000                  * so do not allow connection to be terminated yet. */
1001                 ret->methodState = METHOD_CONT;
1002                 ret->decision = DECISION_COND_SUCC;
1003         } else {
1004                 /* EAP-TTLS/CHAP does not provide tunneled success
1005                  * notification, so assume that Phase2 succeeds. */
1006                 ret->methodState = METHOD_DONE;
1007                 ret->decision = DECISION_COND_SUCC;
1008         }
1009
1010         return 0;
1011 }
1012
1013
1014 static int eap_ttls_phase2_request(struct eap_sm *sm,
1015                                    struct eap_ttls_data *data,
1016                                    struct eap_method_ret *ret,
1017                                    struct eap_hdr *hdr,
1018                                    struct wpabuf **resp)
1019 {
1020         int res = 0;
1021         size_t len;
1022         enum phase2_types phase2_type = data->phase2_type;
1023
1024 #ifdef EAP_TNC
1025         if (data->tnc_started) {
1026                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Processing TNC");
1027                 phase2_type = EAP_TTLS_PHASE2_EAP;
1028         }
1029 #endif /* EAP_TNC */
1030
1031         if (phase2_type == EAP_TTLS_PHASE2_MSCHAPV2 ||
1032             phase2_type == EAP_TTLS_PHASE2_MSCHAP ||
1033             phase2_type == EAP_TTLS_PHASE2_PAP ||
1034             phase2_type == EAP_TTLS_PHASE2_CHAP) {
1035                 if (eap_get_config_identity(sm, &len) == NULL) {
1036                         wpa_printf(MSG_INFO,
1037                                    "EAP-TTLS: Identity not configured");
1038                         eap_sm_request_identity(sm);
1039                         if (eap_get_config_password(sm, &len) == NULL)
1040                                 eap_sm_request_password(sm);
1041                         return 0;
1042                 }
1043
1044                 if (eap_get_config_password(sm, &len) == NULL) {
1045                         wpa_printf(MSG_INFO,
1046                                    "EAP-TTLS: Password not configured");
1047                         eap_sm_request_password(sm);
1048                         return 0;
1049                 }
1050         }
1051
1052         switch (phase2_type) {
1053         case EAP_TTLS_PHASE2_EAP:
1054                 res = eap_ttls_phase2_request_eap(sm, data, ret, hdr, resp);
1055                 break;
1056         case EAP_TTLS_PHASE2_MSCHAPV2:
1057                 res = eap_ttls_phase2_request_mschapv2(sm, data, ret, resp);
1058                 break;
1059         case EAP_TTLS_PHASE2_MSCHAP:
1060                 res = eap_ttls_phase2_request_mschap(sm, data, ret, resp);
1061                 break;
1062         case EAP_TTLS_PHASE2_PAP:
1063                 res = eap_ttls_phase2_request_pap(sm, data, ret, resp);
1064                 break;
1065         case EAP_TTLS_PHASE2_CHAP:
1066                 res = eap_ttls_phase2_request_chap(sm, data, ret, resp);
1067                 break;
1068         default:
1069                 wpa_printf(MSG_ERROR, "EAP-TTLS: Phase 2 - Unknown");
1070                 res = -1;
1071                 break;
1072         }
1073
1074         if (res < 0) {
1075                 ret->methodState = METHOD_DONE;
1076                 ret->decision = DECISION_FAIL;
1077         }
1078
1079         return res;
1080 }
1081
1082
1083 #if EAP_TTLS_VERSION > 0
1084 static struct wpabuf * eap_ttls_build_phase_finished(
1085         struct eap_sm *sm, struct eap_ttls_data *data, int id, int final)
1086 {
1087         struct wpabuf *req, *buf;
1088
1089         buf = tls_connection_ia_send_phase_finished(sm->ssl_ctx,
1090                                                     data->ssl.conn,
1091                                                     final);
1092         if (buf == NULL)
1093                 return NULL;
1094
1095         req = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_TTLS,
1096                             1 + wpabuf_len(buf),
1097                             EAP_CODE_RESPONSE, id);
1098         if (req == NULL) {
1099                 wpabuf_free(buf);
1100                 return NULL;
1101         }
1102
1103         wpabuf_put_u8(req, data->ttls_version);
1104         wpabuf_put_buf(req, buf);
1105         wpabuf_free(buf);
1106         eap_update_len(req);
1107
1108         return req;
1109 }
1110 #endif /* EAP_TTLS_VERSION */
1111
1112
1113 struct ttls_parse_avp {
1114         u8 *mschapv2;
1115         u8 *eapdata;
1116         size_t eap_len;
1117         u8 *chbind_data;
1118         size_t chbind_len;
1119         int mschapv2_error;
1120 };
1121
1122
1123 static int eap_ttls_parse_attr_eap(const u8 *dpos, size_t dlen,
1124                                    struct ttls_parse_avp *parse)
1125 {
1126         wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP - EAP Message");
1127         if (parse->eapdata == NULL) {
1128                 parse->eapdata = os_malloc(dlen);
1129                 if (parse->eapdata == NULL) {
1130                         wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate "
1131                                    "memory for Phase 2 EAP data");
1132                         return -1;
1133                 }
1134                 os_memcpy(parse->eapdata, dpos, dlen);
1135                 parse->eap_len = dlen;
1136         } else {
1137                 u8 *neweap = os_realloc(parse->eapdata, parse->eap_len + dlen);
1138                 if (neweap == NULL) {
1139                         wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate "
1140                                    "memory for Phase 2 EAP data");
1141                         return -1;
1142                 }
1143                 os_memcpy(neweap + parse->eap_len, dpos, dlen);
1144                 parse->eapdata = neweap;
1145                 parse->eap_len += dlen;
1146         }
1147
1148         return 0;
1149 }
1150
1151
1152 static int eap_ttls_parse_attr_chbind(const u8 *dpos, size_t dlen,
1153                                    struct ttls_parse_avp *parse)
1154 {
1155         wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP - Channel Binding Message");
1156
1157         if (parse->chbind_data == NULL) {
1158                 parse->chbind_data = os_malloc(dlen);
1159                 if (parse->chbind_data == NULL) {
1160                         wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate "
1161                                    "memory for Phase 2 channel binding data");
1162                         return -1;
1163                 }
1164                 os_memcpy(parse->chbind_data, dpos, dlen);
1165                 parse->chbind_len = dlen;
1166         } else {
1167         /* TODO: can this really happen?  maybe just make this an error? */
1168                 u8 *newchbind = os_realloc(parse->chbind_data,
1169                                            parse->chbind_len + dlen);
1170                 if (newchbind == NULL) {
1171                         wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to allocate "
1172                                    "memory for Phase 2 channel binding data");
1173                         return -1;
1174                 }
1175                 os_memcpy(newchbind + parse->chbind_len, dpos, dlen);
1176                 parse->chbind_data = newchbind;
1177                 parse->chbind_len += dlen;
1178         }
1179
1180         return 0;
1181 }
1182
1183
1184 static int eap_ttls_parse_avp(u8 *pos, size_t left,
1185                               struct ttls_parse_avp *parse)
1186 {
1187         struct ttls_avp *avp;
1188         u32 avp_code, avp_length, vendor_id = 0;
1189         u8 avp_flags, *dpos;
1190         size_t dlen;
1191
1192         avp = (struct ttls_avp *) pos;
1193         avp_code = be_to_host32(avp->avp_code);
1194         avp_length = be_to_host32(avp->avp_length);
1195         avp_flags = (avp_length >> 24) & 0xff;
1196         avp_length &= 0xffffff;
1197         wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP: code=%d flags=0x%02x "
1198                    "length=%d", (int) avp_code, avp_flags,
1199                    (int) avp_length);
1200
1201         if (avp_length > left) {
1202                 wpa_printf(MSG_WARNING, "EAP-TTLS: AVP overflow "
1203                            "(len=%d, left=%lu) - dropped",
1204                            (int) avp_length, (unsigned long) left);
1205                 return -1;
1206         }
1207
1208         if (avp_length < sizeof(*avp)) {
1209                 wpa_printf(MSG_WARNING, "EAP-TTLS: Invalid AVP length %d",
1210                            avp_length);
1211                 return -1;
1212         }
1213
1214         dpos = (u8 *) (avp + 1);
1215         dlen = avp_length - sizeof(*avp);
1216         if (avp_flags & AVP_FLAGS_VENDOR) {
1217                 if (dlen < 4) {
1218                         wpa_printf(MSG_WARNING, "EAP-TTLS: Vendor AVP "
1219                                    "underflow");
1220                         return -1;
1221                 }
1222                 vendor_id = WPA_GET_BE32(dpos);
1223                 wpa_printf(MSG_DEBUG, "EAP-TTLS: AVP vendor_id %d",
1224                            (int) vendor_id);
1225                 dpos += 4;
1226                 dlen -= 4;
1227         }
1228
1229         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: AVP data", dpos, dlen);
1230
1231         if (vendor_id == 0 && avp_code == RADIUS_ATTR_EAP_MESSAGE) {
1232                 if (eap_ttls_parse_attr_eap(dpos, dlen, parse) < 0)
1233                         return -1;
1234         } else if (vendor_id == RADIUS_VENDOR_ID_UKERNA &&
1235                    avp_code == RADIUS_ATTR_UKERNA_CHBIND) {
1236                 /* message containing channel binding data */
1237                 if (eap_ttls_parse_attr_chbind(dpos, dlen, parse) < 0)
1238                         return -1;
1239         } else if (vendor_id == 0 && avp_code == RADIUS_ATTR_REPLY_MESSAGE) {
1240                 /* This is an optional message that can be displayed to
1241                  * the user. */
1242                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: AVP - Reply-Message",
1243                                   dpos, dlen);
1244         } else if (vendor_id == RADIUS_VENDOR_ID_MICROSOFT &&
1245                    avp_code == RADIUS_ATTR_MS_CHAP2_SUCCESS) {
1246                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: MS-CHAP2-Success",
1247                                   dpos, dlen);
1248                 if (dlen != 43) {
1249                         wpa_printf(MSG_WARNING, "EAP-TTLS: Unexpected "
1250                                    "MS-CHAP2-Success length "
1251                                    "(len=%lu, expected 43)",
1252                                    (unsigned long) dlen);
1253                         return -1;
1254                 }
1255                 parse->mschapv2 = dpos;
1256         } else if (vendor_id == RADIUS_VENDOR_ID_MICROSOFT &&
1257                    avp_code == RADIUS_ATTR_MS_CHAP_ERROR) {
1258                 wpa_hexdump_ascii(MSG_DEBUG, "EAP-TTLS: MS-CHAP-Error",
1259                                   dpos, dlen);
1260                 parse->mschapv2_error = 1;
1261         } else if (avp_flags & AVP_FLAGS_MANDATORY) {
1262                 wpa_printf(MSG_WARNING, "EAP-TTLS: Unsupported mandatory AVP "
1263                            "code %d vendor_id %d - dropped",
1264                            (int) avp_code, (int) vendor_id);
1265                 return -1;
1266         } else {
1267                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Ignoring unsupported AVP "
1268                            "code %d vendor_id %d",
1269                            (int) avp_code, (int) vendor_id);
1270         }
1271
1272         return avp_length;
1273 }
1274
1275
1276 static int eap_ttls_parse_avps(struct wpabuf *in_decrypted,
1277                                struct ttls_parse_avp *parse)
1278 {
1279         u8 *pos;
1280         size_t left, pad;
1281         int avp_length;
1282
1283         pos = wpabuf_mhead(in_decrypted);
1284         left = wpabuf_len(in_decrypted);
1285         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: Decrypted Phase 2 AVPs", pos, left);
1286         if (left < sizeof(struct ttls_avp)) {
1287                 wpa_printf(MSG_WARNING, "EAP-TTLS: Too short Phase 2 AVP frame"
1288                            " len=%lu expected %lu or more - dropped",
1289                            (unsigned long) left,
1290                            (unsigned long) sizeof(struct ttls_avp));
1291                 return -1;
1292         }
1293
1294         /* Parse AVPs */
1295         os_memset(parse, 0, sizeof(*parse));
1296
1297         while (left > 0) {
1298                 avp_length = eap_ttls_parse_avp(pos, left, parse);
1299                 if (avp_length < 0)
1300                         return -1;
1301
1302                 pad = (4 - (avp_length & 3)) & 3;
1303                 pos += avp_length + pad;
1304                 if (left < avp_length + pad)
1305                         left = 0;
1306                 else
1307                         left -= avp_length + pad;
1308         }
1309
1310         return 0;
1311 }
1312
1313
1314 static u8 * eap_ttls_fake_identity_request(void)
1315 {
1316         struct eap_hdr *hdr;
1317         u8 *buf;
1318
1319         wpa_printf(MSG_DEBUG, "EAP-TTLS: empty data in beginning of "
1320                    "Phase 2 - use fake EAP-Request Identity");
1321         buf = os_malloc(sizeof(*hdr) + 1);
1322         if (buf == NULL) {
1323                 wpa_printf(MSG_WARNING, "EAP-TTLS: failed to allocate "
1324                            "memory for fake EAP-Identity Request");
1325                 return NULL;
1326         }
1327
1328         hdr = (struct eap_hdr *) buf;
1329         hdr->code = EAP_CODE_REQUEST;
1330         hdr->identifier = 0;
1331         hdr->length = host_to_be16(sizeof(*hdr) + 1);
1332         buf[sizeof(*hdr)] = EAP_TYPE_IDENTITY;
1333
1334         return buf;
1335 }
1336
1337
1338 static int eap_ttls_encrypt_response(struct eap_sm *sm,
1339                                      struct eap_ttls_data *data,
1340                                      struct wpabuf *resp, u8 identifier,
1341                                      struct wpabuf **out_data)
1342 {
1343         if (resp == NULL)
1344                 return 0;
1345
1346         wpa_hexdump_buf_key(MSG_DEBUG, "EAP-TTLS: Encrypting Phase 2 data",
1347                             resp);
1348         if (eap_peer_tls_encrypt(sm, &data->ssl, EAP_TYPE_TTLS,
1349                                  data->ttls_version, identifier,
1350                                  resp, out_data)) {
1351                 wpa_printf(MSG_INFO, "EAP-TTLS: Failed to encrypt a Phase 2 "
1352                            "frame");
1353                 return -1;
1354         }
1355         wpabuf_free(resp);
1356
1357         return 0;
1358 }
1359
1360 static int eap_ttls_add_chbind_request(struct eap_sm *sm,
1361                                        struct eap_ttls_data *data,
1362                                        struct wpabuf **resp)
1363 {
1364         struct wpabuf *chbind_req, *res;
1365         int length = 1, i;
1366         struct eap_peer_config *config = eap_get_config(sm);
1367
1368         if (!config->chbind_config || config->chbind_config_len <= 0)
1369                 return -1;
1370
1371         for (i=0; i<config->chbind_config_len; i++) {
1372                 length += 3 + config->chbind_config[i].req_data_len;
1373         }
1374
1375         chbind_req = wpabuf_alloc(length);
1376         if (!chbind_req)
1377                 return -1;
1378
1379         wpabuf_put_u8(chbind_req, CHBIND_CODE_REQUEST);
1380         for (i=0; i<config->chbind_config_len; i++) {
1381                 struct eap_peer_chbind_config *chbind_config =
1382                         &config->chbind_config[i];
1383                 wpabuf_put_be16(chbind_req, chbind_config->req_data_len);
1384                 wpabuf_put_u8(chbind_req, chbind_config->nsid);
1385                 wpabuf_put_data(chbind_req, chbind_config->req_data,
1386                                 chbind_config->req_data_len);
1387         }
1388         if (eap_ttls_avp_vsa_encapsulate(&chbind_req,
1389                                          RADIUS_VENDOR_ID_UKERNA,
1390                                          RADIUS_ATTR_UKERNA_CHBIND, 0) < 0)
1391                 return -1;
1392
1393         /* bleh. This will free *resp regardless of whether combined buffer
1394            alloc succeeds, which is not consistent with the other error
1395            condition behavior in this function */
1396         *resp = wpabuf_concat(chbind_req, *resp);
1397
1398         return (*resp) ? 0 : -1;
1399 }
1400
1401
1402 static int eap_ttls_process_chbind(struct eap_sm *sm,
1403                                    struct eap_ttls_data *data,
1404                                    struct eap_method_ret *ret,
1405                                    struct ttls_parse_avp *parse,
1406                                    struct wpabuf **resp)
1407 {
1408         size_t pos=0;
1409         u8 code;
1410         u16 len;
1411         struct chbind_hdr *hdr;
1412         struct eap_peer_config *config = eap_get_config(sm);
1413
1414         if (parse->chbind_data == NULL) {
1415                 wpa_printf(MSG_WARNING, "EAP-TTLS: No channel binding message "
1416                            "in the packet - dropped");
1417                 return -1;
1418         }
1419         if (parse->chbind_len < 1 + sizeof(*hdr)) {
1420                 wpa_printf(MSG_WARNING, "EAP-TTLS: bad channel binding response "
1421                                 "frame (len=%lu, expected %lu or more) - dropped",
1422                                 (unsigned long) parse->chbind_len,
1423                                 (unsigned long) sizeof(*hdr));
1424                 return -1;
1425         }
1426         code = parse->chbind_data[pos++];
1427         while (pos+sizeof(*hdr) < parse->chbind_len) {
1428                 hdr = (struct chbind_hdr *)(&parse->chbind_data[pos]);
1429                 pos += sizeof(*hdr);
1430                 len = be_to_host16(hdr->len);
1431                 if (pos + len <= parse->chbind_len) {
1432                         int i;
1433                         for (i=0; i<config->chbind_config_len; i++) {
1434                                 struct eap_peer_chbind_config *chbind_config =
1435                                         &config->chbind_config[i];
1436                                 if (chbind_config->nsid == hdr->nsid)
1437                                         chbind_config->response_cb(
1438                                                 chbind_config->ctx,
1439                                                 code, hdr->nsid,
1440                                                 &parse->chbind_data[pos], len);
1441                         }
1442                 }
1443                 pos += len;
1444         }
1445         if (pos != parse->chbind_len) {
1446                 wpa_printf(MSG_WARNING, "EAP-TTLS: bad channel binding response "
1447                                 "frame (parsed len=%lu, expected %lu) - dropped",
1448                                 (unsigned long) pos,
1449                                 (unsigned long) parse->chbind_len);
1450                 return -1;
1451         }
1452         return 0;
1453 }
1454
1455 static int eap_ttls_process_phase2_eap(struct eap_sm *sm,
1456                                        struct eap_ttls_data *data,
1457                                        struct eap_method_ret *ret,
1458                                        struct ttls_parse_avp *parse,
1459                                        struct wpabuf **resp)
1460 {
1461         struct eap_hdr *hdr;
1462         size_t len;
1463
1464         if (parse->eapdata == NULL) {
1465                 wpa_printf(MSG_WARNING, "EAP-TTLS: No EAP Message in the "
1466                            "packet - dropped");
1467                 return -1;
1468         }
1469
1470         wpa_hexdump(MSG_DEBUG, "EAP-TTLS: Phase 2 EAP",
1471                     parse->eapdata, parse->eap_len);
1472         hdr = (struct eap_hdr *) parse->eapdata;
1473
1474         if (parse->eap_len < sizeof(*hdr)) {
1475                 wpa_printf(MSG_WARNING, "EAP-TTLS: Too short Phase 2 EAP "
1476                            "frame (len=%lu, expected %lu or more) - dropped",
1477                            (unsigned long) parse->eap_len,
1478                            (unsigned long) sizeof(*hdr));
1479                 return -1;
1480         }
1481         len = be_to_host16(hdr->length);
1482         if (len > parse->eap_len) {
1483                 wpa_printf(MSG_INFO, "EAP-TTLS: Length mismatch in Phase 2 "
1484                            "EAP frame (EAP hdr len=%lu, EAP data len in "
1485                            "AVP=%lu)",
1486                            (unsigned long) len,
1487                            (unsigned long) parse->eap_len);
1488                 return -1;
1489         }
1490         wpa_printf(MSG_DEBUG, "EAP-TTLS: received Phase 2: code=%d "
1491                    "identifier=%d length=%lu",
1492                    hdr->code, hdr->identifier, (unsigned long) len);
1493         switch (hdr->code) {
1494         case EAP_CODE_REQUEST:
1495                 if (eap_ttls_phase2_request(sm, data, ret, hdr, resp)) {
1496                         wpa_printf(MSG_INFO, "EAP-TTLS: Phase2 Request "
1497                                    "processing failed");
1498                         return -1;
1499                 }
1500                 break;
1501         default:
1502                 wpa_printf(MSG_INFO, "EAP-TTLS: Unexpected code=%d in "
1503                            "Phase 2 EAP header", hdr->code);
1504                 return -1;
1505         }
1506
1507         return 0;
1508 }
1509
1510
1511 static int eap_ttls_process_phase2_mschapv2(struct eap_sm *sm,
1512                                             struct eap_ttls_data *data,
1513                                             struct eap_method_ret *ret,
1514                                             struct ttls_parse_avp *parse)
1515 {
1516         if (parse->mschapv2_error) {
1517                 wpa_printf(MSG_DEBUG, "EAP-TTLS/MSCHAPV2: Received "
1518                            "MS-CHAP-Error - failed");
1519                 ret->methodState = METHOD_DONE;
1520                 ret->decision = DECISION_FAIL;
1521                 /* Reply with empty data to ACK error */
1522                 return 1;
1523         }
1524
1525         if (parse->mschapv2 == NULL) {
1526 #ifdef EAP_TNC
1527                 if (data->phase2_success && parse->eapdata) {
1528                         /*
1529                          * Allow EAP-TNC to be started after successfully
1530                          * completed MSCHAPV2.
1531                          */
1532                         return 1;
1533                 }
1534 #endif /* EAP_TNC */
1535                 wpa_printf(MSG_WARNING, "EAP-TTLS: no MS-CHAP2-Success AVP "
1536                            "received for Phase2 MSCHAPV2");
1537                 return -1;
1538         }
1539         if (parse->mschapv2[0] != data->ident) {
1540                 wpa_printf(MSG_WARNING, "EAP-TTLS: Ident mismatch for Phase 2 "
1541                            "MSCHAPV2 (received Ident 0x%02x, expected 0x%02x)",
1542                            parse->mschapv2[0], data->ident);
1543                 return -1;
1544         }
1545         if (!data->auth_response_valid ||
1546             mschapv2_verify_auth_response(data->auth_response,
1547                                           parse->mschapv2 + 1, 42)) {
1548                 wpa_printf(MSG_WARNING, "EAP-TTLS: Invalid authenticator "
1549                            "response in Phase 2 MSCHAPV2 success request");
1550                 return -1;
1551         }
1552
1553         wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 MSCHAPV2 "
1554                    "authentication succeeded");
1555         if (data->ttls_version > 0) {
1556                 /*
1557                  * EAP-TTLSv1 uses TLS/IA FinalPhaseFinished to report
1558                  * success, so do not allow connection to be terminated
1559                  * yet.
1560                  */
1561                 ret->methodState = METHOD_CONT;
1562                 ret->decision = DECISION_COND_SUCC;
1563         } else {
1564                 ret->methodState = METHOD_DONE;
1565                 ret->decision = DECISION_UNCOND_SUCC;
1566                 data->phase2_success = 1;
1567         }
1568
1569         /*
1570          * Reply with empty data; authentication server will reply
1571          * with EAP-Success after this.
1572          */
1573         return 1;
1574 }
1575
1576
1577 #ifdef EAP_TNC
1578 static int eap_ttls_process_tnc_start(struct eap_sm *sm,
1579                                       struct eap_ttls_data *data,
1580                                       struct eap_method_ret *ret,
1581                                       struct ttls_parse_avp *parse,
1582                                       struct wpabuf **resp)
1583 {
1584         /* TNC uses inner EAP method after non-EAP TTLS phase 2. */
1585         if (parse->eapdata == NULL) {
1586                 wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received "
1587                            "unexpected tunneled data (no EAP)");
1588                 return -1;
1589         }
1590
1591         if (!data->ready_for_tnc) {
1592                 wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received "
1593                            "EAP after non-EAP, but not ready for TNC");
1594                 return -1;
1595         }
1596
1597         wpa_printf(MSG_DEBUG, "EAP-TTLS: Start TNC after completed "
1598                    "non-EAP method");
1599         data->tnc_started = 1;
1600
1601         if (eap_ttls_process_phase2_eap(sm, data, ret, parse, resp) < 0)
1602                 return -1;
1603
1604         return 0;
1605 }
1606 #endif /* EAP_TNC */
1607
1608
1609 static int eap_ttls_process_decrypted(struct eap_sm *sm,
1610                                       struct eap_ttls_data *data,
1611                                       struct eap_method_ret *ret,
1612                                       u8 identifier,
1613                                       struct ttls_parse_avp *parse,
1614                                       struct wpabuf *in_decrypted,
1615                                       struct wpabuf **out_data)
1616 {
1617         struct wpabuf *resp = NULL;
1618         struct eap_peer_config *config = eap_get_config(sm);
1619         int res;
1620         enum phase2_types phase2_type = data->phase2_type;
1621
1622 #ifdef EAP_TNC
1623         if (data->tnc_started)
1624                 phase2_type = EAP_TTLS_PHASE2_EAP;
1625 #endif /* EAP_TNC */
1626
1627         switch (phase2_type) {
1628         case EAP_TTLS_PHASE2_EAP:
1629                 if (eap_ttls_process_phase2_eap(sm, data, ret, parse, &resp) <
1630                     0)
1631                         return -1;
1632                 break;
1633         case EAP_TTLS_PHASE2_MSCHAPV2:
1634                 res = eap_ttls_process_phase2_mschapv2(sm, data, ret, parse);
1635 #ifdef EAP_TNC
1636                 if (res == 1 && parse->eapdata && data->phase2_success) {
1637                         /*
1638                          * TNC may be required as the next
1639                          * authentication method within the tunnel.
1640                          */
1641                         ret->methodState = METHOD_MAY_CONT;
1642                         data->ready_for_tnc = 1;
1643                         if (eap_ttls_process_tnc_start(sm, data, ret, parse,
1644                                                        &resp) == 0)
1645                                 break;
1646                 }
1647 #endif /* EAP_TNC */
1648                 return res;
1649         case EAP_TTLS_PHASE2_MSCHAP:
1650         case EAP_TTLS_PHASE2_PAP:
1651         case EAP_TTLS_PHASE2_CHAP:
1652 #ifdef EAP_TNC
1653                 if (eap_ttls_process_tnc_start(sm, data, ret, parse, &resp) <
1654                     0)
1655                         return -1;
1656                 break;
1657 #else /* EAP_TNC */
1658                 /* EAP-TTLS/{MSCHAP,PAP,CHAP} should not send any TLS tunneled
1659                  * requests to the supplicant */
1660                 wpa_printf(MSG_INFO, "EAP-TTLS: Phase 2 received unexpected "
1661                            "tunneled data");
1662                 return -1;
1663 #endif /* EAP_TNC */
1664         }
1665
1666         if (!resp && (config->pending_req_identity ||
1667                         config->pending_req_password ||
1668                         config->pending_req_otp ||
1669                         config->pending_req_new_password)) {
1670                 wpabuf_free(data->pending_phase2_req);
1671                 data->pending_phase2_req = wpabuf_dup(in_decrypted);
1672                 return 0;
1673         }
1674
1675         /* handle channel binding response here */
1676         if (parse->chbind_data) {
1677                 /* received channel binding repsonse */
1678                 if (eap_ttls_process_chbind(sm, data, ret, parse, &resp) < 0)
1679                         return -1;
1680         }
1681         /* issue channel binding request when appropriate */
1682         if (config->chbind_config && config->chbind_config_len > 0 &&
1683                 !data->chbind_req_sent) {
1684                 if (eap_ttls_add_chbind_request(sm, data, &resp) < 0)
1685                         return -1;
1686                 data->chbind_req_sent = 1;
1687         }
1688
1689         if (resp) {
1690                 if (eap_ttls_encrypt_response(sm, data, resp, identifier,
1691                                               out_data) < 0)
1692                         return -1;
1693         }
1694
1695         return 0;
1696 }
1697
1698
1699 #if EAP_TTLS_VERSION > 0
1700 static void eap_ttls_final_phase_finished(struct eap_sm *sm,
1701                                           struct eap_ttls_data *data,
1702                                           struct eap_method_ret *ret,
1703                                           u8 identifier,
1704                                           struct wpabuf **out_data)
1705 {
1706         wpa_printf(MSG_DEBUG, "EAP-TTLS: FinalPhaseFinished received");
1707         wpa_printf(MSG_INFO, "EAP-TTLS: TLS/IA authentication succeeded");
1708         ret->methodState = METHOD_DONE;
1709         ret->decision = DECISION_UNCOND_SUCC;
1710         data->phase2_success = 1;
1711         *out_data = eap_ttls_build_phase_finished(sm, data, identifier, 1);
1712         eap_ttls_v1_derive_key(sm, data);
1713 }
1714 #endif /* EAP_TTLS_VERSION */
1715
1716
1717 static int eap_ttls_implicit_identity_request(struct eap_sm *sm,
1718                                               struct eap_ttls_data *data,
1719                                               struct eap_method_ret *ret,
1720                                               u8 identifier,
1721                                               struct wpabuf **out_data)
1722 {
1723         int retval = 0;
1724         struct eap_hdr *hdr;
1725         struct wpabuf *resp;
1726
1727         hdr = (struct eap_hdr *) eap_ttls_fake_identity_request();
1728         if (hdr == NULL) {
1729                 ret->methodState = METHOD_DONE;
1730                 ret->decision = DECISION_FAIL;
1731                 return -1;
1732         }
1733
1734         resp = NULL;
1735         if (eap_ttls_phase2_request(sm, data, ret, hdr, &resp)) {
1736                 wpa_printf(MSG_INFO, "EAP-TTLS: Phase2 Request "
1737                            "processing failed");
1738                 retval = -1;
1739         } else {
1740                 retval = eap_ttls_encrypt_response(sm, data, resp, identifier,
1741                                                    out_data);
1742         }
1743
1744         os_free(hdr);
1745
1746         if (retval < 0) {
1747                 ret->methodState = METHOD_DONE;
1748                 ret->decision = DECISION_FAIL;
1749         }
1750
1751         return retval;
1752 }
1753
1754
1755 static int eap_ttls_phase2_start(struct eap_sm *sm, struct eap_ttls_data *data,
1756                                  struct eap_method_ret *ret, u8 identifier,
1757                                  struct wpabuf **out_data)
1758 {
1759         data->phase2_start = 0;
1760
1761         /*
1762          * EAP-TTLS does not use Phase2 on fast re-auth; this must be done only
1763          * if TLS part was indeed resuming a previous session. Most
1764          * Authentication Servers terminate EAP-TTLS before reaching this
1765          * point, but some do not. Make wpa_supplicant stop phase 2 here, if
1766          * needed.
1767          */
1768         if (data->reauth &&
1769             tls_connection_resumed(sm->ssl_ctx, data->ssl.conn)) {
1770                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Session resumption - "
1771                            "skip phase 2");
1772                 *out_data = eap_peer_tls_build_ack(identifier, EAP_TYPE_TTLS,
1773                                                    data->ttls_version);
1774                 ret->methodState = METHOD_DONE;
1775                 ret->decision = DECISION_UNCOND_SUCC;
1776                 data->phase2_success = 1;
1777                 return 0;
1778         }
1779
1780         return eap_ttls_implicit_identity_request(sm, data, ret, identifier,
1781                                                   out_data);
1782 }
1783
1784
1785 static int eap_ttls_decrypt(struct eap_sm *sm, struct eap_ttls_data *data,
1786                             struct eap_method_ret *ret, u8 identifier,
1787                             const struct wpabuf *in_data,
1788                             struct wpabuf **out_data)
1789 {
1790         struct wpabuf *in_decrypted = NULL;
1791         int retval = 0;
1792         struct ttls_parse_avp parse;
1793
1794         os_memset(&parse, 0, sizeof(parse));
1795
1796         wpa_printf(MSG_DEBUG, "EAP-TTLS: received %lu bytes encrypted data for"
1797                    " Phase 2",
1798                    in_data ? (unsigned long) wpabuf_len(in_data) : 0);
1799
1800         if (data->pending_phase2_req) {
1801                 wpa_printf(MSG_DEBUG, "EAP-TTLS: Pending Phase 2 request - "
1802                            "skip decryption and use old data");
1803                 /* Clear TLS reassembly state. */
1804                 eap_peer_tls_reset_input(&data->ssl);
1805
1806                 in_decrypted = data->pending_phase2_req;
1807                 data->pending_phase2_req = NULL;
1808                 if (wpabuf_len(in_decrypted) == 0) {
1809                         wpabuf_free(in_decrypted);
1810                         return eap_ttls_implicit_identity_request(
1811                                 sm, data, ret, identifier, out_data);
1812                 }
1813                 goto continue_req;
1814         }
1815
1816         if ((in_data == NULL || wpabuf_len(in_data) == 0) &&
1817             data->phase2_start) {
1818                 return eap_ttls_phase2_start(sm, data, ret, identifier,
1819                                              out_data);
1820         }
1821
1822         if (in_data == NULL || wpabuf_len(in_data) == 0) {
1823                 /* Received TLS ACK - requesting more fragments */
1824                 return eap_peer_tls_encrypt(sm, &data->ssl, EAP_TYPE_TTLS,
1825                                             data->ttls_version,
1826                                             identifier, NULL, out_data);
1827         }
1828
1829         retval = eap_peer_tls_decrypt(sm, &data->ssl, in_data, &in_decrypted);
1830         if (retval)
1831                 goto done;
1832
1833 #if EAP_TTLS_VERSION > 0
1834         if (data->ttls_version > 0 &&
1835             (in_decrypted == NULL || wpabuf_len(in_decrypted) == 0) &&
1836             tls_connection_ia_final_phase_finished(sm->ssl_ctx,
1837                                                    data->ssl.conn)) {
1838                 eap_ttls_final_phase_finished(sm, data, ret, identifier,
1839                                               out_data);
1840                 goto done;
1841         }
1842 #endif /* EAP_TTLS_VERSION */
1843
1844 continue_req:
1845         data->phase2_start = 0;
1846
1847         if (eap_ttls_parse_avps(in_decrypted, &parse) < 0) {
1848                 retval = -1;
1849                 goto done;
1850         }
1851
1852         retval = eap_ttls_process_decrypted(sm, data, ret, identifier,
1853                                             &parse, in_decrypted, out_data);
1854
1855 done:
1856         wpabuf_free(in_decrypted);
1857         os_free(parse.eapdata);
1858
1859         if (retval < 0) {
1860                 ret->methodState = METHOD_DONE;
1861                 ret->decision = DECISION_FAIL;
1862         }
1863
1864         return retval;
1865 }
1866
1867
1868 static int eap_ttls_process_start(struct eap_sm *sm,
1869                                   struct eap_ttls_data *data, u8 flags,
1870                                   struct eap_method_ret *ret)
1871 {
1872         struct eap_peer_config *config = eap_get_config(sm);
1873
1874         wpa_printf(MSG_DEBUG, "EAP-TTLS: Start (server ver=%d, own ver=%d)",
1875                    flags & EAP_TLS_VERSION_MASK, data->ttls_version);
1876 #if EAP_TTLS_VERSION > 0
1877         if ((flags & EAP_TLS_VERSION_MASK) < data->ttls_version)
1878                 data->ttls_version = flags & EAP_TLS_VERSION_MASK;
1879         if (data->force_ttls_version >= 0 &&
1880             data->force_ttls_version != data->ttls_version) {
1881                 wpa_printf(MSG_WARNING, "EAP-TTLS: Failed to select "
1882                            "forced TTLS version %d",
1883                            data->force_ttls_version);
1884                 ret->methodState = METHOD_DONE;
1885                 ret->decision = DECISION_FAIL;
1886                 ret->allowNotifications = FALSE;
1887                 return -1;
1888         }
1889         wpa_printf(MSG_DEBUG, "EAP-TTLS: Using TTLS version %d",
1890                    data->ttls_version);
1891
1892         if (data->ttls_version > 0)
1893                 data->ssl.tls_ia = 1;
1894 #endif /* EAP_TTLS_VERSION */
1895         if (!data->ssl_initialized &&
1896             eap_peer_tls_ssl_init(sm, &data->ssl, config)) {
1897                 wpa_printf(MSG_INFO, "EAP-TTLS: Failed to initialize SSL.");
1898                 return -1;
1899         }
1900         data->ssl_initialized = 1;
1901
1902         wpa_printf(MSG_DEBUG, "EAP-TTLS: Start");
1903
1904         return 0;
1905 }
1906
1907
1908 static int eap_ttls_process_handshake(struct eap_sm *sm,
1909                                       struct eap_ttls_data *data,
1910                                       struct eap_method_ret *ret,
1911                                       u8 identifier,
1912                                       const u8 *in_data, size_t in_len,
1913                                       struct wpabuf **out_data)
1914 {
1915         int res;
1916
1917         res = eap_peer_tls_process_helper(sm, &data->ssl, EAP_TYPE_TTLS,
1918                                           data->ttls_version, identifier,
1919                                           in_data, in_len, out_data);
1920
1921         if (tls_connection_established(sm->ssl_ctx, data->ssl.conn)) {
1922                 wpa_printf(MSG_DEBUG, "EAP-TTLS: TLS done, proceed to "
1923                            "Phase 2");
1924                 if (data->resuming) {
1925                         wpa_printf(MSG_DEBUG, "EAP-TTLS: fast reauth - may "
1926                                    "skip Phase 2");
1927                         ret->decision = DECISION_COND_SUCC;
1928                         ret->methodState = METHOD_MAY_CONT;
1929                 }
1930                 data->phase2_start = 1;
1931                 if (data->ttls_version == 0)
1932                         eap_ttls_v0_derive_key(sm, data);
1933
1934                 if (*out_data == NULL || wpabuf_len(*out_data) == 0) {
1935                         if (eap_ttls_decrypt(sm, data, ret, identifier,
1936                                              NULL, out_data)) {
1937                                 wpa_printf(MSG_WARNING, "EAP-TTLS: "
1938                                            "failed to process early "
1939                                            "start for Phase 2");
1940                         }
1941                         res = 0;
1942                 }
1943                 data->resuming = 0;
1944         }
1945
1946         if (res == 2) {
1947                 struct wpabuf msg;
1948                 /*
1949                  * Application data included in the handshake message.
1950                  */
1951                 wpabuf_free(data->pending_phase2_req);
1952                 data->pending_phase2_req = *out_data;
1953                 *out_data = NULL;
1954                 wpabuf_set(&msg, in_data, in_len);
1955                 res = eap_ttls_decrypt(sm, data, ret, identifier, &msg,
1956                                        out_data);
1957         }
1958
1959         return res;
1960 }
1961
1962
1963 static void eap_ttls_check_auth_status(struct eap_sm *sm, 
1964                                        struct eap_ttls_data *data,
1965                                        struct eap_method_ret *ret)
1966 {
1967         if (data->ttls_version == 0 && ret->methodState == METHOD_DONE) {
1968                 ret->allowNotifications = FALSE;
1969                 if (ret->decision == DECISION_UNCOND_SUCC ||
1970                     ret->decision == DECISION_COND_SUCC) {
1971                         wpa_printf(MSG_DEBUG, "EAP-TTLS: Authentication "
1972                                    "completed successfully");
1973                         data->phase2_success = 1;
1974 #ifdef EAP_TNC
1975                         if (!data->ready_for_tnc && !data->tnc_started) {
1976                                 /*
1977                                  * TNC may be required as the next
1978                                  * authentication method within the tunnel.
1979                                  */
1980                                 ret->methodState = METHOD_MAY_CONT;
1981                                 data->ready_for_tnc = 1;
1982                         }
1983 #endif /* EAP_TNC */
1984                 }
1985         } else if (data->ttls_version == 0 &&
1986                    ret->methodState == METHOD_MAY_CONT &&
1987                    (ret->decision == DECISION_UNCOND_SUCC ||
1988                     ret->decision == DECISION_COND_SUCC)) {
1989                         wpa_printf(MSG_DEBUG, "EAP-TTLS: Authentication "
1990                                    "completed successfully (MAY_CONT)");
1991                         data->phase2_success = 1;
1992         }
1993 }
1994
1995
1996 static struct wpabuf * eap_ttls_process(struct eap_sm *sm, void *priv,
1997                                         struct eap_method_ret *ret,
1998                                         const struct wpabuf *reqData)
1999 {
2000         size_t left;
2001         int res;
2002         u8 flags, id;
2003         struct wpabuf *resp;
2004         const u8 *pos;
2005         struct eap_ttls_data *data = priv;
2006
2007         pos = eap_peer_tls_process_init(sm, &data->ssl, EAP_TYPE_TTLS, ret,
2008                                         reqData, &left, &flags);
2009         if (pos == NULL)
2010                 return NULL;
2011         id = eap_get_id(reqData);
2012
2013         if (flags & EAP_TLS_FLAGS_START) {
2014                 if (eap_ttls_process_start(sm, data, flags, ret) < 0)
2015                         return NULL;
2016
2017                 /* RFC 5281, Ch. 9.2:
2018                  * "This packet MAY contain additional information in the form
2019                  * of AVPs, which may provide useful hints to the client"
2020                  * For now, ignore any potential extra data.
2021                  */
2022                 left = 0;
2023         } else if (!data->ssl_initialized) {
2024                 wpa_printf(MSG_DEBUG, "EAP-TTLS: First message did not "
2025                            "include Start flag");
2026                 ret->methodState = METHOD_DONE;
2027                 ret->decision = DECISION_FAIL;
2028                 ret->allowNotifications = FALSE;
2029                 return NULL;
2030         }
2031
2032         resp = NULL;
2033         if (tls_connection_established(sm->ssl_ctx, data->ssl.conn) &&
2034             !data->resuming) {
2035                 struct wpabuf msg;
2036                 wpabuf_set(&msg, pos, left);
2037                 res = eap_ttls_decrypt(sm, data, ret, id, &msg, &resp);
2038         } else {
2039                 res = eap_ttls_process_handshake(sm, data, ret, id,
2040                                                  pos, left, &resp);
2041         }
2042
2043         eap_ttls_check_auth_status(sm, data, ret);
2044
2045         /* FIX: what about res == -1? Could just move all error processing into
2046          * the other functions and get rid of this res==1 case here. */
2047         if (res == 1) {
2048                 wpabuf_free(resp);
2049                 return eap_peer_tls_build_ack(id, EAP_TYPE_TTLS,
2050                                               data->ttls_version);
2051         }
2052         return resp;
2053 }
2054
2055
2056 static Boolean eap_ttls_has_reauth_data(struct eap_sm *sm, void *priv)
2057 {
2058         struct eap_ttls_data *data = priv;
2059         return tls_connection_established(sm->ssl_ctx, data->ssl.conn) &&
2060                 data->phase2_success;
2061 }
2062
2063
2064 static void eap_ttls_deinit_for_reauth(struct eap_sm *sm, void *priv)
2065 {
2066         struct eap_ttls_data *data = priv;
2067         wpabuf_free(data->pending_phase2_req);
2068         data->pending_phase2_req = NULL;
2069 #ifdef EAP_TNC
2070         data->ready_for_tnc = 0;
2071         data->tnc_started = 0;
2072 #endif /* EAP_TNC */
2073 }
2074
2075
2076 static void * eap_ttls_init_for_reauth(struct eap_sm *sm, void *priv)
2077 {
2078         struct eap_ttls_data *data = priv;
2079         os_free(data->key_data);
2080         data->key_data = NULL;
2081         if (eap_peer_tls_reauth_init(sm, &data->ssl)) {
2082                 os_free(data);
2083                 return NULL;
2084         }
2085         if (data->phase2_priv && data->phase2_method &&
2086             data->phase2_method->init_for_reauth)
2087                 data->phase2_method->init_for_reauth(sm, data->phase2_priv);
2088         data->phase2_start = 0;
2089         data->phase2_success = 0;
2090         data->resuming = 1;
2091         data->reauth = 1;
2092         return priv;
2093 }
2094
2095
2096 static int eap_ttls_get_status(struct eap_sm *sm, void *priv, char *buf,
2097                                size_t buflen, int verbose)
2098 {
2099         struct eap_ttls_data *data = priv;
2100         int len, ret;
2101
2102         len = eap_peer_tls_status(sm, &data->ssl, buf, buflen, verbose);
2103         ret = os_snprintf(buf + len, buflen - len,
2104                           "EAP-TTLSv%d Phase2 method=",
2105                           data->ttls_version);
2106         if (ret < 0 || (size_t) ret >= buflen - len)
2107                 return len;
2108         len += ret;
2109         switch (data->phase2_type) {
2110         case EAP_TTLS_PHASE2_EAP:
2111                 ret = os_snprintf(buf + len, buflen - len, "EAP-%s\n",
2112                                   data->phase2_method ?
2113                                   data->phase2_method->name : "?");
2114                 break;
2115         case EAP_TTLS_PHASE2_MSCHAPV2:
2116                 ret = os_snprintf(buf + len, buflen - len, "MSCHAPV2\n");
2117                 break;
2118         case EAP_TTLS_PHASE2_MSCHAP:
2119                 ret = os_snprintf(buf + len, buflen - len, "MSCHAP\n");
2120                 break;
2121         case EAP_TTLS_PHASE2_PAP:
2122                 ret = os_snprintf(buf + len, buflen - len, "PAP\n");
2123                 break;
2124         case EAP_TTLS_PHASE2_CHAP:
2125                 ret = os_snprintf(buf + len, buflen - len, "CHAP\n");
2126                 break;
2127         default:
2128                 ret = 0;
2129                 break;
2130         }
2131         if (ret < 0 || (size_t) ret >= buflen - len)
2132                 return len;
2133         len += ret;
2134
2135         return len;
2136 }
2137
2138
2139 static Boolean eap_ttls_isKeyAvailable(struct eap_sm *sm, void *priv)
2140 {
2141         struct eap_ttls_data *data = priv;
2142         return data->key_data != NULL && data->phase2_success;
2143 }
2144
2145
2146 static u8 * eap_ttls_getKey(struct eap_sm *sm, void *priv, size_t *len)
2147 {
2148         struct eap_ttls_data *data = priv;
2149         u8 *key;
2150
2151         if (data->key_data == NULL || !data->phase2_success)
2152                 return NULL;
2153
2154         key = os_malloc(EAP_TLS_KEY_LEN);
2155         if (key == NULL)
2156                 return NULL;
2157
2158         *len = EAP_TLS_KEY_LEN;
2159         os_memcpy(key, data->key_data, EAP_TLS_KEY_LEN);
2160
2161         return key;
2162 }
2163
2164
2165 int eap_peer_ttls_register(void)
2166 {
2167         struct eap_method *eap;
2168         int ret;
2169
2170         eap = eap_peer_method_alloc(EAP_PEER_METHOD_INTERFACE_VERSION,
2171                                     EAP_VENDOR_IETF, EAP_TYPE_TTLS, "TTLS");
2172         if (eap == NULL)
2173                 return -1;
2174
2175         eap->init = eap_ttls_init;
2176         eap->deinit = eap_ttls_deinit;
2177         eap->process = eap_ttls_process;
2178         eap->isKeyAvailable = eap_ttls_isKeyAvailable;
2179         eap->getKey = eap_ttls_getKey;
2180         eap->get_status = eap_ttls_get_status;
2181         eap->has_reauth_data = eap_ttls_has_reauth_data;
2182         eap->deinit_for_reauth = eap_ttls_deinit_for_reauth;
2183         eap->init_for_reauth = eap_ttls_init_for_reauth;
2184
2185         ret = eap_peer_method_register(eap);
2186         if (ret)
2187                 eap_peer_method_free(eap);
2188         return ret;
2189 }