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