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