Simplify RFC format attributes
[freeradius.git] / src / lib / radius.c
1 /*
2  * radius.c     Functions to send/receive radius packets.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library 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 GNU
14  *   Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000-2003,2006  The FreeRADIUS server project
21  */
22
23 #include        <freeradius-devel/ident.h>
24 RCSID("$Id$")
25
26 #include        <freeradius-devel/libradius.h>
27 #include        <freeradius-devel/md5.h>
28
29 #include        <fcntl.h>
30 #include        <ctype.h>
31
32 #ifdef WITH_UDPFROMTO
33 #include        <freeradius-devel/udpfromto.h>
34 #endif
35
36 #ifdef HAVE_MALLOC_H
37 #include        <malloc.h>
38 #endif
39
40 /*
41  *  The RFC says 4096 octets max, and most packets are less than 256.
42  */
43 #define MAX_PACKET_LEN 4096
44
45 /*
46  *      The maximum number of attributes which we allow in an incoming
47  *      request.  If there are more attributes than this, the request
48  *      is rejected.
49  *
50  *      This helps to minimize the potential for a DoS, when an
51  *      attacker spoofs Access-Request packets, which don't have a
52  *      Message-Authenticator attribute.  This means that the packet
53  *      is unsigned, and the attacker can use resources on the server,
54  *      even if the end request is rejected.
55  */
56 int fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
58
59 typedef struct radius_packet_t {
60   uint8_t       code;
61   uint8_t       id;
62   uint8_t       length[2];
63   uint8_t       vector[AUTH_VECTOR_LEN];
64   uint8_t       data[1];
65 } radius_packet_t;
66
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
70
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
72   "",
73   "Access-Request",
74   "Access-Accept",
75   "Access-Reject",
76   "Accounting-Request",
77   "Accounting-Response",
78   "Accounting-Status",
79   "Password-Request",
80   "Password-Accept",
81   "Password-Reject",
82   "Accounting-Message",
83   "Access-Challenge",
84   "Status-Server",
85   "Status-Client",
86   "14",
87   "15",
88   "16",
89   "17",
90   "18",
91   "19",
92   "20",
93   "Resource-Free-Request",
94   "Resource-Free-Response",
95   "Resource-Query-Request",
96   "Resource-Query-Response",
97   "Alternate-Resource-Reclaim-Request",
98   "NAS-Reboot-Request",
99   "NAS-Reboot-Response",
100   "28",
101   "Next-Passcode",
102   "New-Pin",
103   "Terminate-Session",
104   "Password-Expired",
105   "Event-Request",
106   "Event-Response",
107   "35",
108   "36",
109   "37",
110   "38",
111   "39",
112   "Disconnect-Request",
113   "Disconnect-ACK",
114   "Disconnect-NAK",
115   "CoA-Request",
116   "CoA-ACK",
117   "CoA-NAK",
118   "46",
119   "47",
120   "48",
121   "49",
122   "IP-Address-Allocate",
123   "IP-Address-Release"
124 };
125
126
127 void fr_printf_log(const char *fmt, ...)
128 {
129         va_list ap;
130
131         va_start(ap, fmt);
132         if ((fr_debug_flag == 0) || !fr_log_fp) {
133                 va_end(ap);
134                 return;
135         }
136
137         vfprintf(fr_log_fp, fmt, ap);
138         va_end(ap);
139
140         return;
141 }
142
143 static void print_hex(RADIUS_PACKET *packet)
144 {
145         int i;
146
147         if (!packet->data) return;
148
149         printf("  Code:\t\t%u\n", packet->data[0]);
150         printf("  Id:\t\t%u\n", packet->data[1]);
151         printf("  Length:\t%u\n", ((packet->data[2] << 8) |
152                                    (packet->data[3])));
153         printf("  Vector:\t");
154         for (i = 4; i < 20; i++) {
155                 printf("%02x", packet->data[i]);
156         }
157         printf("\n");
158
159         if (packet->data_len > 20) {
160                 int total;
161                 const uint8_t *ptr;
162                 printf("  Data:");
163
164                 total = packet->data_len - 20;
165                 ptr = packet->data + 20;
166
167                 while (total > 0) {
168                         int attrlen;
169
170                         printf("\t\t");
171                         if (total < 2) { /* too short */
172                                 printf("%02x\n", *ptr);
173                                 break;
174                         }
175
176                         if (ptr[1] > total) { /* too long */
177                                 for (i = 0; i < total; i++) {
178                                         printf("%02x ", ptr[i]);
179                                 }
180                                 break;
181                         }
182
183                         printf("%02x  %02x  ", ptr[0], ptr[1]);
184                         attrlen = ptr[1] - 2;
185                         ptr += 2;
186                         total -= 2;
187
188                         for (i = 0; i < attrlen; i++) {
189                                 if ((i > 0) && ((i & 0x0f) == 0x00))
190                                         printf("\t\t\t");
191                                 printf("%02x ", ptr[i]);
192                                 if ((i & 0x0f) == 0x0f) printf("\n");
193                         }
194
195                         if ((attrlen & 0x0f) != 0x00) printf("\n");
196
197                         ptr += attrlen;
198                         total -= attrlen;
199                 }
200         }
201         fflush(stdout);
202 }
203
204
205 /*
206  *      Wrapper for sendto which handles sendfromto, IPv6, and all
207  *      possible combinations.
208  */
209 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
210                       fr_ipaddr_t *src_ipaddr, int src_port,
211                       fr_ipaddr_t *dst_ipaddr, int dst_port)
212 {
213         struct sockaddr_storage dst;
214         socklen_t               sizeof_dst;
215
216 #ifdef WITH_UDPFROMTO
217         struct sockaddr_storage src;
218         socklen_t               sizeof_src;
219
220         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
221 #else
222         src_port = src_port;    /* -Wunused */
223 #endif
224
225         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
226                 return -1;
227         }
228
229 #ifdef WITH_UDPFROMTO
230         /*
231          *      Only IPv4 is supported for udpfromto.
232          *
233          *      And if they don't specify a source IP address, don't
234          *      use udpfromto.
235          */
236         if ((dst_ipaddr->af == AF_INET) ||
237             (src_ipaddr->af != AF_UNSPEC)) {
238                 return sendfromto(sockfd, data, data_len, flags,
239                                   (struct sockaddr *)&src, sizeof_src,
240                                   (struct sockaddr *)&dst, sizeof_dst);
241         }
242 #else
243         src_ipaddr = src_ipaddr; /* -Wunused */
244 #endif
245
246         /*
247          *      No udpfromto, OR an IPv6 socket, fail gracefully.
248          */
249         return sendto(sockfd, data, data_len, flags,
250                       (struct sockaddr *) &dst, sizeof_dst);
251 }
252
253
254 void rad_recv_discard(int sockfd)
255 {
256         uint8_t                 header[4];
257         struct sockaddr_storage src;
258         socklen_t               sizeof_src = sizeof(src);
259
260         recvfrom(sockfd, header, sizeof(header), 0,
261                  (struct sockaddr *)&src, &sizeof_src);
262 }
263
264
265 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
266                         int *code)
267 {
268         ssize_t                 data_len, packet_len;
269         uint8_t                 header[4];
270         struct sockaddr_storage src;
271         socklen_t               sizeof_src = sizeof(src);
272
273         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
274                             (struct sockaddr *)&src, &sizeof_src);
275         if (data_len < 0) {
276                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
277                 return -1;
278         }
279
280         /*
281          *      Too little data is available, discard the packet.
282          */
283         if (data_len < 4) {
284                 recvfrom(sockfd, header, sizeof(header), 0,
285                          (struct sockaddr *)&src, &sizeof_src);
286                 return 1;
287
288         } else {                /* we got 4 bytes of data. */
289                 /*
290                  *      See how long the packet says it is.
291                  */
292                 packet_len = (header[2] * 256) + header[3];
293
294                 /*
295                  *      The length in the packet says it's less than
296                  *      a RADIUS header length: discard it.
297                  */
298                 if (packet_len < AUTH_HDR_LEN) {
299                         recvfrom(sockfd, header, sizeof(header), 0,
300                                  (struct sockaddr *)&src, &sizeof_src);
301                         return 1;
302
303                         /*
304                          *      Enforce RFC requirements, for sanity.
305                          *      Anything after 4k will be discarded.
306                          */
307                 } else if (packet_len > MAX_PACKET_LEN) {
308                         recvfrom(sockfd, header, sizeof(header), 0,
309                                  (struct sockaddr *)&src, &sizeof_src);
310                         return 1;
311                 }
312         }
313
314         /*
315          *      Convert AF.  If unknown, discard packet.
316          */
317         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
318                 recvfrom(sockfd, header, sizeof(header), 0,
319                          (struct sockaddr *)&src, &sizeof_src);
320                 return 1;
321         }
322
323         *code = header[0];
324
325         /*
326          *      The packet says it's this long, but the actual UDP
327          *      size could still be smaller.
328          */
329         return packet_len;
330 }
331
332
333 /*
334  *      wrapper for recvfrom, which handles recvfromto, IPv6, and all
335  *      possible combinations.
336  */
337 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
338                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
339                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
340 {
341         struct sockaddr_storage src;
342         struct sockaddr_storage dst;
343         socklen_t               sizeof_src = sizeof(src);
344         socklen_t               sizeof_dst = sizeof(dst);
345         ssize_t                 data_len;
346         uint8_t                 header[4];
347         void                    *buf;
348         size_t                  len;
349         int                     port;
350
351         memset(&src, 0, sizeof_src);
352         memset(&dst, 0, sizeof_dst);
353
354         /*
355          *      Get address family, etc. first, so we know if we
356          *      need to do udpfromto.
357          *
358          *      FIXME: udpfromto also does this, but it's not
359          *      a critical problem.
360          */
361         if (getsockname(sockfd, (struct sockaddr *)&dst,
362                         &sizeof_dst) < 0) return -1;
363
364         /*
365          *      Read the length of the packet, from the packet.
366          *      This lets us allocate the buffer to use for
367          *      reading the rest of the packet.
368          */
369         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
370                             (struct sockaddr *)&src, &sizeof_src);
371         if (data_len < 0) {
372                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
373                 return -1;
374         }
375
376         /*
377          *      Too little data is available, discard the packet.
378          */
379         if (data_len < 4) {
380                 recvfrom(sockfd, header, sizeof(header), flags,
381                          (struct sockaddr *)&src, &sizeof_src);
382                 return 0;
383
384         } else {                /* we got 4 bytes of data. */
385                 /*
386                  *      See how long the packet says it is.
387                  */
388                 len = (header[2] * 256) + header[3];
389
390                 /*
391                  *      The length in the packet says it's less than
392                  *      a RADIUS header length: discard it.
393                  */
394                 if (len < AUTH_HDR_LEN) {
395                         recvfrom(sockfd, header, sizeof(header), flags,
396                                  (struct sockaddr *)&src, &sizeof_src);
397                         return 0;
398
399                         /*
400                          *      Enforce RFC requirements, for sanity.
401                          *      Anything after 4k will be discarded.
402                          */
403                 } else if (len > MAX_PACKET_LEN) {
404                         recvfrom(sockfd, header, sizeof(header), flags,
405                                  (struct sockaddr *)&src, &sizeof_src);
406                         return len;
407                 }
408         }
409
410         buf = malloc(len);
411         if (!buf) return -1;
412
413         /*
414          *      Receive the packet.  The OS will discard any data in the
415          *      packet after "len" bytes.
416          */
417 #ifdef WITH_UDPFROMTO
418         if (dst.ss_family == AF_INET) {
419                 data_len = recvfromto(sockfd, buf, len, flags,
420                                       (struct sockaddr *)&src, &sizeof_src,
421                                       (struct sockaddr *)&dst, &sizeof_dst);
422         } else
423 #endif
424                 /*
425                  *      No udpfromto, OR an IPv6 socket.  Fail gracefully.
426                  */
427                 data_len = recvfrom(sockfd, buf, len, flags,
428                                     (struct sockaddr *)&src, &sizeof_src);
429         if (data_len < 0) {
430                 free(buf);
431                 return data_len;
432         }
433
434         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
435                 free(buf);
436                 return -1;      /* Unknown address family, Die Die Die! */
437         }
438         *src_port = port;
439
440         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
441         *dst_port = port;
442
443         /*
444          *      Different address families should never happen.
445          */
446         if (src.ss_family != dst.ss_family) {
447                 free(buf);
448                 return -1;
449         }
450
451         /*
452          *      Tell the caller about the data
453          */
454         *pbuf = buf;
455
456         return data_len;
457 }
458
459
460 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
461 /*************************************************************************
462  *
463  *      Function: make_secret
464  *
465  *      Purpose: Build an encrypted secret value to return in a reply
466  *               packet.  The secret is hidden by xoring with a MD5 digest
467  *               created from the shared secret and the authentication
468  *               vector.  We put them into MD5 in the reverse order from
469  *               that used when encrypting passwords to RADIUS.
470  *
471  *************************************************************************/
472 static void make_secret(uint8_t *digest, const uint8_t *vector,
473                         const char *secret, const uint8_t *value)
474 {
475         FR_MD5_CTX context;
476         int             i;
477
478         fr_MD5Init(&context);
479         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
480         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
481         fr_MD5Final(digest, &context);
482
483         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
484                 digest[i] ^= value[i];
485         }
486 }
487
488 #define MAX_PASS_LEN (128)
489 static void make_passwd(uint8_t *output, size_t *outlen,
490                         const uint8_t *input, size_t inlen,
491                         const char *secret, const uint8_t *vector)
492 {
493         FR_MD5_CTX context, old;
494         uint8_t digest[AUTH_VECTOR_LEN];
495         uint8_t passwd[MAX_PASS_LEN];
496         int     i, n;
497         int     len;
498
499         /*
500          *      If the length is zero, round it up.
501          */
502         len = inlen;
503
504         if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
505
506         memcpy(passwd, input, len);
507         memset(passwd + len, 0, sizeof(passwd) - len);
508
509         if (len == 0) {
510                 len = AUTH_PASS_LEN;
511         }
512
513         else if ((len & 0x0f) != 0) {
514                 len += 0x0f;
515                 len &= ~0x0f;
516         }
517         *outlen = len;
518
519         fr_MD5Init(&context);
520         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
521         old = context;
522
523         /*
524          *      Do first pass.
525          */
526         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
527
528         for (n = 0; n < len; n += AUTH_PASS_LEN) {
529                 if (n > 0) {
530                         context = old;
531                         fr_MD5Update(&context,
532                                        passwd + n - AUTH_PASS_LEN,
533                                        AUTH_PASS_LEN);
534                 }
535
536                 fr_MD5Final(digest, &context);
537                 for (i = 0; i < AUTH_PASS_LEN; i++) {
538                         passwd[i + n] ^= digest[i];
539                 }
540         }
541
542         memcpy(output, passwd, len);
543 }
544
545 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
546                                const uint8_t *input, size_t inlen, size_t room,
547                                const char *secret, const uint8_t *vector)
548 {
549         FR_MD5_CTX context, old;
550         uint8_t digest[AUTH_VECTOR_LEN];
551         uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
552         int     i, n;
553         int     len;
554
555         /*
556          *      Be paranoid.
557          */
558         if (room > 253) room = 253;
559
560         /*
561          *      Account for 2 bytes of the salt, and round the room
562          *      available down to the nearest multiple of 16.  Then,
563          *      subtract one from that to account for the length byte,
564          *      and the resulting number is the upper bound on the data
565          *      to copy.
566          *
567          *      We could short-cut this calculation just be forcing
568          *      inlen to be no more than 239.  It would work for all
569          *      VSA's, as we don't pack multiple VSA's into one
570          *      attribute.
571          *
572          *      However, this calculation is more general, if a little
573          *      complex.  And it will work in the future for all possible
574          *      kinds of weird attribute packing.
575          */
576         room -= 2;
577         room -= (room & 0x0f);
578         room--;
579
580         if (inlen > room) inlen = room;
581
582         /*
583          *      Length of the encrypted data is password length plus
584          *      one byte for the length of the password.
585          */
586         len = inlen + 1;
587         if ((len & 0x0f) != 0) {
588                 len += 0x0f;
589                 len &= ~0x0f;
590         }
591         *outlen = len + 2;      /* account for the salt */
592
593         /*
594          *      Copy the password over.
595          */
596         memcpy(passwd + 3, input, inlen);
597         memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
598
599         /*
600          *      Generate salt.  The RFC's say:
601          *
602          *      The high bit of salt[0] must be set, each salt in a
603          *      packet should be unique, and they should be random
604          *
605          *      So, we set the high bit, add in a counter, and then
606          *      add in some CSPRNG data.  should be OK..
607          */
608         passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
609                      (fr_rand() & 0x07));
610         passwd[1] = fr_rand();
611         passwd[2] = inlen;      /* length of the password string */
612
613         fr_MD5Init(&context);
614         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
615         old = context;
616
617         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
618         fr_MD5Update(&context, &passwd[0], 2);
619
620         for (n = 0; n < len; n += AUTH_PASS_LEN) {
621                 if (n > 0) {
622                         context = old;
623                         fr_MD5Update(&context,
624                                        passwd + 2 + n - AUTH_PASS_LEN,
625                                        AUTH_PASS_LEN);
626                 }
627
628                 fr_MD5Final(digest, &context);
629                 for (i = 0; i < AUTH_PASS_LEN; i++) {
630                         passwd[i + 2 + n] ^= digest[i];
631                 }
632         }
633         memcpy(output, passwd, len + 2);
634 }
635
636 /*
637  *      Returns the end of the data.
638  */
639 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
640                    const char *secret, const VALUE_PAIR *vp, uint8_t *start,
641                    size_t room)
642 {
643         uint32_t lvalue;
644         size_t len;
645         const uint8_t *data;
646         uint8_t *ptr = start;
647         uint8_t array[4];
648
649         /*
650          *      Set up the default sources for the data.
651          */
652         data = vp->vp_octets;
653         len = vp->length;
654
655         switch(vp->type) {
656         case PW_TYPE_STRING:
657         case PW_TYPE_OCTETS:
658         case PW_TYPE_IFID:
659         case PW_TYPE_IPV6ADDR:
660         case PW_TYPE_IPV6PREFIX:
661         case PW_TYPE_ABINARY:
662                 /* nothing more to do */
663                 break;
664
665         case PW_TYPE_BYTE:
666                 len = 1;        /* just in case */
667                 array[0] = vp->vp_integer & 0xff;
668                 data = array;
669                 break;
670
671         case PW_TYPE_SHORT:
672                 len = 2;        /* just in case */
673                 array[0] = (vp->vp_integer >> 8) & 0xff;
674                 array[1] = vp->vp_integer & 0xff;
675                 data = array;
676                 break;
677
678         case PW_TYPE_INTEGER:
679                 len = 4;        /* just in case */
680                 lvalue = htonl(vp->vp_integer);
681                 memcpy(array, &lvalue, sizeof(lvalue));
682                 data = array;
683                 break;
684
685         case PW_TYPE_IPADDR:
686                 data = (const uint8_t *) &vp->vp_ipaddr;
687                 len = 4;        /* just in case */
688                 break;
689
690                 /*
691                  *  There are no tagged date attributes.
692                  */
693         case PW_TYPE_DATE:
694                 lvalue = htonl(vp->vp_date);
695                 data = (const uint8_t *) &lvalue;
696                 len = 4;        /* just in case */
697                 break;
698
699         case PW_TYPE_SIGNED:
700         {
701                 int32_t slvalue;
702
703                 len = 4;        /* just in case */
704                 slvalue = htonl(vp->vp_signed);
705                 memcpy(array, &slvalue, sizeof(slvalue));
706                 break;
707         }
708
709         case PW_TYPE_TLV:
710                 data = vp->vp_tlv;
711                 if (!data) {
712                         fr_strerror_printf("ERROR: Cannot encode NULL TLV");
713                         return -1;
714                 }
715                 if (vp->length > room) return 0; /* can't chop TLVs to fit */
716                 break;
717
718         default:                /* unknown type: ignore it */
719                 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
720                 return -1;
721         }
722
723         /*
724          *      Bound the data to the calling size
725          */
726         if (len > room) len = room;
727
728         /*
729          *      Encrypt the various password styles
730          *
731          *      Attributes with encrypted values MUST be less than
732          *      128 bytes long.
733          */
734         switch (vp->flags.encrypt) {
735         case FLAG_ENCRYPT_USER_PASSWORD:
736                 make_passwd(ptr, &len, data, len,
737                             secret, packet->vector);
738                 break;
739
740         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
741                 /*
742                  *      Check if there's enough room.  If there isn't,
743                  *      we discard the attribute.
744                  *
745                  *      This is ONLY a problem if we have multiple VSA's
746                  *      in one Vendor-Specific, though.
747                  */
748                 if (room < 19) return 0;
749
750                 switch (packet->code) {
751                 case PW_AUTHENTICATION_ACK:
752                 case PW_AUTHENTICATION_REJECT:
753                 case PW_ACCESS_CHALLENGE:
754                 default:
755                         if (!original) {
756                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
757                                 return -1;
758                         }
759                         ptr[0] = vp->flags.tag;
760                         make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
761                                            secret, original->vector);
762                         break;
763                 case PW_ACCOUNTING_REQUEST:
764                 case PW_DISCONNECT_REQUEST:
765                 case PW_COA_REQUEST:
766                         ptr[0] = vp->flags.tag;
767                         make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
768                                            secret, packet->vector);
769                         break;
770                 }
771                 break;
772
773                 /*
774                  *      The code above ensures that this attribute
775                  *      always fits.
776                  */
777         case FLAG_ENCRYPT_ASCEND_SECRET:
778                 make_secret(ptr, packet->vector, secret, data);
779                 len = AUTH_VECTOR_LEN;
780                 break;
781
782
783         default:
784                 if (vp->flags.has_tag && TAG_VALID(vp->flags.tag)) {
785                         if (vp->type == PW_TYPE_STRING) {
786                                 if (len > (room - 1)) len = room - 1;
787                                 ptr[0] = vp->flags.tag;
788                                 ptr++;
789                         } else if (vp->type == PW_TYPE_INTEGER) {
790                                 array[0] = vp->flags.tag;
791                         } /* else it can't be any other type */
792                 }
793                 memcpy(ptr, data, len);
794                 break;
795         } /* switch over encryption flags */
796
797         return len + (ptr - start);;
798 }
799
800
801 static int rad_vp2rfc(const RADIUS_PACKET *packet,
802                       const RADIUS_PACKET *original,
803                       const char *secret, const VALUE_PAIR *vp,
804                       unsigned int attribute, uint8_t *ptr, size_t room)
805 {
806         int len;
807
808         if (room < 2) return 0;
809
810         ptr[0] = attribute & 0xff; /* NOT vp->attribute */
811         ptr[1] = 2;
812
813         len = vp2data(packet, original, secret, vp, ptr + 2, room - 2);
814         if (len < 0) return len;
815
816         ptr[1] += len;
817
818         return ptr[1];
819 }
820
821
822 /*
823  *      Parse a data structure into a RADIUS attribute.
824  */
825 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
826                 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
827                 size_t room)
828 {
829         int             vendorcode;
830         int             len, total_length;
831         uint32_t        lvalue;
832         uint8_t         *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
833         uint8_t         *sub_length_ptr; /* evil */
834
835         ptr = start;
836         vendorcode = total_length = 0;
837         length_ptr = vsa_length_ptr = tlv_length_ptr = sub_length_ptr = NULL;
838
839         /*
840          *      For interoperability, always put vendor attributes
841          *      into their own VSA.
842          */
843         if ((vendorcode = vp->vendor) == 0) {
844                 len = rad_vp2rfc(packet, original, secret, vp,
845                                  vp->attribute, start, room);
846                 if (len < 0) return -1;
847
848                 /*
849                  *      RFC 2865 section 5 says that zero-length
850                  *      attributes MUST NOT be sent.
851                  *
852                  *      ... and the WiMAX forum ignores
853                  *      this... because of one vendor.  Don't they
854                  *      have anything better to do with their time?
855                  */
856                 if ((len == 0) &&
857                     (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
858
859                 return len;
860
861         } else {
862                 int vsa_tlen = 1;
863                 int vsa_llen = 1;
864                 int vsa_offset = 0;
865                 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
866
867                 /*
868                  *      This must be an RFC-format attribute.  If it
869                  *      wasn't, then the "decode" function would have
870                  *      made a Vendor-Specific attribute (i.e. type
871                  *      26), and we would have "vendorcode == 0" here.
872                  */
873                 if (dv) {
874                         vsa_tlen = dv->type;
875                         vsa_llen = dv->length;
876                         if (dv->flags) vsa_offset = 1;
877                 }
878
879                 if (room < (6 + vsa_tlen + vsa_llen + vsa_offset)) return 0;
880                 room -= 6 + vsa_tlen + vsa_llen + vsa_offset;
881
882                 /*
883                  *      Build a VSA header.
884                  */
885                 *ptr++ = PW_VENDOR_SPECIFIC;
886                 vsa_length_ptr = ptr;
887                 *ptr++ = 6;
888                 lvalue = htonl(vendorcode);
889                 memcpy(ptr, &lvalue, 4);
890                 ptr += 4;
891                 total_length += 6;
892
893                 switch (vsa_tlen) {
894                 case 1:
895                         ptr[0] = (vp->attribute & 0xFF);
896                         break;
897
898                 case 2:
899                         ptr[0] = ((vp->attribute >> 8) & 0xFF);
900                         ptr[1] = (vp->attribute & 0xFF);
901                         break;
902
903                 case 4:
904                         ptr[0] = 0;
905                         ptr[1] = 0;
906                         ptr[2] = ((vp->attribute >> 8) & 0xFF);
907                         ptr[3] = (vp->attribute & 0xFF);
908                         break;
909
910                 default:
911                         return 0; /* silently discard it */
912                 }
913                 ptr += vsa_tlen;
914
915                 switch (vsa_llen) {
916                 case 0:
917                         length_ptr = vsa_length_ptr;
918                         vsa_length_ptr = NULL;
919                         break;
920                 case 1:
921                         ptr[0] = 0;
922                         length_ptr = ptr;
923                         break;
924                 case 2:
925                         ptr[0] = 0;
926                         ptr[1] = 0;
927                         length_ptr = ptr + 1;
928                         break;
929
930                 default:
931                         return 0; /* silently discard it */
932                 }
933                 ptr += vsa_llen;
934
935                 /*
936                  *      Allow for some continuation.
937                  */
938                 if (vsa_offset) {
939                         ptr[0] = 0x00;
940                         ptr++;
941
942                         /*
943                          *      Ignore TLVs that don't have data, OR
944                          *      have too much data to fit in the
945                          *      packet, OR have too much data to fit
946                          *      in the attribute
947                          *
948                          *      This shouldn't happen in normal
949                          *      operation, as the code assumes that
950                          *      the "tlv" type shouldn't be used.
951                          */
952                         if (vp->flags.has_tlv &&
953                             (!vp->vp_tlv || (vp->length > room) ||
954
955                              /*
956                               *         6 + 1 (vsa_tlen) + 1 (vsa_llen)
957                               *         + 1 (vsa_offset).
958                               */
959                              (vp->length > (255 - 9)))) return 0;
960
961
962                         /*
963                          *      sub-TLV's can only be in one format.
964                          */
965                         if (vp->flags.is_tlv) {
966                                 if (room < 2) return 0;
967                                 room -= 2;
968
969                                 *(ptr++) = (vp->attribute & 0xff00) >> 8;
970                                 tlv_length_ptr = ptr;
971                                 *(ptr++) = 2;
972                                 vsa_offset += 2;
973
974                                 /*
975                                  *      WiMAX is like sticking knitting
976                                  *      needles up your nose, and claiming
977                                  *      you like it.
978                                  */
979                                 if ((vp->attribute & 0xff0000) != 0) {
980                                         *(ptr++) = (vp->attribute >> 16) & 0xff;
981                                         sub_length_ptr = ptr;
982                                         *(ptr++) = 2;
983                                         vsa_offset += 2;
984                                         *tlv_length_ptr += 2;
985                                 }
986                         }
987                 }
988
989                 total_length += vsa_tlen + vsa_llen + vsa_offset;
990                 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
991                 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
992         }
993
994         len = vp2data(packet, original, secret, vp, ptr, room);
995         if (len < 0) return len;
996
997         /*
998          *      Update the various lengths.
999          */
1000         *length_ptr += len;
1001         if (vsa_length_ptr) *vsa_length_ptr += len;
1002         if (tlv_length_ptr) *tlv_length_ptr += len;
1003         if (sub_length_ptr) *sub_length_ptr += len;
1004         ptr += len;
1005         total_length += len;
1006
1007         return total_length;    /* of attribute */
1008 }
1009
1010 /*
1011  *  Swap 123a -> 0321
1012  */
1013 #define REORDER(x) ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000 >> 24))
1014
1015 static int rad_encode_wimax(const RADIUS_PACKET *packet,
1016                             const RADIUS_PACKET *original,
1017                             const char *secret, VALUE_PAIR *reply,
1018                             uint8_t *start, size_t room)
1019 {
1020         int len, total_len = 0;
1021         uint8_t *wimax = NULL;
1022         uint8_t *ptr = start;
1023         uint32_t maxattr;
1024         VALUE_PAIR *vp = reply;
1025
1026         /*
1027          *      Swap the order of the WiMAX hacks, to make later
1028          *      comparisons easier.
1029          */
1030         maxattr = REORDER(vp->attribute);
1031
1032 redo:
1033         len = rad_vp2attr(packet, original, secret, vp, ptr,
1034                           (start + room) - ptr);
1035         if (len <= 0) return total_len;
1036
1037         /*
1038          *      After adding an attribute with the simplest encoding,
1039          *      check to see if we can append it to the previous one.
1040          */
1041         if (wimax) {
1042                 if ((wimax[1] + (ptr[1] - 6)) <= 255) {
1043                         unsigned int hack;
1044
1045                         hack = ptr[7] - 3;
1046                         memmove(ptr, ptr + 9, hack);
1047                         wimax[1] += hack;
1048                         wimax[7] += hack;
1049                         len -= 9;
1050
1051                         /*
1052                          *      See if we can nest sub-TLVs, too, in
1053                          *      order to shorten the encoding.
1054                          */
1055
1056                 } else {
1057                         wimax[8] = 0x80; /* set continuation */
1058                         wimax = ptr;
1059                 }
1060         } else {
1061                 wimax = ptr;
1062         }
1063
1064         total_len += len;
1065         ptr += len;
1066
1067         vp->flags.encoded = 1;
1068         vp = vp->next;
1069
1070         /*
1071          *      Look at the NEXT tlv.  Ensure that we encode
1072          *      attributes into a common VSA *only* if they are for
1073          *      the same WiMAX VSA, AND if the TLVs are in numerically
1074          *      increasing order.
1075          */
1076         if (vp && vp->flags.is_tlv && (reply->vendor == vp->vendor) &&
1077             ((reply->attribute & 0xff) == (vp->attribute & 0xff))) {
1078                 uint32_t attr;
1079
1080                 attr = REORDER(vp->attribute);
1081                 if (attr >= maxattr) {
1082                         maxattr = attr;
1083                         goto redo;
1084                 }
1085         }
1086
1087         return total_len;
1088 }
1089
1090
1091 /*
1092  *      Encode a packet.
1093  */
1094 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1095                const char *secret)
1096 {
1097         radius_packet_t *hdr;
1098         uint8_t         *ptr;
1099         uint16_t        total_length;
1100         int             len;
1101         VALUE_PAIR      *reply;
1102         const char      *what;
1103         char            ip_buffer[128];
1104
1105         /*
1106          *      A 4K packet, aligned on 64-bits.
1107          */
1108         uint64_t        data[MAX_PACKET_LEN / sizeof(uint64_t)];
1109
1110         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1111                 what = fr_packet_codes[packet->code];
1112         } else {
1113                 what = "Reply";
1114         }
1115
1116         DEBUG("Sending %s of id %d to %s port %d\n",
1117               what, packet->id,
1118               inet_ntop(packet->dst_ipaddr.af,
1119                         &packet->dst_ipaddr.ipaddr,
1120                         ip_buffer, sizeof(ip_buffer)),
1121               packet->dst_port);
1122
1123         /*
1124          *      Double-check some things based on packet code.
1125          */
1126         switch (packet->code) {
1127         case PW_AUTHENTICATION_ACK:
1128         case PW_AUTHENTICATION_REJECT:
1129         case PW_ACCESS_CHALLENGE:
1130                 if (!original) {
1131                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1132                         return -1;
1133                 }
1134                 break;
1135
1136                 /*
1137                  *      These packet vectors start off as all zero.
1138                  */
1139         case PW_ACCOUNTING_REQUEST:
1140         case PW_DISCONNECT_REQUEST:
1141         case PW_COA_REQUEST:
1142                 memset(packet->vector, 0, sizeof(packet->vector));
1143                 break;
1144
1145         default:
1146                 break;
1147         }
1148
1149         /*
1150          *      Use memory on the stack, until we know how
1151          *      large the packet will be.
1152          */
1153         hdr = (radius_packet_t *) data;
1154
1155         /*
1156          *      Build standard header
1157          */
1158         hdr->code = packet->code;
1159         hdr->id = packet->id;
1160
1161         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1162
1163         total_length = AUTH_HDR_LEN;
1164
1165         /*
1166          *      Load up the configuration values for the user
1167          */
1168         ptr = hdr->data;
1169         packet->offset = 0;
1170
1171         /*
1172          *      FIXME: Loop twice over the reply list.  The first time,
1173          *      calculate the total length of data.  The second time,
1174          *      allocate the memory, and fill in the VP's.
1175          *
1176          *      Hmm... this may be slower than just doing a small
1177          *      memcpy.
1178          */
1179
1180         /*
1181          *      Loop over the reply attributes for the packet.
1182          */
1183         for (reply = packet->vps; reply; reply = reply->next) {
1184                 /*
1185                  *      Ignore non-wire attributes
1186                  */
1187                 if ((reply->vendor == 0) &&
1188                     ((reply->attribute & 0xFFFF) > 0xff)) {
1189 #ifndef NDEBUG
1190                         /*
1191                          *      Permit the admin to send BADLY formatted
1192                          *      attributes with a debug build.
1193                          */
1194                         if (reply->attribute == PW_RAW_ATTRIBUTE) {
1195                                 memcpy(ptr, reply->vp_octets, reply->length);
1196                                 len = reply->length;
1197                                 goto next;
1198                         }
1199 #endif
1200                         continue;
1201                 }
1202
1203                 /*
1204                  *      Set the Message-Authenticator to the correct
1205                  *      length and initial value.
1206                  */
1207                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1208                         reply->length = AUTH_VECTOR_LEN;
1209                         memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1210
1211                         /*
1212                          *      Cache the offset to the
1213                          *      Message-Authenticator
1214                          */
1215                         packet->offset = total_length;
1216                 }
1217
1218                 /*
1219                  *      Print out ONLY the attributes which
1220                  *      we're sending over the wire, and print
1221                  *      them out BEFORE they're encrypted.
1222                  */
1223                 debug_pair(reply);
1224
1225                 /*
1226                  *      Skip attributes that are encoded.
1227                  */
1228                 if (reply->flags.encoded) continue;
1229
1230                 if (reply->flags.is_tlv) {
1231                         len = rad_encode_wimax(packet, original, secret,
1232                                                reply, ptr,
1233                                                ((uint8_t *) data) + sizeof(data) - ptr);
1234                 } else {
1235
1236                         len = rad_vp2attr(packet, original, secret, reply, ptr,
1237                                           ((uint8_t *) data) + sizeof(data) - ptr);
1238                 }
1239
1240                 if (len < 0) return -1;
1241
1242         next:
1243                 ptr += len;
1244                 total_length += len;
1245         } /* done looping over all attributes */
1246
1247         /*
1248          *      Fill in the rest of the fields, and copy the data over
1249          *      from the local stack to the newly allocated memory.
1250          *
1251          *      Yes, all this 'memcpy' is slow, but it means
1252          *      that we only allocate the minimum amount of
1253          *      memory for a request.
1254          */
1255         packet->data_len = total_length;
1256         packet->data = (uint8_t *) malloc(packet->data_len);
1257         if (!packet->data) {
1258                 fr_strerror_printf("Out of memory");
1259                 return -1;
1260         }
1261
1262         memcpy(packet->data, hdr, packet->data_len);
1263         hdr = (radius_packet_t *) packet->data;
1264
1265         total_length = htons(total_length);
1266         memcpy(hdr->length, &total_length, sizeof(total_length));
1267
1268         return 0;
1269 }
1270
1271
1272 /*
1273  *      Sign a previously encoded packet.
1274  */
1275 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1276              const char *secret)
1277 {
1278         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1279
1280         /*
1281          *      It wasn't assigned an Id, this is bad!
1282          */
1283         if (packet->id < 0) {
1284                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1285                 return -1;
1286         }
1287
1288         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1289             (packet->offset < 0)) {
1290                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1291                 return -1;
1292         }
1293
1294         /*
1295          *      If there's a Message-Authenticator, update it
1296          *      now, BEFORE updating the authentication vector.
1297          */
1298         if (packet->offset > 0) {
1299                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1300
1301                 switch (packet->code) {
1302                 case PW_ACCOUNTING_REQUEST:
1303                 case PW_ACCOUNTING_RESPONSE:
1304                 case PW_DISCONNECT_REQUEST:
1305                 case PW_DISCONNECT_ACK:
1306                 case PW_DISCONNECT_NAK:
1307                 case PW_COA_REQUEST:
1308                 case PW_COA_ACK:
1309                 case PW_COA_NAK:
1310                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1311                         break;
1312
1313                 case PW_AUTHENTICATION_ACK:
1314                 case PW_AUTHENTICATION_REJECT:
1315                 case PW_ACCESS_CHALLENGE:
1316                         if (!original) {
1317                                 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1318                                 return -1;
1319                         }
1320                         memcpy(hdr->vector, original->vector,
1321                                AUTH_VECTOR_LEN);
1322                         break;
1323
1324                 default:        /* others have vector already set to zero */
1325                         break;
1326
1327                 }
1328
1329                 /*
1330                  *      Set the authentication vector to zero,
1331                  *      calculate the signature, and put it
1332                  *      into the Message-Authenticator
1333                  *      attribute.
1334                  */
1335                 fr_hmac_md5(packet->data, packet->data_len,
1336                             (const uint8_t *) secret, strlen(secret),
1337                             calc_auth_vector);
1338                 memcpy(packet->data + packet->offset + 2,
1339                        calc_auth_vector, AUTH_VECTOR_LEN);
1340
1341                 /*
1342                  *      Copy the original request vector back
1343                  *      to the raw packet.
1344                  */
1345                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1346         }
1347
1348         /*
1349          *      Switch over the packet code, deciding how to
1350          *      sign the packet.
1351          */
1352         switch (packet->code) {
1353                 /*
1354                  *      Request packets are not signed, bur
1355                  *      have a random authentication vector.
1356                  */
1357         case PW_AUTHENTICATION_REQUEST:
1358         case PW_STATUS_SERVER:
1359                 break;
1360
1361                 /*
1362                  *      Reply packets are signed with the
1363                  *      authentication vector of the request.
1364                  */
1365         default:
1366                 {
1367                         uint8_t digest[16];
1368
1369                         FR_MD5_CTX      context;
1370                         fr_MD5Init(&context);
1371                         fr_MD5Update(&context, packet->data, packet->data_len);
1372                         fr_MD5Update(&context, (const uint8_t *) secret,
1373                                      strlen(secret));
1374                         fr_MD5Final(digest, &context);
1375
1376                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1377                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1378                         break;
1379                 }
1380         }/* switch over packet codes */
1381
1382         return 0;
1383 }
1384
1385 /*
1386  *      Reply to the request.  Also attach
1387  *      reply attribute value pairs and any user message provided.
1388  */
1389 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1390              const char *secret)
1391 {
1392         VALUE_PAIR              *reply;
1393         const char              *what;
1394         char                    ip_buffer[128];
1395
1396         /*
1397          *      Maybe it's a fake packet.  Don't send it.
1398          */
1399         if (!packet || (packet->sockfd < 0)) {
1400                 return 0;
1401         }
1402
1403         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1404                 what = fr_packet_codes[packet->code];
1405         } else {
1406                 what = "Reply";
1407         }
1408
1409         /*
1410          *  First time through, allocate room for the packet
1411          */
1412         if (!packet->data) {
1413                 /*
1414                  *      Encode the packet.
1415                  */
1416                 if (rad_encode(packet, original, secret) < 0) {
1417                         return -1;
1418                 }
1419
1420                 /*
1421                  *      Re-sign it, including updating the
1422                  *      Message-Authenticator.
1423                  */
1424                 if (rad_sign(packet, original, secret) < 0) {
1425                         return -1;
1426                 }
1427
1428                 /*
1429                  *      If packet->data points to data, then we print out
1430                  *      the VP list again only for debugging.
1431                  */
1432         } else if (fr_debug_flag) {
1433                 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1434                       inet_ntop(packet->dst_ipaddr.af,
1435                                 &packet->dst_ipaddr.ipaddr,
1436                                 ip_buffer, sizeof(ip_buffer)),
1437                       packet->dst_port);
1438
1439                 for (reply = packet->vps; reply; reply = reply->next) {
1440                         if ((reply->vendor == 0) &&
1441                             ((reply->attribute & 0xFFFF) > 0xff)) continue;
1442                         debug_pair(reply);
1443                 }
1444         }
1445
1446         /*
1447          *      And send it on it's way.
1448          */
1449         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1450                           &packet->src_ipaddr, packet->src_port,
1451                           &packet->dst_ipaddr, packet->dst_port);
1452 }
1453
1454 /*
1455  *      Do a comparison of two authentication digests by comparing
1456  *      the FULL digest.  Otehrwise, the server can be subject to
1457  *      timing attacks that allow attackers find a valid message
1458  *      authenticator.
1459  *
1460  *      http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1461  */
1462 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1463 {
1464         int result = 0;
1465         size_t i;
1466
1467         for (i = 0; i < length; i++) {
1468                 result |= a[i] ^ b[i];
1469         }
1470
1471         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
1472 }
1473
1474
1475 /*
1476  *      Validates the requesting client NAS.  Calculates the
1477  *      signature based on the clients private key.
1478  */
1479 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1480 {
1481         uint8_t         digest[AUTH_VECTOR_LEN];
1482         FR_MD5_CTX              context;
1483
1484         /*
1485          *      Zero out the auth_vector in the received packet.
1486          *      Then append the shared secret to the received packet,
1487          *      and calculate the MD5 sum. This must be the same
1488          *      as the original MD5 sum (packet->vector).
1489          */
1490         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1491
1492         /*
1493          *  MD5(packet + secret);
1494          */
1495         fr_MD5Init(&context);
1496         fr_MD5Update(&context, packet->data, packet->data_len);
1497         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1498         fr_MD5Final(digest, &context);
1499
1500         /*
1501          *      Return 0 if OK, 2 if not OK.
1502          */
1503         if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1504         return 0;
1505 }
1506
1507
1508 /*
1509  *      Validates the requesting client NAS.  Calculates the
1510  *      signature based on the clients private key.
1511  */
1512 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1513                             const char *secret)
1514 {
1515         uint8_t         calc_digest[AUTH_VECTOR_LEN];
1516         FR_MD5_CTX              context;
1517
1518         /*
1519          *      Very bad!
1520          */
1521         if (original == NULL) {
1522                 return 3;
1523         }
1524
1525         /*
1526          *  Copy the original vector in place.
1527          */
1528         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1529
1530         /*
1531          *  MD5(packet + secret);
1532          */
1533         fr_MD5Init(&context);
1534         fr_MD5Update(&context, packet->data, packet->data_len);
1535         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1536         fr_MD5Final(calc_digest, &context);
1537
1538         /*
1539          *  Copy the packet's vector back to the packet.
1540          */
1541         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1542
1543         /*
1544          *      Return 0 if OK, 2 if not OK.
1545          */
1546         if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1547         return 0;
1548 }
1549
1550
1551 /*
1552  *      See if the data pointed to by PTR is a valid RADIUS packet.
1553  *
1554  *      packet is not 'const * const' because we may update data_len,
1555  *      if there's more data in the UDP packet than in the RADIUS packet.
1556  */
1557 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1558 {
1559         uint8_t                 *attr;
1560         int                     totallen;
1561         int                     count;
1562         radius_packet_t         *hdr;
1563         char                    host_ipaddr[128];
1564         int                     require_ma = 0;
1565         int                     seen_ma = 0;
1566         int                     num_attributes;
1567
1568         /*
1569          *      Check for packets smaller than the packet header.
1570          *
1571          *      RFC 2865, Section 3., subsection 'length' says:
1572          *
1573          *      "The minimum length is 20 ..."
1574          */
1575         if (packet->data_len < AUTH_HDR_LEN) {
1576                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1577                            inet_ntop(packet->src_ipaddr.af,
1578                                      &packet->src_ipaddr.ipaddr,
1579                                      host_ipaddr, sizeof(host_ipaddr)),
1580                                    (int) packet->data_len, AUTH_HDR_LEN);
1581                 return 0;
1582         }
1583
1584         /*
1585          *      RFC 2865, Section 3., subsection 'length' says:
1586          *
1587          *      " ... and maximum length is 4096."
1588          */
1589         if (packet->data_len > MAX_PACKET_LEN) {
1590                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1591                            inet_ntop(packet->src_ipaddr.af,
1592                                      &packet->src_ipaddr.ipaddr,
1593                                      host_ipaddr, sizeof(host_ipaddr)),
1594                                    (int) packet->data_len, MAX_PACKET_LEN);
1595                 return 0;
1596         }
1597
1598         /*
1599          *      Check for packets with mismatched size.
1600          *      i.e. We've received 128 bytes, and the packet header
1601          *      says it's 256 bytes long.
1602          */
1603         totallen = (packet->data[2] << 8) | packet->data[3];
1604         hdr = (radius_packet_t *)packet->data;
1605
1606         /*
1607          *      Code of 0 is not understood.
1608          *      Code of 16 or greate is not understood.
1609          */
1610         if ((hdr->code == 0) ||
1611             (hdr->code >= FR_MAX_PACKET_CODE)) {
1612                 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1613                            inet_ntop(packet->src_ipaddr.af,
1614                                      &packet->src_ipaddr.ipaddr,
1615                                      host_ipaddr, sizeof(host_ipaddr)),
1616                            hdr->code);
1617                 return 0;
1618         }
1619
1620         /*
1621          *      Message-Authenticator is required in Status-Server
1622          *      packets, otherwise they can be trivially forged.
1623          */
1624         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1625
1626         /*
1627          *      It's also required if the caller asks for it.
1628          */
1629         if (flags) require_ma = 1;
1630
1631         /*
1632          *      Repeat the length checks.  This time, instead of
1633          *      looking at the data we received, look at the value
1634          *      of the 'length' field inside of the packet.
1635          *
1636          *      Check for packets smaller than the packet header.
1637          *
1638          *      RFC 2865, Section 3., subsection 'length' says:
1639          *
1640          *      "The minimum length is 20 ..."
1641          */
1642         if (totallen < AUTH_HDR_LEN) {
1643                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1644                            inet_ntop(packet->src_ipaddr.af,
1645                                      &packet->src_ipaddr.ipaddr,
1646                                      host_ipaddr, sizeof(host_ipaddr)),
1647                            totallen, AUTH_HDR_LEN);
1648                 return 0;
1649         }
1650
1651         /*
1652          *      And again, for the value of the 'length' field.
1653          *
1654          *      RFC 2865, Section 3., subsection 'length' says:
1655          *
1656          *      " ... and maximum length is 4096."
1657          */
1658         if (totallen > MAX_PACKET_LEN) {
1659                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1660                            inet_ntop(packet->src_ipaddr.af,
1661                                      &packet->src_ipaddr.ipaddr,
1662                                      host_ipaddr, sizeof(host_ipaddr)),
1663                            totallen, MAX_PACKET_LEN);
1664                 return 0;
1665         }
1666
1667         /*
1668          *      RFC 2865, Section 3., subsection 'length' says:
1669          *
1670          *      "If the packet is shorter than the Length field
1671          *      indicates, it MUST be silently discarded."
1672          *
1673          *      i.e. No response to the NAS.
1674          */
1675         if (packet->data_len < totallen) {
1676                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1677                            inet_ntop(packet->src_ipaddr.af,
1678                                      &packet->src_ipaddr.ipaddr,
1679                                      host_ipaddr, sizeof(host_ipaddr)),
1680                                    (int) packet->data_len, totallen);
1681                 return 0;
1682         }
1683
1684         /*
1685          *      RFC 2865, Section 3., subsection 'length' says:
1686          *
1687          *      "Octets outside the range of the Length field MUST be
1688          *      treated as padding and ignored on reception."
1689          */
1690         if (packet->data_len > totallen) {
1691                 /*
1692                  *      We're shortening the packet below, but just
1693                  *      to be paranoid, zero out the extra data.
1694                  */
1695                 memset(packet->data + totallen, 0, packet->data_len - totallen);
1696                 packet->data_len = totallen;
1697         }
1698
1699         /*
1700          *      Walk through the packet's attributes, ensuring that
1701          *      they add up EXACTLY to the size of the packet.
1702          *
1703          *      If they don't, then the attributes either under-fill
1704          *      or over-fill the packet.  Any parsing of the packet
1705          *      is impossible, and will result in unknown side effects.
1706          *
1707          *      This would ONLY happen with buggy RADIUS implementations,
1708          *      or with an intentional attack.  Either way, we do NOT want
1709          *      to be vulnerable to this problem.
1710          */
1711         attr = hdr->data;
1712         count = totallen - AUTH_HDR_LEN;
1713         num_attributes = 0;
1714
1715         while (count > 0) {
1716                 /*
1717                  *      Attribute number zero is NOT defined.
1718                  */
1719                 if (attr[0] == 0) {
1720                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1721                                    inet_ntop(packet->src_ipaddr.af,
1722                                              &packet->src_ipaddr.ipaddr,
1723                                              host_ipaddr, sizeof(host_ipaddr)));
1724                         return 0;
1725                 }
1726
1727                 /*
1728                  *      Attributes are at LEAST as long as the ID & length
1729                  *      fields.  Anything shorter is an invalid attribute.
1730                  */
1731                 if (attr[1] < 2) {
1732                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1733                                    inet_ntop(packet->src_ipaddr.af,
1734                                              &packet->src_ipaddr.ipaddr,
1735                                              host_ipaddr, sizeof(host_ipaddr)),
1736                                    attr[0]);
1737                         return 0;
1738                 }
1739
1740                 /*
1741                  *      Sanity check the attributes for length.
1742                  */
1743                 switch (attr[0]) {
1744                 default:        /* don't do anything by default */
1745                         break;
1746
1747                         /*
1748                          *      If there's an EAP-Message, we require
1749                          *      a Message-Authenticator.
1750                          */
1751                 case PW_EAP_MESSAGE:
1752                         require_ma = 1;
1753                         break;
1754
1755                 case PW_MESSAGE_AUTHENTICATOR:
1756                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1757                                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1758                                            inet_ntop(packet->src_ipaddr.af,
1759                                                      &packet->src_ipaddr.ipaddr,
1760                                                      host_ipaddr, sizeof(host_ipaddr)),
1761                                            attr[1] - 2);
1762                                 return 0;
1763                         }
1764                         seen_ma = 1;
1765                         break;
1766                 }
1767
1768                 /*
1769                  *      FIXME: Look up the base 255 attributes in the
1770                  *      dictionary, and switch over their type.  For
1771                  *      integer/date/ip, the attribute length SHOULD
1772                  *      be 6.
1773                  */
1774                 count -= attr[1];       /* grab the attribute length */
1775                 attr += attr[1];
1776                 num_attributes++;       /* seen one more attribute */
1777         }
1778
1779         /*
1780          *      If the attributes add up to a packet, it's allowed.
1781          *
1782          *      If not, we complain, and throw the packet away.
1783          */
1784         if (count != 0) {
1785                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1786                            inet_ntop(packet->src_ipaddr.af,
1787                                      &packet->src_ipaddr.ipaddr,
1788                                      host_ipaddr, sizeof(host_ipaddr)));
1789                 return 0;
1790         }
1791
1792         /*
1793          *      If we're configured to look for a maximum number of
1794          *      attributes, and we've seen more than that maximum,
1795          *      then throw the packet away, as a possible DoS.
1796          */
1797         if ((fr_max_attributes > 0) &&
1798             (num_attributes > fr_max_attributes)) {
1799                 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1800                            inet_ntop(packet->src_ipaddr.af,
1801                                      &packet->src_ipaddr.ipaddr,
1802                                      host_ipaddr, sizeof(host_ipaddr)),
1803                            num_attributes, fr_max_attributes);
1804                 return 0;
1805         }
1806
1807         /*
1808          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1809          *
1810          *      A packet with an EAP-Message attribute MUST also have
1811          *      a Message-Authenticator attribute.
1812          *
1813          *      A Message-Authenticator all by itself is OK, though.
1814          *
1815          *      Similarly, Status-Server packets MUST contain
1816          *      Message-Authenticator attributes.
1817          */
1818         if (require_ma && ! seen_ma) {
1819                 fr_strerror_printf("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1820                            inet_ntop(packet->src_ipaddr.af,
1821                                      &packet->src_ipaddr.ipaddr,
1822                                      host_ipaddr, sizeof(host_ipaddr)));
1823                 return 0;
1824         }
1825
1826         /*
1827          *      Fill RADIUS header fields
1828          */
1829         packet->code = hdr->code;
1830         packet->id = hdr->id;
1831         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1832
1833         return 1;
1834 }
1835
1836
1837 /*
1838  *      Receive UDP client requests, and fill in
1839  *      the basics of a RADIUS_PACKET structure.
1840  */
1841 RADIUS_PACKET *rad_recv(int fd, int flags)
1842 {
1843         int sock_flags = 0;
1844         RADIUS_PACKET           *packet;
1845
1846         /*
1847          *      Allocate the new request data structure
1848          */
1849         if ((packet = malloc(sizeof(*packet))) == NULL) {
1850                 fr_strerror_printf("out of memory");
1851                 return NULL;
1852         }
1853         memset(packet, 0, sizeof(*packet));
1854
1855         if (flags & 0x02) {
1856                 sock_flags = MSG_PEEK;
1857                 flags &= ~0x02;
1858         }
1859
1860         packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1861                                         &packet->src_ipaddr, &packet->src_port,
1862                                         &packet->dst_ipaddr, &packet->dst_port);
1863
1864         /*
1865          *      Check for socket errors.
1866          */
1867         if (packet->data_len < 0) {
1868                 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1869                 /* packet->data is NULL */
1870                 free(packet);
1871                 return NULL;
1872         }
1873
1874         /*
1875          *      If the packet is too big, then rad_recvfrom did NOT
1876          *      allocate memory.  Instead, it just discarded the
1877          *      packet.
1878          */
1879         if (packet->data_len > MAX_PACKET_LEN) {
1880                 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1881                 /* packet->data is NULL */
1882                 free(packet);
1883                 return NULL;
1884         }
1885
1886         /*
1887          *      Read no data.  Continue.
1888          *      This check is AFTER the MAX_PACKET_LEN check above, because
1889          *      if the packet is larger than MAX_PACKET_LEN, we also have
1890          *      packet->data == NULL
1891          */
1892         if ((packet->data_len == 0) || !packet->data) {
1893                 fr_strerror_printf("Empty packet: Socket is not ready.");
1894                 free(packet);
1895                 return NULL;
1896         }
1897
1898         /*
1899          *      See if it's a well-formed RADIUS packet.
1900          */
1901         if (!rad_packet_ok(packet, flags)) {
1902                 rad_free(&packet);
1903                 return NULL;
1904         }
1905
1906         /*
1907          *      Remember which socket we read the packet from.
1908          */
1909         packet->sockfd = fd;
1910
1911         /*
1912          *      FIXME: Do even more filtering by only permitting
1913          *      certain IP's.  The problem is that we don't know
1914          *      how to do this properly for all possible clients...
1915          */
1916
1917         /*
1918          *      Explicitely set the VP list to empty.
1919          */
1920         packet->vps = NULL;
1921
1922         if (fr_debug_flag) {
1923                 char host_ipaddr[128];
1924
1925                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1926                         DEBUG("rad_recv: %s packet from host %s port %d",
1927                               fr_packet_codes[packet->code],
1928                               inet_ntop(packet->src_ipaddr.af,
1929                                         &packet->src_ipaddr.ipaddr,
1930                                         host_ipaddr, sizeof(host_ipaddr)),
1931                               packet->src_port);
1932                 } else {
1933                         DEBUG("rad_recv: Packet from host %s port %d code=%d",
1934                               inet_ntop(packet->src_ipaddr.af,
1935                                         &packet->src_ipaddr.ipaddr,
1936                                         host_ipaddr, sizeof(host_ipaddr)),
1937                               packet->src_port,
1938                               packet->code);
1939                 }
1940                 DEBUG(", id=%d, length=%d\n",
1941                       packet->id, (int) packet->data_len);
1942         }
1943
1944         return packet;
1945 }
1946
1947
1948 /*
1949  *      Verify the signature of a packet.
1950  */
1951 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1952                const char *secret)
1953 {
1954         uint8_t                 *ptr;
1955         int                     length;
1956         int                     attrlen;
1957
1958         if (!packet || !packet->data) return -1;
1959
1960         /*
1961          *      Before we allocate memory for the attributes, do more
1962          *      sanity checking.
1963          */
1964         ptr = packet->data + AUTH_HDR_LEN;
1965         length = packet->data_len - AUTH_HDR_LEN;
1966         while (length > 0) {
1967                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1968                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1969
1970                 attrlen = ptr[1];
1971
1972                 switch (ptr[0]) {
1973                 default:        /* don't do anything. */
1974                         break;
1975
1976                         /*
1977                          *      Note that more than one Message-Authenticator
1978                          *      attribute is invalid.
1979                          */
1980                 case PW_MESSAGE_AUTHENTICATOR:
1981                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1982                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1983
1984                         switch (packet->code) {
1985                         default:
1986                                 break;
1987
1988                         case PW_ACCOUNTING_REQUEST:
1989                         case PW_ACCOUNTING_RESPONSE:
1990                         case PW_DISCONNECT_REQUEST:
1991                         case PW_DISCONNECT_ACK:
1992                         case PW_DISCONNECT_NAK:
1993                         case PW_COA_REQUEST:
1994                         case PW_COA_ACK:
1995                         case PW_COA_NAK:
1996                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1997                                 break;
1998
1999                         case PW_AUTHENTICATION_ACK:
2000                         case PW_AUTHENTICATION_REJECT:
2001                         case PW_ACCESS_CHALLENGE:
2002                                 if (!original) {
2003                                         fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2004                                         return -1;
2005                                 }
2006                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2007                                 break;
2008                         }
2009
2010                         fr_hmac_md5(packet->data, packet->data_len,
2011                                     (const uint8_t *) secret, strlen(secret),
2012                                     calc_auth_vector);
2013                         if (digest_cmp(calc_auth_vector, msg_auth_vector,
2014                                    sizeof(calc_auth_vector)) != 0) {
2015                                 char buffer[32];
2016                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
2017                                            inet_ntop(packet->src_ipaddr.af,
2018                                                      &packet->src_ipaddr.ipaddr,
2019                                                      buffer, sizeof(buffer)));
2020                                 /* Silently drop packet, according to RFC 3579 */
2021                                 return -1;
2022                         } /* else the message authenticator was good */
2023
2024                         /*
2025                          *      Reinitialize Authenticators.
2026                          */
2027                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2028                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2029                         break;
2030                 } /* switch over the attributes */
2031
2032                 ptr += attrlen;
2033                 length -= attrlen;
2034         } /* loop over the packet, sanity checking the attributes */
2035
2036         /*
2037          *      It looks like a RADIUS packet, but we can't validate
2038          *      the signature.
2039          */
2040         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2041                 char buffer[32];
2042                 fr_strerror_printf("Received Unknown packet code %d "
2043                            "from client %s port %d: Cannot validate signature.",
2044                            packet->code,
2045                            inet_ntop(packet->src_ipaddr.af,
2046                                      &packet->src_ipaddr.ipaddr,
2047                                      buffer, sizeof(buffer)),
2048                            packet->src_port);
2049                 return -1;
2050         }
2051
2052         /*
2053          *      Calculate and/or verify digest.
2054          */
2055         switch(packet->code) {
2056                 int rcode;
2057                 char buffer[32];
2058
2059                 case PW_AUTHENTICATION_REQUEST:
2060                 case PW_STATUS_SERVER:
2061                         /*
2062                          *      The authentication vector is random
2063                          *      nonsense, invented by the client.
2064                          */
2065                         break;
2066
2067                 case PW_COA_REQUEST:
2068                 case PW_DISCONNECT_REQUEST:
2069                 case PW_ACCOUNTING_REQUEST:
2070                         if (calc_acctdigest(packet, secret) > 1) {
2071                                 fr_strerror_printf("Received %s packet "
2072                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
2073                                            fr_packet_codes[packet->code],
2074                                            inet_ntop(packet->src_ipaddr.af,
2075                                                      &packet->src_ipaddr.ipaddr,
2076                                                      buffer, sizeof(buffer)));
2077                                 return -1;
2078                         }
2079                         break;
2080
2081                         /* Verify the reply digest */
2082                 case PW_AUTHENTICATION_ACK:
2083                 case PW_AUTHENTICATION_REJECT:
2084                 case PW_ACCESS_CHALLENGE:
2085                 case PW_ACCOUNTING_RESPONSE:
2086                 case PW_DISCONNECT_ACK:
2087                 case PW_DISCONNECT_NAK:
2088                 case PW_COA_ACK:
2089                 case PW_COA_NAK:
2090                         rcode = calc_replydigest(packet, original, secret);
2091                         if (rcode > 1) {
2092                                 fr_strerror_printf("Received %s packet "
2093                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
2094                                            fr_packet_codes[packet->code],
2095                                            inet_ntop(packet->src_ipaddr.af,
2096                                                      &packet->src_ipaddr.ipaddr,
2097                                                      buffer, sizeof(buffer)),
2098                                            packet->src_port,
2099                                            rcode);
2100                                 return -1;
2101                         }
2102                         break;
2103
2104                 default:
2105                         fr_strerror_printf("Received Unknown packet code %d "
2106                                    "from client %s port %d: Cannot validate signature",
2107                                    packet->code,
2108                                    inet_ntop(packet->src_ipaddr.af,
2109                                              &packet->src_ipaddr.ipaddr,
2110                                                      buffer, sizeof(buffer)),
2111                                    packet->src_port);
2112                         return -1;
2113         }
2114
2115         return 0;
2116 }
2117
2118
2119 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2120                            const RADIUS_PACKET *original,
2121                            const char *secret, size_t length,
2122                            const uint8_t *data, VALUE_PAIR *vp)
2123 {
2124         int offset = 0;
2125
2126         /*
2127          *      If length is greater than 253, something is SERIOUSLY
2128          *      wrong.
2129          */
2130         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2131
2132         vp->length = length;
2133         vp->operator = T_OP_EQ;
2134         vp->next = NULL;
2135
2136         /*
2137          *      Handle tags.
2138          */
2139         if (vp->flags.has_tag) {
2140                 if (TAG_VALID(data[0]) ||
2141                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2142                         /*
2143                          *      Tunnel passwords REQUIRE a tag, even
2144                          *      if don't have a valid tag.
2145                          */
2146                         vp->flags.tag = data[0];
2147
2148                         if ((vp->type == PW_TYPE_STRING) ||
2149                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
2150                 }
2151         }
2152
2153         /*
2154          *      Copy the data to be decrypted
2155          */
2156         memcpy(&vp->vp_octets[0], data + offset, length - offset);
2157         vp->length -= offset;
2158
2159         /*
2160          *      Decrypt the attribute.
2161          */
2162         switch (vp->flags.encrypt) {
2163                 /*
2164                  *  User-Password
2165                  */
2166         case FLAG_ENCRYPT_USER_PASSWORD:
2167                 if (original) {
2168                         rad_pwdecode((char *)vp->vp_strvalue,
2169                                      vp->length, secret,
2170                                      original->vector);
2171                 } else {
2172                         rad_pwdecode((char *)vp->vp_strvalue,
2173                                      vp->length, secret,
2174                                      packet->vector);
2175                 }
2176                 if (vp->attribute == PW_USER_PASSWORD) {
2177                         vp->length = strlen(vp->vp_strvalue);
2178                 }
2179                 break;
2180
2181                 /*
2182                  *      Tunnel-Password's may go ONLY
2183                  *      in response packets.
2184                  */
2185         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2186                 if (!original) goto raw;
2187
2188                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2189                                         secret, original->vector) < 0) {
2190                         goto raw;
2191                 }
2192                 break;
2193
2194                 /*
2195                  *  Ascend-Send-Secret
2196                  *  Ascend-Receive-Secret
2197                  */
2198         case FLAG_ENCRYPT_ASCEND_SECRET:
2199                 if (!original) {
2200                         goto raw;
2201                 } else {
2202                         uint8_t my_digest[AUTH_VECTOR_LEN];
2203                         make_secret(my_digest,
2204                                     original->vector,
2205                                     secret, data);
2206                         memcpy(vp->vp_strvalue, my_digest,
2207                                AUTH_VECTOR_LEN );
2208                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2209                         vp->length = strlen(vp->vp_strvalue);
2210                 }
2211                 break;
2212
2213         default:
2214                 break;
2215         } /* switch over encryption flags */
2216
2217
2218         switch (vp->type) {
2219         case PW_TYPE_STRING:
2220         case PW_TYPE_OCTETS:
2221         case PW_TYPE_ABINARY:
2222                 /* nothing more to do */
2223                 break;
2224
2225         case PW_TYPE_BYTE:
2226                 if (vp->length != 1) goto raw;
2227
2228                 vp->vp_integer = vp->vp_octets[0];
2229                 break;
2230
2231
2232         case PW_TYPE_SHORT:
2233                 if (vp->length != 2) goto raw;
2234
2235                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2236                 break;
2237
2238         case PW_TYPE_INTEGER:
2239                 if (vp->length != 4) goto raw;
2240
2241                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2242                 vp->vp_integer = ntohl(vp->vp_integer);
2243
2244                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2245
2246                 /*
2247                  *      Try to get named VALUEs
2248                  */
2249                 {
2250                         DICT_VALUE *dval;
2251                         dval = dict_valbyattr(vp->attribute, vp->vendor,
2252                                               vp->vp_integer);
2253                         if (dval) {
2254                                 strlcpy(vp->vp_strvalue,
2255                                         dval->name,
2256                                         sizeof(vp->vp_strvalue));
2257                         }
2258                 }
2259                 break;
2260
2261         case PW_TYPE_DATE:
2262                 if (vp->length != 4) goto raw;
2263
2264                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2265                 vp->vp_date = ntohl(vp->vp_date);
2266                 break;
2267
2268
2269         case PW_TYPE_IPADDR:
2270                 if (vp->length != 4) goto raw;
2271
2272                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2273                 break;
2274
2275                 /*
2276                  *      IPv6 interface ID is 8 octets long.
2277                  */
2278         case PW_TYPE_IFID:
2279                 if (vp->length != 8) goto raw;
2280                 /* vp->vp_ifid == vp->vp_octets */
2281                 break;
2282
2283                 /*
2284                  *      IPv6 addresses are 16 octets long
2285                  */
2286         case PW_TYPE_IPV6ADDR:
2287                 if (vp->length != 16) goto raw;
2288                 /* vp->vp_ipv6addr == vp->vp_octets */
2289                 break;
2290
2291                 /*
2292                  *      IPv6 prefixes are 2 to 18 octets long.
2293                  *
2294                  *      RFC 3162: The first octet is unused.
2295                  *      The second is the length of the prefix
2296                  *      the rest are the prefix data.
2297                  *
2298                  *      The prefix length can have value 0 to 128.
2299                  */
2300         case PW_TYPE_IPV6PREFIX:
2301                 if (vp->length < 2 || vp->length > 18) goto raw;
2302                 if (vp->vp_octets[1] > 128) goto raw;
2303
2304                 /*
2305                  *      FIXME: double-check that
2306                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2307                  */
2308                 if (vp->length < 18) {
2309                         memset(vp->vp_octets + vp->length, 0,
2310                                18 - vp->length);
2311                 }
2312                 break;
2313
2314         case PW_TYPE_SIGNED:
2315                 if (vp->length != 4) goto raw;
2316
2317                 /*
2318                  *      Overload vp_integer for ntohl, which takes
2319                  *      uint32_t, not int32_t
2320                  */
2321                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2322                 vp->vp_integer = ntohl(vp->vp_integer);
2323                 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2324                 break;
2325
2326         case PW_TYPE_TLV:
2327                 vp->length = length;
2328                 vp->vp_tlv = malloc(length);
2329                 if (!vp->vp_tlv) {
2330                         pairfree(&vp);
2331                         fr_strerror_printf("No memory");
2332                         return NULL;
2333                 }
2334                 memcpy(vp->vp_tlv, data, length);
2335                 break;
2336
2337         case PW_TYPE_COMBO_IP:
2338                 if (vp->length == 4) {
2339                         vp->type = PW_TYPE_IPADDR;
2340                         memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2341                         break;
2342
2343                 } else if (vp->length == 16) {
2344                         vp->type = PW_TYPE_IPV6ADDR;
2345                         /* vp->vp_ipv6addr == vp->vp_octets */
2346                         break;
2347
2348                 }
2349                 /* FALL-THROUGH */
2350
2351         default:
2352         raw:
2353                 vp->type = PW_TYPE_OCTETS;
2354                 vp->length = length;
2355                 memcpy(vp->vp_octets, data, length);
2356
2357
2358                 /*
2359                  *      Ensure there's no encryption or tag stuff,
2360                  *      we just pass the attribute as-is.
2361                  */
2362                 memset(&vp->flags, 0, sizeof(vp->flags));
2363         }
2364
2365         return vp;
2366 }
2367
2368 static void rad_sortvp(VALUE_PAIR **head)
2369 {
2370         int swapped;
2371         VALUE_PAIR *vp, **tail;
2372
2373         /*
2374          *      Walk over the VP's, sorting them in order.  Did I
2375          *      mention that I hate WiMAX continuations?
2376          *
2377          *      And bubble sort!  WTF is up with that?
2378          */
2379         do {
2380                 swapped = 0;
2381                 tail = head;
2382                 while (*tail) {
2383                         vp = *tail;
2384                         if (!vp->next) break;
2385
2386                         if (vp->attribute > vp->next->attribute) {
2387                                 *tail = vp->next;
2388                                 vp->next = (*tail)->next;
2389                                 (*tail)->next = vp;
2390                                 swapped = 1;
2391                         }
2392                         tail = &(vp->next);
2393                 }
2394         } while (swapped);
2395 }
2396
2397
2398 /*
2399  *      Walk the packet, looking for continuations of this attribute.
2400  *
2401  *      This is (worst-case) O(N^2) in the number of RADIUS
2402  *      attributes.  That happens only when perverse clients create
2403  *      continued attributes, AND separate the fragmented portions
2404  *      with a lot of other attributes.
2405  *
2406  *      Sane clients should put the fragments next to each other, in
2407  *      which case this is O(N), in the number of fragments.
2408  */
2409 static uint8_t *rad_coalesce(unsigned int attribute, int vendor,
2410                              size_t length, uint8_t *data,
2411                              size_t packet_length, size_t *ptlv_length)
2412                              
2413 {
2414         uint32_t lvalue;
2415         size_t tlv_length = length;
2416         uint8_t *ptr, *tlv, *tlv_data;
2417
2418         for (ptr = data + length;
2419              ptr != (data + packet_length);
2420              ptr += ptr[1]) {
2421                 /* FIXME: Check that there are 6 bytes of data here... */
2422                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2423                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2424                     (ptr[2] != 0) || (ptr[3] != 0) ||  /* our requirement */
2425                     (ptr[4] != ((vendor >> 8) & 0xff)) ||
2426                     (ptr[5] != (vendor & 0xff))) {
2427                         continue;
2428                 }
2429
2430                 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2431                 lvalue = ntohl(lvalue);
2432                 lvalue <<= 16;
2433                 lvalue |= ptr[2 + 4]; /* add in VSA number */
2434                 if (lvalue != attribute) continue;
2435
2436                 /*
2437                  *      If the vendor-length is too small, it's badly
2438                  *      formed, so we stop.
2439                  */
2440                 if ((ptr[2 + 4 + 1]) < 3) break;
2441
2442                 tlv_length += ptr[2 + 4 + 1] - 3;
2443                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2444         }
2445
2446         tlv = tlv_data = malloc(tlv_length);
2447         if (!tlv_data) return NULL;
2448
2449         memcpy(tlv, data, length);
2450         tlv += length;
2451
2452         /*
2453          *      Now we walk the list again, copying the data over to
2454          *      our newly created memory.
2455          */
2456         for (ptr = data + length;
2457              ptr != (data + packet_length);
2458              ptr += ptr[1]) {
2459                 int this_length;
2460
2461                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2462                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2463                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2464                         continue;
2465                 }
2466
2467                 memcpy(&lvalue, ptr + 2, 4);
2468                 lvalue = ntohl(lvalue);
2469                 lvalue <<= 16;
2470                 lvalue |= ptr[2 + 4];
2471                 if (lvalue != attribute) continue;
2472
2473                 /*
2474                  *      If the vendor-length is too small, it's badly
2475                  *      formed, so we stop.
2476                  */
2477                 if ((ptr[2 + 4 + 1]) < 3) break;
2478
2479                 this_length = ptr[2 + 4 + 1] - 3;
2480                 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2481                 tlv += this_length;
2482
2483                 ptr[2 + 4] = 0; /* What a hack! */
2484                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2485         }
2486
2487         *ptlv_length = tlv_length;
2488         return tlv_data;
2489 }
2490
2491 /*
2492  *      Walk over Evil WIMAX Hell, creating attributes.
2493  *
2494  *      Won't someone think of the children?  What if they read this code?
2495  */
2496 static VALUE_PAIR *recurse_evil(const RADIUS_PACKET *packet,
2497                                 const RADIUS_PACKET *original,
2498                                 const char *secret,
2499                                 int attribute, int vendor,
2500                                 uint8_t *ptr, size_t len)
2501 {
2502         VALUE_PAIR *head = NULL;
2503         VALUE_PAIR **tail = &head;
2504         VALUE_PAIR *vp;
2505         uint8_t *y;             /* why do I need to do this? */
2506
2507         /*
2508          *      Sanity check the attribute.
2509          */
2510         for (y = ptr; y < (ptr + len); y += y[1]) {
2511                 if ((y[0] == 0) || ((y + 2) > (ptr + len)) ||
2512                     (y[1] < 2) || ((y + y[1]) > (ptr + len))) {
2513                         return NULL;
2514                 }
2515         }
2516
2517         for (y = ptr; y < (ptr + len); y += y[1]) {
2518                 vp = paircreate(attribute | (ptr[0] << 16), vendor,
2519                                 PW_TYPE_OCTETS);
2520                 if (!vp) {
2521                 error:
2522                         pairfree(&head);
2523                         return NULL;
2524                 }
2525
2526                 if (!data2vp(packet, original, secret,
2527                              y[1] - 2, y + 2, vp)) {
2528                         goto error;
2529                 }
2530
2531                 *tail = vp;
2532                 tail = &(vp->next);
2533         }
2534
2535         return head;
2536 }
2537
2538 /*
2539  *      Start at the *data* portion of a continued attribute.  search
2540  *      through the rest of the attributes to find a matching one, and
2541  *      add it's contents to our contents.
2542  */
2543 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2544                                        const RADIUS_PACKET *original,
2545                                        const char *secret, int attribute,
2546                                        int vendor,
2547                                        int length, /* CANNOT be zero */
2548                                        uint8_t *data, size_t packet_length,
2549                                        int flag, DICT_ATTR *da)
2550 {
2551         size_t tlv_length, left;
2552         uint8_t *ptr;
2553         uint8_t *tlv_data;
2554         VALUE_PAIR *vp, *head, **tail;
2555         DICT_ATTR *tlv_da;
2556
2557         /*
2558          *      Ensure we have data that hasn't been split across
2559          *      multiple attributes.
2560          */
2561         if (flag) {
2562                 tlv_data = rad_coalesce(attribute, vendor, length,
2563                                         data, packet_length, &tlv_length);
2564                 if (!tlv_data) return NULL;
2565         } else {
2566                 tlv_data = data;
2567                 tlv_length = length;
2568         }
2569
2570         /*
2571          *      Non-TLV types cannot be continued across multiple
2572          *      attributes.  This is true even of keys that are
2573          *      encrypted with the tunnel-password method.  The spec
2574          *      says that they can be continued... but also that the
2575          *      keys are 160 bits, which means that they CANNOT be
2576          *      continued.  <sigh>
2577          *
2578          *      Note that we don't check "flag" here.  The calling
2579          *      code ensures that 
2580          */
2581         if (!da || (da->type != PW_TYPE_TLV)) {
2582         not_well_formed:
2583                 if (tlv_data == data) { /* true if we had 'goto' */
2584                         tlv_data = malloc(tlv_length);
2585                         if (!tlv_data) return NULL;
2586                         memcpy(tlv_data, data, tlv_length);
2587                 }
2588                 
2589                 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2590                 if (!vp) return NULL;
2591                         
2592                 vp->type = PW_TYPE_TLV;
2593                 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2594                 vp->flags.has_tag = 0;
2595                 vp->flags.is_tlv = 0;
2596                 vp->vp_tlv = tlv_data;
2597                 vp->length = tlv_length;
2598                 return vp;
2599         } /* else it WAS a TLV, go decode the sub-tlv's */
2600
2601         /*
2602          *      Now (sigh) we walk over the TLV, seeing if it is
2603          *      well-formed.
2604          */
2605         left = tlv_length;
2606         for (ptr = tlv_data;
2607              ptr != (tlv_data + tlv_length);
2608              ptr += ptr[1]) {
2609                 if ((left < 2) ||
2610                     (ptr[1] < 2) ||
2611                     (ptr[1] > left)) {
2612                         goto not_well_formed;
2613                 }
2614
2615                 left -= ptr[1];
2616         }
2617
2618         /*
2619          *      Now we walk over the TLV *again*, creating sub-tlv's.
2620          */
2621         head = NULL;
2622         tail = &head;
2623
2624         for (ptr = tlv_data;
2625              ptr != (tlv_data + tlv_length);
2626              ptr += ptr[1]) {
2627
2628                 tlv_da = dict_attrbyvalue(attribute | (ptr[0] << 8), vendor);
2629                 if (tlv_da && (tlv_da->type == PW_TYPE_TLV)) {
2630                         vp = recurse_evil(packet, original, secret,
2631                                           attribute | (ptr[0] << 8),
2632                                           vendor, ptr + 2, ptr[1] - 2);
2633
2634                         if (!vp) {
2635                                 pairfree(&head);
2636                                 goto not_well_formed;
2637                         }
2638                 } else {
2639                         vp = paircreate(attribute | (ptr[0] << 8), vendor,
2640                                         PW_TYPE_OCTETS);
2641                         if (!vp) {
2642                                 pairfree(&head);
2643                                 goto not_well_formed;
2644                         }
2645
2646                         if (!data2vp(packet, original, secret,
2647                                      ptr[1] - 2, ptr + 2, vp)) {
2648                                 pairfree(&head);
2649                                 goto not_well_formed;
2650                         }
2651                 }
2652
2653                 *tail = vp;
2654
2655                 while (*tail) tail = &((*tail)->next);
2656         }
2657
2658         /*
2659          *      TLV's MAY be continued, but sometimes they're not.
2660          */
2661         if (tlv_data != data) free(tlv_data);
2662
2663         if (head->next) rad_sortvp(&head);
2664
2665         return head;
2666 }
2667
2668
2669 /*
2670  *      Parse a RADIUS attribute into a data structure.
2671  */
2672 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet,
2673                         const RADIUS_PACKET *original,
2674                         const char *secret, int attribute, int vendor,
2675                         int length, const uint8_t *data)
2676 {
2677         VALUE_PAIR *vp;
2678
2679         vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2680         if (!vp) return NULL;
2681
2682         return data2vp(packet, original, secret, length, data, vp);
2683 }
2684
2685
2686 /*
2687  *      Calculate/check digest, and decode radius attributes.
2688  *      Returns:
2689  *      -1 on decoding error
2690  *      0 on success
2691  */
2692 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2693                const char *secret)
2694 {
2695         uint32_t                lvalue;
2696         uint32_t                vendorcode;
2697         VALUE_PAIR              **tail;
2698         VALUE_PAIR              *pair;
2699         uint8_t                 *ptr, *vsa_ptr;
2700         int                     packet_length;
2701         int                     attribute;
2702         int                     attrlen;
2703         int                     vendorlen;
2704         radius_packet_t         *hdr;
2705         int                     vsa_tlen, vsa_llen, vsa_offset;
2706         DICT_VENDOR             *dv = NULL;
2707         int                     num_attributes = 0;
2708
2709         /*
2710          *      Extract attribute-value pairs
2711          */
2712         hdr = (radius_packet_t *)packet->data;
2713         ptr = hdr->data;
2714         packet_length = packet->data_len - AUTH_HDR_LEN;
2715
2716         /*
2717          *      There may be VP's already in the packet.  Don't
2718          *      destroy them.
2719          */
2720         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2721                 /* nothing */
2722         }
2723
2724         vendorcode = 0;
2725         vendorlen  = 0;
2726         vsa_tlen = vsa_llen = 1;
2727         vsa_offset = 0;
2728
2729         /*
2730          *      We have to read at least two bytes.
2731          *
2732          *      rad_recv() above ensures that this is OK.
2733          */
2734         while (packet_length > 0) {
2735                 attribute = -1;
2736                 attrlen = -1;
2737
2738                 /*
2739                  *      Normal attribute, handle it like normal.
2740                  */
2741                 if (vendorcode == 0) {
2742                         /*
2743                          *      No room to read attr/length,
2744                          *      or bad attribute, or attribute is
2745                          *      too short, or attribute is too long,
2746                          *      stop processing the packet.
2747                          */
2748                         if ((packet_length < 2) ||
2749                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2750                             (ptr[1] > packet_length)) break;
2751
2752                         attribute = *ptr++;
2753                         attrlen   = *ptr++;
2754
2755                         attrlen -= 2;
2756                         packet_length  -= 2;
2757
2758                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2759
2760                         /*
2761                          *      No vendor code, or ONLY vendor code.
2762                          */
2763                         if (attrlen <= 4) goto create_pair;
2764
2765                         vendorlen = 0;
2766                 }
2767
2768                 /*
2769                  *      Handle Vendor-Specific
2770                  */
2771                 if (vendorlen == 0) {
2772                         uint8_t *subptr;
2773                         int sublen;
2774                         int myvendor;
2775
2776                         /*
2777                          *      attrlen was checked above.
2778                          */
2779                         memcpy(&lvalue, ptr, 4);
2780                         myvendor = ntohl(lvalue);
2781
2782                         /*
2783                          *      Zero isn't allowed.
2784                          */
2785                         if (myvendor == 0) goto create_pair;
2786
2787                         /*
2788                          *      This is an implementation issue.
2789                          *      We currently pack vendor into the upper
2790                          *      16 bits of a 32-bit attribute number,
2791                          *      so we can't handle vendor numbers larger
2792                          *      than 16 bits.
2793                          */
2794                         if (myvendor > 65535) goto create_pair;
2795
2796                         vsa_tlen = vsa_llen = 1;
2797                         vsa_offset = 0;
2798                         dv = dict_vendorbyvalue(myvendor);
2799                         if (dv) {
2800                                 vsa_tlen = dv->type;
2801                                 vsa_llen = dv->length;
2802                                 if (dv->flags) vsa_offset = 1;
2803                         }
2804
2805                         /*
2806                          *      Sweep through the list of VSA's,
2807                          *      seeing if they exactly fill the
2808                          *      outer Vendor-Specific attribute.
2809                          *
2810                          *      If not, create a raw Vendor-Specific.
2811                          */
2812                         subptr = ptr + 4;
2813                         sublen = attrlen - 4;
2814
2815                         /*
2816                          *      See if we can parse it.
2817                          */
2818                         do {
2819                                 int myattr = 0;
2820
2821                                 /*
2822                                  *      Not enough room for one more
2823                                  *      attribute.  Die!
2824                                  */
2825                                 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2826
2827                                 /*
2828                                  *      Ensure that the attribute number
2829                                  *      is OK.
2830                                  */
2831                                 switch (vsa_tlen) {
2832                                 case 1:
2833                                         myattr = subptr[0];
2834                                         break;
2835
2836                                 case 2:
2837                                         myattr = (subptr[0] << 8) | subptr[1];
2838                                         break;
2839
2840                                 case 4:
2841                                         if ((subptr[0] != 0) ||
2842                                             (subptr[1] != 0)) goto create_pair;
2843
2844                                         myattr = (subptr[2] << 8) | subptr[3];
2845                                         break;
2846
2847                                         /*
2848                                          *      Our dictionary is broken.
2849                                          */
2850                                 default:
2851                                         goto create_pair;
2852                                 }
2853
2854                                 switch (vsa_llen) {
2855                                 case 0:
2856                                         attribute = myattr;
2857                                         ptr += 4 + vsa_tlen;
2858                                         attrlen -= (4 + vsa_tlen);
2859                                         packet_length -= 4 + vsa_tlen;
2860                                         goto create_pair;
2861
2862                                 case 1:
2863                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2864                                                 goto create_pair;
2865
2866                                         if (subptr[vsa_tlen] > sublen)
2867                                                 goto create_pair;
2868
2869                                         /*
2870                                          *      WiMAX: 0bCrrrrrrr
2871                                          *      Reserved bits MUST be
2872                                          *      zero.
2873                                          */
2874                                         if (vsa_offset &&
2875                                             ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2876                                                 goto create_pair;
2877
2878                                         sublen -= subptr[vsa_tlen];
2879                                         subptr += subptr[vsa_tlen];
2880                                         break;
2881
2882                                 case 2:
2883                                         if (subptr[vsa_tlen] != 0) goto create_pair;
2884                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2885                                                 goto create_pair;
2886                                         if (subptr[vsa_tlen + 1] > sublen)
2887                                                 goto create_pair;
2888                                         sublen -= subptr[vsa_tlen + 1];
2889                                         subptr += subptr[vsa_tlen + 1];
2890                                         break;
2891
2892                                         /*
2893                                          *      Our dictionaries are
2894                                          *      broken.
2895                                          */
2896                                 default:
2897                                         goto create_pair;
2898                                 }
2899                         } while (sublen > 0);
2900
2901                         vendorcode = myvendor;
2902                         vendorlen = attrlen - 4;
2903                         packet_length -= 4;
2904
2905                         ptr += 4;
2906                 }
2907
2908                 /*
2909                  *      attrlen is the length of this attribute.
2910                  *      total_len is the length of the encompassing
2911                  *      attribute.
2912                  */
2913                 switch (vsa_tlen) {
2914                 case 1:
2915                         attribute = ptr[0];
2916                         break;
2917
2918                 case 2:
2919                         attribute = (ptr[0] << 8) | ptr[1];
2920                         break;
2921
2922                 default:        /* can't hit this. */
2923                         return -1;
2924                 }
2925                 vsa_ptr = ptr;
2926                 ptr += vsa_tlen;
2927
2928                 switch (vsa_llen) {
2929                 case 1:
2930                         attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2931                         break;
2932
2933                 case 2:
2934                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2935                         break;
2936
2937                 default:        /* can't hit this. */
2938                         return -1;
2939                 }
2940
2941                 ptr += vsa_llen + vsa_offset;
2942                 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2943                 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2944
2945                 /*
2946                  *      Ignore VSAs that have no data.
2947                  */
2948                 if (attrlen == 0) goto next;
2949
2950                 /*
2951                  *      WiMAX attributes of type 0 are ignored.  They
2952                  *      are a secret flag to us that the attribute has
2953                  *      already been dealt with.
2954                  */
2955                 if ((vendorcode == VENDORPEC_WIMAX) && (attribute == 0)) {
2956                         goto next;
2957                 }
2958
2959                 if (vsa_offset) {
2960                         DICT_ATTR *da;
2961
2962                         da = dict_attrbyvalue(attribute, vendorcode);
2963
2964                         /*
2965                          *      If it's NOT continued, AND we know
2966                          *      about it, AND it's not a TLV, we can
2967                          *      create a normal pair.
2968                          */
2969                         if (((vsa_ptr[2] & 0x80) == 0) &&
2970                             da && (da->type != PW_TYPE_TLV)) goto create_pair;
2971
2972                         /*
2973                          *      Else it IS continued, or it's a TLV.
2974                          *      Go do a lot of work to find the stuff.
2975                          */
2976                         pair = rad_continuation2vp(packet, original, secret,
2977                                                    attribute, vendorcode,
2978                                                    attrlen, ptr,
2979                                                    packet_length,
2980                                                    ((vsa_ptr[2] & 0x80) != 0),
2981                                                    da);
2982                         goto created_pair;
2983                 }
2984
2985                 /*
2986                  *      Create the attribute, setting the default type
2987                  *      to 'octets'.  If the type in the dictionary
2988                  *      is different, then the dictionary type will
2989                  *      over-ride this one.
2990                  *
2991                  *      If the attribute has no data, then discard it.
2992                  *
2993                  *      Unless it's CUI.  Damn you, CUI!
2994                  */
2995         create_pair:
2996                 if (!attrlen &&
2997                     (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2998
2999                 pair = rad_attr2vp(packet, original, secret,
3000                                    attribute, vendorcode, attrlen, ptr);
3001                 if (!pair) {
3002                         pairfree(&packet->vps);
3003                         fr_strerror_printf("out of memory");
3004                         return -1;
3005                 }
3006
3007         created_pair:
3008                 *tail = pair;
3009                 while (pair) {
3010                         num_attributes++;
3011                         debug_pair(pair);
3012                         tail = &pair->next;
3013                         pair = pair->next;
3014                 }
3015
3016                 /*
3017                  *      VSA's may not have been counted properly in
3018                  *      rad_packet_ok() above, as it is hard to count
3019                  *      then without using the dictionary.  We
3020                  *      therefore enforce the limits here, too.
3021                  */
3022                 if ((fr_max_attributes > 0) &&
3023                     (num_attributes > fr_max_attributes)) {
3024                         char host_ipaddr[128];
3025
3026                         pairfree(&packet->vps);
3027                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3028                                    inet_ntop(packet->src_ipaddr.af,
3029                                              &packet->src_ipaddr.ipaddr,
3030                                              host_ipaddr, sizeof(host_ipaddr)),
3031                                    num_attributes, fr_max_attributes);
3032                         return -1;
3033                 }
3034
3035         next:
3036                 if (vendorlen == 0) vendorcode = 0;
3037                 ptr += attrlen;
3038                 packet_length -= attrlen;
3039         }
3040
3041         /*
3042          *      Merge information from the outside world into our
3043          *      random pool.
3044          */
3045         fr_rand_seed(packet->data, AUTH_HDR_LEN);
3046
3047         return 0;
3048 }
3049
3050
3051 /*
3052  *      Encode password.
3053  *
3054  *      We assume that the passwd buffer passed is big enough.
3055  *      RFC2138 says the password is max 128 chars, so the size
3056  *      of the passwd buffer must be at least 129 characters.
3057  *      Preferably it's just MAX_STRING_LEN.
3058  *
3059  *      int *pwlen is updated to the new length of the encrypted
3060  *      password - a multiple of 16 bytes.
3061  */
3062 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3063                  const uint8_t *vector)
3064 {
3065         FR_MD5_CTX context, old;
3066         uint8_t digest[AUTH_VECTOR_LEN];
3067         int     i, n, secretlen;
3068         int     len;
3069
3070         /*
3071          *      RFC maximum is 128 bytes.
3072          *
3073          *      If length is zero, pad it out with zeros.
3074          *
3075          *      If the length isn't aligned to 16 bytes,
3076          *      zero out the extra data.
3077          */
3078         len = *pwlen;
3079
3080         if (len > 128) len = 128;
3081
3082         if (len == 0) {
3083                 memset(passwd, 0, AUTH_PASS_LEN);
3084                 len = AUTH_PASS_LEN;
3085         } else if ((len % AUTH_PASS_LEN) != 0) {
3086                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3087                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3088         }
3089         *pwlen = len;
3090
3091         /*
3092          *      Use the secret to setup the decryption digest
3093          */
3094         secretlen = strlen(secret);
3095
3096         fr_MD5Init(&context);
3097         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3098         old = context;          /* save intermediate work */
3099
3100         /*
3101          *      Encrypt it in place.  Don't bother checking
3102          *      len, as we've ensured above that it's OK.
3103          */
3104         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3105                 if (n == 0) {
3106                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3107                         fr_MD5Final(digest, &context);
3108                 } else {
3109                         context = old;
3110                         fr_MD5Update(&context,
3111                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
3112                                      AUTH_PASS_LEN);
3113                         fr_MD5Final(digest, &context);
3114                 }
3115
3116                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3117                         passwd[i + n] ^= digest[i];
3118                 }
3119         }
3120
3121         return 0;
3122 }
3123
3124 /*
3125  *      Decode password.
3126  */
3127 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3128                  const uint8_t *vector)
3129 {
3130         FR_MD5_CTX context, old;
3131         uint8_t digest[AUTH_VECTOR_LEN];
3132         int     i;
3133         size_t  n, secretlen;
3134
3135         /*
3136          *      The RFC's say that the maximum is 128.
3137          *      The buffer we're putting it into above is 254, so
3138          *      we don't need to do any length checking.
3139          */
3140         if (pwlen > 128) pwlen = 128;
3141
3142         /*
3143          *      Catch idiots.
3144          */
3145         if (pwlen == 0) goto done;
3146
3147         /*
3148          *      Use the secret to setup the decryption digest
3149          */
3150         secretlen = strlen(secret);
3151
3152         fr_MD5Init(&context);
3153         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3154         old = context;          /* save intermediate work */
3155
3156         /*
3157          *      The inverse of the code above.
3158          */
3159         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3160                 if (n == 0) {
3161                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3162                         fr_MD5Final(digest, &context);
3163
3164                         context = old;
3165                         if (pwlen > AUTH_PASS_LEN) {
3166                                 fr_MD5Update(&context, (uint8_t *) passwd,
3167                                              AUTH_PASS_LEN);
3168                         }
3169                 } else {
3170                         fr_MD5Final(digest, &context);
3171
3172                         context = old;
3173                         if (pwlen > (n + AUTH_PASS_LEN)) {
3174                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
3175                                              AUTH_PASS_LEN);
3176                         }
3177                 }
3178
3179                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3180                         passwd[i + n] ^= digest[i];
3181                 }
3182         }
3183
3184  done:
3185         passwd[pwlen] = '\0';
3186         return strlen(passwd);
3187 }
3188
3189
3190 /*
3191  *      Encode Tunnel-Password attributes when sending them out on the wire.
3192  *
3193  *      int *pwlen is updated to the new length of the encrypted
3194  *      password - a multiple of 16 bytes.
3195  *
3196  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
3197  *      value MD5 hash.
3198  */
3199 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3200                         const uint8_t *vector)
3201 {
3202         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3203         unsigned char   digest[AUTH_VECTOR_LEN];
3204         char*   salt;
3205         int     i, n, secretlen;
3206         unsigned len, n2;
3207
3208         len = *pwlen;
3209
3210         if (len > 127) len = 127;
3211
3212         /*
3213          * Shift the password 3 positions right to place a salt and original
3214          * length, tag will be added automatically on packet send
3215          */
3216         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3217         salt = passwd;
3218         passwd += 2;
3219         /*
3220          * save original password length as first password character;
3221          */
3222         *passwd = len;
3223         len += 1;
3224
3225
3226         /*
3227          *      Generate salt.  The RFC's say:
3228          *
3229          *      The high bit of salt[0] must be set, each salt in a
3230          *      packet should be unique, and they should be random
3231          *
3232          *      So, we set the high bit, add in a counter, and then
3233          *      add in some CSPRNG data.  should be OK..
3234          */
3235         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3236                    (fr_rand() & 0x07));
3237         salt[1] = fr_rand();
3238
3239         /*
3240          *      Padd password to multiple of AUTH_PASS_LEN bytes.
3241          */
3242         n = len % AUTH_PASS_LEN;
3243         if (n) {
3244                 n = AUTH_PASS_LEN - n;
3245                 for (; n > 0; n--, len++)
3246                         passwd[len] = 0;
3247         }
3248         /* set new password length */
3249         *pwlen = len + 2;
3250
3251         /*
3252          *      Use the secret to setup the decryption digest
3253          */
3254         secretlen = strlen(secret);
3255         memcpy(buffer, secret, secretlen);
3256
3257         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3258                 if (!n2) {
3259                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3260                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3261                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3262                 } else {
3263                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3264                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3265                 }
3266
3267                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3268                         passwd[i + n2] ^= digest[i];
3269                 }
3270         }
3271         passwd[n2] = 0;
3272         return 0;
3273 }
3274
3275 /*
3276  *      Decode Tunnel-Password encrypted attributes.
3277  *
3278  *      Defined in RFC-2868, this uses a two char SALT along with the
3279  *      initial intermediate value, to differentiate it from the
3280  *      above.
3281  */
3282 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3283                         const uint8_t *vector)
3284 {
3285         FR_MD5_CTX  context, old;
3286         uint8_t         digest[AUTH_VECTOR_LEN];
3287         int             secretlen;
3288         unsigned        i, n, len, reallen;
3289
3290         len = *pwlen;
3291
3292         /*
3293          *      We need at least a salt.
3294          */
3295         if (len < 2) {
3296                 fr_strerror_printf("tunnel password is too short");
3297                 return -1;
3298         }
3299
3300         /*
3301          *      There's a salt, but no password.  Or, there's a salt
3302          *      and a 'data_len' octet.  It's wrong, but at least we
3303          *      can figure out what it means: the password is empty.
3304          *
3305          *      Note that this means we ignore the 'data_len' field,
3306          *      if the attribute length tells us that there's no
3307          *      more data.  So the 'data_len' field may be wrong,
3308          *      but that's ok...
3309          */
3310         if (len <= 3) {
3311                 passwd[0] = 0;
3312                 *pwlen = 0;
3313                 return 0;
3314         }
3315
3316         len -= 2;               /* discount the salt */
3317
3318         /*
3319          *      Use the secret to setup the decryption digest
3320          */
3321         secretlen = strlen(secret);
3322
3323         fr_MD5Init(&context);
3324         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3325         old = context;          /* save intermediate work */
3326
3327         /*
3328          *      Set up the initial key:
3329          *
3330          *       b(1) = MD5(secret + vector + salt)
3331          */
3332         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3333         fr_MD5Update(&context, passwd, 2);
3334
3335         reallen = 0;
3336         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3337                 int base = 0;
3338
3339                 if (n == 0) {
3340                         fr_MD5Final(digest, &context);
3341
3342                         context = old;
3343
3344                         /*
3345                          *      A quick check: decrypt the first octet
3346                          *      of the password, which is the
3347                          *      'data_len' field.  Ensure it's sane.
3348                          */
3349                         reallen = passwd[2] ^ digest[0];
3350                         if (reallen >= len) {
3351                                 fr_strerror_printf("tunnel password is too long for the attribute");
3352                                 return -1;
3353                         }
3354
3355                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3356
3357                         base = 1;
3358                 } else {
3359                         fr_MD5Final(digest, &context);
3360
3361                         context = old;
3362                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3363                 }
3364
3365                 for (i = base; i < AUTH_PASS_LEN; i++) {
3366                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3367                 }
3368         }
3369
3370         /*
3371          *      See make_tunnel_password, above.
3372          */
3373         if (reallen > 239) reallen = 239;
3374
3375         *pwlen = reallen;
3376         passwd[reallen] = 0;
3377
3378         return reallen;
3379 }
3380
3381 /*
3382  *      Encode a CHAP password
3383  *
3384  *      FIXME: might not work with Ascend because
3385  *      we use vp->length, and Ascend gear likes
3386  *      to send an extra '\0' in the string!
3387  */
3388 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3389                     VALUE_PAIR *password)
3390 {
3391         int             i;
3392         uint8_t         *ptr;
3393         uint8_t         string[MAX_STRING_LEN * 2 + 1];
3394         VALUE_PAIR      *challenge;
3395
3396         /*
3397          *      Sanity check the input parameters
3398          */
3399         if ((packet == NULL) || (password == NULL)) {
3400                 return -1;
3401         }
3402
3403         /*
3404          *      Note that the password VP can be EITHER
3405          *      a User-Password attribute (from a check-item list),
3406          *      or a CHAP-Password attribute (the client asking
3407          *      the library to encode it).
3408          */
3409
3410         i = 0;
3411         ptr = string;
3412         *ptr++ = id;
3413
3414         i++;
3415         memcpy(ptr, password->vp_strvalue, password->length);
3416         ptr += password->length;
3417         i += password->length;
3418
3419         /*
3420          *      Use Chap-Challenge pair if present,
3421          *      Request-Authenticator otherwise.
3422          */
3423         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
3424         if (challenge) {
3425                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3426                 i += challenge->length;
3427         } else {
3428                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3429                 i += AUTH_VECTOR_LEN;
3430         }
3431
3432         *output = id;
3433         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3434
3435         return 0;
3436 }
3437
3438
3439 /*
3440  *      Seed the random number generator.
3441  *
3442  *      May be called any number of times.
3443  */
3444 void fr_rand_seed(const void *data, size_t size)
3445 {
3446         uint32_t hash;
3447
3448         /*
3449          *      Ensure that the pool is initialized.
3450          */
3451         if (!fr_rand_initialized) {
3452                 int fd;
3453
3454                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3455
3456                 fd = open("/dev/urandom", O_RDONLY);
3457                 if (fd >= 0) {
3458                         size_t total;
3459                         ssize_t this;
3460
3461                         total = this = 0;
3462                         while (total < sizeof(fr_rand_pool.randrsl)) {
3463                                 this = read(fd, fr_rand_pool.randrsl,
3464                                             sizeof(fr_rand_pool.randrsl) - total);
3465                                 if ((this < 0) && (errno != EINTR)) break;
3466                                 if (this > 0) total += this;
3467                         }
3468                         close(fd);
3469                 } else {
3470                         fr_rand_pool.randrsl[0] = fd;
3471                         fr_rand_pool.randrsl[1] = time(NULL);
3472                         fr_rand_pool.randrsl[2] = errno;
3473                 }
3474
3475                 fr_randinit(&fr_rand_pool, 1);
3476                 fr_rand_pool.randcnt = 0;
3477                 fr_rand_initialized = 1;
3478         }
3479
3480         if (!data) return;
3481
3482         /*
3483          *      Hash the user data
3484          */
3485         hash = fr_rand();
3486         if (!hash) hash = fr_rand();
3487         hash = fr_hash_update(data, size, hash);
3488
3489         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3490 }
3491
3492
3493 /*
3494  *      Return a 32-bit random number.
3495  */
3496 uint32_t fr_rand(void)
3497 {
3498         uint32_t num;
3499
3500         /*
3501          *      Ensure that the pool is initialized.
3502          */
3503         if (!fr_rand_initialized) {
3504                 fr_rand_seed(NULL, 0);
3505         }
3506
3507         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3508         if (fr_rand_pool.randcnt >= 256) {
3509                 fr_rand_pool.randcnt = 0;
3510                 fr_isaac(&fr_rand_pool);
3511         }
3512
3513         return num;
3514 }
3515
3516
3517 /*
3518  *      Allocate a new RADIUS_PACKET
3519  */
3520 RADIUS_PACKET *rad_alloc(int newvector)
3521 {
3522         RADIUS_PACKET   *rp;
3523
3524         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3525                 fr_strerror_printf("out of memory");
3526                 return NULL;
3527         }
3528         memset(rp, 0, sizeof(*rp));
3529         rp->id = -1;
3530         rp->offset = -1;
3531
3532         if (newvector) {
3533                 int i;
3534                 uint32_t hash, base;
3535
3536                 /*
3537                  *      Don't expose the actual contents of the random
3538                  *      pool.
3539                  */
3540                 base = fr_rand();
3541                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3542                         hash = fr_rand() ^ base;
3543                         memcpy(rp->vector + i, &hash, sizeof(hash));
3544                 }
3545         }
3546         fr_rand();              /* stir the pool again */
3547
3548         return rp;
3549 }
3550
3551 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3552 {
3553         RADIUS_PACKET *reply;
3554
3555         if (!packet) return NULL;
3556
3557         reply = rad_alloc(0);
3558         if (!reply) return NULL;
3559
3560         /*
3561          *      Initialize the fields from the request.
3562          */
3563         reply->sockfd = packet->sockfd;
3564         reply->dst_ipaddr = packet->src_ipaddr;
3565         reply->src_ipaddr = packet->dst_ipaddr;
3566         reply->dst_port = packet->src_port;
3567         reply->src_port = packet->dst_port;
3568         reply->id = packet->id;
3569         reply->code = 0; /* UNKNOWN code */
3570         memcpy(reply->vector, packet->vector,
3571                sizeof(reply->vector));
3572         reply->vps = NULL;
3573         reply->data = NULL;
3574         reply->data_len = 0;
3575
3576         return reply;
3577 }
3578
3579
3580 /*
3581  *      Free a RADIUS_PACKET
3582  */
3583 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3584 {
3585         RADIUS_PACKET *radius_packet;
3586
3587         if (!radius_packet_ptr || !*radius_packet_ptr) return;
3588         radius_packet = *radius_packet_ptr;
3589
3590         free(radius_packet->data);
3591
3592         pairfree(&radius_packet->vps);
3593
3594         free(radius_packet);
3595
3596         *radius_packet_ptr = NULL;
3597 }