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