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