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