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