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