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