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