Merge branch 'sam'
[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         uint8_t buffer[256];
2818
2819         if (length == 0) {
2820                 /*
2821                  *      Hacks for CUI.  The WiMAX spec says that it
2822                  *      can be zero length, even though this is
2823                  *      forbidden by the RADIUS specs.  So... we make
2824                  *      a special case for it.
2825                  */
2826                 if ((vendor == 0) &&
2827                     (attribute == PW_CHARGEABLE_USER_IDENTITY)) {
2828                         data = (const uint8_t *) "";
2829                         length = 1;
2830                 } else {
2831                         *pvp = NULL;
2832                         return 0;
2833                 }
2834         }
2835
2836         da = dict_attrbyvalue(attribute, vendor);
2837
2838         /*
2839          *      Unknown attribute.  Create it as a "raw" attribute.
2840          */
2841         if (!da) {
2842                 VP_TRACE("Not found %u.%u\n", vendor, attribute);
2843         raw:
2844                 if (vp) pairfree(&vp);
2845                 return data2vp_raw(packet, original, secret,
2846                                    attribute, vendor, data, length, pvp);
2847         }
2848
2849         /*
2850          *      TLVs are handled first.  They can't be tagged, and
2851          *      they can't be encrypted.
2852          */
2853         if (da->type == PW_TYPE_TLV) {
2854                 VP_TRACE("Found TLV %u.%u\n", vendor, attribute);
2855                 return data2vp_tlvs(packet, original, secret,
2856                                     attribute, vendor, nest,
2857                                     data, length, pvp);
2858         }
2859
2860         /*
2861          *      The data is very long.
2862          */
2863         if (length > sizeof(vp->vp_octets)) {
2864                 /*
2865                  *      Long encrypted attributes are forbidden.
2866                  */
2867                 if (da->flags.encrypt != FLAG_ENCRYPT_NONE) goto raw;
2868
2869 #ifndef NDEBUG
2870                 /*
2871                  *      Catch programming errors.
2872                  */
2873                 if ((da->type != PW_TYPE_STRING) &&
2874                     (da->type != PW_TYPE_OCTETS)) goto raw;
2875
2876 #endif
2877
2878                 /*
2879                  *      FIXME: Figure out how to deal with long
2880                  *      strings and binary data!
2881                  */
2882                 goto raw;
2883         }
2884
2885         /*
2886          *      The attribute is known, and well formed.  We can now
2887          *      create it.  The main failure from here on in is being
2888          *      out of memory.
2889          */
2890         vp = pairalloc(da);
2891         if (!vp) return -1;
2892
2893         /*
2894          *      Handle tags.
2895          */
2896         if (vp->flags.has_tag) {
2897                 if (TAG_VALID(data[0]) ||
2898                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2899                         /*
2900                          *      Tunnel passwords REQUIRE a tag, even
2901                          *      if don't have a valid tag.
2902                          */
2903                         vp->flags.tag = data[0];
2904
2905                         if ((vp->type == PW_TYPE_STRING) ||
2906                             (vp->type == PW_TYPE_OCTETS)) {
2907                                 if (length == 0) goto raw;
2908                                 data_offset = 1;
2909                         }
2910                 }
2911         }
2912
2913         /*
2914          *      Copy the data to be decrypted
2915          */
2916         vp->length = length - data_offset;      
2917         memcpy(buffer, data + data_offset, vp->length);
2918
2919         /*
2920          *      Decrypt the attribute.
2921          */
2922         if (secret && packet) switch (vp->flags.encrypt) {
2923                 /*
2924                  *  User-Password
2925                  */
2926         case FLAG_ENCRYPT_USER_PASSWORD:
2927                 if (original) {
2928                         rad_pwdecode((char *) buffer,
2929                                      vp->length, secret,
2930                                      original->vector);
2931                 } else {
2932                         rad_pwdecode((char *) buffer,
2933                                      vp->length, secret,
2934                                      packet->vector);
2935                 }
2936                 buffer[253] = '\0';
2937                 if (vp->attribute == PW_USER_PASSWORD) {
2938                         vp->length = strlen((char *) buffer);
2939                 }
2940                 break;
2941
2942                 /*
2943                  *      Tunnel-Password's may go ONLY
2944                  *      in response packets.
2945                  */
2946         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2947                 if (!original) goto raw;
2948
2949                 if (rad_tunnel_pwdecode(buffer, &vp->length,
2950                                         secret, original->vector) < 0) {
2951                         goto raw;
2952                 }
2953                 break;
2954
2955                 /*
2956                  *  Ascend-Send-Secret
2957                  *  Ascend-Receive-Secret
2958                  */
2959         case FLAG_ENCRYPT_ASCEND_SECRET:
2960                 if (!original) {
2961                         goto raw;
2962                 } else {
2963                         uint8_t my_digest[AUTH_VECTOR_LEN];
2964                         make_secret(my_digest,
2965                                     original->vector,
2966                                     secret, data);
2967                         memcpy(buffer, my_digest,
2968                                AUTH_VECTOR_LEN );
2969                         buffer[AUTH_VECTOR_LEN] = '\0';
2970                         vp->length = strlen((char *) buffer);
2971                 }
2972                 break;
2973
2974         default:
2975                 break;
2976         } /* switch over encryption flags */
2977
2978
2979         switch (vp->type) {
2980         case PW_TYPE_STRING:
2981                 memcpy(vp->vp_strvalue, buffer, vp->length);
2982                 vp->vp_strvalue[vp->length] = '\0';
2983                 break;
2984
2985         case PW_TYPE_OCTETS:
2986         case PW_TYPE_ABINARY:
2987                 memcpy(vp->vp_octets, buffer, vp->length);
2988                 break;
2989
2990         case PW_TYPE_BYTE:
2991                 if (vp->length != 1) goto raw;
2992
2993                 vp->vp_integer = buffer[0];
2994                 break;
2995
2996
2997         case PW_TYPE_SHORT:
2998                 if (vp->length != 2) goto raw;
2999
3000                 vp->vp_integer = (buffer[0] << 8) | buffer[1];
3001                 break;
3002
3003         case PW_TYPE_INTEGER:
3004                 if (vp->length != 4) goto raw;
3005
3006                 memcpy(&vp->vp_integer, buffer, 4);
3007                 vp->vp_integer = ntohl(vp->vp_integer);
3008
3009                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
3010                 break;
3011
3012         case PW_TYPE_INTEGER64:
3013                 if (vp->length != 8) goto raw;
3014
3015                 /* vp_integer64 is a union with vp_octets */
3016                 memcpy(&vp->vp_integer64, buffer, 8);
3017                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3018                 break;
3019
3020         case PW_TYPE_DATE:
3021                 if (vp->length != 4) goto raw;
3022
3023                 memcpy(&vp->vp_date, buffer, 4);
3024                 vp->vp_date = ntohl(vp->vp_date);
3025                 break;
3026
3027
3028         case PW_TYPE_IPADDR:
3029                 if (vp->length != 4) goto raw;
3030
3031                 memcpy(&vp->vp_ipaddr, buffer, 4);
3032                 break;
3033
3034                 /*
3035                  *      IPv6 interface ID is 8 octets long.
3036                  */
3037         case PW_TYPE_IFID:
3038                 if (vp->length != 8) goto raw;
3039                 memcpy(&vp->vp_ifid, buffer, 8);
3040                 break;
3041
3042                 /*
3043                  *      IPv6 addresses are 16 octets long
3044                  */
3045         case PW_TYPE_IPV6ADDR:
3046                 if (vp->length != 16) goto raw;
3047                 memcpy(&vp->vp_ipv6addr, buffer, 16);
3048                 break;
3049
3050                 /*
3051                  *      IPv6 prefixes are 2 to 18 octets long.
3052                  *
3053                  *      RFC 3162: The first octet is unused.
3054                  *      The second is the length of the prefix
3055                  *      the rest are the prefix data.
3056                  *
3057                  *      The prefix length can have value 0 to 128.
3058                  */
3059         case PW_TYPE_IPV6PREFIX:
3060                 if (vp->length < 2 || vp->length > 18) goto raw;
3061                 if (buffer[1] > 128) goto raw;
3062
3063                 /*
3064                  *      FIXME: double-check that
3065                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
3066                  */
3067                 memcpy(&vp->vp_ipv6prefix, buffer, vp->length);
3068                 if (vp->length < 18) {
3069                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3070                                18 - vp->length);
3071                 }
3072                 break;
3073
3074         case PW_TYPE_SIGNED:
3075                 if (vp->length != 4) goto raw;
3076
3077                 /*
3078                  *      Overload vp_integer for ntohl, which takes
3079                  *      uint32_t, not int32_t
3080                  */
3081                 memcpy(&vp->vp_integer, buffer, 4);
3082                 vp->vp_integer = ntohl(vp->vp_integer);
3083                 break;
3084
3085         case PW_TYPE_TLV:
3086                 pairfree(&vp);
3087                 fr_strerror_printf("data2vp_any: Internal sanity check failed");
3088                 return -1;
3089
3090         case PW_TYPE_COMBO_IP:
3091                 if (vp->length == 4) {
3092                         vp->type = PW_TYPE_IPADDR;
3093                         memcpy(&vp->vp_ipaddr, buffer, 4);
3094                         break;
3095
3096                 } else if (vp->length == 16) {
3097                         vp->type = PW_TYPE_IPV6ADDR;
3098                         memcpy(&vp->vp_ipv6addr, buffer, 16);
3099                         break;
3100
3101                 }
3102                 /* FALL-THROUGH */
3103
3104         default:
3105                 goto raw;
3106         }
3107
3108         *pvp = vp;
3109
3110         return length;
3111 }
3112
3113
3114 /**
3115  * @brief Convert a top-level VSA to a VP.
3116  */
3117 static ssize_t attr2vp_vsa(const RADIUS_PACKET *packet,
3118                            const RADIUS_PACKET *original,
3119                            const char *secret, unsigned int vendor,
3120                            size_t dv_type, size_t dv_length,
3121                            const uint8_t *data, size_t length,
3122                            VALUE_PAIR **pvp)
3123 {
3124         unsigned int attribute;
3125         ssize_t attrlen, my_len;
3126
3127 #ifndef NDEBUG
3128         if (length <= (dv_type + dv_length)) {
3129                 fr_strerror_printf("attr2vp_vsa: Failure to call rad_tlv_ok");
3130                 return -1;
3131         }
3132 #endif  
3133
3134         switch (dv_type) {
3135         case 4:
3136                 /* data[0] must be zero */
3137                 attribute = data[1] << 16;
3138                 attribute |= data[2] << 8;
3139                 attribute |= data[3];
3140                 break;
3141
3142         case 2:
3143                 attribute = data[0] << 8;
3144                 attribute |= data[1];
3145                 break;
3146
3147         case 1:
3148                 attribute = data[0];
3149                 break;
3150
3151         default:
3152                 fr_strerror_printf("attr2vp_vsa: Internal sanity check failed");
3153                 return -1;
3154         }
3155
3156         switch (dv_length) {
3157         case 2:
3158                 /* data[dv_type] must be zero */
3159                 attrlen = data[dv_type + 1];
3160                 break;
3161
3162         case 1:
3163                 attrlen = data[dv_type];
3164                 break;
3165
3166         case 0:
3167                 attrlen = length;
3168                 break;
3169
3170         default:
3171                 fr_strerror_printf("attr2vp_vsa: Internal sanity check failed");
3172                 return -1;
3173         }
3174
3175 #ifndef NDEBUG
3176         if (attrlen <= (ssize_t) (dv_type + dv_length)) {
3177                 fr_strerror_printf("attr2vp_vsa: Failure to call rad_tlv_ok");
3178                 return -1;
3179         }
3180 #endif
3181
3182         attrlen -= (dv_type + dv_length);
3183         
3184         my_len = data2vp_any(packet, original, secret, 0,
3185                              attribute, vendor,
3186                              data + dv_type + dv_length, attrlen, pvp);
3187         if (my_len < 0) return my_len;
3188
3189 #ifndef NDEBUG
3190         if (my_len != attrlen) {
3191                 pairfree(pvp);
3192                 fr_strerror_printf("attr2vp_vsa: Incomplete decode %d != %d",
3193                                    (int) my_len, (int) attrlen);
3194                 return -1;
3195         }
3196 #endif
3197
3198         return dv_type + dv_length + attrlen;
3199 }
3200
3201 /**
3202  * @brief Convert one or more TLVs to VALUE_PAIRs.  This function can
3203  *      be called recursively...
3204  */
3205 static ssize_t data2vp_tlvs(const RADIUS_PACKET *packet,
3206                             const RADIUS_PACKET *original,
3207                             const char *secret,
3208                             unsigned int attribute, unsigned int vendor,
3209                             int nest,
3210                             const uint8_t *start, size_t length,
3211                             VALUE_PAIR **pvp)
3212 {
3213         size_t dv_type, dv_length;
3214         const uint8_t *data, *end;
3215         VALUE_PAIR *head, **last, *vp;
3216
3217         data = start;
3218
3219         /*
3220          *      The default format for a VSA is the RFC recommended
3221          *      format.
3222          */
3223         dv_type = 1;
3224         dv_length = 1;
3225
3226         /*
3227          *      Top-level TLVs can be of a weird format.  TLVs
3228          *      encapsulated in a TLV can only be in the RFC format.
3229          */
3230         if (nest == 1) {
3231                 DICT_VENDOR *dv;
3232                 dv = dict_vendorbyvalue(vendor);        
3233                 if (dv) {
3234                         dv_type = dv->type;
3235                         dv_length = dv->length;
3236                         /* dict.c enforces sane values on the above fields */
3237                 }
3238         }
3239
3240         if (nest >= fr_attr_max_tlv) {
3241                 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in recursion");
3242                 return -1;
3243         }
3244
3245         /*
3246          *      The VSAs do not exactly fill the data,
3247          *      The *entire* TLV is malformed.
3248          */
3249         if (rad_tlv_ok(data, length, dv_type, dv_length) < 0) {
3250                 VP_TRACE("TLV malformed %u.%u\n", vendor, attribute);
3251                 return data2vp_raw(packet, original, secret,
3252                                    attribute, vendor, data, length, pvp);
3253         }
3254
3255         end = data + length;
3256         head = NULL;
3257         last = &head;
3258
3259         while (data < end) {
3260                 unsigned int my_attr;
3261                 unsigned int my_len;
3262
3263 #ifndef NDEBUG
3264                 if ((data + dv_type + dv_length) > end) {
3265                         fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: Insufficient data");
3266                         pairfree(&head);
3267                         return -1;
3268                 }
3269 #endif
3270
3271                 switch (dv_type) {
3272                 case 1:
3273                         my_attr = attribute;
3274                         my_attr |= ((data[0] & fr_attr_mask[nest + 1])
3275                                     << fr_attr_shift[nest + 1]);
3276                         break;
3277                 case 2:
3278                         my_attr = (data[0] << 8) | data[1];
3279                         break;
3280
3281                 case 4:
3282                         my_attr = (data[1] << 16) | (data[1] << 8) | data[3];
3283                         break;
3284
3285                 default:
3286                         fr_strerror_printf("data2vp_tlvs: Internal sanity check failed");
3287                         return -1;
3288                 }
3289
3290                 switch (dv_length) {
3291                 case 0:
3292                         my_len = length;
3293                         break;
3294
3295                 case 1:
3296                 case 2:
3297                         my_len = data[dv_type + dv_length - 1];
3298                         break;
3299
3300                 default:
3301                         fr_strerror_printf("data2vp_tlvs: Internal sanity check failed");
3302                         return -1;
3303                 }
3304                 
3305 #ifndef NDEBUG
3306                 if (my_len < (dv_type + dv_length)) {
3307                         fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: underflow");
3308                         pairfree(&head);
3309                         return -1;
3310                 }
3311
3312                 if ((data + my_len) > end) {
3313                         fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: overflow");
3314                         pairfree(&head);
3315                         return -1;
3316                 }
3317 #endif
3318
3319                 my_len -= dv_type + dv_length;
3320
3321                 /*
3322                  *      If this returns > 0, it returns "my_len"
3323                  */
3324                 if (data2vp_any(packet, original, secret, nest + 1,
3325                                 my_attr, vendor,
3326                                 data + dv_type + dv_length, my_len, &vp) < 0) {
3327                         pairfree(&head);
3328                         return -1;
3329                 }
3330
3331                 data += my_len + dv_type + dv_length;
3332                 *last = vp;
3333
3334                 while (vp) {
3335                         last = &(vp->next);
3336                         vp = vp->next;
3337                 }
3338         }
3339
3340         *pvp = head;
3341         return data - start;
3342 }
3343
3344
3345 /**
3346  * @brief Group "continued" attributes together, and create VPs from them.
3347  *
3348  *      The caller ensures that the RADIUS packet is OK, and that the
3349  *      continuations have all been checked.
3350  */
3351 static ssize_t data2vp_continued(const RADIUS_PACKET *packet,
3352                                  const RADIUS_PACKET *original,
3353                                  const char *secret,
3354                                  const uint8_t *start, size_t length,
3355                                  VALUE_PAIR **pvp, int nest,
3356                                  unsigned int attribute, unsigned int vendor,
3357                                  int first_offset, int later_offset,
3358                                  ssize_t attrlen)
3359 {
3360         ssize_t left;
3361         uint8_t *attr, *ptr;
3362         const uint8_t *data;
3363
3364         attr = malloc(attrlen);
3365         if (!attr) {
3366                 fr_strerror_printf("Out of memory");
3367                 return -1;
3368         }
3369
3370         left = attrlen;
3371         ptr = attr;
3372         data = start;
3373
3374         /*
3375          *      Do the first one.
3376          */
3377         memcpy(ptr, data + first_offset, data[1] - first_offset);
3378         ptr += data[1] - first_offset;
3379         left -= data[1] - first_offset;
3380         data += data[1];
3381
3382         while (left > 0) {
3383 #ifndef NDEBUG
3384                 if (data >= (start + length)) {
3385                         free(attr);
3386                         fr_strerror_printf("data2vp_continued: Internal sanity check failed");
3387                         return -1;
3388                 }
3389 #endif
3390                 memcpy(ptr, data + later_offset, data[1] - later_offset);
3391                 ptr += data[1] - later_offset;
3392                 left -= data[1] - later_offset;
3393                 data += data[1];
3394         }
3395
3396         left = data2vp_any(packet, original, secret, nest,
3397                            attribute, vendor,
3398                            attr, attrlen, pvp);
3399         free(attr);
3400         if (left < 0) return left;
3401
3402         return data - start;
3403 }
3404
3405
3406 /**
3407  * @brief Create a "raw" VALUE_PAIR from a RADIUS attribute.
3408  */
3409 ssize_t rad_attr2vp_raw(const RADIUS_PACKET *packet,
3410                         const RADIUS_PACKET *original,
3411                         const char *secret,
3412                         const uint8_t *data, size_t length,
3413                         VALUE_PAIR **pvp)
3414 {
3415         ssize_t my_len;
3416
3417         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3418                 fr_strerror_printf("rad_attr2vp_raw: Invalid length");
3419                 return -1;
3420         }
3421
3422         my_len = data2vp_raw(packet, original, secret, data[0], 0,
3423                              data + 2, data[1] - 2, pvp);
3424         if (my_len < 0) return my_len;
3425         
3426         return data[1];
3427 }
3428
3429
3430 /**
3431  * @brief Get the length of the data portion of all of the contiguous
3432  *      continued attributes.
3433  * @return
3434  *      0 for "no continuation"
3435  *      -1 on malformed packets (continuation followed by non-wimax, etc.)
3436  */
3437 static ssize_t wimax_attrlen(uint32_t vendor,
3438                              const uint8_t *start, const uint8_t *end)
3439 {
3440         ssize_t total;
3441         const uint8_t *data = start;
3442
3443         if ((data[8] & 0x80) == 0) return 0;
3444         total = data[7] - 3;
3445         data += data[1];
3446
3447         while (data < end) {
3448                 
3449                 if ((data + 9) > end) return -1;
3450
3451                 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3452                     (data[1] < 9) ||
3453                     (memcmp(data + 2, &vendor, 4) != 0) ||
3454                     (data[6] != start[6]) ||
3455                     ((data[7] + 6) != data[1])) return -1;
3456
3457                 total += data[7] - 3;
3458                 if ((data[8] & 0x80) == 0) break;
3459                 data += data[1];
3460         }
3461
3462         return total;
3463 }
3464
3465
3466 /**
3467  * @brief Get the length of the data portion of all of the contiguous
3468  *      continued attributes.
3469  *
3470  * @return
3471  *      0 for "no continuation"
3472  *      -1 on malformed packets (continuation followed by non-wimax, etc.)
3473  */
3474 static ssize_t extended_attrlen(const uint8_t *start, const uint8_t *end)
3475 {
3476         ssize_t total;
3477         const uint8_t *data = start;
3478
3479         if ((data[3] & 0x80) == 0) return 0;
3480         total = data[1] - 4;
3481         data += data[1];
3482         
3483         while (data < end) {
3484                 if ((data + 4) > end) return -1;
3485
3486                 if ((data[0] != start[0]) ||
3487                     (data[1] < 4) ||
3488                     (data[2] != start[2])) return -1;
3489
3490                 total += data[1] - 4;
3491                 if ((data[3] & 0x80) == 0) break;
3492                 data += data[1];
3493         }
3494
3495         return total;
3496 }
3497
3498
3499 /**
3500  * @brief Create WiMAX VALUE_PAIRs from a RADIUS attribute.
3501  */
3502 ssize_t rad_attr2vp_wimax(const RADIUS_PACKET *packet,
3503                           const RADIUS_PACKET *original,
3504                           const char *secret,
3505                           const uint8_t *data,  size_t length,
3506                           VALUE_PAIR **pvp)
3507 {
3508         ssize_t my_len;
3509         unsigned int attribute;
3510         uint32_t lvalue;
3511
3512         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3513                 fr_strerror_printf("rad_attr2vp_wimax: Invalid length");
3514                 return -1;
3515         }
3516
3517         if (data[0] != PW_VENDOR_SPECIFIC) {
3518                 fr_strerror_printf("rad_attr2vp_wimax: Invalid attribute");
3519                 return -1;
3520         }
3521
3522         /*
3523          *      Not enough room for a Vendor-Id. + WiMAX header
3524          */
3525         if (data[1] < 9) {
3526                 return rad_attr2vp_raw(packet, original, secret,
3527                                        data, length, pvp);
3528         }
3529
3530         memcpy(&lvalue, data + 2, 4);
3531         lvalue = ntohl(lvalue);
3532
3533         /*
3534          *      Not WiMAX format.
3535          */
3536         if (lvalue != VENDORPEC_WIMAX) {
3537                 DICT_VENDOR *dv;
3538
3539                 dv = dict_vendorbyvalue(lvalue);
3540                 if (!dv || !dv->flags) {
3541                         fr_strerror_printf("rad_attr2vp_wimax: Not a WiMAX attribute");
3542                         return -1;
3543                 }
3544         }
3545
3546         /*
3547          *      The WiMAX attribute is encapsulated in a VSA.  If the
3548          *      WiMAX length disagrees with the VSA length, it's malformed.
3549          */
3550         if ((data[7] + 6) != data[1]) {
3551                 return rad_attr2vp_raw(packet, original, secret,
3552                                        data, length, pvp);
3553         }
3554
3555         attribute = data[6];
3556
3557         /*
3558          *      Attribute is continued.  Do some more work.
3559          */
3560         if (data[8] != 0) {
3561                 my_len = wimax_attrlen(htonl(lvalue), data, data + length);
3562                 if (my_len < 0) {
3563                         return rad_attr2vp_raw(packet, original, secret,
3564                                                data, length, pvp);
3565                 }
3566
3567                 return data2vp_continued(packet, original, secret,
3568                                          data, length, pvp, 0,
3569                                          data[6], lvalue,
3570                                          9, 9, my_len);
3571         }
3572
3573         my_len = data2vp_any(packet, original, secret, 0, attribute, lvalue,
3574                              data + 9, data[1] - 9, pvp);
3575         if (my_len < 0) return my_len;
3576
3577         return data[1];
3578 }
3579
3580 /**
3581  * @brief Create Vendor-Specifc VALUE_PAIRs from a RADIUS attribute.
3582  */
3583 ssize_t rad_attr2vp_vsa(const RADIUS_PACKET *packet,
3584                         const RADIUS_PACKET *original,
3585                         const char *secret,
3586                         const uint8_t *data, size_t length,
3587                         VALUE_PAIR **pvp)
3588 {
3589         size_t dv_type, dv_length;
3590         ssize_t my_len;
3591         uint32_t lvalue;
3592         DICT_VENDOR *dv;
3593
3594         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3595                 fr_strerror_printf("rad_attr2vp_vsa: Invalid length");
3596                 return -1;
3597         }
3598
3599         if (data[0] != PW_VENDOR_SPECIFIC) {
3600                 fr_strerror_printf("rad_attr2vp_vsa: Invalid attribute");
3601                 return -1;
3602         }
3603
3604         /*
3605          *      Not enough room for a Vendor-Id.
3606          *      Or the high octet of the Vendor-Id is set.
3607          */
3608         if ((data[1] < 6) || (data[2] != 0)) {
3609                 return rad_attr2vp_raw(packet, original, secret,
3610                                        data, length, pvp);
3611         }
3612
3613         memcpy(&lvalue, data + 2, 4);
3614         lvalue = ntohl(lvalue);
3615
3616         /*
3617          *      WiMAX gets its own set of magic.
3618          */
3619         if (lvalue == VENDORPEC_WIMAX) {
3620         wimax:
3621                 return rad_attr2vp_wimax(packet, original, secret,
3622                                          data, length, pvp);
3623         }
3624
3625         dv_type = dv_length = 1;
3626         dv = dict_vendorbyvalue(lvalue);
3627         if (dv) {
3628                 dv_type = dv->type;
3629                 dv_length = dv->length;
3630
3631                 if (dv->flags) goto wimax;
3632         }
3633
3634         /*
3635          *      Attribute is not in the correct form.
3636          */
3637         if (rad_tlv_ok(data + 6, data[1] - 6, dv_type, dv_length) < 0) {
3638                 return rad_attr2vp_raw(packet, original, secret,
3639                                        data, length, pvp);
3640         }
3641
3642         my_len = attr2vp_vsa(packet, original, secret,
3643                              lvalue, dv_type, dv_length,
3644                              data + 6, data[1] - 6, pvp);
3645         if (my_len < 0) return my_len;
3646
3647         /*
3648          *      Incomplete decode means that something is wrong
3649          *      with the attribute.  Back up, and make it "raw".
3650          */
3651         if (my_len != (data[1] - 6)) {
3652                 pairfree(pvp);
3653                 return rad_attr2vp_raw(packet, original, secret,
3654                                        data, length, pvp);
3655         }
3656
3657         return data[1];
3658 }
3659
3660 /**
3661  * @brief Create an "extended" VALUE_PAIR from a RADIUS attribute.
3662  */
3663 ssize_t rad_attr2vp_extended(const RADIUS_PACKET *packet,
3664                              const RADIUS_PACKET *original,
3665                              const char *secret,
3666                              const uint8_t *start, size_t length,
3667                              VALUE_PAIR **pvp)
3668 {
3669         unsigned int attribute;
3670         int shift = 1;
3671         int continued = 0;
3672         unsigned int vendor = VENDORPEC_EXTENDED;
3673         size_t data_len = length;
3674         const uint8_t *data;
3675         DICT_ATTR *da;
3676
3677         data = start;
3678
3679         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3680                 fr_strerror_printf("rad_attr2vp_extended: Invalid length");
3681                 return -1;
3682         }
3683
3684         da = dict_attrbyvalue(data[0], vendor);
3685         if (!da ||
3686             (!da->flags.extended && !da->flags.extended_flags)) {
3687                 fr_strerror_printf("rad_attr2vp_extended: Attribute is not extended format");
3688                 return -1;
3689         }
3690
3691         data = start;
3692
3693         /*
3694          *      No Extended-Type.  It's a raw attribute.
3695          *      Also, if there's no data following the Extended-Type,
3696          *      it's a raw attribute.
3697          */
3698         if (data[1] <= 3) {
3699         raw:
3700                 return rad_attr2vp_raw(packet, original, secret, start,
3701                                        length, pvp);
3702         }
3703
3704         /*
3705          *      The attribute is "241.1", for example.  Go look that
3706          *      up to see what type it is.
3707          */
3708         attribute = data[0];
3709         attribute |= (data[2] << fr_attr_shift[1]);
3710
3711         da = dict_attrbyvalue(attribute, vendor);
3712         if (!da) goto raw;
3713
3714         vendor = VENDORPEC_EXTENDED;
3715
3716         data_len = length;
3717         if (data[1] < length) data_len = data[1];
3718
3719         data += 3;
3720         data_len -= 3;
3721
3722         /*
3723          *      If there's supposed to be a flag octet.  If not, it's
3724          *      a raw attribute.  If the flag is set, it's supposed to
3725          *      be continued.
3726          */
3727         if (da->flags.extended_flags) {
3728                 if (data_len == 0) goto raw;
3729
3730                 continued = ((data[0] & 0x80) != 0);
3731                 data++;
3732                 data_len--;
3733         }
3734         
3735         /*
3736          *      Extended VSAs have 4 octets of
3737          *      Vendor-Id followed by one octet of
3738          *      Vendor-Type.
3739          */
3740         if (da->flags.evs) {
3741                 if (data_len < 5) goto raw;
3742                 
3743                 /*
3744                  *      Vendor Ids can only be 24-bit.
3745                  */
3746                 if (data[0] != 0) goto raw;
3747                 
3748                 vendor = ((data[1] << 16) |
3749                           (data[2] << 8) |
3750                           data[3]);
3751                 
3752                 /*
3753                  *      Pack the *encapsulating* attribute number into
3754                  *      the vendor id.  This number should be >= 241.
3755                  */
3756                 vendor |= start[0] * FR_MAX_VENDOR;
3757                 shift = 0;
3758                 
3759                 /*
3760                  *      Over-write the attribute with the
3761                  *      VSA.
3762                  */
3763                 attribute = data[4];
3764                 data += 5;
3765                 data_len -= 5;
3766         }
3767
3768         if (continued) {
3769                 int first_offset = 4;
3770                 ssize_t my_len;
3771
3772                 if (vendor != VENDORPEC_EXTENDED) first_offset += 5;
3773
3774                 my_len = extended_attrlen(start, start + length);
3775                 if (my_len < 0) goto raw;
3776
3777                 if (vendor != VENDORPEC_EXTENDED) my_len -= 5;
3778
3779                 return data2vp_continued(packet, original, secret,
3780                                          start, length, pvp, shift,
3781                                          attribute, vendor,
3782                                          first_offset, 4, my_len);
3783         }
3784
3785         if (data2vp_any(packet, original, secret, shift,
3786                         attribute, vendor, data, data_len, pvp) < 0) {
3787                 return -1;
3788         }
3789
3790         return (data + data_len) - start;
3791 }
3792
3793
3794 /**
3795  * @brief Create a "standard" RFC VALUE_PAIR from the given data.
3796  */
3797 ssize_t rad_attr2vp_rfc(const RADIUS_PACKET *packet,
3798                         const RADIUS_PACKET *original,
3799                         const char *secret,
3800                         const uint8_t *data, size_t length,
3801                         VALUE_PAIR **pvp)
3802 {
3803         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3804                 fr_strerror_printf("rad_attr2vp_rfc: Insufficient data");
3805                 return -1;
3806         }
3807         
3808         if (data2vp_any(packet, original, secret, 0,
3809                         data[0], 0, data + 2, data[1] - 2, pvp) < 0) {
3810                 return -1;
3811         }
3812
3813         return data[1];
3814 }       
3815
3816 /**
3817  * @brief Create a "normal" VALUE_PAIR from the given data.
3818  */
3819 ssize_t rad_attr2vp(const RADIUS_PACKET *packet,
3820                     const RADIUS_PACKET *original,
3821                     const char *secret,
3822                     const uint8_t *data, size_t length,
3823                     VALUE_PAIR **pvp)
3824 {
3825         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3826                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3827                 return -1;
3828         }
3829
3830         /*
3831          *      VSAs get their own handler.
3832          */
3833         if (data[0] == PW_VENDOR_SPECIFIC) {
3834                 return rad_attr2vp_vsa(packet, original, secret,
3835                                        data, length, pvp);
3836         }
3837
3838         /*
3839          *      Extended attribute format gets their own handler.
3840          */
3841         if (dict_attrbyvalue(data[0], VENDORPEC_EXTENDED) != NULL) {
3842                 return rad_attr2vp_extended(packet, original, secret,
3843                                             data, length, pvp);
3844         }
3845
3846         return rad_attr2vp_rfc(packet, original, secret, data, length, pvp);
3847 }
3848
3849
3850 /**
3851  * @brief Calculate/check digest, and decode radius attributes.
3852  * @return -1 on decoding error, 0 on success
3853  */
3854 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3855                const char *secret)
3856 {
3857         int                     packet_length;
3858         int                     num_attributes;
3859         uint8_t                 *ptr;
3860         radius_packet_t         *hdr;
3861         VALUE_PAIR *head, **tail, *vp;
3862
3863         /*
3864          *      Extract attribute-value pairs
3865          */
3866         hdr = (radius_packet_t *)packet->data;
3867         ptr = hdr->data;
3868         packet_length = packet->data_len - AUTH_HDR_LEN;
3869
3870         head = NULL;
3871         tail = &head;
3872         num_attributes = 0;
3873
3874         /*
3875          *      Loop over the attributes, decoding them into VPs.
3876          */
3877         while (packet_length > 0) {
3878                 ssize_t my_len;
3879
3880                 /*
3881                  *      This may return many VPs
3882                  */
3883                 my_len = rad_attr2vp(packet, original, secret,
3884                                      ptr, packet_length, &vp);
3885                 if (my_len < 0) {
3886                         pairfree(&head);
3887                         return -1;
3888                 }
3889
3890                 *tail = vp;
3891                 while (vp) {
3892                         num_attributes++;
3893                         debug_pair(vp);
3894                         tail = &(vp->next);
3895                         vp = vp->next;
3896                 }
3897
3898                 /*
3899                  *      VSA's may not have been counted properly in
3900                  *      rad_packet_ok() above, as it is hard to count
3901                  *      then without using the dictionary.  We
3902                  *      therefore enforce the limits here, too.
3903                  */
3904                 if ((fr_max_attributes > 0) &&
3905                     (num_attributes > fr_max_attributes)) {
3906                         char host_ipaddr[128];
3907
3908                         pairfree(&head);
3909                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3910                                    inet_ntop(packet->src_ipaddr.af,
3911                                              &packet->src_ipaddr.ipaddr,
3912                                              host_ipaddr, sizeof(host_ipaddr)),
3913                                    num_attributes, fr_max_attributes);
3914                         return -1;
3915                 }
3916
3917                 ptr += my_len;
3918                 packet_length -= my_len;
3919         }
3920
3921         /*
3922          *      Merge information from the outside world into our
3923          *      random pool.
3924          */
3925         fr_rand_seed(packet->data, AUTH_HDR_LEN);
3926         
3927         /*
3928          *      There may be VP's already in the packet.  Don't
3929          *      destroy them.  Instead, add the decoded attributes to
3930          *      the tail of the list.
3931          */
3932         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
3933                 /* nothing */
3934         }
3935         *tail = head;
3936
3937         return 0;
3938 }
3939
3940
3941 /**
3942  * @brief Encode password.
3943  *
3944  *      We assume that the passwd buffer passed is big enough.
3945  *      RFC2138 says the password is max 128 chars, so the size
3946  *      of the passwd buffer must be at least 129 characters.
3947  *      Preferably it's just MAX_STRING_LEN.
3948  *
3949  *      int *pwlen is updated to the new length of the encrypted
3950  *      password - a multiple of 16 bytes.
3951  */
3952 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3953                  const uint8_t *vector)
3954 {
3955         FR_MD5_CTX context, old;
3956         uint8_t digest[AUTH_VECTOR_LEN];
3957         int     i, n, secretlen;
3958         int     len;
3959
3960         /*
3961          *      RFC maximum is 128 bytes.
3962          *
3963          *      If length is zero, pad it out with zeros.
3964          *
3965          *      If the length isn't aligned to 16 bytes,
3966          *      zero out the extra data.
3967          */
3968         len = *pwlen;
3969
3970         if (len > 128) len = 128;
3971
3972         if (len == 0) {
3973                 memset(passwd, 0, AUTH_PASS_LEN);
3974                 len = AUTH_PASS_LEN;
3975         } else if ((len % AUTH_PASS_LEN) != 0) {
3976                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3977                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3978         }
3979         *pwlen = len;
3980
3981         /*
3982          *      Use the secret to setup the decryption digest
3983          */
3984         secretlen = strlen(secret);
3985
3986         fr_MD5Init(&context);
3987         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3988         old = context;          /* save intermediate work */
3989
3990         /*
3991          *      Encrypt it in place.  Don't bother checking
3992          *      len, as we've ensured above that it's OK.
3993          */
3994         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3995                 if (n == 0) {
3996                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3997                         fr_MD5Final(digest, &context);
3998                 } else {
3999                         context = old;
4000                         fr_MD5Update(&context,
4001                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4002                                      AUTH_PASS_LEN);
4003                         fr_MD5Final(digest, &context);
4004                 }
4005
4006                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4007                         passwd[i + n] ^= digest[i];
4008                 }
4009         }
4010
4011         return 0;
4012 }
4013
4014 /**
4015  * @brief Decode password.
4016  */
4017 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
4018                  const uint8_t *vector)
4019 {
4020         FR_MD5_CTX context, old;
4021         uint8_t digest[AUTH_VECTOR_LEN];
4022         int     i;
4023         size_t  n, secretlen;
4024
4025         /*
4026          *      The RFC's say that the maximum is 128.
4027          *      The buffer we're putting it into above is 254, so
4028          *      we don't need to do any length checking.
4029          */
4030         if (pwlen > 128) pwlen = 128;
4031
4032         /*
4033          *      Catch idiots.
4034          */
4035         if (pwlen == 0) goto done;
4036
4037         /*
4038          *      Use the secret to setup the decryption digest
4039          */
4040         secretlen = strlen(secret);
4041
4042         fr_MD5Init(&context);
4043         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
4044         old = context;          /* save intermediate work */
4045
4046         /*
4047          *      The inverse of the code above.
4048          */
4049         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4050                 if (n == 0) {
4051                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
4052                         fr_MD5Final(digest, &context);
4053
4054                         context = old;
4055                         if (pwlen > AUTH_PASS_LEN) {
4056                                 fr_MD5Update(&context, (uint8_t *) passwd,
4057                                              AUTH_PASS_LEN);
4058                         }
4059                 } else {
4060                         fr_MD5Final(digest, &context);
4061
4062                         context = old;
4063                         if (pwlen > (n + AUTH_PASS_LEN)) {
4064                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
4065                                              AUTH_PASS_LEN);
4066                         }
4067                 }
4068
4069                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4070                         passwd[i + n] ^= digest[i];
4071                 }
4072         }
4073
4074  done:
4075         passwd[pwlen] = '\0';
4076         return strlen(passwd);
4077 }
4078
4079
4080 /**
4081  * @brief Encode Tunnel-Password attributes when sending them out on the wire.
4082  *
4083  *      int *pwlen is updated to the new length of the encrypted
4084  *      password - a multiple of 16 bytes.
4085  *
4086  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
4087  *      value MD5 hash.
4088  */
4089 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
4090                         const uint8_t *vector)
4091 {
4092         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4093         unsigned char   digest[AUTH_VECTOR_LEN];
4094         char*   salt;
4095         int     i, n, secretlen;
4096         unsigned len, n2;
4097
4098         len = *pwlen;
4099
4100         if (len > 127) len = 127;
4101
4102         /*
4103          * Shift the password 3 positions right to place a salt and original
4104          * length, tag will be added automatically on packet send
4105          */
4106         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4107         salt = passwd;
4108         passwd += 2;
4109         /*
4110          * save original password length as first password character;
4111          */
4112         *passwd = len;
4113         len += 1;
4114
4115
4116         /*
4117          *      Generate salt.  The RFC's say:
4118          *
4119          *      The high bit of salt[0] must be set, each salt in a
4120          *      packet should be unique, and they should be random
4121          *
4122          *      So, we set the high bit, add in a counter, and then
4123          *      add in some CSPRNG data.  should be OK..
4124          */
4125         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4126                    (fr_rand() & 0x07));
4127         salt[1] = fr_rand();
4128
4129         /*
4130          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4131          */
4132         n = len % AUTH_PASS_LEN;
4133         if (n) {
4134                 n = AUTH_PASS_LEN - n;
4135                 for (; n > 0; n--, len++)
4136                         passwd[len] = 0;
4137         }
4138         /* set new password length */
4139         *pwlen = len + 2;
4140
4141         /*
4142          *      Use the secret to setup the decryption digest
4143          */
4144         secretlen = strlen(secret);
4145         memcpy(buffer, secret, secretlen);
4146
4147         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4148                 if (!n2) {
4149                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4150                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4151                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4152                 } else {
4153                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4154                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4155                 }
4156
4157                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4158                         passwd[i + n2] ^= digest[i];
4159                 }
4160         }
4161         passwd[n2] = 0;
4162         return 0;
4163 }
4164
4165 /**
4166  * @brief Decode Tunnel-Password encrypted attributes.
4167  *
4168  *      Defined in RFC-2868, this uses a two char SALT along with the
4169  *      initial intermediate value, to differentiate it from the
4170  *      above.
4171  */
4172 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
4173                         const uint8_t *vector)
4174 {
4175         FR_MD5_CTX  context, old;
4176         uint8_t         digest[AUTH_VECTOR_LEN];
4177         int             secretlen;
4178         unsigned        i, n, len, reallen;
4179
4180         len = *pwlen;
4181
4182         /*
4183          *      We need at least a salt.
4184          */
4185         if (len < 2) {
4186                 fr_strerror_printf("tunnel password is too short");
4187                 return -1;
4188         }
4189
4190         /*
4191          *      There's a salt, but no password.  Or, there's a salt
4192          *      and a 'data_len' octet.  It's wrong, but at least we
4193          *      can figure out what it means: the password is empty.
4194          *
4195          *      Note that this means we ignore the 'data_len' field,
4196          *      if the attribute length tells us that there's no
4197          *      more data.  So the 'data_len' field may be wrong,
4198          *      but that's ok...
4199          */
4200         if (len <= 3) {
4201                 passwd[0] = 0;
4202                 *pwlen = 0;
4203                 return 0;
4204         }
4205
4206         len -= 2;               /* discount the salt */
4207
4208         /*
4209          *      Use the secret to setup the decryption digest
4210          */
4211         secretlen = strlen(secret);
4212
4213         fr_MD5Init(&context);
4214         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
4215         old = context;          /* save intermediate work */
4216
4217         /*
4218          *      Set up the initial key:
4219          *
4220          *       b(1) = MD5(secret + vector + salt)
4221          */
4222         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
4223         fr_MD5Update(&context, passwd, 2);
4224
4225         reallen = 0;
4226         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4227                 int base = 0;
4228
4229                 if (n == 0) {
4230                         fr_MD5Final(digest, &context);
4231
4232                         context = old;
4233
4234                         /*
4235                          *      A quick check: decrypt the first octet
4236                          *      of the password, which is the
4237                          *      'data_len' field.  Ensure it's sane.
4238                          */
4239                         reallen = passwd[2] ^ digest[0];
4240                         if (reallen >= len) {
4241                                 fr_strerror_printf("tunnel password is too long for the attribute");
4242                                 return -1;
4243                         }
4244
4245                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
4246
4247                         base = 1;
4248                 } else {
4249                         fr_MD5Final(digest, &context);
4250
4251                         context = old;
4252                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
4253                 }
4254
4255                 for (i = base; i < AUTH_PASS_LEN; i++) {
4256                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4257                 }
4258         }
4259
4260         /*
4261          *      See make_tunnel_password, above.
4262          */
4263         if (reallen > 239) reallen = 239;
4264
4265         *pwlen = reallen;
4266         passwd[reallen] = 0;
4267
4268         return reallen;
4269 }
4270
4271 /**
4272  * @brief Encode a CHAP password
4273  *
4274  *      @bug FIXME: might not work with Ascend because
4275  *      we use vp->length, and Ascend gear likes
4276  *      to send an extra '\0' in the string!
4277  */
4278 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4279                     VALUE_PAIR *password)
4280 {
4281         int             i;
4282         uint8_t         *ptr;
4283         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4284         VALUE_PAIR      *challenge;
4285
4286         /*
4287          *      Sanity check the input parameters
4288          */
4289         if ((packet == NULL) || (password == NULL)) {
4290                 return -1;
4291         }
4292
4293         /*
4294          *      Note that the password VP can be EITHER
4295          *      a User-Password attribute (from a check-item list),
4296          *      or a CHAP-Password attribute (the client asking
4297          *      the library to encode it).
4298          */
4299
4300         i = 0;
4301         ptr = string;
4302         *ptr++ = id;
4303
4304         i++;
4305         memcpy(ptr, password->vp_strvalue, password->length);
4306         ptr += password->length;
4307         i += password->length;
4308
4309         /*
4310          *      Use Chap-Challenge pair if present,
4311          *      Request-Authenticator otherwise.
4312          */
4313         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
4314         if (challenge) {
4315                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4316                 i += challenge->length;
4317         } else {
4318                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4319                 i += AUTH_VECTOR_LEN;
4320         }
4321
4322         *output = id;
4323         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4324
4325         return 0;
4326 }
4327
4328
4329 /**
4330  * @brief Seed the random number generator.
4331  *
4332  *      May be called any number of times.
4333  */
4334 void fr_rand_seed(const void *data, size_t size)
4335 {
4336         uint32_t hash;
4337
4338         /*
4339          *      Ensure that the pool is initialized.
4340          */
4341         if (!fr_rand_initialized) {
4342                 int fd;
4343
4344                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4345
4346                 fd = open("/dev/urandom", O_RDONLY);
4347                 if (fd >= 0) {
4348                         size_t total;
4349                         ssize_t this;
4350
4351                         total = 0;
4352                         while (total < sizeof(fr_rand_pool.randrsl)) {
4353                                 this = read(fd, fr_rand_pool.randrsl,
4354                                             sizeof(fr_rand_pool.randrsl) - total);
4355                                 if ((this < 0) && (errno != EINTR)) break;
4356                                 if (this > 0) total += this;
4357                         }
4358                         close(fd);
4359                 } else {
4360                         fr_rand_pool.randrsl[0] = fd;
4361                         fr_rand_pool.randrsl[1] = time(NULL);
4362                         fr_rand_pool.randrsl[2] = errno;
4363                 }
4364
4365                 fr_randinit(&fr_rand_pool, 1);
4366                 fr_rand_pool.randcnt = 0;
4367                 fr_rand_initialized = 1;
4368         }
4369
4370         if (!data) return;
4371
4372         /*
4373          *      Hash the user data
4374          */
4375         hash = fr_rand();
4376         if (!hash) hash = fr_rand();
4377         hash = fr_hash_update(data, size, hash);
4378
4379         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4380 }
4381
4382
4383 /**
4384  * @brief Return a 32-bit random number.
4385  */
4386 uint32_t fr_rand(void)
4387 {
4388         uint32_t num;
4389
4390         /*
4391          *      Ensure that the pool is initialized.
4392          */
4393         if (!fr_rand_initialized) {
4394                 fr_rand_seed(NULL, 0);
4395         }
4396
4397         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4398         if (fr_rand_pool.randcnt >= 256) {
4399                 fr_rand_pool.randcnt = 0;
4400                 fr_isaac(&fr_rand_pool);
4401         }
4402
4403         return num;
4404 }
4405
4406
4407 /**
4408  * @brief Allocate a new RADIUS_PACKET
4409  */
4410 RADIUS_PACKET *rad_alloc(int newvector)
4411 {
4412         RADIUS_PACKET   *rp;
4413
4414         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
4415                 fr_strerror_printf("out of memory");
4416                 return NULL;
4417         }
4418         memset(rp, 0, sizeof(*rp));
4419         rp->id = -1;
4420         rp->offset = -1;
4421
4422         if (newvector) {
4423                 int i;
4424                 uint32_t hash, base;
4425
4426                 /*
4427                  *      Don't expose the actual contents of the random
4428                  *      pool.
4429                  */
4430                 base = fr_rand();
4431                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4432                         hash = fr_rand() ^ base;
4433                         memcpy(rp->vector + i, &hash, sizeof(hash));
4434                 }
4435         }
4436         fr_rand();              /* stir the pool again */
4437
4438         return rp;
4439 }
4440
4441 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
4442 {
4443         RADIUS_PACKET *reply;
4444
4445         if (!packet) return NULL;
4446
4447         reply = rad_alloc(0);
4448         if (!reply) return NULL;
4449
4450         /*
4451          *      Initialize the fields from the request.
4452          */
4453         reply->sockfd = packet->sockfd;
4454         reply->dst_ipaddr = packet->src_ipaddr;
4455         reply->src_ipaddr = packet->dst_ipaddr;
4456         reply->dst_port = packet->src_port;
4457         reply->src_port = packet->dst_port;
4458         reply->id = packet->id;
4459         reply->code = 0; /* UNKNOWN code */
4460         memcpy(reply->vector, packet->vector,
4461                sizeof(reply->vector));
4462         reply->vps = NULL;
4463         reply->data = NULL;
4464         reply->data_len = 0;
4465
4466         return reply;
4467 }
4468
4469
4470 /**
4471  * @brief Free a RADIUS_PACKET
4472  */
4473 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4474 {
4475         RADIUS_PACKET *radius_packet;
4476
4477         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4478         radius_packet = *radius_packet_ptr;
4479
4480         free(radius_packet->data);
4481
4482         pairfree(&radius_packet->vps);
4483
4484         free(radius_packet);
4485
4486         *radius_packet_ptr = NULL;
4487 }