more lvalue to vp_* changes
[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->vp_integer, data, vp->length);
271                         
272                         /*
273                          *      Stored in host byte order: change it.
274                          */
275                         vp->vp_integer = ntohl(vp->vp_integer);
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->vp_ipaddr, 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->vp_integer); /* stored in host order */
496                         memcpy(p, &attr, sizeof(attr));
497                         length = 4;
498                         break;
499
500                 case PW_TYPE_IPADDR:
501                         memcpy(p, &vp->vp_ipaddr, 4); /* network order */
502                         length = 4;
503                         break;
504
505                 case PW_TYPE_STRING:
506                 case PW_TYPE_OCTETS:
507                 default:
508                         memcpy(p, vp->vp_strvalue, vp->length);
509                         length = vp->length;
510                         break;
511                 }
512
513                 /*
514                  *      Skip to the end of the data.
515                  */
516                 p += length;
517                 total += length;
518
519                 /*
520                  *      Align the data to a multiple of 4 bytes.
521                  */
522                 if ((total & 0x03) != 0) {
523                         unsigned int i;
524
525                         length = 4 - (total & 0x03);
526                         for (i = 0; i < length; i++) {
527                                 *p = '\0';
528                                 p++;
529                                 total++;
530                         }
531                 }
532         } /* loop over the VP's to write. */
533
534         /*
535          *      Write the data in the buffer to the SSL session.
536          */
537         if (total > 0) {
538 #ifndef NDEBUG
539                 unsigned int i;
540
541                 if (debug_flag > 2) {
542                         for (i = 0; i < total; i++) {
543                                 if ((i & 0x0f) == 0) printf("  TTLS tunnel data out %04x: ", i);
544
545                                 printf("%02x ", buffer[i]);
546
547                                 if ((i & 0x0f) == 0x0f) printf("\n");
548                         }
549                         if ((total & 0x0f) != 0) printf("\n");
550                 }
551 #endif
552
553                 (tls_session->record_plus)(&tls_session->clean_in, buffer, total);
554
555                 /*
556                  *      FIXME: Check the return code.
557                  */
558                 tls_handshake_send(tls_session);
559         }
560
561         /*
562          *      Everything's OK.
563          */
564         return 1;
565 }
566
567 /*
568  *      Use a reply packet to determine what to do.
569  */
570 static int process_reply(EAP_HANDLER *handler, tls_session_t *tls_session,
571                          REQUEST *request, RADIUS_PACKET *reply)
572 {
573         int rcode = RLM_MODULE_REJECT;
574         VALUE_PAIR *vp;
575         ttls_tunnel_t *t = tls_session->opaque;
576
577         handler = handler;      /* -Wunused */
578
579         /*
580          *      If the response packet was Access-Accept, then
581          *      we're OK.  If not, die horribly.
582          *
583          *      FIXME: Take MS-CHAP2-Success attribute, and
584          *      tunnel it back to the client, to authenticate
585          *      ourselves to the client.
586          *
587          *      FIXME: If we have an Access-Challenge, then
588          *      the Reply-Message is tunneled back to the client.
589          *
590          *      FIXME: If we have an EAP-Message, then that message
591          *      must be tunneled back to the client.
592          *
593          *      FIXME: If we have an Access-Challenge with a State
594          *      attribute, then do we tunnel that to the client, or
595          *      keep track of it ourselves?
596          *
597          *      FIXME: EAP-Messages can only start with 'identity',
598          *      NOT 'eap start', so we should check for that....
599          */
600         switch (reply->code) {
601         case PW_AUTHENTICATION_ACK:
602                 DEBUG2("  TTLS: Got tunneled Access-Accept");
603
604                 rcode = RLM_MODULE_OK;
605
606                 /*
607                  *      MS-CHAP2-Success means that we do NOT return
608                  *      an Access-Accept, but instead tunnel that
609                  *      attribute to the client, and keep going with
610                  *      the TTLS session.  Once the client accepts
611                  *      our identity, it will respond with an empty
612                  *      packet, and we will send EAP-Success.
613                  */
614                 vp = NULL;
615                 pairmove2(&vp, &reply->vps, PW_MSCHAP2_SUCCESS);
616                 if (vp) {
617                         DEBUG2("  TTLS: Got MS-CHAP2-Success, tunneling it to the client in a challenge.");
618                         rcode = RLM_MODULE_HANDLED;
619                         t->authenticated = TRUE;
620                         
621                         /*
622                          *      Delete MPPE keys & encryption policy.  We don't
623                          *      want these here.
624                          */
625                         pairdelete(&reply->vps, ((311 << 16) | 7));
626                         pairdelete(&reply->vps, ((311 << 16) | 8));
627                         pairdelete(&reply->vps, ((311 << 16) | 16));
628                         pairdelete(&reply->vps, ((311 << 16) | 17));
629                         
630                         /*
631                          *      Use the tunneled reply, but not now.
632                          */
633                         if (t->use_tunneled_reply) {
634                                 t->reply = reply->vps;
635                                 reply->vps = NULL;
636                         }
637
638                 } else { /* no MS-CHAP2-Success */
639                         /*
640                          *      Can only have EAP-Message if there's
641                          *      no MS-CHAP2-Success.  (FIXME: EAP-MSCHAP?)
642                          *
643                          *      We also do NOT tunnel the EAP-Success
644                          *      attribute back to the client, as the client
645                          *      can figure it out, from the non-tunneled
646                          *      EAP-Success packet.
647                          */
648                         pairmove2(&vp, &reply->vps, PW_EAP_MESSAGE);
649                         pairfree(&vp);
650                 }
651
652                 /*
653                  *      Handle the ACK, by tunneling any necessary reply
654                  *      VP's back to the client.
655                  */
656                 if (vp) {
657                         vp2diameter(tls_session, vp);
658                         pairfree(&vp);
659                 }
660
661                 /*
662                  *      If we've been told to use the attributes from
663                  *      the reply, then do so.
664                  *
665                  *      WARNING: This may leak information about the
666                  *      tunneled user!
667                  */
668                 if (t->use_tunneled_reply) {
669                         pairdelete(&reply->vps, PW_PROXY_STATE);
670                         pairadd(&request->reply->vps, reply->vps);
671                         reply->vps = NULL;
672                 }
673                 break;
674
675
676         case PW_AUTHENTICATION_REJECT:
677                 DEBUG2("  TTLS: Got tunneled Access-Reject");
678                 rcode = RLM_MODULE_REJECT;
679                 break;
680
681                 /*
682                  *      Handle Access-Challenge, but only if we
683                  *      send tunneled reply data.  This is because
684                  *      an Access-Challenge means that we MUST tunnel
685                  *      a Reply-Message to the client.
686                  */
687         case PW_ACCESS_CHALLENGE:
688                 DEBUG2("  TTLS: Got tunneled Access-Challenge");
689
690                 /*
691                  *      Keep the State attribute, if necessary.
692                  *
693                  *      Get rid of the old State, too.
694                  */
695                 pairfree(&t->state);
696                 pairmove2(&t->state, &reply->vps, PW_STATE);
697
698                 /*
699                  *      We should really be a bit smarter about this,
700                  *      and move over only those attributes which
701                  *      are relevant to the authentication request,
702                  *      but that's a lot more work, and this "dumb"
703                  *      method works in 99.9% of the situations.
704                  */
705                 vp = NULL;
706                 pairmove2(&vp, &reply->vps, PW_EAP_MESSAGE);
707
708                 /*
709                  *      There MUST be a Reply-Message in the challenge,
710                  *      which we tunnel back to the client.
711                  *
712                  *      If there isn't one in the reply VP's, then
713                  *      we MUST create one, with an empty string as
714                  *      it's value.
715                  */
716                 pairmove2(&vp, &reply->vps, PW_REPLY_MESSAGE);
717
718                 /*
719                  *      Handle the ACK, by tunneling any necessary reply
720                  *      VP's back to the client.
721                  */
722                 if (vp) {
723                         vp2diameter(tls_session, vp);
724                         pairfree(&vp);
725                 }
726                 rcode = RLM_MODULE_HANDLED;
727                 break;
728
729         default:
730                 DEBUG2("  TTLS: Unknown RADIUS packet type %d: rejecting tunneled user", reply->code);
731                 rcode = RLM_MODULE_INVALID;
732                 break;
733         }
734
735         return rcode;
736 }
737
738
739 /*
740  *      Do post-proxy processing,
741  */
742 static int eapttls_postproxy(EAP_HANDLER *handler, void *data)
743 {
744         int rcode;
745         tls_session_t *tls_session = (tls_session_t *) data;
746         REQUEST *fake;
747
748         DEBUG2("  TTLS: Passing reply from proxy back into the tunnel.");
749
750         /*
751          *      If there was a fake request associated with the proxied
752          *      request, do more processing of it.
753          */
754         fake = (REQUEST *) request_data_get(handler->request,
755                                             handler->request->proxy,
756                                             REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK);
757         
758         /*
759          *      Do the callback, if it exists, and if it was a success.
760          */
761         if (fake && (handler->request->proxy_reply->code == PW_AUTHENTICATION_ACK)) {
762                 VALUE_PAIR *vp;
763                 REQUEST *request = handler->request;
764
765                 /*
766                  *      Terrible hacks.
767                  */
768                 rad_assert(fake->packet == NULL);
769                 fake->packet = request->proxy;
770                 request->proxy = NULL;
771
772                 rad_assert(fake->reply == NULL);
773                 fake->reply = request->proxy_reply;
774                 request->proxy_reply = NULL;
775
776                 /*
777                  *      Perform a post-auth stage for the tunneled
778                  *      session.
779                  */
780                 fake->options &= ~RAD_REQUEST_OPTION_PROXY_EAP;
781                 rcode = rad_postauth(fake);
782                 DEBUG2("  POST-AUTH %d", rcode);
783
784 #ifndef NDEBUG
785                 if (debug_flag > 0) {
786                         printf("  TTLS: Final reply from tunneled session code %d\n",
787                                fake->reply->code);
788                         
789                         for (vp = fake->reply->vps; vp != NULL; vp = vp->next) {
790                                 putchar('\t');vp_print(stdout, vp);putchar('\n');
791                         }
792                 }
793 #endif
794
795                 /*
796                  *      Terrible hacks.
797                  */
798                 request->proxy = fake->packet;
799                 fake->packet = NULL;
800                 request->proxy_reply = fake->reply;
801                 fake->reply = NULL;
802
803                 /*
804                  *      And we're done with this request.
805                  */
806
807                 switch (rcode) {
808                 case RLM_MODULE_FAIL:
809                         request_free(&fake);
810                         eaptls_fail(handler->eap_ds, 0);
811                         return 0;
812                         break;
813                         
814                 default:  /* Don't Do Anything */
815                         DEBUG2(" TTLS: Got reply %d",
816                                request->proxy_reply->code);
817                         break;
818                 }       
819         }
820         request_free(&fake);    /* robust if fake == NULL */
821
822         /*
823          *      Process the reply from the home server.
824          */
825         rcode = process_reply(handler, tls_session, handler->request,
826                               handler->request->proxy_reply);
827
828         /*
829          *      The proxy code uses the reply from the home server as
830          *      the basis for the reply to the NAS.  We don't want that,
831          *      so we toss it, after we've had our way with it.
832          */
833         pairfree(&handler->request->proxy_reply->vps);
834
835         switch (rcode) {
836         case RLM_MODULE_REJECT:
837                 DEBUG2("  TTLS: Reply was rejected");
838                 break;
839
840         case RLM_MODULE_HANDLED:
841                 DEBUG2("  TTLS: Reply was handled");
842                 eaptls_request(handler->eap_ds, tls_session);
843                 return 1;
844
845         case RLM_MODULE_OK:
846                 DEBUG2("  TTLS: Reply was OK");
847                 eaptls_success(handler->eap_ds, 0);
848                 eaptls_gen_mppe_keys(&handler->request->reply->vps,
849                                      tls_session->ssl,
850                                      "ttls keying material");
851                 return 1;
852
853         default:
854                 DEBUG2("  TTLS: Reply was unknown.");
855                 break;
856         }
857
858         eaptls_fail(handler->eap_ds, 0);
859         return 0;
860 }
861
862
863 /*
864  *      Free a request.
865  */
866 static void my_request_free(void *data)
867 {
868         REQUEST *request = (REQUEST *)data;
869
870         request_free(&request);
871 }
872
873
874 /*
875  *      Process the "diameter" contents of the tunneled data.
876  */
877 int eapttls_process(EAP_HANDLER *handler, tls_session_t *tls_session)
878 {
879         int err;
880         int rcode = PW_AUTHENTICATION_REJECT;
881         REQUEST *fake;
882         VALUE_PAIR *vp;
883         ttls_tunnel_t *t;
884         const uint8_t *data;
885         unsigned int data_len;
886         char buffer[1024];
887         REQUEST *request = handler->request;
888
889         /*
890          *      Grab the dirty data, and copy it to our buffer.
891          *
892          *      I *really* don't like these 'record_t' things...
893          */
894         data_len = (tls_session->record_minus)(&tls_session->dirty_in, buffer, sizeof(buffer));
895         data = buffer;
896
897         /*
898          *      Write the data from the dirty buffer (i.e. packet
899          *      data) into the buffer which we will give to SSL for
900          *      decoding.
901          *
902          *      Some of this code COULD technically go into the TLS
903          *      module, in eaptls_process(), where it returns EAPTLS_OK.
904          *
905          *      Similarly, the writing of data to the SSL context could
906          *      go there, too...
907          */
908         BIO_write(tls_session->into_ssl, buffer, data_len);
909         (tls_session->record_init)(&tls_session->clean_out);
910
911         /*
912          *      Read (and decrypt) the tunneled data from the SSL session,
913          *      and put it into the decrypted data buffer.
914          */
915         err = SSL_read(tls_session->ssl, tls_session->clean_out.data,
916                        sizeof(tls_session->clean_out.data));
917         if (err < 0) {
918                 /*
919                  *      FIXME: Call SSL_get_error() to see what went
920                  *      wrong.
921                  */
922                 radlog(L_INFO, "rlm_eap_ttls: SSL_read Error");
923                 return PW_AUTHENTICATION_REJECT;
924         }
925
926         t = (ttls_tunnel_t *) tls_session->opaque;
927
928         /*
929          *      If there's no data, maybe this is an ACK to an
930          *      MS-CHAP2-Success.
931          */
932         if (err == 0) {
933                 if (t->authenticated) {
934                         DEBUG2("  TTLS: Got ACK, and the user was already authenticated.");
935                         return PW_AUTHENTICATION_ACK;
936                 } /* else no session, no data, die. */
937
938                 /*
939                  *      FIXME: Call SSL_get_error() to see what went
940                  *      wrong.
941                  */
942                 radlog(L_INFO, "rlm_eap_ttls: SSL_read Error");
943                 return PW_AUTHENTICATION_REJECT;
944         }
945
946         data_len = tls_session->clean_out.used = err;
947         data = tls_session->clean_out.data;
948
949 #ifndef NDEBUG
950         if (debug_flag > 2) {
951                 unsigned int i;
952
953                 for (i = 0; i < data_len; i++) {
954                         if ((i & 0x0f) == 0) printf("  TTLS tunnel data in %04x: ", i);
955
956                         printf("%02x ", data[i]);
957
958                         if ((i & 0x0f) == 0x0f) printf("\n");
959                 }
960                 if ((data_len & 0x0f) != 0) printf("\n");
961         }
962 #endif
963
964         if (!diameter_verify(data, data_len)) {
965                 return PW_AUTHENTICATION_REJECT;
966         }
967
968         /*
969          *      Allocate a fake REQUEST structe.
970          */
971         fake = request_alloc_fake(request);
972
973         rad_assert(fake->packet->vps == NULL);
974
975         /*
976          *      Add the tunneled attributes to the fake request.
977          */
978         fake->packet->vps = diameter2vp(tls_session->ssl, data, data_len);
979         if (!fake->packet->vps) {
980                 return PW_AUTHENTICATION_REJECT;
981         }
982
983         /*
984          *      Tell the request that it's a fake one.
985          */
986         vp = pairmake("Freeradius-Proxied-To", "127.0.0.1", T_OP_EQ);
987         if (vp) {
988                 pairadd(&fake->packet->vps, vp);
989         }
990
991 #ifndef NDEBUG
992         if (debug_flag > 0) {
993                 printf("  TTLS: Got tunneled request\n");
994                 
995                 for (vp = fake->packet->vps; vp != NULL; vp = vp->next) {
996                         putchar('\t');vp_print(stdout, vp);putchar('\n');
997                 }
998         }
999 #endif
1000
1001         /*
1002          *      Update other items in the REQUEST data structure.
1003          */
1004         fake->username = pairfind(fake->packet->vps, PW_USER_NAME);
1005         fake->password = pairfind(fake->packet->vps, PW_USER_PASSWORD);
1006
1007         /*
1008          *      No User-Name, try to create one from stored data.
1009          */
1010         if (!fake->username) {
1011                 /*
1012                  *      No User-Name in the stored data, look for
1013                  *      an EAP-Identity, and pull it out of there.
1014                  */
1015                 if (!t->username) {
1016                         vp = pairfind(fake->packet->vps, PW_EAP_MESSAGE);
1017                         if (vp &&
1018                             (vp->length >= EAP_HEADER_LEN + 2) &&
1019                             (vp->vp_strvalue[0] == PW_EAP_RESPONSE) &&
1020                             (vp->vp_strvalue[EAP_HEADER_LEN] == PW_EAP_IDENTITY) &&
1021                             (vp->vp_strvalue[EAP_HEADER_LEN + 1] != 0)) {
1022                                 /*
1023                                  *      Create & remember a User-Name
1024                                  */
1025                                 t->username = pairmake("User-Name", "", T_OP_EQ);
1026                                 rad_assert(t->username != NULL);
1027
1028                                 memcpy(t->username->vp_strvalue, vp->vp_strvalue + 5,
1029                                        vp->length - 5);
1030                                 t->username->length = vp->length - 5;
1031                                 t->username->vp_strvalue[t->username->length] = 0;
1032
1033                                 DEBUG2("  TTLS: Got tunneled identity of %s",
1034                                        t->username->vp_strvalue);
1035
1036                                 /*
1037                                  *      If there's a default EAP type,
1038                                  *      set it here.
1039                                  */
1040                                 if (t->default_eap_type != 0) {
1041                                         DEBUG2("  TTLS: Setting default EAP type for tunneled EAP session.");
1042                                         vp = paircreate(PW_EAP_TYPE,
1043                                                         PW_TYPE_INTEGER);
1044                                         rad_assert(vp != NULL);
1045                                         vp->vp_integer = t->default_eap_type;
1046                                         pairadd(&fake->config_items, vp);
1047                                 }
1048
1049                         } else {
1050                                 /*
1051                                  *      Don't reject the request outright,
1052                                  *      as it's permitted to do EAP without
1053                                  *      user-name.
1054                                  */
1055                                 DEBUG2("  rlm_eap_ttls: WARNING! No EAP-Identity found to start EAP conversation.");
1056                         }
1057                 } /* else there WAS a t->username */
1058
1059                 if (t->username) {
1060                         vp = paircopy(t->username);
1061                         pairadd(&fake->packet->vps, vp);
1062                         fake->username = pairfind(fake->packet->vps, PW_USER_NAME);
1063                 }
1064         } /* else the request ALREADY had a User-Name */
1065
1066         /*
1067          *      Add the State attribute, too, if it exists.
1068          */
1069         if (t->state) {
1070                 DEBUG2("  TTLS: Adding old state with %02x %02x",
1071                        t->state->vp_strvalue[0], t->state->vp_strvalue[1]);
1072                 vp = paircopy(t->state);
1073                 if (vp) pairadd(&fake->packet->vps, vp);
1074         }
1075
1076         /*
1077          *      If this is set, we copy SOME of the request attributes
1078          *      from outside of the tunnel to inside of the tunnel.
1079          *
1080          *      We copy ONLY those attributes which do NOT already
1081          *      exist in the tunneled request.
1082          */
1083         if (t->copy_request_to_tunnel) {
1084                 VALUE_PAIR *copy;
1085
1086                 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
1087                         /*
1088                          *      The attribute is a server-side thingy,
1089                          *      don't copy it.
1090                          */
1091                         if ((vp->attribute > 255) &&
1092                             (((vp->attribute >> 16) & 0xffff) == 0)) {
1093                                 continue;
1094                         }
1095
1096                         /*
1097                          *      The outside attribute is already in the
1098                          *      tunnel, don't copy it.
1099                          *
1100                          *      This works for BOTH attributes which
1101                          *      are originally in the tunneled request,
1102                          *      AND attributes which are copied there
1103                          *      from below.
1104                          */
1105                         if (pairfind(fake->packet->vps, vp->attribute)) {
1106                                 continue;
1107                         }
1108
1109                         /*
1110                          *      Some attributes are handled specially.
1111                          */
1112                         switch (vp->attribute) {
1113                                 /*
1114                                  *      NEVER copy Message-Authenticator,
1115                                  *      EAP-Message, or State.  They're
1116                                  *      only for outside of the tunnel.
1117                                  */
1118                         case PW_USER_NAME:
1119                         case PW_USER_PASSWORD:
1120                         case PW_CHAP_PASSWORD:
1121                         case PW_CHAP_CHALLENGE:
1122                         case PW_PROXY_STATE:
1123                         case PW_MESSAGE_AUTHENTICATOR:
1124                         case PW_EAP_MESSAGE:
1125                         case PW_STATE:
1126                                 continue;
1127                                 break;
1128
1129                                 /*
1130                                  *      By default, copy it over.
1131                                  */
1132                         default:
1133                                 break;
1134                         }
1135
1136                         /*
1137                          *      Don't copy from the head, we've already
1138                          *      checked it.
1139                          */
1140                         copy = paircopy2(vp, vp->attribute);
1141                         pairadd(&fake->packet->vps, copy);
1142                 }
1143         }
1144
1145 #ifndef NDEBUG
1146         if (debug_flag > 0) {
1147           printf("  TTLS: Sending tunneled request\n");
1148
1149           for (vp = fake->packet->vps; vp != NULL; vp = vp->next) {
1150             putchar('\t');vp_print(stdout, vp);putchar('\n');
1151           }
1152         }
1153 #endif
1154
1155         /*
1156          *      Call authentication recursively, which will
1157          *      do PAP, CHAP, MS-CHAP, etc.
1158          */
1159         rad_authenticate(fake);
1160
1161         /*
1162          *      Note that we don't do *anything* with the reply
1163          *      attributes.
1164          */
1165 #ifndef NDEBUG
1166         if (debug_flag > 0) {
1167           printf("  TTLS: Got tunneled reply RADIUS code %d\n",
1168                  fake->reply->code);
1169
1170           for (vp = fake->reply->vps; vp != NULL; vp = vp->next) {
1171             putchar('\t');vp_print(stdout, vp);putchar('\n');
1172           }
1173         }
1174 #endif
1175
1176         /*
1177          *      Decide what to do with the reply.
1178          */
1179         switch (fake->reply->code) {
1180         case 0:                 /* No reply code, must be proxied... */
1181                 vp = pairfind(fake->config_items, PW_PROXY_TO_REALM);
1182                 if (vp) {
1183                         eap_tunnel_data_t *tunnel;
1184                         DEBUG2("  TTLS: Tunneled authentication will be proxied to %s", vp->vp_strvalue);
1185
1186                         /*
1187                          *      Tell the original request that it's going
1188                          *      to be proxied.
1189                          */
1190                         pairmove2(&(request->config_items),
1191                                   &(fake->config_items),
1192                                   PW_PROXY_TO_REALM);
1193
1194                         /*
1195                          *      Seed the proxy packet with the
1196                          *      tunneled request.
1197                          */
1198                         rad_assert(request->proxy == NULL);
1199                         request->proxy = fake->packet;
1200                         fake->packet = NULL;
1201                         rad_free(&fake->reply);
1202                         fake->reply = NULL;
1203
1204                         /*
1205                          *      Set up the callbacks for the tunnel
1206                          */
1207                         tunnel = rad_malloc(sizeof(*tunnel));
1208                         memset(tunnel, 0, sizeof(*tunnel));
1209
1210                         tunnel->tls_session = tls_session;
1211                         tunnel->callback = eapttls_postproxy;
1212
1213                         /*
1214                          *      Associate the callback with the request.
1215                          */
1216                         rcode = request_data_add(request,
1217                                                  request->proxy,
1218                                                  REQUEST_DATA_EAP_TUNNEL_CALLBACK,
1219                                                  tunnel, free);
1220                         rad_assert(rcode == 0);
1221                         
1222                         /*
1223                          *      rlm_eap.c has taken care of associating
1224                          *      the handler with the fake request.
1225                          *
1226                          *      So we associate the fake request with
1227                          *      this request.
1228                          */
1229                         rcode = request_data_add(request,
1230                                                  request->proxy,
1231                                                  REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK,
1232                                                  fake, my_request_free);
1233                         rad_assert(rcode == 0);
1234                         fake = NULL;
1235
1236                         /*
1237                          *      Didn't authenticate the packet, but
1238                          *      we're proxying it.
1239                          */
1240                         rcode = PW_STATUS_CLIENT;
1241
1242                 } else {
1243                         DEBUG2("  TTLS: No tunneled reply was found for request %d , and the request was not proxied: rejecting the user.",
1244                                request->number);
1245                         rcode = PW_AUTHENTICATION_REJECT;
1246                 }
1247                 break;
1248
1249         default:
1250                 /*
1251                  *      Returns RLM_MODULE_FOO, and we want to return
1252                  *      PW_FOO
1253                  */
1254                 rcode = process_reply(handler, tls_session, request,
1255                                       fake->reply);
1256                 switch (rcode) {
1257                 case RLM_MODULE_REJECT:
1258                         rcode = PW_AUTHENTICATION_REJECT;
1259                         break;
1260                         
1261                 case RLM_MODULE_HANDLED:
1262                         rcode = PW_ACCESS_CHALLENGE;
1263                         break;
1264                         
1265                 case RLM_MODULE_OK:
1266                         rcode = PW_AUTHENTICATION_ACK;
1267                         break;
1268                         
1269                 default:
1270                         rcode = PW_AUTHENTICATION_REJECT;
1271                         break;
1272                 }
1273                 break;
1274         }
1275
1276         request_free(&fake);
1277
1278         return rcode;
1279 }