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