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