Move restrictions on vendor ID from 32767 to 65535
[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: ", 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->reply = 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 /*
794  *      Do post-proxy processing,
795  */
796 static int eapttls_postproxy(EAP_HANDLER *handler, void *data)
797 {
798         int rcode;
799         tls_session_t *tls_session = (tls_session_t *) data;
800         REQUEST *fake, *request = handler->request;
801
802         RDEBUG("Passing reply from proxy back into the tunnel.");
803
804         /*
805          *      If there was a fake request associated with the proxied
806          *      request, do more processing of it.
807          */
808         fake = (REQUEST *) request_data_get(handler->request,
809                                             handler->request->proxy,
810                                             REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK);
811
812         /*
813          *      Do the callback, if it exists, and if it was a success.
814          */
815         if (fake && (handler->request->proxy_reply->code == PW_AUTHENTICATION_ACK)) {
816                 /*
817                  *      Terrible hacks.
818                  */
819                 rad_assert(fake->packet == NULL);
820                 fake->packet = request->proxy;
821                 fake->packet->src_ipaddr = request->packet->src_ipaddr;
822                 request->proxy = NULL;
823
824                 rad_assert(fake->reply == NULL);
825                 fake->reply = request->proxy_reply;
826                 request->proxy_reply = NULL;
827
828                 if ((debug_flag > 0) && fr_log_fp) {
829                         fprintf(fr_log_fp, "server %s {\n",
830                                 (fake->server == NULL) ? "" : fake->server);
831                 }
832
833                 /*
834                  *      Perform a post-auth stage for the tunneled
835                  *      session.
836                  */
837                 fake->options &= ~RAD_REQUEST_OPTION_PROXY_EAP;
838                 rcode = rad_postauth(fake);
839                 RDEBUG2("post-auth returns %d", rcode);
840
841                 if ((debug_flag > 0) && fr_log_fp) {
842                         fprintf(fr_log_fp, "} # server %s\n",
843                                 (fake->server == NULL) ? "" : fake->server);
844                         
845                         RDEBUG("Final reply from tunneled session code %d",
846                                fake->reply->code);
847                         debug_pair_list(fake->reply->vps);
848                 }
849
850                 /*
851                  *      Terrible hacks.
852                  */
853                 request->proxy = fake->packet;
854                 fake->packet = NULL;
855                 request->proxy_reply = fake->reply;
856                 fake->reply = NULL;
857
858                 /*
859                  *      And we're done with this request.
860                  */
861
862                 switch (rcode) {
863                 case RLM_MODULE_FAIL:
864                         request_free(&fake);
865                         eaptls_fail(handler, 0);
866                         return 0;
867                         break;
868
869                 default:  /* Don't Do Anything */
870                         RDEBUG2("sGot reply %d",
871                                request->proxy_reply->code);
872                         break;
873                 }
874         }
875         request_free(&fake);    /* robust if fake == NULL */
876
877         /*
878          *      Process the reply from the home server.
879          */
880         rcode = process_reply(handler, tls_session, handler->request,
881                               handler->request->proxy_reply);
882
883         /*
884          *      The proxy code uses the reply from the home server as
885          *      the basis for the reply to the NAS.  We don't want that,
886          *      so we toss it, after we've had our way with it.
887          */
888         pairfree(&handler->request->proxy_reply->vps);
889
890         switch (rcode) {
891         case RLM_MODULE_REJECT:
892                 RDEBUG("Reply was rejected");
893                 break;
894
895         case RLM_MODULE_HANDLED:
896                 RDEBUG("Reply was handled");
897                 eaptls_request(handler->eap_ds, tls_session);
898                 return 1;
899
900         case RLM_MODULE_OK:
901                 RDEBUG("Reply was OK");
902
903                 /*
904                  *      Success: Automatically return MPPE keys.
905                  */
906                 return eaptls_success(handler, 0);
907
908         default:
909                 RDEBUG("Reply was unknown.");
910                 break;
911         }
912
913         eaptls_fail(handler, 0);
914         return 0;
915 }
916
917
918 /*
919  *      Free a request.
920  */
921 static void my_request_free(void *data)
922 {
923         REQUEST *request = (REQUEST *)data;
924
925         request_free(&request);
926 }
927
928
929 /*
930  *      Process the "diameter" contents of the tunneled data.
931  */
932 int eapttls_process(EAP_HANDLER *handler, tls_session_t *tls_session)
933 {
934         int rcode = PW_AUTHENTICATION_REJECT;
935         REQUEST *fake;
936         VALUE_PAIR *vp;
937         ttls_tunnel_t *t;
938         const uint8_t *data;
939         size_t data_len;
940         REQUEST *request = handler->request;
941
942         /*
943          *      Just look at the buffer directly, without doing
944          *      record_minus.
945          */
946         data_len = tls_session->clean_out.used;
947         tls_session->clean_out.used = 0;
948         data = tls_session->clean_out.data;
949
950         t = (ttls_tunnel_t *) tls_session->opaque;
951
952         /*
953          *      If there's no data, maybe this is an ACK to an
954          *      MS-CHAP2-Success.
955          */
956         if (data_len == 0) {
957                 if (t->authenticated) {
958                         RDEBUG("Got ACK, and the user was already authenticated.");
959                         return PW_AUTHENTICATION_ACK;
960                 } /* else no session, no data, die. */
961
962                 /*
963                  *      FIXME: Call SSL_get_error() to see what went
964                  *      wrong.
965                  */
966                 RDEBUG2("SSL_read Error");
967                 return PW_AUTHENTICATION_REJECT;
968         }
969
970 #ifndef NDEBUG
971         if ((debug_flag > 2) && fr_log_fp) {
972                 size_t i;
973
974                 for (i = 0; i < data_len; i++) {
975                         if ((i & 0x0f) == 0) fprintf(fr_log_fp, "  TTLS tunnel data in %04x: ", i);
976
977                         fprintf(fr_log_fp, "%02x ", data[i]);
978
979                         if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
980                 }
981                 if ((data_len & 0x0f) != 0) fprintf(fr_log_fp, "\n");
982         }
983 #endif
984
985         if (!diameter_verify(request, data, data_len)) {
986                 return PW_AUTHENTICATION_REJECT;
987         }
988
989         /*
990          *      Allocate a fake REQUEST structe.
991          */
992         fake = request_alloc_fake(request);
993
994         rad_assert(fake->packet->vps == NULL);
995
996         /*
997          *      Add the tunneled attributes to the fake request.
998          */
999         fake->packet->vps = diameter2vp(request, tls_session->ssl, data, data_len);
1000         if (!fake->packet->vps) {
1001                 request_free(&fake);
1002                 return PW_AUTHENTICATION_REJECT;
1003         }
1004
1005         /*
1006          *      Tell the request that it's a fake one.
1007          */
1008         vp = pairmake("Freeradius-Proxied-To", "127.0.0.1", T_OP_EQ);
1009         if (vp) {
1010                 pairadd(&fake->packet->vps, vp);
1011         }
1012
1013         if ((debug_flag > 0) && fr_log_fp) {
1014                 RDEBUG("Got tunneled request");
1015
1016                 debug_pair_list(fake->packet->vps);
1017         }
1018
1019         /*
1020          *      Update other items in the REQUEST data structure.
1021          */
1022         fake->username = pairfind(fake->packet->vps, PW_USER_NAME);
1023         fake->password = pairfind(fake->packet->vps, PW_USER_PASSWORD);
1024
1025         /*
1026          *      No User-Name, try to create one from stored data.
1027          */
1028         if (!fake->username) {
1029                 /*
1030                  *      No User-Name in the stored data, look for
1031                  *      an EAP-Identity, and pull it out of there.
1032                  */
1033                 if (!t->username) {
1034                         vp = pairfind(fake->packet->vps, PW_EAP_MESSAGE);
1035                         if (vp &&
1036                             (vp->length >= EAP_HEADER_LEN + 2) &&
1037                             (vp->vp_strvalue[0] == PW_EAP_RESPONSE) &&
1038                             (vp->vp_strvalue[EAP_HEADER_LEN] == PW_EAP_IDENTITY) &&
1039                             (vp->vp_strvalue[EAP_HEADER_LEN + 1] != 0)) {
1040                                 /*
1041                                  *      Create & remember a User-Name
1042                                  */
1043                                 t->username = pairmake("User-Name", "", T_OP_EQ);
1044                                 rad_assert(t->username != NULL);
1045
1046                                 memcpy(t->username->vp_strvalue, vp->vp_strvalue + 5,
1047                                        vp->length - 5);
1048                                 t->username->length = vp->length - 5;
1049                                 t->username->vp_strvalue[t->username->length] = 0;
1050
1051                                 RDEBUG("Got tunneled identity of %s",
1052                                        t->username->vp_strvalue);
1053
1054                                 /*
1055                                  *      If there's a default EAP type,
1056                                  *      set it here.
1057                                  */
1058                                 if (t->default_eap_type != 0) {
1059                                         RDEBUG("Setting default EAP type for tunneled EAP session.");
1060                                         vp = paircreate(PW_EAP_TYPE,
1061                                                         PW_TYPE_INTEGER);
1062                                         rad_assert(vp != NULL);
1063                                         vp->vp_integer = t->default_eap_type;
1064                                         pairadd(&fake->config_items, vp);
1065                                 }
1066
1067                         } else {
1068                                 /*
1069                                  *      Don't reject the request outright,
1070                                  *      as it's permitted to do EAP without
1071                                  *      user-name.
1072                                  */
1073                                 RDEBUG2("WARNING! No EAP-Identity found to start EAP conversation.");
1074                         }
1075                 } /* else there WAS a t->username */
1076
1077                 if (t->username) {
1078                         vp = paircopy(t->username);
1079                         pairadd(&fake->packet->vps, vp);
1080                         fake->username = pairfind(fake->packet->vps, PW_USER_NAME);
1081                 }
1082         } /* else the request ALREADY had a User-Name */
1083
1084         /*
1085          *      Add the State attribute, too, if it exists.
1086          */
1087         if (t->state) {
1088                 vp = paircopy(t->state);
1089                 if (vp) pairadd(&fake->packet->vps, vp);
1090         }
1091
1092         /*
1093          *      If this is set, we copy SOME of the request attributes
1094          *      from outside of the tunnel to inside of the tunnel.
1095          *
1096          *      We copy ONLY those attributes which do NOT already
1097          *      exist in the tunneled request.
1098          */
1099         if (t->copy_request_to_tunnel) {
1100                 VALUE_PAIR *copy;
1101
1102                 for (vp = request->packet->vps; vp != NULL; vp = vp->next) {
1103                         /*
1104                          *      The attribute is a server-side thingy,
1105                          *      don't copy it.
1106                          */
1107                         if ((vp->attribute > 255) &&
1108                             (((vp->attribute >> 16) & 0xffff) == 0)) {
1109                                 continue;
1110                         }
1111
1112                         /*
1113                          *      The outside attribute is already in the
1114                          *      tunnel, don't copy it.
1115                          *
1116                          *      This works for BOTH attributes which
1117                          *      are originally in the tunneled request,
1118                          *      AND attributes which are copied there
1119                          *      from below.
1120                          */
1121                         if (pairfind(fake->packet->vps, vp->attribute)) {
1122                                 continue;
1123                         }
1124
1125                         /*
1126                          *      Some attributes are handled specially.
1127                          */
1128                         switch (vp->attribute) {
1129                                 /*
1130                                  *      NEVER copy Message-Authenticator,
1131                                  *      EAP-Message, or State.  They're
1132                                  *      only for outside of the tunnel.
1133                                  */
1134                         case PW_USER_NAME:
1135                         case PW_USER_PASSWORD:
1136                         case PW_CHAP_PASSWORD:
1137                         case PW_CHAP_CHALLENGE:
1138                         case PW_PROXY_STATE:
1139                         case PW_MESSAGE_AUTHENTICATOR:
1140                         case PW_EAP_MESSAGE:
1141                         case PW_STATE:
1142                                 continue;
1143                                 break;
1144
1145                                 /*
1146                                  *      By default, copy it over.
1147                                  */
1148                         default:
1149                                 break;
1150                         }
1151
1152                         /*
1153                          *      Don't copy from the head, we've already
1154                          *      checked it.
1155                          */
1156                         copy = paircopy2(vp, vp->attribute);
1157                         pairadd(&fake->packet->vps, copy);
1158                 }
1159         }
1160
1161         if ((vp = pairfind(request->config_items, PW_VIRTUAL_SERVER)) != NULL) {
1162                 fake->server = vp->vp_strvalue;
1163
1164         } else if (t->virtual_server) {
1165                 fake->server = t->virtual_server;
1166
1167         } /* else fake->server == request->server */
1168
1169
1170         if ((debug_flag > 0) && fr_log_fp) {
1171                 RDEBUG("Sending tunneled request");
1172
1173                 debug_pair_list(fake->packet->vps);
1174
1175                 fprintf(fr_log_fp, "server %s {\n",
1176                         (fake->server == NULL) ? "" : fake->server);
1177         }
1178
1179         /*
1180          *      Call authentication recursively, which will
1181          *      do PAP, CHAP, MS-CHAP, etc.
1182          */
1183         rad_authenticate(fake);
1184
1185         /*
1186          *      Note that we don't do *anything* with the reply
1187          *      attributes.
1188          */
1189         if ((debug_flag > 0) && fr_log_fp) {
1190                 fprintf(fr_log_fp, "} # server %s\n",
1191                         (fake->server == NULL) ? "" : fake->server);
1192
1193                 RDEBUG("Got tunneled reply code %d", fake->reply->code);
1194                 
1195                 debug_pair_list(fake->reply->vps);
1196         }
1197
1198         /*
1199          *      Decide what to do with the reply.
1200          */
1201         switch (fake->reply->code) {
1202         case 0:                 /* No reply code, must be proxied... */
1203                 vp = pairfind(fake->config_items, PW_PROXY_TO_REALM);
1204                 if (vp) {
1205                         eap_tunnel_data_t *tunnel;
1206                         RDEBUG("Tunneled authentication will be proxied to %s", vp->vp_strvalue);
1207
1208                         /*
1209                          *      Tell the original request that it's going
1210                          *      to be proxied.
1211                          */
1212                         pairmove2(&(request->config_items),
1213                                   &(fake->config_items),
1214                                   PW_PROXY_TO_REALM);
1215
1216                         /*
1217                          *      Seed the proxy packet with the
1218                          *      tunneled request.
1219                          */
1220                         rad_assert(request->proxy == NULL);
1221                         request->proxy = fake->packet;
1222                         fake->packet = NULL;
1223                         rad_free(&fake->reply);
1224                         fake->reply = NULL;
1225
1226                         /*
1227                          *      Set up the callbacks for the tunnel
1228                          */
1229                         tunnel = rad_malloc(sizeof(*tunnel));
1230                         memset(tunnel, 0, sizeof(*tunnel));
1231
1232                         tunnel->tls_session = tls_session;
1233                         tunnel->callback = eapttls_postproxy;
1234
1235                         /*
1236                          *      Associate the callback with the request.
1237                          */
1238                         rcode = request_data_add(request,
1239                                                  request->proxy,
1240                                                  REQUEST_DATA_EAP_TUNNEL_CALLBACK,
1241                                                  tunnel, free);
1242                         rad_assert(rcode == 0);
1243
1244                         /*
1245                          *      rlm_eap.c has taken care of associating
1246                          *      the handler with the fake request.
1247                          *
1248                          *      So we associate the fake request with
1249                          *      this request.
1250                          */
1251                         rcode = request_data_add(request,
1252                                                  request->proxy,
1253                                                  REQUEST_DATA_EAP_MSCHAP_TUNNEL_CALLBACK,
1254                                                  fake, my_request_free);
1255                         rad_assert(rcode == 0);
1256                         fake = NULL;
1257
1258                         /*
1259                          *      Didn't authenticate the packet, but
1260                          *      we're proxying it.
1261                          */
1262                         rcode = PW_STATUS_CLIENT;
1263
1264                 } else {
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 }