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