update usage of pairmoveto
[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                 /* move channel binding responses; we need to send them */
742                 pairmove2(&vp, &reply->vps, PW_UKERNA_CHBIND, VENDORPEC_UKERNA, TAG_ANY);
743
744                 /*
745                  *      Handle the ACK, by tunneling any necessary reply
746                  *      VP's back to the client.
747                  */
748                 if (vp) {
749                         RDEBUG("sending tunneled reply attributes");
750                         debug_pair_list(vp);
751                         RDEBUG("end tunneled reply attributes");
752                         vp2diameter(request, tls_session, vp);
753                         pairfree(&vp);
754                 }
755
756                 /*
757                  *      If we've been told to use the attributes from
758                  *      the reply, then do so.
759                  *
760                  *      WARNING: This may leak information about the
761                  *      tunneled user!
762                  */
763                 if (t->use_tunneled_reply) {
764                         pairdelete(&reply->vps, PW_PROXY_STATE, 0, TAG_ANY);
765                         pairadd(&request->reply->vps, reply->vps);
766                         reply->vps = NULL;
767                 }
768                 break;
769
770
771         case PW_AUTHENTICATION_REJECT:
772                 RDEBUG("Got tunneled Access-Reject");
773                 rcode = RLM_MODULE_REJECT;
774                 break;
775
776                 /*
777                  *      Handle Access-Challenge, but only if we
778                  *      send tunneled reply data.  This is because
779                  *      an Access-Challenge means that we MUST tunnel
780                  *      a Reply-Message to the client.
781                  */
782         case PW_ACCESS_CHALLENGE:
783                 RDEBUG("Got tunneled Access-Challenge");
784
785                 /*
786                  *      Keep the State attribute, if necessary.
787                  *
788                  *      Get rid of the old State, too.
789                  */
790                 pairfree(&t->state);
791                 pairmove2(&t->state, &reply->vps, PW_STATE, 0, TAG_ANY);
792
793                 /*
794                  *      We should really be a bit smarter about this,
795                  *      and move over only those attributes which
796                  *      are relevant to the authentication request,
797                  *      but that's a lot more work, and this "dumb"
798                  *      method works in 99.9% of the situations.
799                  */
800                 vp = NULL;
801                 pairmove2(&vp, &reply->vps, PW_EAP_MESSAGE, 0, TAG_ANY);
802
803                 /*
804                  *      There MUST be a Reply-Message in the challenge,
805                  *      which we tunnel back to the client.
806                  *
807                  *      If there isn't one in the reply VP's, then
808                  *      we MUST create one, with an empty string as
809                  *      it's value.
810                  */
811                 pairmove2(&vp, &reply->vps, PW_REPLY_MESSAGE, 0, TAG_ANY);
812
813                 /* also move chbind messages, if any */
814                 pairmove2(&vp, &reply->vps, PW_UKERNA_CHBIND, VENDORPEC_UKERNA,
815                           TAG_ANY);
816
817                 /*
818                  *      Handle the ACK, by tunneling any necessary reply
819                  *      VP's back to the client.
820                  */
821                 if (vp) {
822                         vp2diameter(request, tls_session, vp);
823                         pairfree(&vp);
824                 }
825                 rcode = RLM_MODULE_HANDLED;
826                 break;
827
828         default:
829                 RDEBUG("Unknown RADIUS packet type %d: rejecting tunneled user", reply->code);
830                 rcode = RLM_MODULE_INVALID;
831                 break;
832         }
833
834         return rcode;
835 }
836
837
838 #ifdef WITH_PROXY
839 /*
840  *      Do post-proxy processing,
841  */
842 static int eapttls_postproxy(EAP_HANDLER *handler, void *data)
843 {
844         int rcode;
845         tls_session_t *tls_session = (tls_session_t *) data;
846         REQUEST *fake, *request = handler->request;
847
848         rad_assert(request != NULL);
849         RDEBUG("Passing reply from proxy back into the tunnel.");
850
851         /*
852          *      If there was a fake request associated with the proxied
853          *      request, do more processing of it.
854          */
855         fake = (REQUEST *) request_data_get(handler->request,
856                                             handler->request->proxy,
857                                             REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK);
858
859         /*
860          *      Do the callback, if it exists, and if it was a success.
861          */
862         if (fake &&
863             handler->request->proxy_reply &&
864             (handler->request->proxy_reply->code == PW_AUTHENTICATION_ACK)) {
865                 /*
866                  *      Terrible hacks.
867                  */
868                 rad_assert(fake->packet == NULL);
869                 fake->packet = request->proxy;
870                 fake->packet->src_ipaddr = request->packet->src_ipaddr;
871                 request->proxy = NULL;
872
873                 rad_assert(fake->reply == NULL);
874                 fake->reply = request->proxy_reply;
875                 request->proxy_reply = NULL;
876
877                 if ((debug_flag > 0) && fr_log_fp) {
878                         fprintf(fr_log_fp, "server %s {\n",
879                                 (fake->server == NULL) ? "" : fake->server);
880                 }
881
882                 /*
883                  *      Perform a post-auth stage for the tunneled
884                  *      session.
885                  */
886                 fake->options &= ~RAD_REQUEST_OPTION_PROXY_EAP;
887                 rcode = rad_postauth(fake);
888                 RDEBUG2("post-auth returns %d", rcode);
889
890                 if ((debug_flag > 0) && fr_log_fp) {
891                         fprintf(fr_log_fp, "} # server %s\n",
892                                 (fake->server == NULL) ? "" : fake->server);
893                         
894                         RDEBUG("Final reply from tunneled session code %d",
895                                fake->reply->code);
896                         debug_pair_list(fake->reply->vps);
897                 }
898
899                 /*
900                  *      Terrible hacks.
901                  */
902                 request->proxy = fake->packet;
903                 fake->packet = NULL;
904                 request->proxy_reply = fake->reply;
905                 fake->reply = NULL;
906
907                 /*
908                  *      And we're done with this request.
909                  */
910
911                 switch (rcode) {
912                 case RLM_MODULE_FAIL:
913                         request_free(&fake);
914                         eaptls_fail(handler, 0);
915                         return 0;
916                         break;
917
918                 default:  /* Don't Do Anything */
919                         RDEBUG2("Got reply %d",
920                                request->proxy_reply->code);
921                         break;
922                 }
923         }
924         request_free(&fake);    /* robust if fake == NULL */
925
926         /*
927          *      Process the reply from the home server.
928          */
929         rcode = process_reply(handler, tls_session, handler->request,
930                               handler->request->proxy_reply);
931
932         /*
933          *      The proxy code uses the reply from the home server as
934          *      the basis for the reply to the NAS.  We don't want that,
935          *      so we toss it, after we've had our way with it.
936          */
937         pairfree(&handler->request->proxy_reply->vps);
938
939         switch (rcode) {
940         case RLM_MODULE_REJECT:
941                 RDEBUG("Reply was rejected");
942                 break;
943
944         case RLM_MODULE_HANDLED:
945                 RDEBUG("Reply was handled");
946                 eaptls_request(handler->eap_ds, tls_session);
947                 return 1;
948
949         case RLM_MODULE_OK:
950                 RDEBUG("Reply was OK");
951
952                 /*
953                  *      Success: Automatically return MPPE keys.
954                  */
955                 return eaptls_success(handler, 0);
956
957         default:
958                 RDEBUG("Reply was unknown.");
959                 break;
960         }
961
962         eaptls_fail(handler, 0);
963         return 0;
964 }
965
966
967 /*
968  *      Free a request.
969  */
970 static void my_request_free(void *data)
971 {
972         REQUEST *request = (REQUEST *)data;
973
974         request_free(&request);
975 }
976 #endif  /* WITH_PROXY */
977
978 /*
979  *      Process the "diameter" contents of the tunneled data.
980  */
981 int eapttls_process(EAP_HANDLER *handler, tls_session_t *tls_session)
982 {
983         int rcode = PW_AUTHENTICATION_REJECT;
984         REQUEST *fake;
985         VALUE_PAIR *vp;
986         ttls_tunnel_t *t;
987         const uint8_t *data;
988         size_t data_len;
989         REQUEST *request = handler->request;
990         eap_chbind_packet_t *chbind_packet;
991         size_t chbind_len;
992
993         rad_assert(request != NULL);
994
995         /*
996          *      Just look at the buffer directly, without doing
997          *      record_minus.
998          */
999         data_len = tls_session->clean_out.used;
1000         tls_session->clean_out.used = 0;
1001         data = tls_session->clean_out.data;
1002
1003         t = (ttls_tunnel_t *) tls_session->opaque;
1004
1005         /*
1006          *      If there's no data, maybe this is an ACK to an
1007          *      MS-CHAP2-Success.
1008          */
1009         if (data_len == 0) {
1010                 if (t->authenticated) {
1011                         RDEBUG("Got ACK, and the user was already authenticated.");
1012                         return PW_AUTHENTICATION_ACK;
1013                 } /* else no session, no data, die. */
1014
1015                 /*
1016                  *      FIXME: Call SSL_get_error() to see what went
1017                  *      wrong.
1018                  */
1019                 RDEBUG2("SSL_read Error");
1020                 return PW_AUTHENTICATION_REJECT;
1021         }
1022
1023 #ifndef NDEBUG
1024         if ((debug_flag > 2) && fr_log_fp) {
1025                 size_t i;
1026
1027                 for (i = 0; i < data_len; i++) {
1028                         if ((i & 0x0f) == 0) fprintf(fr_log_fp, "  TTLS tunnel data in %04x: ", (int) i);
1029
1030                         fprintf(fr_log_fp, "%02x ", data[i]);
1031
1032                         if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
1033                 }
1034                 if ((data_len & 0x0f) != 0) fprintf(fr_log_fp, "\n");
1035         }
1036 #endif
1037
1038         if (!diameter_verify(request, data, data_len)) {
1039                 return PW_AUTHENTICATION_REJECT;
1040         }
1041
1042         /*
1043          *      Allocate a fake REQUEST structe.
1044          */
1045         fake = request_alloc_fake(request);
1046
1047         rad_assert(fake->packet->vps == NULL);
1048
1049         /*
1050          *      Add the tunneled attributes to the fake request.
1051          */
1052         fake->packet->vps = diameter2vp(request, tls_session->ssl, data, data_len);
1053         if (!fake->packet->vps) {
1054                 request_free(&fake);
1055                 return PW_AUTHENTICATION_REJECT;
1056         }
1057
1058         /*
1059          *      Tell the request that it's a fake one.
1060          */
1061         vp = pairmake("Freeradius-Proxied-To", "127.0.0.1", T_OP_EQ);
1062         if (vp) {
1063                 pairadd(&fake->packet->vps, vp);
1064         }
1065
1066         if ((debug_flag > 0) && fr_log_fp) {
1067                 RDEBUG("Got tunneled request");
1068
1069                 debug_pair_list(fake->packet->vps);
1070         }
1071
1072         /*
1073          *      Update other items in the REQUEST data structure.
1074          */
1075         fake->username = pairfind(fake->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1076         fake->password = pairfind(fake->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
1077
1078         /*
1079          *      No User-Name, try to create one from stored data.
1080          */
1081         if (!fake->username) {
1082                 /*
1083                  *      No User-Name in the stored data, look for
1084                  *      an EAP-Identity, and pull it out of there.
1085                  */
1086                 if (!t->username) {
1087                         vp = pairfind(fake->packet->vps, PW_EAP_MESSAGE, 0, TAG_ANY);
1088                         if (vp &&
1089                             (vp->length >= EAP_HEADER_LEN + 2) &&
1090                             (vp->vp_strvalue[0] == PW_EAP_RESPONSE) &&
1091                             (vp->vp_strvalue[EAP_HEADER_LEN] == PW_EAP_IDENTITY) &&
1092                             (vp->vp_strvalue[EAP_HEADER_LEN + 1] != 0)) {
1093                                 /*
1094                                  *      Create & remember a User-Name
1095                                  */
1096                                 t->username = pairmake("User-Name", "", T_OP_EQ);
1097                                 rad_assert(t->username != NULL);
1098
1099                                 memcpy(t->username->vp_strvalue, vp->vp_strvalue + 5,
1100                                        vp->length - 5);
1101                                 t->username->length = vp->length - 5;
1102                                 t->username->vp_strvalue[t->username->length] = 0;
1103
1104                                 RDEBUG("Got tunneled identity of %s",
1105                                        t->username->vp_strvalue);
1106
1107                                 /*
1108                                  *      If there's a default EAP type,
1109                                  *      set it here.
1110                                  */
1111                                 if (t->default_eap_type != 0) {
1112                                         RDEBUG("Setting default EAP type for tunneled EAP session.");
1113                                         vp = paircreate(PW_EAP_TYPE, 0);
1114                                         rad_assert(vp != NULL);
1115                                         vp->vp_integer = t->default_eap_type;
1116                                         pairadd(&fake->config_items, vp);
1117                                 }
1118
1119                         } else {
1120                                 /*
1121                                  *      Don't reject the request outright,
1122                                  *      as it's permitted to do EAP without
1123                                  *      user-name.
1124                                  */
1125                                 RDEBUG2W("No EAP-Identity found to start EAP conversation.");
1126                         }
1127                 } /* else there WAS a t->username */
1128
1129                 if (t->username) {
1130                         vp = paircopy(t->username);
1131                         pairadd(&fake->packet->vps, vp);
1132                         fake->username = pairfind(fake->packet->vps, PW_USER_NAME, 0, TAG_ANY);
1133                 }
1134         } /* else the request ALREADY had a User-Name */
1135
1136         /*
1137          *      Add the State attribute, too, if it exists.
1138          */
1139         if (t->state) {
1140                 vp = paircopy(t->state);
1141                 if (vp) pairadd(&fake->packet->vps, vp);
1142         }
1143
1144         /*
1145          *      If this is set, we copy SOME of the request attributes
1146          *      from outside of the tunnel to inside of the tunnel.
1147          *
1148          *      We copy ONLY those attributes which do NOT already
1149          *      exist in the tunneled request.
1150          */
1151         if (t->copy_request_to_tunnel) {
1152                 VALUE_PAIR *copy;
1153
1154                 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
1155                         /*
1156                          *      The attribute is a server-side thingy,
1157                          *      don't copy it.
1158                          */
1159                         if ((vp->da->attr > 255) &&
1160                             (vp->da->vendor == 0)) {
1161                                 continue;
1162                         }
1163
1164                         /*
1165                          *      The outside attribute is already in the
1166                          *      tunnel, don't copy it.
1167                          *
1168                          *      This works for BOTH attributes which
1169                          *      are originally in the tunneled request,
1170                          *      AND attributes which are copied there
1171                          *      from below.
1172                          */
1173                         if (pairfind(fake->packet->vps, vp->da->attr, vp->da->vendor, TAG_ANY)) {
1174                                 continue;
1175                         }
1176
1177                         /*
1178                          *      Some attributes are handled specially.
1179                          */
1180                         switch (vp->da->attr) {
1181                                 /*
1182                                  *      NEVER copy Message-Authenticator,
1183                                  *      EAP-Message, or State.  They're
1184                                  *      only for outside of the tunnel.
1185                                  */
1186                         case PW_USER_NAME:
1187                         case PW_USER_PASSWORD:
1188                         case PW_CHAP_PASSWORD:
1189                         case PW_CHAP_CHALLENGE:
1190                         case PW_PROXY_STATE:
1191                         case PW_MESSAGE_AUTHENTICATOR:
1192                         case PW_EAP_MESSAGE:
1193                         case PW_STATE:
1194                                 continue;
1195                                 break;
1196
1197                                 /*
1198                                  *      By default, copy it over.
1199                                  */
1200                         default:
1201                                 break;
1202                         }
1203
1204                         /*
1205                          *      Don't copy from the head, we've already
1206                          *      checked it.
1207                          */
1208                         copy = paircopy2(vp, vp->da->attr, vp->da->vendor, TAG_ANY);
1209                         pairadd(&fake->packet->vps, copy);
1210                 }
1211         }
1212
1213         if ((vp = pairfind(request->config_items, PW_VIRTUAL_SERVER, 0, TAG_ANY)) != NULL) {
1214                 fake->server = vp->vp_strvalue;
1215
1216         } else if (t->virtual_server) {
1217                 fake->server = t->virtual_server;
1218
1219         } /* else fake->server == request->server */
1220
1221
1222         if ((debug_flag > 0) && fr_log_fp) {
1223                 RDEBUG("Sending tunneled request");
1224
1225                 debug_pair_list(fake->packet->vps);
1226
1227                 fprintf(fr_log_fp, "server %s {\n",
1228                         (fake->server == NULL) ? "" : fake->server);
1229         }
1230
1231         /*
1232          *      Process channel binding here.
1233          */
1234         chbind_len = eap_chbind_vp2packet(fake->packet->vps, &chbind_packet);
1235         if (chbind_len > 0) {
1236                 int chbind_rcode;
1237                 CHBIND_REQ *req = chbind_allocate();
1238
1239                 RDEBUG("received chbind request");
1240                 req->chbind_req_pkt = (uint8_t *)chbind_packet;
1241                 req->chbind_req_len = chbind_len;
1242                 if (fake->username) {
1243                         req->username = fake->username->vp_octets;
1244                         req->username_len = fake->username->length;
1245                 } else {
1246                         req->username = NULL;
1247                         req->username_len = 0;
1248                 }
1249                 chbind_rcode = chbind_process(request, req);
1250
1251                 /* free the chbind packet; we're done with it */
1252                 free(chbind_packet);
1253
1254                 /* encapsulate response here */
1255                 if (req->chbind_resp_len > 0) {
1256                         RDEBUG("sending chbind response");
1257                         pairadd(&fake->reply->vps,
1258                                  eap_chbind_packet2vp((eap_chbind_packet_t *)req->chbind_resp,
1259                                                       req->chbind_resp_len));
1260                 } else {
1261                         RDEBUG("no chbind response");
1262                 }
1263
1264                 /* clean up chbind req */
1265                 chbind_free(req);
1266
1267                 if (chbind_rcode != PW_AUTHENTICATION_ACK)
1268                         return chbind_rcode;
1269         }
1270
1271         /*
1272          *      Call authentication recursively, which will
1273          *      do PAP, CHAP, MS-CHAP, etc.
1274          */
1275         rad_virtual_server(fake);
1276
1277         /*
1278          *      Note that we don't do *anything* with the reply
1279          *      attributes.
1280          */
1281         if ((debug_flag > 0) && fr_log_fp) {
1282                 fprintf(fr_log_fp, "} # server %s\n",
1283                         (fake->server == NULL) ? "" : fake->server);
1284
1285                 RDEBUG("Got tunneled reply code %d", fake->reply->code);
1286                 
1287                 debug_pair_list(fake->reply->vps);
1288         }
1289
1290         /*
1291          *      Decide what to do with the reply.
1292          */
1293         switch (fake->reply->code) {
1294         case 0:                 /* No reply code, must be proxied... */
1295 #ifdef WITH_PROXY
1296           vp = pairfind(fake->config_items, PW_PROXY_TO_REALM, 0, TAG_ANY);
1297                 if (vp) {
1298                         eap_tunnel_data_t *tunnel;
1299                         RDEBUG("Tunneled authentication will be proxied to %s", vp->vp_strvalue);
1300
1301                         /*
1302                          *      Tell the original request that it's going
1303                          *      to be proxied.
1304                          */
1305                         pairmove2(&(request->config_items),
1306                                   &(fake->config_items),
1307                                   PW_PROXY_TO_REALM, 0, TAG_ANY);
1308
1309                         /*
1310                          *      Seed the proxy packet with the
1311                          *      tunneled request.
1312                          */
1313                         rad_assert(request->proxy == NULL);
1314                         request->proxy = fake->packet;
1315                         memset(&request->proxy->src_ipaddr, 0,
1316                                sizeof(request->proxy->src_ipaddr));
1317                         memset(&request->proxy->src_ipaddr, 0,
1318                                sizeof(request->proxy->src_ipaddr));
1319                         request->proxy->src_port = 0;
1320                         request->proxy->dst_port = 0;
1321                         fake->packet = NULL;
1322                         rad_free(&fake->reply);
1323                         fake->reply = NULL;
1324
1325                         /*
1326                          *      Set up the callbacks for the tunnel
1327                          */
1328                         tunnel = rad_malloc(sizeof(*tunnel));
1329                         memset(tunnel, 0, sizeof(*tunnel));
1330
1331                         tunnel->tls_session = tls_session;
1332                         tunnel->callback = eapttls_postproxy;
1333
1334                         /*
1335                          *      Associate the callback with the request.
1336                          */
1337                         rcode = request_data_add(request,
1338                                                  request->proxy,
1339                                                  REQUEST_DATA_EAP_TUNNEL_CALLBACK,
1340                                                  tunnel, free);
1341                         rad_assert(rcode == 0);
1342
1343                         /*
1344                          *      rlm_eap.c has taken care of associating
1345                          *      the handler with the fake request.
1346                          *
1347                          *      So we associate the fake request with
1348                          *      this request.
1349                          */
1350                         rcode = request_data_add(request,
1351                                                  request->proxy,
1352                                                  REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK,
1353                                                  fake, my_request_free);
1354                         rad_assert(rcode == 0);
1355                         fake = NULL;
1356
1357                         /*
1358                          *      Didn't authenticate the packet, but
1359                          *      we're proxying it.
1360                          */
1361                         rcode = PW_STATUS_CLIENT;
1362
1363                 } else
1364 #endif  /* WITH_PROXY */
1365                   {
1366                         RDEBUG("No tunneled reply was found for request %d , and the request was not proxied: rejecting the user.",
1367                                request->number);
1368                         rcode = PW_AUTHENTICATION_REJECT;
1369                 }
1370                 break;
1371
1372         default:
1373                 /*
1374                  *      Returns RLM_MODULE_FOO, and we want to return
1375                  *      PW_FOO
1376                  */
1377                 rcode = process_reply(handler, tls_session, request,
1378                                       fake->reply);
1379                 switch (rcode) {
1380                 case RLM_MODULE_REJECT:
1381                         rcode = PW_AUTHENTICATION_REJECT;
1382                         break;
1383
1384                 case RLM_MODULE_HANDLED:
1385                         rcode = PW_ACCESS_CHALLENGE;
1386                         break;
1387
1388                 case RLM_MODULE_OK:
1389                         rcode = PW_AUTHENTICATION_ACK;
1390                         break;
1391
1392                 default:
1393                         rcode = PW_AUTHENTICATION_REJECT;
1394                         break;
1395                 }
1396                 break;
1397         }
1398
1399         request_free(&fake);
1400
1401         return rcode;
1402 }