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