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