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