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