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