Merge branch 'sam'
[freeradius.git] / src / modules / rlm_eap / types / rlm_eap_ttls / ttls.c
1 /*
2  * rlm_eap_ttls.c  contains the interfaces that are called from eap
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 2003 Alan DeKok <aland@freeradius.org>
21  *   Copyright 2006 The FreeRADIUS server project
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include "eap_ttls.h"
28
29 /*
30  *    0                   1                   2                   3
31  *    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
32  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
33  *   |                           AVP Code                            |
34  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
35  *   |V M r r r r r r|                  AVP Length                   |
36  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37  *   |                        Vendor-ID (opt)                        |
38  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
39  *   |    Data ...
40  *   +-+-+-+-+-+-+-+-+
41  */
42
43 /*
44  *      Verify that the diameter packet is valid.
45  */
46 static int diameter_verify(REQUEST *request,
47                            const uint8_t *data, unsigned int data_len)
48 {
49         uint32_t attr;
50         uint32_t length;
51         unsigned int offset;
52         unsigned int data_left = data_len;
53
54         while (data_left > 0) {
55                 if (data_len < 12) {
56                         RDEBUG2(" Diameter attribute is too small to contain a Diameter header");
57                         return 0;
58                 }
59
60                 rad_assert(data_left <= data_len);
61                 memcpy(&attr, data, sizeof(attr));
62                 data += 4;
63                 attr = ntohl(attr);
64                 if (attr > 255) {
65                         RDEBUG2(" Non-RADIUS attribute in tunneled authentication is not supported");
66                         return 0;
67                 }
68
69                 memcpy(&length, data , sizeof(length));
70                 data += 4;
71                 length = ntohl(length);
72
73                 /*
74                  *      A "vendor" flag, with a vendor ID of zero,
75                  *      is equivalent to no vendor.  This is stupid.
76                  */
77                 offset = 8;
78                 if ((length & (1 << 31)) != 0) {
79                         uint32_t vendor;
80                         DICT_ATTR *da;
81
82                         memcpy(&vendor, data, sizeof(vendor));
83                         vendor = ntohl(vendor);
84
85                         if (vendor > FR_MAX_VENDOR) {
86                                 RDEBUG2("Vendor codes larger than 2^24 are not supported");
87                                 return 0;
88                         }
89
90                         da = dict_attrbyvalue(attr, vendor);
91
92                         /*
93                          *      SHOULD check ((length & (1 << 30)) != 0)
94                          *      for the mandatory bit.
95                          */
96                         if (!da) {
97                                 RDEBUG2("Fatal! Vendor %u, Attribute %u was not found in our dictionary. ",
98                                        vendor, attr);
99                                 return 0;
100                         }
101
102                         data += 4; /* skip the vendor field */
103                         offset += 4; /* offset to value field */
104                 }
105
106                 /*
107                  *      Ignore the M bit.  We support all RADIUS attributes...
108                  */
109
110                 /*
111                  *      Get the length.  If it's too big, die.
112                  */
113                 length &= 0x00ffffff;
114
115                 /*
116                  *      Too short or too long is bad.
117                  */
118                 if (length < offset) {
119                         RDEBUG2("Tunneled attribute %d is too short (%d)to contain anything useful.", attr, length);
120                         return 0;
121                 }
122
123                 /*
124                  *      EAP Messages cane be longer than MAX_STRING_LEN.
125                  *      Other attributes cannot be.
126                  */
127                 if ((attr != PW_EAP_MESSAGE) &&
128                     (length > (MAX_STRING_LEN + 8))) {
129                         RDEBUG2("Tunneled attribute %d is too long (%d) to pack into a RADIUS attribute.", attr, length);
130                         return 0;
131                 }
132
133                 if (length > data_left) {
134                         RDEBUG2("Tunneled attribute %d is longer than room left in the packet (%d > %d).", attr, length, data_left);
135                         return 0;
136                 }
137
138                 /*
139                  *      Check for broken implementations, which don't
140                  *      pad the AVP to a 4-octet boundary.
141                  */
142                 if (data_left == length) break;
143
144                 /*
145                  *      The length does NOT include the padding, so
146                  *      we've got to account for it here by rounding up
147                  *      to the nearest 4-byte boundary.
148                  */
149                 length += 0x03;
150                 length &= ~0x03;
151
152                 /*
153                  *      If the rest of the diameter packet is larger than
154                  *      this attribute, continue.
155                  *
156                  *      Otherwise, if the attribute over-flows the end
157                  *      of the packet, die.
158                  */
159                 if (data_left < length) {
160                         RDEBUG2("ERROR! Diameter attribute overflows packet!");
161                         return 0;
162                 }
163
164                 /*
165                  *      Check again for equality, now that we're padded
166                  *      length to a multiple of 4 octets.
167                  */
168                 if (data_left == length) break;
169
170                 /*
171                  *      data_left > length, continue.
172                  */
173                 data_left -= length;
174                 data += length - offset;
175         }
176
177         /*
178          *      We got this far.  It looks OK.
179          */
180         return 1;
181 }
182
183
184 /*
185  *      Convert diameter attributes to our VALUE_PAIR's
186  */
187 static VALUE_PAIR *diameter2vp(REQUEST *request, SSL *ssl,
188                                const uint8_t *data, size_t data_len)
189 {
190         uint32_t        attr;
191         uint32_t        vendor;
192         uint32_t        length;
193         size_t          offset;
194         size_t          size;
195         size_t          data_left = data_len;
196         VALUE_PAIR      *first = NULL;
197         VALUE_PAIR      **last = &first;
198         VALUE_PAIR      *vp;
199
200         while (data_left > 0) {
201                 rad_assert(data_left <= data_len);
202                 memcpy(&attr, data, sizeof(attr));
203                 data += 4;
204                 attr = ntohl(attr);
205                 vendor = 0;
206
207                 memcpy(&length, data, sizeof(length));
208                 data += 4;
209                 length = ntohl(length);
210
211                 /*
212                  *      A "vendor" flag, with a vendor ID of zero,
213                  *      is equivalent to no vendor.  This is stupid.
214                  */
215                 offset = 8;
216                 if ((length & (1 << 31)) != 0) {
217                         memcpy(&vendor, data, sizeof(vendor));
218                         vendor = ntohl(vendor);
219
220                         if (vendor > FR_MAX_VENDOR) {
221                                 RDEBUG2("Cannot handle vendor Id greater than 2^&24");
222                                 pairfree(&first);
223                                 return NULL;
224                         }
225
226                         data += 4; /* skip the vendor field, it's zero */
227                         offset += 4; /* offset to value field */
228                 }
229
230                 /*
231                  *      Vendor attributes can be larger than 255.
232                  *      Normal attributes cannot be.
233                  */
234                 if ((attr > 255) && (vendor == 0)) {
235                         RDEBUG2("Cannot handle Diameter attributes");
236                         pairfree(&first);
237                         return NULL;
238                 }
239
240                 /*
241                  *      FIXME: Handle the M bit.  For now, we assume that
242                  *      some other module takes care of any attribute
243                  *      with the M bit set.
244                  */
245                 
246                 /*
247                  *      Get the length.
248                  */
249                 length &= 0x00ffffff;
250
251                 /*
252                  *      Get the size of the value portion of the
253                  *      attribute.
254                  */
255                 size = length - offset;
256
257                 /*
258                  *      Create it.
259                  */
260                 vp = paircreate(attr, vendor, PW_TYPE_OCTETS);
261                 if (!vp) {
262                         RDEBUG2("Failure in creating VP");
263                         pairfree(&first);
264                         return NULL;
265                 }
266
267                 /*
268                  *      If it's a type from our dictionary, then
269                  *      we need to put the data in a relevant place.
270                  */
271                 switch (vp->type) {
272                 case PW_TYPE_INTEGER:
273                 case PW_TYPE_DATE:
274                         if (size != vp->length) {
275                                 RDEBUG2("Invalid length attribute %d",
276                                        attr);
277                                 pairfree(&first);
278                                 pairfree(&vp);
279                                 return NULL;
280                         }
281                         memcpy(&vp->vp_integer, data, vp->length);
282
283                         /*
284                          *      Stored in host byte order: change it.
285                          */
286                         vp->vp_integer = ntohl(vp->vp_integer);
287                         break;
288
289                 case PW_TYPE_INTEGER64:
290                         if (size != vp->length) {
291                                 RDEBUG2("Invalid length attribute %d",
292                                        attr);
293                                 pairfree(&first);
294                                 pairfree(&vp);
295                                 return NULL;
296                         }
297                         memcpy(&vp->vp_integer64, data, vp->length);
298
299                         /*
300                          *      Stored in host byte order: change it.
301                          */
302                         vp->vp_integer64 = ntohll(vp->vp_integer64);
303                         break;
304
305                 case PW_TYPE_IPADDR:
306                         if (size != vp->length) {
307                                 RDEBUG2("Invalid length attribute %d",
308                                        attr);
309                                 pairfree(&first);
310                                 pairfree(&vp);
311                                 return NULL;
312                         }
313                   memcpy(&vp->vp_ipaddr, data, vp->length);
314
315                   /*
316                    *    Stored in network byte order: don't change it.
317                    */
318                   break;
319
320                   /*
321                    *    String, octet, etc.  Copy the data from the
322                    *    value field over verbatim.
323                    *
324                    *    FIXME: Ipv6 attributes ?
325                    *
326                    */
327                 case PW_TYPE_OCTETS:
328                         if (attr == PW_EAP_MESSAGE) {
329                                 const uint8_t *eap_message = data;
330
331                                 /*
332                                  *      vp exists the first time around.
333                                  */
334                                 while (1) {
335                                         vp->length = size;
336                                         if (vp->length > 253) vp->length = 253;
337                                         memcpy(vp->vp_octets, eap_message,
338                                                vp->length);
339
340                                         size -= vp->length;
341                                         eap_message += vp->length;
342
343                                         *last = vp;
344                                         last = &(vp->next);
345
346                                         if (size == 0) break;
347
348                                         vp = paircreate(attr, vendor, PW_TYPE_OCTETS);
349                                         if (!vp) {
350                                                 RDEBUG2("Failure in creating VP");
351                                                 pairfree(&first);
352                                                 return NULL;
353                                         }
354                                 }
355
356                                 goto next_attr;
357                         } /* else it's another kind of attribute */
358                         /* FALL-THROUGH */
359
360                 default:
361                         vp->length = size;
362                         memcpy(vp->vp_strvalue, data, vp->length);
363                         break;
364                 }
365
366                 /*
367                  *      User-Password is NUL padded to a multiple
368                  *      of 16 bytes.  Let's chop it to something
369                  *      more reasonable.
370                  *
371                  *      NOTE: This means that the User-Password
372                  *      attribute CANNOT EVER have embedded zeros in it!
373                  */
374                 switch (vp->attribute) {
375                 case PW_USER_PASSWORD:
376                         /*
377                          *      If the password is exactly 16 octets,
378                          *      it won't be zero-terminated.
379                          */
380                         vp->vp_strvalue[vp->length] = '\0';
381                         vp->length = strlen(vp->vp_strvalue);
382                         break;
383
384                         /*
385                          *      Ensure that the client is using the
386                          *      correct challenge.  This weirdness is
387                          *      to protect against against replay
388                          *      attacks, where anyone observing the
389                          *      CHAP exchange could pose as that user,
390                          *      by simply choosing to use the same
391                          *      challenge.
392                          *
393                          *      By using a challenge based on
394                          *      information from the current session,
395                          *      we can guarantee that the client is
396                          *      not *choosing* a challenge.
397                          *
398                          *      We're a little forgiving in that we
399                          *      have loose checks on the length, and
400                          *      we do NOT check the Id (first octet of
401                          *      the response to the challenge)
402                          *
403                          *      But if the client gets the challenge correct,
404                          *      we're not too worried about the Id.
405                          */
406                 case PW_CHAP_CHALLENGE:
407                 case PW_MSCHAP_CHALLENGE:
408                         if ((vp->length < 8) ||
409                             (vp->length > 16)) {
410                                 RDEBUG("Tunneled challenge has invalid length");
411                                 pairfree(&first);
412                                 pairfree(&vp);
413                                 return NULL;
414
415                         } else {
416                                 uint8_t challenge[16];
417
418                                 eapttls_gen_challenge(ssl, challenge,
419                                                       sizeof(challenge));
420
421                                 if (memcmp(challenge, vp->vp_octets,
422                                            vp->length) != 0) {
423                                         RDEBUG("Tunneled challenge is incorrect");
424                                         pairfree(&first);
425                                         pairfree(&vp);
426                                         return NULL;
427                                 }
428                         }
429                         break;
430
431                 default:
432                         break;
433                 } /* switch over checking/re-writing of attributes. */
434
435                 /*
436                  *      Update the list.
437                  */
438                 *last = vp;
439                 last = &(vp->next);
440
441         next_attr:
442                 /*
443                  *      Catch non-aligned attributes.
444                  */
445                 if (data_left == length) break;
446
447                 /*
448                  *      The length does NOT include the padding, so
449                  *      we've got to account for it here by rounding up
450                  *      to the nearest 4-byte boundary.
451                  */
452                 length += 0x03;
453                 length &= ~0x03;
454
455                 rad_assert(data_left >= length);
456                 data_left -= length;
457                 data += length - offset; /* already updated */
458         }
459
460         /*
461          *      We got this far.  It looks OK.
462          */
463         return first;
464 }
465
466 /*
467  *      Convert VALUE_PAIR's to diameter attributes, and write them
468  *      to an SSL session.
469  *
470  *      The ONLY VALUE_PAIR's which may be passed to this function
471  *      are ones which can go inside of a RADIUS (i.e. diameter)
472  *      packet.  So no server-configuration attributes, or the like.
473  */
474 static int vp2diameter(REQUEST *request, tls_session_t *tls_session, VALUE_PAIR *first)
475 {
476         /*
477          *      RADIUS packets are no more than 4k in size, so if
478          *      we've got more than 4k of data to write, it's very
479          *      bad.
480          */
481         uint8_t         buffer[4096];
482         uint8_t         *p;
483         uint32_t        attr;
484         uint32_t        length;
485         uint32_t        vendor;
486         size_t          total;
487         uint64_t        attr64;
488         VALUE_PAIR      *vp;
489
490         p = buffer;
491         total = 0;
492
493         for (vp = first; vp != NULL; vp = vp->next) {
494                 /*
495                  *      Too much data: die.
496                  */
497                 if ((total + vp->length + 12) >= sizeof(buffer)) {
498                         RDEBUG2("output buffer is full!");
499                         return 0;
500                 }
501
502                 /*
503                  *      Hmm... we don't group multiple EAP-Messages
504                  *      together.  Maybe we should...
505                  */
506
507                 /*
508                  *      Length is no more than 253, due to RADIUS
509                  *      issues.
510                  */
511                 length = vp->length;
512                 vendor = vp->vendor;
513                 if (vendor != 0) {
514                         attr = vp->attribute & 0xffff;
515                         length |= (1 << 31);
516                 } else {
517                         attr = vp->attribute;
518                 }
519
520                 /*
521                  *      Hmm... set the M bit for all attributes?
522                  */
523                 length |= (1 << 30);
524
525                 attr = ntohl(attr);
526
527                 memcpy(p, &attr, sizeof(attr));
528                 p += 4;
529                 total += 4;
530
531                 length += 8;    /* includes 8 bytes of attr & length */
532
533                 if (vendor != 0) {
534                         length += 4; /* include 4 bytes of vendor */
535
536                         length = ntohl(length);
537                         memcpy(p, &length, sizeof(length));
538                         p += 4;
539                         total += 4;
540
541                         vendor = ntohl(vendor);
542                         memcpy(p, &vendor, sizeof(vendor));
543                         p += 4;
544                         total += 4;
545                 } else {
546                         length = ntohl(length);
547                         memcpy(p, &length, sizeof(length));
548                         p += 4;
549                         total += 4;
550                 }
551
552                 switch (vp->type) {
553                 case PW_TYPE_INTEGER:
554                 case PW_TYPE_DATE:
555                         attr = htonl(vp->vp_integer); /* stored in host order */
556                         memcpy(p, &attr, sizeof(attr));
557                         length = 4;
558                         break;
559
560                 case PW_TYPE_INTEGER64:
561                         attr64 = htonll(vp->vp_integer64); /* stored in host order */
562                         memcpy(p, &attr64, sizeof(attr64));
563                         length = 8;
564                         break;
565
566                 case PW_TYPE_IPADDR:
567                         memcpy(p, &vp->vp_ipaddr, 4); /* network order */
568                         length = 4;
569                         break;
570
571                 case PW_TYPE_STRING:
572                 case PW_TYPE_OCTETS:
573                 default:
574                         memcpy(p, vp->vp_strvalue, vp->length);
575                         length = vp->length;
576                         break;
577                 }
578
579                 /*
580                  *      Skip to the end of the data.
581                  */
582                 p += length;
583                 total += length;
584
585                 /*
586                  *      Align the data to a multiple of 4 bytes.
587                  */
588                 if ((total & 0x03) != 0) {
589                         size_t i;
590
591                         length = 4 - (total & 0x03);
592                         for (i = 0; i < length; i++) {
593                                 *p = '\0';
594                                 p++;
595                                 total++;
596                         }
597                 }
598         } /* loop over the VP's to write. */
599
600         /*
601          *      Write the data in the buffer to the SSL session.
602          */
603         if (total > 0) {
604 #ifndef NDEBUG
605                 size_t i;
606
607                 if ((debug_flag > 2) && fr_log_fp) {
608                         for (i = 0; i < total; i++) {
609                                 if ((i & 0x0f) == 0) fprintf(fr_log_fp, "  TTLS tunnel data out %04x: ", (int) i);
610
611                                 fprintf(fr_log_fp, "%02x ", buffer[i]);
612
613                                 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
614                         }
615                         if ((total & 0x0f) != 0) fprintf(fr_log_fp, "\n");
616                 }
617 #endif
618
619                 (tls_session->record_plus)(&tls_session->clean_in, buffer, total);
620
621                 /*
622                  *      FIXME: Check the return code.
623                  */
624                 tls_handshake_send(request, tls_session);
625         }
626
627         /*
628          *      Everything's OK.
629          */
630         return 1;
631 }
632
633 /*
634  *      Use a reply packet to determine what to do.
635  */
636 static int process_reply(EAP_HANDLER *handler, tls_session_t *tls_session,
637                          REQUEST *request, RADIUS_PACKET *reply)
638 {
639         int rcode = RLM_MODULE_REJECT;
640         VALUE_PAIR *vp;
641         ttls_tunnel_t *t = tls_session->opaque;
642
643         handler = handler;      /* -Wunused */
644         rad_assert(request != NULL);
645         rad_assert(handler->request == request);
646
647         /*
648          *      If the response packet was Access-Accept, then
649          *      we're OK.  If not, die horribly.
650          *
651          *      FIXME: Take MS-CHAP2-Success attribute, and
652          *      tunnel it back to the client, to authenticate
653          *      ourselves to the client.
654          *
655          *      FIXME: If we have an Access-Challenge, then
656          *      the Reply-Message is tunneled back to the client.
657          *
658          *      FIXME: If we have an EAP-Message, then that message
659          *      must be tunneled back to the client.
660          *
661          *      FIXME: If we have an Access-Challenge with a State
662          *      attribute, then do we tunnel that to the client, or
663          *      keep track of it ourselves?
664          *
665          *      FIXME: EAP-Messages can only start with 'identity',
666          *      NOT 'eap start', so we should check for that....
667          */
668         switch (reply->code) {
669         case PW_AUTHENTICATION_ACK:
670                 RDEBUG("Got tunneled Access-Accept");
671
672                 rcode = RLM_MODULE_OK;
673
674                 /*
675                  *      MS-CHAP2-Success means that we do NOT return
676                  *      an Access-Accept, but instead tunnel that
677                  *      attribute to the client, and keep going with
678                  *      the TTLS session.  Once the client accepts
679                  *      our identity, it will respond with an empty
680                  *      packet, and we will send EAP-Success.
681                  */
682                 vp = NULL;
683                 pairmove2(&vp, &reply->vps, PW_MSCHAP2_SUCCESS, VENDORPEC_MICROSOFT);
684                 if (vp) {
685                         RDEBUG("Got MS-CHAP2-Success, tunneling it to the client in a challenge.");
686                         rcode = RLM_MODULE_HANDLED;
687                         t->authenticated = TRUE;
688
689                         /*
690                          *      Delete MPPE keys & encryption policy.  We don't
691                          *      want these here.
692                          */
693                         pairdelete(&reply->vps, 7, VENDORPEC_MICROSOFT);
694                         pairdelete(&reply->vps, 8, VENDORPEC_MICROSOFT);
695                         pairdelete(&reply->vps, 16, VENDORPEC_MICROSOFT);
696                         pairdelete(&reply->vps, 17, VENDORPEC_MICROSOFT);
697
698                         /*
699                          *      Use the tunneled reply, but not now.
700                          */
701                         if (t->use_tunneled_reply) {
702                                 t->accept_vps = reply->vps;
703                                 reply->vps = NULL;
704                         }
705
706                 } else { /* no MS-CHAP2-Success */
707                         /*
708                          *      Can only have EAP-Message if there's
709                          *      no MS-CHAP2-Success.  (FIXME: EAP-MSCHAP?)
710                          *
711                          *      We also do NOT tunnel the EAP-Success
712                          *      attribute back to the client, as the client
713                          *      can figure it out, from the non-tunneled
714                          *      EAP-Success packet.
715                          */
716                         pairmove2(&vp, &reply->vps, PW_EAP_MESSAGE, 0);
717                         pairfree(&vp);
718                 }
719
720                 /*
721                  *      Handle the ACK, by tunneling any necessary reply
722                  *      VP's back to the client.
723                  */
724                 if (vp) {
725                         vp2diameter(request, tls_session, vp);
726                         pairfree(&vp);
727                 }
728
729                 /*
730                  *      If we've been told to use the attributes from
731                  *      the reply, then do so.
732                  *
733                  *      WARNING: This may leak information about the
734                  *      tunneled user!
735                  */
736                 if (t->use_tunneled_reply) {
737                         pairdelete(&reply->vps, PW_PROXY_STATE, 0);
738                         pairadd(&request->reply->vps, reply->vps);
739                         reply->vps = NULL;
740                 }
741                 break;
742
743
744         case PW_AUTHENTICATION_REJECT:
745                 RDEBUG("Got tunneled Access-Reject");
746                 rcode = RLM_MODULE_REJECT;
747                 break;
748
749                 /*
750                  *      Handle Access-Challenge, but only if we
751                  *      send tunneled reply data.  This is because
752                  *      an Access-Challenge means that we MUST tunnel
753                  *      a Reply-Message to the client.
754                  */
755         case PW_ACCESS_CHALLENGE:
756                 RDEBUG("Got tunneled Access-Challenge");
757
758                 /*
759                  *      Keep the State attribute, if necessary.
760                  *
761                  *      Get rid of the old State, too.
762                  */
763                 pairfree(&t->state);
764                 pairmove2(&t->state, &reply->vps, PW_STATE, 0);
765
766                 /*
767                  *      We should really be a bit smarter about this,
768                  *      and move over only those attributes which
769                  *      are relevant to the authentication request,
770                  *      but that's a lot more work, and this "dumb"
771                  *      method works in 99.9% of the situations.
772                  */
773                 vp = NULL;
774                 pairmove2(&vp, &reply->vps, PW_EAP_MESSAGE, 0);
775
776                 /*
777                  *      There MUST be a Reply-Message in the challenge,
778                  *      which we tunnel back to the client.
779                  *
780                  *      If there isn't one in the reply VP's, then
781                  *      we MUST create one, with an empty string as
782                  *      it's value.
783                  */
784                 pairmove2(&vp, &reply->vps, PW_REPLY_MESSAGE, 0);
785
786                 /*
787                  *      Handle the ACK, by tunneling any necessary reply
788                  *      VP's back to the client.
789                  */
790                 if (vp) {
791                         vp2diameter(request, tls_session, vp);
792                         pairfree(&vp);
793                 }
794                 rcode = RLM_MODULE_HANDLED;
795                 break;
796
797         default:
798                 RDEBUG("Unknown RADIUS packet type %d: rejecting tunneled user", reply->code);
799                 rcode = RLM_MODULE_INVALID;
800                 break;
801         }
802
803         return rcode;
804 }
805
806
807 #ifdef WITH_PROXY
808 /*
809  *      Do post-proxy processing,
810  */
811 static int eapttls_postproxy(EAP_HANDLER *handler, void *data)
812 {
813         int rcode;
814         tls_session_t *tls_session = (tls_session_t *) data;
815         REQUEST *fake, *request = handler->request;
816
817         rad_assert(request != NULL);
818         RDEBUG("Passing reply from proxy back into the tunnel.");
819
820         /*
821          *      If there was a fake request associated with the proxied
822          *      request, do more processing of it.
823          */
824         fake = (REQUEST *) request_data_get(handler->request,
825                                             handler->request->proxy,
826                                             REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK);
827
828         /*
829          *      Do the callback, if it exists, and if it was a success.
830          */
831         if (fake && (handler->request->proxy_reply->code == PW_AUTHENTICATION_ACK)) {
832                 /*
833                  *      Terrible hacks.
834                  */
835                 rad_assert(fake->packet == NULL);
836                 fake->packet = request->proxy;
837                 fake->packet->src_ipaddr = request->packet->src_ipaddr;
838                 request->proxy = NULL;
839
840                 rad_assert(fake->reply == NULL);
841                 fake->reply = request->proxy_reply;
842                 request->proxy_reply = NULL;
843
844                 if ((debug_flag > 0) && fr_log_fp) {
845                         fprintf(fr_log_fp, "server %s {\n",
846                                 (fake->server == NULL) ? "" : fake->server);
847                 }
848
849                 /*
850                  *      Perform a post-auth stage for the tunneled
851                  *      session.
852                  */
853                 fake->options &= ~RAD_REQUEST_OPTION_PROXY_EAP;
854                 rcode = rad_postauth(fake);
855                 RDEBUG2("post-auth returns %d", rcode);
856
857                 if ((debug_flag > 0) && fr_log_fp) {
858                         fprintf(fr_log_fp, "} # server %s\n",
859                                 (fake->server == NULL) ? "" : fake->server);
860                         
861                         RDEBUG("Final reply from tunneled session code %d",
862                                fake->reply->code);
863                         debug_pair_list(fake->reply->vps);
864                 }
865
866                 /*
867                  *      Terrible hacks.
868                  */
869                 request->proxy = fake->packet;
870                 fake->packet = NULL;
871                 request->proxy_reply = fake->reply;
872                 fake->reply = NULL;
873
874                 /*
875                  *      And we're done with this request.
876                  */
877
878                 switch (rcode) {
879                 case RLM_MODULE_FAIL:
880                         request_free(&fake);
881                         eaptls_fail(handler, 0);
882                         return 0;
883                         break;
884
885                 default:  /* Don't Do Anything */
886                         RDEBUG2("Got reply %d",
887                                request->proxy_reply->code);
888                         break;
889                 }
890         }
891         request_free(&fake);    /* robust if fake == NULL */
892
893         /*
894          *      Process the reply from the home server.
895          */
896         rcode = process_reply(handler, tls_session, handler->request,
897                               handler->request->proxy_reply);
898
899         /*
900          *      The proxy code uses the reply from the home server as
901          *      the basis for the reply to the NAS.  We don't want that,
902          *      so we toss it, after we've had our way with it.
903          */
904         pairfree(&handler->request->proxy_reply->vps);
905
906         switch (rcode) {
907         case RLM_MODULE_REJECT:
908                 RDEBUG("Reply was rejected");
909                 break;
910
911         case RLM_MODULE_HANDLED:
912                 RDEBUG("Reply was handled");
913                 eaptls_request(handler->eap_ds, tls_session);
914                 return 1;
915
916         case RLM_MODULE_OK:
917                 RDEBUG("Reply was OK");
918
919                 /*
920                  *      Success: Automatically return MPPE keys.
921                  */
922                 return eaptls_success(handler, 0);
923
924         default:
925                 RDEBUG("Reply was unknown.");
926                 break;
927         }
928
929         eaptls_fail(handler, 0);
930         return 0;
931 }
932
933
934 /*
935  *      Free a request.
936  */
937 static void my_request_free(void *data)
938 {
939         REQUEST *request = (REQUEST *)data;
940
941         request_free(&request);
942 }
943 #endif  /* WITH_PROXY */
944
945 /*
946  *      Process the "diameter" contents of the tunneled data.
947  */
948 int eapttls_process(EAP_HANDLER *handler, tls_session_t *tls_session)
949 {
950         int rcode = PW_AUTHENTICATION_REJECT;
951         REQUEST *fake;
952         VALUE_PAIR *vp;
953         ttls_tunnel_t *t;
954         const uint8_t *data;
955         size_t data_len;
956         REQUEST *request = handler->request;
957         eap_chbind_packet_t *chbind_packet;
958         size_t chbind_len;
959
960         rad_assert(request != NULL);
961
962         /*
963          *      Just look at the buffer directly, without doing
964          *      record_minus.
965          */
966         data_len = tls_session->clean_out.used;
967         tls_session->clean_out.used = 0;
968         data = tls_session->clean_out.data;
969
970         t = (ttls_tunnel_t *) tls_session->opaque;
971
972         /*
973          *      If there's no data, maybe this is an ACK to an
974          *      MS-CHAP2-Success.
975          */
976         if (data_len == 0) {
977                 if (t->authenticated) {
978                         RDEBUG("Got ACK, and the user was already authenticated.");
979                         return PW_AUTHENTICATION_ACK;
980                 } /* else no session, no data, die. */
981
982                 /*
983                  *      FIXME: Call SSL_get_error() to see what went
984                  *      wrong.
985                  */
986                 RDEBUG2("SSL_read Error");
987                 return PW_AUTHENTICATION_REJECT;
988         }
989
990 #ifndef NDEBUG
991         if ((debug_flag > 2) && fr_log_fp) {
992                 size_t i;
993
994                 for (i = 0; i < data_len; i++) {
995                         if ((i & 0x0f) == 0) fprintf(fr_log_fp, "  TTLS tunnel data in %04x: ", (int) i);
996
997                         fprintf(fr_log_fp, "%02x ", data[i]);
998
999                         if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1000                 }
1001                 if ((data_len & 0x0f) != 0) fprintf(fr_log_fp, "\n");
1002         }
1003 #endif
1004
1005         if (!diameter_verify(request, data, data_len)) {
1006                 return PW_AUTHENTICATION_REJECT;
1007         }
1008
1009         /*
1010          *      Allocate a fake REQUEST structe.
1011          */
1012         fake = request_alloc_fake(request);
1013
1014         rad_assert(fake->packet->vps == NULL);
1015
1016         /*
1017          *      Add the tunneled attributes to the fake request.
1018          */
1019         fake->packet->vps = diameter2vp(request, tls_session->ssl, data, data_len);
1020         if (!fake->packet->vps) {
1021                 request_free(&fake);
1022                 return PW_AUTHENTICATION_REJECT;
1023         }
1024
1025         /*
1026          *      Tell the request that it's a fake one.
1027          */
1028         vp = pairmake("Freeradius-Proxied-To", "127.0.0.1", T_OP_EQ);
1029         if (vp) {
1030                 pairadd(&fake->packet->vps, vp);
1031         }
1032
1033         if ((debug_flag > 0) && fr_log_fp) {
1034                 RDEBUG("Got tunneled request");
1035
1036                 debug_pair_list(fake->packet->vps);
1037         }
1038
1039         /*
1040          *      Update other items in the REQUEST data structure.
1041          */
1042         fake->username = pairfind(fake->packet->vps, PW_USER_NAME, 0);
1043         fake->password = pairfind(fake->packet->vps, PW_USER_PASSWORD, 0);
1044
1045         /*
1046          *      No User-Name, try to create one from stored data.
1047          */
1048         if (!fake->username) {
1049                 /*
1050                  *      No User-Name in the stored data, look for
1051                  *      an EAP-Identity, and pull it out of there.
1052                  */
1053                 if (!t->username) {
1054                         vp = pairfind(fake->packet->vps, PW_EAP_MESSAGE, 0);
1055                         if (vp &&
1056                             (vp->length >= EAP_HEADER_LEN + 2) &&
1057                             (vp->vp_strvalue[0] == PW_EAP_RESPONSE) &&
1058                             (vp->vp_strvalue[EAP_HEADER_LEN] == PW_EAP_IDENTITY) &&
1059                             (vp->vp_strvalue[EAP_HEADER_LEN + 1] != 0)) {
1060                                 /*
1061                                  *      Create & remember a User-Name
1062                                  */
1063                                 t->username = pairmake("User-Name", "", T_OP_EQ);
1064                                 rad_assert(t->username != NULL);
1065
1066                                 memcpy(t->username->vp_strvalue, vp->vp_strvalue + 5,
1067                                        vp->length - 5);
1068                                 t->username->length = vp->length - 5;
1069                                 t->username->vp_strvalue[t->username->length] = 0;
1070
1071                                 RDEBUG("Got tunneled identity of %s",
1072                                        t->username->vp_strvalue);
1073
1074                                 /*
1075                                  *      If there's a default EAP type,
1076                                  *      set it here.
1077                                  */
1078                                 if (t->default_eap_type != 0) {
1079                                         RDEBUG("Setting default EAP type for tunneled EAP session.");
1080                                         vp = paircreate(PW_EAP_TYPE, 0,
1081                                                         PW_TYPE_INTEGER);
1082                                         rad_assert(vp != NULL);
1083                                         vp->vp_integer = t->default_eap_type;
1084                                         pairadd(&fake->config_items, vp);
1085                                 }
1086
1087                         } else {
1088                                 /*
1089                                  *      Don't reject the request outright,
1090                                  *      as it's permitted to do EAP without
1091                                  *      user-name.
1092                                  */
1093                                 RDEBUG2("WARNING! No EAP-Identity found to start EAP conversation.");
1094                         }
1095                 } /* else there WAS a t->username */
1096
1097                 if (t->username) {
1098                         vp = paircopy(t->username);
1099                         pairadd(&fake->packet->vps, vp);
1100                         fake->username = pairfind(fake->packet->vps, PW_USER_NAME, 0);
1101                 }
1102         } /* else the request ALREADY had a User-Name */
1103
1104         /*
1105          *      Add the State attribute, too, if it exists.
1106          */
1107         if (t->state) {
1108                 vp = paircopy(t->state);
1109                 if (vp) pairadd(&fake->packet->vps, vp);
1110         }
1111
1112         /*
1113          *      If this is set, we copy SOME of the request attributes
1114          *      from outside of the tunnel to inside of the tunnel.
1115          *
1116          *      We copy ONLY those attributes which do NOT already
1117          *      exist in the tunneled request.
1118          */
1119         if (t->copy_request_to_tunnel) {
1120                 VALUE_PAIR *copy;
1121
1122                 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
1123                         /*
1124                          *      The attribute is a server-side thingy,
1125                          *      don't copy it.
1126                          */
1127                         if ((vp->attribute > 255) &&
1128                             (vp->vendor == 0)) {
1129                                 continue;
1130                         }
1131
1132                         /*
1133                          *      The outside attribute is already in the
1134                          *      tunnel, don't copy it.
1135                          *
1136                          *      This works for BOTH attributes which
1137                          *      are originally in the tunneled request,
1138                          *      AND attributes which are copied there
1139                          *      from below.
1140                          */
1141                         if (pairfind(fake->packet->vps, vp->attribute, vp->vendor)) {
1142                                 continue;
1143                         }
1144
1145                         /*
1146                          *      Some attributes are handled specially.
1147                          */
1148                         switch (vp->attribute) {
1149                                 /*
1150                                  *      NEVER copy Message-Authenticator,
1151                                  *      EAP-Message, or State.  They're
1152                                  *      only for outside of the tunnel.
1153                                  */
1154                         case PW_USER_NAME:
1155                         case PW_USER_PASSWORD:
1156                         case PW_CHAP_PASSWORD:
1157                         case PW_CHAP_CHALLENGE:
1158                         case PW_PROXY_STATE:
1159                         case PW_MESSAGE_AUTHENTICATOR:
1160                         case PW_EAP_MESSAGE:
1161                         case PW_STATE:
1162                                 continue;
1163                                 break;
1164
1165                                 /*
1166                                  *      By default, copy it over.
1167                                  */
1168                         default:
1169                                 break;
1170                         }
1171
1172                         /*
1173                          *      Don't copy from the head, we've already
1174                          *      checked it.
1175                          */
1176                         copy = paircopy2(vp, vp->attribute, vp->vendor);
1177                         pairadd(&fake->packet->vps, copy);
1178                 }
1179         }
1180
1181         if ((vp = pairfind(request->config_items, PW_VIRTUAL_SERVER, 0)) != NULL) {
1182                 fake->server = vp->vp_strvalue;
1183
1184         } else if (t->virtual_server) {
1185                 fake->server = t->virtual_server;
1186
1187         } /* else fake->server == request->server */
1188
1189
1190         if ((debug_flag > 0) && fr_log_fp) {
1191                 RDEBUG("Sending tunneled request");
1192
1193                 debug_pair_list(fake->packet->vps);
1194
1195                 fprintf(fr_log_fp, "server %s {\n",
1196                         (fake->server == NULL) ? "" : fake->server);
1197         }
1198
1199         /*
1200          *      Process channel binding here.
1201          */
1202         chbind_len = eap_chbind_vp2packet(fake->packet->vps, &chbind_packet);
1203         if (chbind_len > 0) {
1204                 /*CHBIND_REQ *req = chbind_allocate();
1205                 req->chbind_req = chbind_packet;
1206                 req->chbind_req_len = chbind_len;
1207                 if (fake->username) {
1208                         req->username = fake->username->vp_octets;
1209                         req->username_len = fake->username->length;
1210                 } else {
1211                         req->username = NULL;
1212                         req->username_len = 0;
1213                 }
1214                 chbind_process(request, req);
1215                 */
1216
1217                 /* free the chbind packet; we're done with it */
1218                 free(chbind_packet);
1219
1220                 /* encapsulate response here */
1221                 /*pairadd(replyvps, eap_chbind_packet2vp(req->chbind_resp,
1222                                                        req->chbind_resp_len));
1223                 */
1224
1225                 /* clean up chbind req */
1226                 /*chbind_free(req);*/
1227         }
1228
1229         /*
1230          *      Call authentication recursively, which will
1231          *      do PAP, CHAP, MS-CHAP, etc.
1232          */
1233         rad_authenticate(fake);
1234
1235         /*
1236          *      Note that we don't do *anything* with the reply
1237          *      attributes.
1238          */
1239         if ((debug_flag > 0) && fr_log_fp) {
1240                 fprintf(fr_log_fp, "} # server %s\n",
1241                         (fake->server == NULL) ? "" : fake->server);
1242
1243                 RDEBUG("Got tunneled reply code %d", fake->reply->code);
1244                 
1245                 debug_pair_list(fake->reply->vps);
1246         }
1247
1248         /*
1249          *      Decide what to do with the reply.
1250          */
1251         switch (fake->reply->code) {
1252         case 0:                 /* No reply code, must be proxied... */
1253 #ifdef WITH_PROXY
1254           vp = pairfind(fake->config_items, PW_PROXY_TO_REALM, 0);
1255                 if (vp) {
1256                         eap_tunnel_data_t *tunnel;
1257                         RDEBUG("Tunneled authentication will be proxied to %s", vp->vp_strvalue);
1258
1259                         /*
1260                          *      Tell the original request that it's going
1261                          *      to be proxied.
1262                          */
1263                         pairmove2(&(request->config_items),
1264                                   &(fake->config_items),
1265                                   PW_PROXY_TO_REALM, 0);
1266
1267                         /*
1268                          *      Seed the proxy packet with the
1269                          *      tunneled request.
1270                          */
1271                         rad_assert(request->proxy == NULL);
1272                         request->proxy = fake->packet;
1273                         memset(&request->proxy->src_ipaddr, 0,
1274                                sizeof(request->proxy->src_ipaddr));
1275                         memset(&request->proxy->src_ipaddr, 0,
1276                                sizeof(request->proxy->src_ipaddr));
1277                         request->proxy->src_port = 0;
1278                         request->proxy->dst_port = 0;
1279                         fake->packet = NULL;
1280                         rad_free(&fake->reply);
1281                         fake->reply = NULL;
1282
1283                         /*
1284                          *      Set up the callbacks for the tunnel
1285                          */
1286                         tunnel = rad_malloc(sizeof(*tunnel));
1287                         memset(tunnel, 0, sizeof(*tunnel));
1288
1289                         tunnel->tls_session = tls_session;
1290                         tunnel->callback = eapttls_postproxy;
1291
1292                         /*
1293                          *      Associate the callback with the request.
1294                          */
1295                         rcode = request_data_add(request,
1296                                                  request->proxy,
1297                                                  REQUEST_DATA_EAP_TUNNEL_CALLBACK,
1298                                                  tunnel, free);
1299                         rad_assert(rcode == 0);
1300
1301                         /*
1302                          *      rlm_eap.c has taken care of associating
1303                          *      the handler with the fake request.
1304                          *
1305                          *      So we associate the fake request with
1306                          *      this request.
1307                          */
1308                         rcode = request_data_add(request,
1309                                                  request->proxy,
1310                                                  REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK,
1311                                                  fake, my_request_free);
1312                         rad_assert(rcode == 0);
1313                         fake = NULL;
1314
1315                         /*
1316                          *      Didn't authenticate the packet, but
1317                          *      we're proxying it.
1318                          */
1319                         rcode = PW_STATUS_CLIENT;
1320
1321                 } else
1322 #endif  /* WITH_PROXY */
1323                   {
1324                         RDEBUG("No tunneled reply was found for request %d , and the request was not proxied: rejecting the user.",
1325                                request->number);
1326                         rcode = PW_AUTHENTICATION_REJECT;
1327                 }
1328                 break;
1329
1330         default:
1331                 /*
1332                  *      Returns RLM_MODULE_FOO, and we want to return
1333                  *      PW_FOO
1334                  */
1335                 rcode = process_reply(handler, tls_session, request,
1336                                       fake->reply);
1337                 switch (rcode) {
1338                 case RLM_MODULE_REJECT:
1339                         rcode = PW_AUTHENTICATION_REJECT;
1340                         break;
1341
1342                 case RLM_MODULE_HANDLED:
1343                         rcode = PW_ACCESS_CHALLENGE;
1344                         break;
1345
1346                 case RLM_MODULE_OK:
1347                         rcode = PW_AUTHENTICATION_ACK;
1348                         break;
1349
1350                 default:
1351                         rcode = PW_AUTHENTICATION_REJECT;
1352                         break;
1353                 }
1354                 break;
1355         }
1356
1357         request_free(&fake);
1358
1359         return rcode;
1360 }