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