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