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