More readable debug output
[freeradius.git] / src / modules / rlm_eap / eap.c
1 /*
2  * eap.c    rfc2284 & rfc2869 implementation
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000-2003,2006  The FreeRADIUS server project
21  * Copyright 2001  hereUare Communications, Inc. <raghud@hereuare.com>
22  * Copyright 2003  Alan DeKok <aland@freeradius.org>
23  */
24 /*
25  *  EAP PACKET FORMAT
26  *  --- ------ ------
27  *  0                   1                   2                   3
28  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
29  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30  * |     Code      |  Identifier   |            Length             |
31  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32  * |    Data ...
33  * +-+-+-+-+
34  *
35  *
36  * EAP Request and Response Packet Format
37  * --- ------- --- -------- ------ ------
38  *  0                   1                   2                   3
39  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
40  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
41  * |     Code      |  Identifier   |            Length             |
42  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
43  * |     Type      |  Type-Data ...
44  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
45  *
46  *
47  * EAP Success and Failure Packet Format
48  * --- ------- --- ------- ------ ------
49  *  0                   1                   2                   3
50  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
51  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52  * |     Code      |  Identifier   |            Length             |
53  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
54  *
55  */
56
57 #include <freeradius-devel/ident.h>
58 RCSID("$Id$")
59
60 #include "rlm_eap.h"
61
62 static const char *eap_codes[] = {
63   "",                           /* 0 is invalid */
64   "request",
65   "response",
66   "success",
67   "failure"
68 };
69
70 /*
71  * Load all the required eap authentication types.
72  * Get all the supported EAP-types from config file.
73  */
74 int eaptype_load(EAP_TYPES **type, int eap_type, CONF_SECTION *cs)
75 {
76         char            buffer[64];
77         char            namebuf[64];
78         const char      *eaptype_name;
79         lt_dlhandle     handle;
80         EAP_TYPES       *node;
81
82         eaptype_name = eaptype_type2name(eap_type, namebuf, sizeof(namebuf));
83         snprintf(buffer, sizeof(buffer), "rlm_eap_%s", eaptype_name);
84
85         /* Link the loaded EAP-Type */
86         handle = lt_dlopenext(buffer);
87         if (handle == NULL) {
88                 radlog(L_ERR, "rlm_eap: Failed to link EAP-Type/%s: %s",
89                        eaptype_name, lt_dlerror());
90                 return -1;
91         }
92
93         /* Make room for the EAP-Type */
94         node = (EAP_TYPES *)malloc(sizeof(EAP_TYPES));
95         if (node == NULL) {
96                 radlog(L_ERR, "rlm_eap: out of memory");
97                 return -1;
98         }
99         memset(node, 0, sizeof(*node));
100
101         /* fill in the structure */
102         node->handle = handle;
103         node->cs = cs;
104
105         /*
106          *      In general, this is a terrible idea.  It works here
107          *      solely because the eap_type2name function returns a
108          *      'static const char *' pointer sometimes, and we can
109          *      ONLY link to module which are named in that static
110          *      array.
111          */
112         node->typename = eaptype_name;
113         node->type_data = NULL;
114
115         node->type = (EAP_TYPE *)lt_dlsym(node->handle, buffer);
116         if (!node->type) {
117                 radlog(L_ERR, "rlm_eap: Failed linking to %s structure in %s: %s",
118                                 buffer, eaptype_name, lt_dlerror());
119                 lt_dlclose(node->handle);       /* ignore any errors */
120                 free(node);
121                 return -1;
122         }
123         DEBUG("eap: Linked to sub-module %s", buffer);
124
125         DEBUG("eap: Instantiating eap-%s", eaptype_name);
126
127         if ((node->type->attach) &&
128             ((node->type->attach)(node->cs, &(node->type_data)) < 0)) {
129
130                 radlog(L_ERR, "rlm_eap: Failed to initialize type %s",
131                        eaptype_name);
132                 lt_dlclose(node->handle);
133                 free(node);
134                 return -1;
135         }
136
137         *type = node;
138         return 0;
139 }
140
141 /*
142  * Call the appropriate handle with the right eap_type.
143  */
144 static int eaptype_call(EAP_TYPES *atype, EAP_HANDLER *handler)
145 {
146         int rcode = 1;
147
148         DEBUG2("  rlm_eap: processing type %s", atype->typename);
149
150         rad_assert(atype != NULL);
151
152         switch (handler->stage) {
153         case INITIATE:
154                 if (!atype->type->initiate(atype->type_data, handler))
155                         rcode = 0;
156                 break;
157
158         case AUTHORIZE:
159                 /*
160                  *   The called function updates the EAP reply packet.
161                  */
162                 if (!atype->type->authorize ||
163                     !atype->type->authorize(atype->type_data, handler))
164                         rcode = 0;
165                 break;
166
167         case AUTHENTICATE:
168                 /*
169                  *   The called function updates the EAP reply packet.
170                  */
171                 if (!atype->type->authenticate ||
172                     !atype->type->authenticate(atype->type_data, handler))
173                         rcode = 0;
174                 break;
175
176         default:
177                 /* Should never enter here */
178                 radlog(L_DBG, "rlm_eap: Invalid operation on eap_type");
179                 rcode = 0;
180                 break;
181         }
182
183         return rcode;
184 }
185
186 /*
187  * Based on TYPE, call the appropriate EAP-type handler
188  * Default to the configured EAP-Type
189  * for all Unsupported EAP-Types
190  */
191 int eaptype_select(rlm_eap_t *inst, EAP_HANDLER *handler)
192 {
193         unsigned int    default_eap_type = inst->default_eap_type;
194         eaptype_t       *eaptype;
195         VALUE_PAIR      *vp;
196         char            namebuf[64];
197         const char      *eaptype_name;
198
199         eaptype = &handler->eap_ds->response->type;
200
201         /*
202          *      Don't trust anyone.
203          */
204         if ((eaptype->type == 0) ||
205             (eaptype->type > PW_EAP_MAX_TYPES)) {
206                 DEBUG2(" rlm_eap: Asked to select bad type");
207                 return EAP_INVALID;
208         }
209
210         /*
211          *      Figure out what to do.
212          */
213         switch(eaptype->type) {
214         case PW_EAP_IDENTITY:
215                 DEBUG2("  rlm_eap: EAP Identity");
216
217                 /*
218                  *      Allow per-user configuration of EAP types.
219                  */
220                 vp = pairfind(handler->request->config_items,
221                               PW_EAP_TYPE);
222                 if (vp) default_eap_type = vp->vp_integer;
223
224         do_initiate:
225                 /*
226                  *      Ensure it's valid.
227                  */
228                 if ((default_eap_type < PW_EAP_MD5) ||
229                     (default_eap_type > PW_EAP_MAX_TYPES) ||
230                     (inst->types[default_eap_type] == NULL)) {
231                         DEBUG2(" rlm_eap: No such EAP type %s",
232                                eaptype_type2name(default_eap_type,
233                                                  namebuf, sizeof(namebuf)));
234                         return EAP_INVALID;
235                 }
236
237                 handler->stage = INITIATE;
238                 handler->eap_type = default_eap_type;
239
240                 /*
241                  *      Wild & crazy stuff!  For TTLS & PEAP, we
242                  *      initiate a TLS session, and then pass that
243                  *      session data to TTLS or PEAP for the
244                  *      authenticate stage.
245                  *
246                  *      Handler->eap_type holds the TRUE type.
247                  */
248                 if ((default_eap_type == PW_EAP_TTLS) ||
249                     (default_eap_type == PW_EAP_PEAP)) {
250                         default_eap_type = PW_EAP_TLS;
251                 }
252
253
254                 /*
255                  *      We don't do TLS inside of TLS, as it's a bad
256                  *      idea...
257                  */
258                 if ((handler->request->packet->dst_port == 0) &&
259                     (default_eap_type == PW_EAP_TLS)) {
260                         DEBUG2(" rlm_eap: Unable to tunnel TLS inside of TLS");
261                         return EAP_INVALID;
262                 }
263
264                 if (eaptype_call(inst->types[default_eap_type],
265                                  handler) == 0) {
266                         DEBUG2(" rlm_eap: Default EAP type %s failed in initiate",
267                                eaptype_type2name(default_eap_type,
268                                                  namebuf, sizeof(namebuf)));
269                         return EAP_INVALID;
270                 }
271                 break;
272
273         case PW_EAP_NAK:
274                 /*
275                  *      The NAK data is the preferred EAP type(s) of
276                  *      the client.
277                  *
278                  *      RFC 3748 says to list one or more proposed
279                  *      alternative types, one per octet, or to use
280                  *      0 for no alternative.
281                  */
282                 DEBUG2("  rlm_eap: EAP NAK");
283
284                 /*
285                  *      Delete old data, if necessary.
286                  */
287                 if (handler->opaque && handler->free_opaque) {
288                         handler->free_opaque(handler->opaque);
289                         handler->free_opaque = NULL;
290                         handler->opaque = NULL;
291                 }
292
293                 /*
294                  *      It is invalid to request identity,
295                  *      notification & nak in nak
296                  */
297                 if (eaptype->data == NULL) {
298                         DEBUG2(" rlm_eap: Empty NAK packet, cannot decide what EAP type the client wants.");
299                         return EAP_INVALID;
300                 }
301
302                 /*
303                  *      FIXME: Pick one type out of the one they asked
304                  *      for, as they may have asked for many.
305                  */
306                 if ((eaptype->data[0] < PW_EAP_MD5) ||
307                     (eaptype->data[0] > PW_EAP_MAX_TYPES)) {
308                         DEBUG2(" rlm_eap: NAK asked for bad type %d",
309                                eaptype->data[0]);
310                         return EAP_INVALID;
311                 }
312
313                 default_eap_type = eaptype->data[0];
314                 eaptype_name = eaptype_type2name(default_eap_type,
315                                                  namebuf, sizeof(namebuf));
316                 DEBUG2(" rlm_eap: EAP-NAK asked for EAP-Type/%s",
317                        eaptype_name);
318
319                 /*
320                  *      Prevent a firestorm if the client is confused.
321                  */
322                 if (handler->eap_type == default_eap_type) {
323                         DEBUG2(" rlm_eap: ERROR! Our request for %s was NAK'd with a request for %s, what is the client thinking?",
324                                eaptype_name, eaptype_name);
325                         return EAP_INVALID;
326                 }
327
328                 /*
329                  *      Enforce per-user configuration of EAP types.
330                  */
331                 vp = pairfind(handler->request->config_items,
332                               PW_EAP_TYPE);
333                 if (vp && (vp->vp_integer != default_eap_type)) {
334                         char    mynamebuf[64];
335                         DEBUG2("  rlm_eap: Client wants %s, while we require %s, rejecting the user.",
336                                eaptype_name,
337                                eaptype_type2name(vp->vp_integer,
338                                                  mynamebuf,
339                                                  sizeof(mynamebuf)));
340                         return EAP_INVALID;
341                 }
342                 goto do_initiate;
343                 break;
344
345                 /*
346                  *      Key off of the configured sub-modules.
347                  */
348                 default:
349                         eaptype_name = eaptype_type2name(eaptype->type,
350                                                          namebuf,
351                                                          sizeof(namebuf));
352                         DEBUG2("  rlm_eap: EAP/%s", eaptype_name);
353
354                         /*
355                          *      We haven't configured it, it doesn't exit.
356                          */
357                         if (!inst->types[eaptype->type]) {
358                                 DEBUG2(" rlm_eap: EAP type %d is unsupported",
359                                        eaptype->type);
360                                 return EAP_INVALID;
361                         }
362
363                         rad_assert(handler->stage == AUTHENTICATE);
364                         handler->eap_type = eaptype->type;
365                         if (eaptype_call(inst->types[eaptype->type],
366                                          handler) == 0) {
367                                 DEBUG2(" rlm_eap: Handler failed in EAP/%s",
368                                        eaptype_name);
369                                 return EAP_INVALID;
370                         }
371                 break;
372         }
373
374         return EAP_OK;
375 }
376
377
378 /*
379  *      EAP packet format to be sent over the wire
380  *
381  *      i.e. code+id+length+data where data = null/type+typedata
382  *      based on code.
383  */
384 static int eap_wireformat(EAP_PACKET *reply)
385 {
386         eap_packet_t    *hdr;
387         uint16_t total_length = 0;
388
389         if (reply == NULL) return EAP_INVALID;
390
391         total_length = EAP_HEADER_LEN;
392         if (reply->code < 3) {
393                 total_length += 1/*EAPtype*/;
394                 if (reply->type.data && reply->type.length > 0) {
395                         total_length += reply->type.length;
396                 }
397         }
398
399         reply->packet = (unsigned char *)malloc(total_length);
400         hdr = (eap_packet_t *)reply->packet;
401         if (!hdr) {
402                 radlog(L_ERR, "rlm_eap: out of memory");
403                 return EAP_INVALID;
404         }
405
406         hdr->code = (reply->code & 0xFF);
407         hdr->id = (reply->id & 0xFF);
408         total_length = htons(total_length);
409         memcpy(hdr->length, &total_length, sizeof(uint16_t));
410
411         /*
412          *      Request and Response packets are special.
413          */
414         if ((reply->code == PW_EAP_REQUEST) ||
415             (reply->code == PW_EAP_RESPONSE)) {
416                 hdr->data[0] = (reply->type.type & 0xFF);
417
418                 /*
419                  * Here since we cannot know the typedata format and length
420                  *
421                  * Type_data is expected to be wired by each EAP-Type
422                  *
423                  * Zero length/No typedata is supported as long as
424                  * type is defined
425                  */
426                 if (reply->type.data && reply->type.length > 0) {
427                         memcpy(&hdr->data[1], reply->type.data, reply->type.length);
428                         free(reply->type.data);
429                         reply->type.data = reply->packet + EAP_HEADER_LEN + 1/*EAPtype*/;
430                 }
431         }
432
433         return EAP_VALID;
434 }
435
436 /*
437  *      compose EAP reply packet in EAP-Message attr of RADIUS.  If
438  *      EAP exceeds 253, frame it in multiple EAP-Message attrs.
439  *
440  *      Set the RADIUS reply codes based on EAP request codes.  Append
441  *      any additonal VPs to RADIUS reply
442  */
443 int eap_compose(EAP_HANDLER *handler)
444 {
445         uint16_t eap_len, len;
446         VALUE_PAIR *eap_msg;
447         VALUE_PAIR *vp;
448         eap_packet_t *eap_packet;
449         unsigned char   *ptr;
450         REQUEST *request = handler->request;
451         EAP_DS *eap_ds = handler->eap_ds;
452         EAP_PACKET *reply = eap_ds->request;
453         int rcode;
454
455         /*
456          *      The Id for the EAP packet to the NAS wasn't set.
457          *      Do so now.
458          *
459          *      LEAP requires the Id to be incremented on EAP-Success
460          *      in Stage 4, so that we can carry on the conversation
461          *      where the client asks us to authenticate ourselves
462          *      in stage 5.
463          */
464         if (!eap_ds->set_request_id) {
465                 /*
466                  *      Id serves to suppport request/response
467                  *      retransmission in the EAP layer and as such
468                  *      must be different for 'adjacent' packets
469                  *      except in case of success/failure-replies.
470                  *
471                  *      RFC2716 (EAP-TLS) requires this to be
472                  *      incremented, RFC2284 only makes the above-
473                  *      mentioned restriction.
474                  */
475                 reply->id = handler->eap_ds->response->id;
476
477                 switch (reply->code) {
478                         /*
479                          *      The Id is a simple "ack" for success
480                          *      and failure.
481                          *
482                          *      RFC 3748 section 4.2 says
483                          *
484                          *      ... The Identifier field MUST match
485                          *      the Identifier field of the Response
486                          *      packet that it is sent in response
487                          *      to.
488                          */
489                 case PW_EAP_SUCCESS:
490                 case PW_EAP_FAILURE:
491                         break;
492
493                         /*
494                          *      We've sent a response to their
495                          *      request, the Id is incremented.
496                          */
497                 default:
498                         ++reply->id;
499                 }
500         } else {
501                 DEBUG2("  rlm_eap: Underlying EAP-Type set EAP ID to %d",
502                        reply->id);
503         }
504
505         /*
506          *      For Request & Response packets, set the EAP sub-type,
507          *      if the EAP sub-module didn't already set it.
508          *
509          *      This allows the TLS module to be "morphic", and means
510          *      that the TTLS and PEAP modules can call it to do most
511          *      of their dirty work.
512          */
513         if (((eap_ds->request->code == PW_EAP_REQUEST) ||
514              (eap_ds->request->code == PW_EAP_RESPONSE)) &&
515             (eap_ds->request->type.type == 0)) {
516                 rad_assert(handler->eap_type >= PW_EAP_MD5);
517                 rad_assert(handler->eap_type <= PW_EAP_MAX_TYPES);
518
519                 eap_ds->request->type.type = handler->eap_type;
520         }
521
522
523         if (eap_wireformat(reply) == EAP_INVALID) {
524                 return RLM_MODULE_INVALID;
525         }
526         eap_packet = (eap_packet_t *)reply->packet;
527
528         memcpy(&eap_len, &(eap_packet->length), sizeof(uint16_t));
529         len = eap_len = ntohs(eap_len);
530         ptr = (unsigned char *)eap_packet;
531
532         do {
533                 if (eap_len > 253) {
534                         len = 253;
535                         eap_len -= 253;
536                 } else {
537                         len = eap_len;
538                         eap_len = 0;
539                 }
540
541                 /*
542                  * create a value pair & append it to the request reply list
543                  * This memory gets freed up when request is freed up
544                  */
545                 eap_msg = paircreate(PW_EAP_MESSAGE, PW_TYPE_OCTETS);
546                 memcpy(eap_msg->vp_octets, ptr, len);
547                 eap_msg->length = len;
548                 pairadd(&(request->reply->vps), eap_msg);
549                 ptr += len;
550                 eap_msg = NULL;
551         } while (eap_len);
552
553         /*
554          *      EAP-Message is always associated with
555          *      Message-Authenticator but not vice-versa.
556          *
557          *      Don't add a Message-Authenticator if it's already
558          *      there.
559          */
560         vp = pairfind(request->reply->vps, PW_MESSAGE_AUTHENTICATOR);
561         if (!vp) {
562                 vp = paircreate(PW_MESSAGE_AUTHENTICATOR, PW_TYPE_OCTETS);
563                 memset(vp->vp_octets, 0, AUTH_VECTOR_LEN);
564                 vp->length = AUTH_VECTOR_LEN;
565                 pairadd(&(request->reply->vps), vp);
566         }
567
568         /* Set request reply code, but only if it's not already set. */
569         rcode = RLM_MODULE_OK;
570         if (!request->reply->code) switch(reply->code) {
571         case PW_EAP_RESPONSE:
572                 request->reply->code = PW_AUTHENTICATION_ACK;
573                 rcode = RLM_MODULE_HANDLED; /* leap weirdness */
574                 break;
575         case PW_EAP_SUCCESS:
576                 request->reply->code = PW_AUTHENTICATION_ACK;
577                 rcode = RLM_MODULE_OK;
578                 break;
579         case PW_EAP_FAILURE:
580                 request->reply->code = PW_AUTHENTICATION_REJECT;
581                 rcode = RLM_MODULE_REJECT;
582                 break;
583         case PW_EAP_REQUEST:
584                 request->reply->code = PW_ACCESS_CHALLENGE;
585                 rcode = RLM_MODULE_HANDLED;
586                 break;
587         default:
588                 /*
589                  *      When we're pulling MS-CHAPv2 out of EAP-MS-CHAPv2,
590                  *      we do so WITHOUT setting a reply code, as the
591                  *      request is being proxied.
592                  */
593                 if (request->options & RAD_REQUEST_OPTION_PROXY_EAP) {
594                         return RLM_MODULE_HANDLED;
595                 }
596
597                 /* Should never enter here */
598                 radlog(L_ERR, "rlm_eap: reply code %d is unknown, Rejecting the request.", reply->code);
599                 request->reply->code = PW_AUTHENTICATION_REJECT;
600                 reply->code = PW_EAP_FAILURE;
601                 rcode = RLM_MODULE_REJECT;
602                 break;
603         }
604
605         return rcode;
606 }
607
608 /*
609  * Radius criteria, EAP-Message is invalid without Message-Authenticator
610  * For EAP_START, send Access-Challenge with EAP Identity request.
611  */
612 int eap_start(rlm_eap_t *inst, REQUEST *request)
613 {
614         VALUE_PAIR *vp, *proxy;
615         VALUE_PAIR *eap_msg;
616
617         eap_msg = pairfind(request->packet->vps, PW_EAP_MESSAGE);
618         if (eap_msg == NULL) {
619                 DEBUG2("  rlm_eap: No EAP-Message, not doing EAP");
620                 return EAP_NOOP;
621         }
622
623         /*
624          *      Look for EAP-Type = None (FreeRADIUS specific attribute)
625          *      this allows you to NOT do EAP for some users.
626          */
627         vp = pairfind(request->packet->vps, PW_EAP_TYPE);
628         if (vp && vp->vp_integer == 0) {
629                 DEBUG2("  rlm_eap: Found EAP-Message, but EAP-Type = None, so we're not doing EAP.");
630                 return EAP_NOOP;
631         }
632
633         /*
634          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
635          *
636          *      Checks for Message-Authenticator are handled by rad_recv().
637          */
638
639         /*
640          *      Check for a Proxy-To-Realm.  Don't get excited over LOCAL
641          *      realms (sigh).
642          */
643         proxy = pairfind(request->config_items, PW_PROXY_TO_REALM);
644         if (proxy) {
645                 REALM *realm;
646
647                 /*
648                  *      If it's a LOCAL realm, then we're not proxying
649                  *      to it.
650                  */
651                 realm = realm_find(proxy->vp_strvalue);
652                 if (realm && (realm->auth_pool == NULL)) {
653                         proxy = NULL;
654                 }
655         }
656
657         /*
658          *      Check the length before de-referencing the contents.
659          *
660          *      Lengths of zero are required by the RFC for EAP-Start,
661          *      but we've never seen them in practice.
662          *
663          *      Lengths of two are what we see in practice as
664          *      EAP-Starts.
665          */
666         if ((eap_msg->length == 0) || (eap_msg->length == 2)) {
667                 EAP_DS *eap_ds;
668                 EAP_HANDLER handler;
669
670                 /*
671                  *      It's a valid EAP-Start, but the request
672                  *      was marked as being proxied.  So we don't
673                  *      do EAP, as the home server will do it.
674                  */
675                 if (proxy) {
676                 do_proxy:
677                         DEBUG2("  rlm_eap: Request is supposed to be proxied to Realm %s.  Not doing EAP.", proxy->vp_strvalue);
678                         return EAP_NOOP;
679                 }
680                 
681                 DEBUG2("  rlm_eap: Got EAP_START message");
682                 if ((eap_ds = eap_ds_alloc()) == NULL) {
683                         DEBUG2("  rlm_eap: EAP Start failed in allocation");
684                         return EAP_FAIL;
685                 }
686                 
687                 /*
688                  *      It's an EAP-Start packet.  Tell them to stop wasting
689                  *      our time, and give us an EAP-Identity packet.
690                  *
691                  *      Hmm... we should probably check the contents of the
692                  *      EAP-Start packet for something...
693                  */
694                 eap_ds->request->code = PW_EAP_REQUEST;
695                 eap_ds->request->type.type = PW_EAP_IDENTITY;
696                 
697                 /*
698                  *      We don't have a handler, but eap_compose needs one,
699                  *      (for various reasons), so we fake it out here.
700                  */
701                 memset(&handler, 0, sizeof(handler));
702                 handler.request = request;
703                 handler.eap_ds = eap_ds;
704                 
705                 eap_compose(&handler);
706                 
707                 eap_ds_free(&eap_ds);
708                 return EAP_FOUND;
709         } /* end of handling EAP-Start */
710
711         /*
712          *      The EAP packet header is 4 bytes, plus one byte of
713          *      EAP sub-type.  Short packets are discarded, unless
714          *      we're proxying.
715          */
716         if (eap_msg->length < (EAP_HEADER_LEN + 1)) {
717                 if (proxy) goto do_proxy;
718
719                 DEBUG2("  rlm_eap: Ignoring EAP-Message which is too short to be meaningful.");
720                 return EAP_FAIL;
721         }
722
723         /*
724          *      Create an EAP-Type containing the EAP-type
725          *      from the packet.
726          */
727         vp = paircreate(PW_EAP_TYPE, PW_TYPE_INTEGER);
728         if (vp) {
729                 vp->vp_integer = eap_msg->vp_octets[4];
730                 pairadd(&(request->packet->vps), vp);
731         }
732
733         /*
734          *      If the request was marked to be proxied, do it now.
735          *      This is done after checking for a valid length
736          *      (which may not be good), and after adding the EAP-Type
737          *      attribute.  This lets other modules selectively cancel
738          *      proxying based on EAP-Type.
739          */
740         if (proxy) goto do_proxy;
741
742         /*
743          *      From now on, we're supposed to be handling the
744          *      EAP packet.  We better understand it...
745          */
746
747         /*
748          *      We're allowed only a few codes.  Request, Response,
749          *      Success, or Failure.
750          */
751         if ((eap_msg->vp_octets[0] == 0) ||
752             (eap_msg->vp_octets[0] > PW_EAP_MAX_CODES)) {
753                 DEBUG2("  rlm_eap: Unknown EAP packet");
754         } else {
755                 DEBUG2("  rlm_eap: EAP packet type %s id %d length %d",
756                        eap_codes[eap_msg->vp_octets[0]],
757                        eap_msg->vp_octets[1],
758                        eap_msg->length);
759         }
760
761         /*
762          *      We handle request and responses.  The only other defined
763          *      codes are success and fail.  The client SHOULD NOT be
764          *      sending success/fail packets to us, as it doesn't make
765          *      sense.
766          */
767         if ((eap_msg->vp_octets[0] != PW_EAP_REQUEST) &&
768             (eap_msg->vp_octets[0] != PW_EAP_RESPONSE)) {
769                 DEBUG2("  rlm_eap: Ignoring EAP packet which we don't know how to handle.");
770                 return EAP_FAIL;
771         }
772
773         /*
774          *      We've been told to ignore unknown EAP types, AND it's
775          *      an unknown type.  Return "NOOP", which will cause the
776          *      eap_authorize() to return NOOP.
777          *
778          *      EAP-Identity, Notification, and NAK are all handled
779          *      internally, so they never have handlers.
780          */
781         if ((eap_msg->vp_octets[4] >= PW_EAP_MD5) &&
782             inst->ignore_unknown_eap_types &&
783             ((eap_msg->vp_octets[4] == 0) ||
784              (eap_msg->vp_octets[4] > PW_EAP_MAX_TYPES) ||
785              (inst->types[eap_msg->vp_octets[4]] == NULL))) {
786                 DEBUG2("  rlm_eap:  Ignoring Unknown EAP type");
787                 return EAP_NOOP;
788         }
789                 
790         /*
791          *      They're NAKing the EAP type we wanted to use, and
792          *      asking for one which we don't support.
793          *
794          *      NAK is code + id + length1 + length + NAK
795          *             + requested EAP type(s).
796          *
797          *      We know at this point that we can't handle the
798          *      request.  We could either return an EAP-Fail here, but
799          *      it's not too critical.
800          *
801          *      By returning "noop", we can ensure that authorize()
802          *      returns NOOP, and another module may choose to proxy
803          *      the request.
804          */
805         if ((eap_msg->vp_octets[4] == PW_EAP_NAK) &&
806             (eap_msg->length >= (EAP_HEADER_LEN + 2)) &&
807             inst->ignore_unknown_eap_types &&
808             ((eap_msg->vp_octets[5] == 0) ||
809              (eap_msg->vp_octets[5] > PW_EAP_MAX_TYPES) ||
810              (inst->types[eap_msg->vp_octets[5]] == NULL))) {
811                 DEBUG2("  rlm_eap: Ignoring NAK with request for unknown EAP type");
812                 return EAP_NOOP;
813         }
814
815         if ((eap_msg->vp_octets[4] == PW_EAP_TTLS) ||
816             (eap_msg->vp_octets[4] == PW_EAP_PEAP)) {
817                 DEBUG2("  rlm_eap: Continuing tunnel setup.");
818                 return EAP_OK;
819         }
820
821         /*
822          *      Later EAP messages are longer than the 'start'
823          *      message, so if everything is OK, this function returns
824          *      'no start found', so that the rest of the EAP code can
825          *      use the State attribute to match this EAP-Message to
826          *      an ongoing conversation.
827          */
828         DEBUG2("  rlm_eap: No EAP Start, assuming it's an on-going EAP conversation");
829
830         return EAP_NOTFOUND;
831 }
832
833 /*
834  *      compose EAP FAILURE packet in EAP-Message
835  */
836 void eap_fail(EAP_HANDLER *handler)
837 {
838         handler->eap_ds->request->code = PW_EAP_FAILURE;
839         eap_compose(handler);
840 }
841
842 /*
843  *      compose EAP SUCCESS packet in EAP-Message
844  */
845 void eap_success(EAP_HANDLER *handler)
846 {
847         handler->eap_ds->request->code = PW_EAP_SUCCESS;
848         eap_compose(handler);
849 }
850
851 /*
852  * Basic EAP packet verfications & validations
853  */
854 static int eap_validation(eap_packet_t *eap_packet)
855 {
856         uint16_t len;
857
858         memcpy(&len, eap_packet->length, sizeof(uint16_t));
859         len = ntohs(len);
860
861         /*
862          *      High level EAP packet checks
863          */
864         if ((len <= EAP_HEADER_LEN) ||
865             ((eap_packet->code != PW_EAP_RESPONSE) &&
866              (eap_packet->code != PW_EAP_REQUEST)) ||
867             (eap_packet->data[0] <= 0) ||
868             (eap_packet->data[0] > PW_EAP_MAX_TYPES)) {
869
870                 radlog(L_AUTH, "rlm_eap: Incorrect EAP Message, "
871                                 "Ignoring the packet");
872                 return EAP_INVALID;
873         }
874
875         /* we don't expect notification, but we send it */
876         if (eap_packet->data[0] == PW_EAP_NOTIFICATION) {
877                 radlog(L_AUTH, "rlm_eap: Got NOTIFICATION, "
878                                 "Ignoring the packet");
879                 return EAP_INVALID;
880         }
881
882         return EAP_VALID;
883 }
884
885
886 /*
887  *  Get the user Identity only from EAP-Identity packets
888  */
889 static char *eap_identity(eap_packet_t *eap_packet)
890 {
891         int size;
892         uint16_t len;
893         char *identity;
894
895         if ((eap_packet == NULL) ||
896             (eap_packet->code != PW_EAP_RESPONSE) ||
897             (eap_packet->data[0] != PW_EAP_IDENTITY)) {
898                 return NULL;
899         }
900
901         memcpy(&len, eap_packet->length, sizeof(uint16_t));
902         len = ntohs(len);
903
904         if ((len <= 5) || (eap_packet->data[1] == 0x00)) {
905                 radlog(L_ERR, "rlm_eap: UserIdentity Unknown ");
906                 return NULL;
907         }
908
909         size = len - 5;
910         identity = (char *)malloc(size + 1);
911         if (identity == NULL) {
912                 radlog(L_ERR, "rlm_eap: out of memory");
913                 return NULL;
914         }
915         memcpy(identity, &eap_packet->data[1], size);
916         identity[size] = '\0';
917
918         return identity;
919 }
920
921
922 /*
923  *      Create our Request-Response data structure with the eap packet
924  */
925 static EAP_DS *eap_buildds(eap_packet_t **eap_packet_p)
926 {
927         EAP_DS          *eap_ds = NULL;
928         eap_packet_t    *eap_packet = *eap_packet_p;
929         int             typelen;
930         uint16_t        len;
931
932         if ((eap_ds = eap_ds_alloc()) == NULL) {
933                 return NULL;
934         }
935
936         eap_ds->response->packet = (unsigned char *)eap_packet;
937         eap_ds->response->code = eap_packet->code;
938         eap_ds->response->id = eap_packet->id;
939         eap_ds->response->type.type = eap_packet->data[0];
940
941         memcpy(&len, eap_packet->length, sizeof(uint16_t));
942         len = ntohs(len);
943         eap_ds->response->length = len;
944
945         /*
946          *      We've eaten the eap packet into the eap_ds.
947          */
948         *eap_packet_p = NULL;
949
950         /*
951          *      First 5 bytes in eap, are code + id + length(2) + type.
952          *
953          *      The rest is type-specific data.  We skip type while
954          *      getting typedata from data.
955          */
956         typelen = len - 5/*code + id + length + type */;
957         if (typelen > 0) {
958                 /*
959                  *      Since the packet contains the complete
960                  *      eap_packet, typedata will be a ptr in packet
961                  *      to its typedata
962                  */
963                 eap_ds->response->type.data = eap_ds->response->packet + 5/*code+id+length+type*/;
964                 eap_ds->response->type.length = typelen;
965         } else {
966                 eap_ds->response->type.length = 0;
967                 eap_ds->response->type.data = NULL;
968         }
969
970         return eap_ds;
971 }
972
973
974 /*
975  * If identity response then create a fresh handler & fill the identity
976  * else handler MUST be in our list, get that.
977  * This handler creation cannot fail
978  *
979  * username contains REQUEST->username which might have been stripped.
980  * identity contains the one sent in EAP-Identity response
981  */
982 EAP_HANDLER *eap_handler(rlm_eap_t *inst, eap_packet_t **eap_packet_p,
983                          REQUEST *request)
984 {
985         EAP_HANDLER     *handler = NULL;
986         eap_packet_t    *eap_packet = *eap_packet_p;
987         VALUE_PAIR      *vp;
988
989         /*
990          *      Ensure it's a valid EAP-Request, or EAP-Response.
991          */
992         if (eap_validation(eap_packet) == EAP_INVALID) {
993                 free(*eap_packet_p);
994                 *eap_packet_p = NULL;
995                 return NULL;
996         }
997
998         /*
999          *      EAP_HANDLER MUST be found in the list if it is not
1000          *      EAP-Identity response
1001          */
1002         if (eap_packet->data[0] != PW_EAP_IDENTITY) {
1003                 handler = eaplist_find(inst, request, eap_packet);
1004                 if (handler == NULL) {
1005                         /* Either send EAP_Identity or EAP-Fail */
1006                         radlog(L_ERR, "rlm_eap: Either EAP-request timed out OR"
1007                                 " EAP-response to an unknown EAP-request");
1008                         free(*eap_packet_p);
1009                         *eap_packet_p = NULL;
1010                         return NULL;
1011                 }
1012
1013                 /*
1014                  *      Even more paranoia.  Without this, some weird
1015                  *      clients could do crazy things.
1016                  *
1017                  *      It's ok to send EAP sub-type NAK in response
1018                  *      to a request for a particular type, but it's NOT
1019                  *      OK to blindly return data for another type.
1020                  */
1021                 if ((eap_packet->data[0] != PW_EAP_NAK) &&
1022                     (eap_packet->data[0] != handler->eap_type)) {
1023                         radlog(L_ERR, "rlm_eap: Response appears to match, but EAP type is wrong.");
1024                         free(*eap_packet_p);
1025                         *eap_packet_p = NULL;
1026                         return NULL;
1027                 }
1028
1029                vp = pairfind(request->packet->vps, PW_USER_NAME);
1030                if (!vp) {
1031                        /*
1032                         *       NAS did not set the User-Name
1033                         *       attribute, so we set it here and
1034                         *       prepend it to the beginning of the
1035                         *       request vps so that autz's work
1036                         *       correctly
1037                         */
1038                        radlog(L_INFO, "rlm_eap: Broken NAS did not set User-Name, setting from EAP Identity");
1039                        vp = pairmake("User-Name", handler->identity, T_OP_EQ);
1040                        if (vp == NULL) {
1041                                radlog(L_ERR, "rlm_eap: out of memory");
1042                                free(*eap_packet_p);
1043                                *eap_packet_p = NULL;
1044                                return NULL;
1045                        }
1046                        vp->next = request->packet->vps;
1047                        request->packet->vps = vp;
1048
1049                } else {
1050                        /*
1051                         *      A little more paranoia.  If the NAS
1052                         *      *did* set the User-Name, and it doesn't
1053                         *      match the identity, (i.e. If they
1054                         *      change their User-Name part way through
1055                         *      the EAP transaction), then reject the
1056                         *      request as the NAS is doing something
1057                         *      funny.
1058                         */
1059                        if (strncmp(handler->identity, vp->vp_strvalue,
1060                                    MAX_STRING_LEN) != 0) {
1061                                radlog(L_ERR, "rlm_eap: Identity does not match User-Name.  Authentication failed.");
1062                                free(*eap_packet_p);
1063                                *eap_packet_p = NULL;
1064                                return NULL;
1065                        }
1066                }
1067         } else {                /* packet was EAP identity */
1068                 handler = eap_handler_alloc();
1069                 if (handler == NULL) {
1070                         radlog(L_ERR, "rlm_eap: out of memory");
1071                         free(*eap_packet_p);
1072                         *eap_packet_p = NULL;
1073                         return NULL;
1074                 }
1075
1076                 /*
1077                  *      All fields in the handler are set to zero.
1078                  */
1079                 handler->identity = eap_identity(eap_packet);
1080                 if (handler->identity == NULL) {
1081                         radlog(L_ERR, "rlm_eap: Identity Unknown, authentication failed");
1082                         free(*eap_packet_p);
1083                         *eap_packet_p = NULL;
1084                         eap_handler_free(handler);
1085                         return NULL;
1086                 }
1087
1088                vp = pairfind(request->packet->vps, PW_USER_NAME);
1089                if (!vp) {
1090                        /*
1091                         *       NAS did not set the User-Name
1092                         *       attribute, so we set it here and
1093                         *       prepend it to the beginning of the
1094                         *       request vps so that autz's work
1095                         *       correctly
1096                         */
1097                        radlog(L_INFO, "rlm_eap: WARNING NAS did not set User-Name.  Setting it locally from EAP Identity");
1098                        vp = pairmake("User-Name", handler->identity, T_OP_EQ);
1099                        if (vp == NULL) {
1100                                radlog(L_ERR, "rlm_eap: out of memory");
1101                                free(*eap_packet_p);
1102                                *eap_packet_p = NULL;
1103                                return NULL;
1104                        }
1105                        vp->next = request->packet->vps;
1106                        request->packet->vps = vp;
1107                } else {
1108                        /*
1109                         *      Paranoia.  If the NAS *did* set the
1110                         *      User-Name, and it doesn't match the
1111                         *      identity, the NAS is doing something
1112                         *      funny, so reject the request.
1113                         */
1114                        if (strncmp(handler->identity, vp->vp_strvalue,
1115                                    MAX_STRING_LEN) != 0) {
1116                                radlog(L_ERR, "rlm_eap: Identity does not match User-Name, setting from EAP Identity.");
1117                                free(*eap_packet_p);
1118                                *eap_packet_p = NULL;
1119                                eap_handler_free(handler);
1120                                return NULL;
1121                        }
1122                }
1123         }
1124
1125         handler->eap_ds = eap_buildds(eap_packet_p);
1126         if (handler->eap_ds == NULL) {
1127                 free(*eap_packet_p);
1128                 *eap_packet_p = NULL;
1129                 eap_handler_free(handler);
1130                 return NULL;
1131         }
1132
1133         handler->timestamp = request->timestamp;
1134         handler->request = request; /* LEAP needs this */
1135         return handler;
1136 }