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