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