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