Reverse the order of const and type specifier e.g. const char * becomes char const *
[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                 break;
908         }
909
910         case PW_TYPE_TLV:
911         do_tlv:
912                 data = vp->vp_tlv;
913                 if (!data) {
914                         fr_strerror_printf("ERROR: Cannot encode NULL TLV");
915                         return -1;
916                 }
917                 break;
918
919         default:                /* unknown type: ignore it */
920                 fr_strerror_printf("ERROR: Unknown attribute type %d",
921                                    vp->da->type);
922                 return -1;
923         }
924
925         /*
926          *      No data: skip it.
927          */
928         if (len == 0) {
929                 *pvp = vp->next;
930                 return 0;
931         }
932
933         /*
934          *      Bound the data to the calling size
935          */
936         if (len > (ssize_t) room) len = room;
937
938         /*
939          *      Encrypt the various password styles
940          *
941          *      Attributes with encrypted values MUST be less than
942          *      128 bytes long.
943          */
944         switch (vp->da->flags.encrypt) {
945         case FLAG_ENCRYPT_USER_PASSWORD:
946                 make_passwd(ptr, &len, data, len,
947                             secret, packet->vector);
948                 break;
949
950         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
951                 lvalue = 0;
952                 if (vp->da->flags.has_tag) lvalue = 1;
953
954                 /*
955                  *      Check if there's enough room.  If there isn't,
956                  *      we discard the attribute.
957                  *
958                  *      This is ONLY a problem if we have multiple VSA's
959                  *      in one Vendor-Specific, though.
960                  */
961                 if (room < (18 + lvalue)) return 0;
962
963                 switch (packet->code) {
964                 case PW_AUTHENTICATION_ACK:
965                 case PW_AUTHENTICATION_REJECT:
966                 case PW_ACCESS_CHALLENGE:
967                 default:
968                         if (!original) {
969                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
970                                 return -1;
971                         }
972
973                         if (lvalue) ptr[0] = vp->tag;
974                         make_tunnel_passwd(ptr + lvalue, &len, data, len,
975                                            room - lvalue,
976                                            secret, original->vector);
977                         break;
978                 case PW_ACCOUNTING_REQUEST:
979                 case PW_DISCONNECT_REQUEST:
980                 case PW_COA_REQUEST:
981                         ptr[0] = vp->tag;
982                         make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
983                                            secret, packet->vector);
984                         break;
985                 }
986                 break;
987
988                 /*
989                  *      The code above ensures that this attribute
990                  *      always fits.
991                  */
992         case FLAG_ENCRYPT_ASCEND_SECRET:
993                 if (len != 16) return 0;
994                 make_secret(ptr, packet->vector, secret, data);
995                 len = AUTH_VECTOR_LEN;
996                 break;
997
998
999         default:
1000                 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
1001                         if (vp->da->type == PW_TYPE_STRING) {
1002                                 if (len > ((ssize_t) (room - 1))) len = room - 1;
1003                                 ptr[0] = vp->tag;
1004                                 ptr++;
1005                         } else if (vp->da->type == PW_TYPE_INTEGER) {
1006                                 array[0] = vp->tag;
1007                         } /* else it can't be any other type */
1008                 }
1009                 memcpy(ptr, data, len);
1010                 break;
1011         } /* switch over encryption flags */
1012
1013         *pvp = vp->next;
1014         return len + (ptr - start);
1015 }
1016
1017 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1018                           uint8_t *ptr, int hdr_len, ssize_t len,
1019                           int flag_offset, int vsa_offset)
1020 {
1021         int check_len = len - ptr[1];
1022         int total = len + hdr_len;
1023         
1024         /*
1025          *      Pass 1: Check if the addition of the headers
1026          *      overflows the available room.  If so, return
1027          *      what we were capable of encoding.
1028          */
1029         
1030         while (check_len > (255 - hdr_len)) {
1031                 total += hdr_len;
1032                 check_len -= (255 - hdr_len);
1033         }
1034
1035         /*
1036          *      Note that this results in a number of attributes maybe
1037          *      being marked as "encoded", but which aren't in the
1038          *      packet.  Oh well.  The solution is to fix the
1039          *      "vp2data_any" function to take into account the header
1040          *      lengths.
1041          */
1042         if ((ptr + ptr[1] + total) > end) {
1043                 return (ptr + ptr[1]) - start;
1044         }
1045         
1046         /*
1047          *      Pass 2: Now that we know there's enough room,
1048          *      re-arrange the data to form a set of valid
1049          *      RADIUS attributes.
1050          */
1051         while (1) {
1052                 int sublen = 255 - ptr[1];
1053                 
1054                 if (len <= sublen) {
1055                         break;
1056                 }
1057                 
1058                 len -= sublen;
1059                 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1060                 memcpy(ptr + 255, ptr, hdr_len);
1061                 ptr[1] += sublen;
1062                 if (vsa_offset) ptr[vsa_offset] += sublen;
1063                 ptr[flag_offset] |= 0x80;
1064                 
1065                 ptr += 255;
1066                 ptr[1] = hdr_len;
1067                 if (vsa_offset) ptr[vsa_offset] = 3;
1068         }
1069
1070         ptr[1] += len;
1071         if (vsa_offset) ptr[vsa_offset] += len;
1072
1073         return (ptr + ptr[1]) - start;
1074 }
1075
1076
1077 /**
1078  * @brief Encode an "extended" attribute.
1079  */
1080 int rad_vp2extended(RADIUS_PACKET const *packet,
1081                     RADIUS_PACKET const *original,
1082                     char const *secret, VALUE_PAIR const **pvp,
1083                     uint8_t *ptr, size_t room)
1084 {
1085         int len;
1086         int hdr_len;
1087         uint8_t *start = ptr;
1088         const VALUE_PAIR *vp = *pvp;
1089
1090         if (!vp->da->flags.extended) {
1091                 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1092                 return -1;
1093         }
1094
1095         /*
1096          *      The attribute number is encoded into the upper 8 bits
1097          *      of the vendor ID.
1098          */
1099         ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1100
1101         if (!vp->da->flags.long_extended) {
1102                 if (room < 3) return 0;
1103         
1104                 ptr[1] = 3;
1105                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1106
1107         } else {
1108                 if (room < 4) return 0;
1109
1110                 ptr[1] = 4;
1111                 ptr[2] = vp->da->attr & fr_attr_mask[0];
1112                 ptr[3] = 0;
1113         }
1114
1115         /*
1116          *      Only "flagged" attributes can be longer than one
1117          *      attribute.
1118          */
1119         if (!vp->da->flags.long_extended && (room > 255)) {
1120                 room = 255;
1121         }
1122
1123         /*
1124          *      Handle EVS VSAs.
1125          */
1126         if (vp->da->flags.evs) {
1127                 uint8_t *evs = ptr + ptr[1];
1128
1129                 if (room < (size_t) (ptr[1] + 5)) return 0;
1130
1131                 ptr[2] = 26;
1132
1133                 evs[0] = 0;     /* always zero */
1134                 evs[1] = (vp->da->vendor >> 16) & 0xff;
1135                 evs[2] = (vp->da->vendor >> 8) & 0xff;
1136                 evs[3] = vp->da->vendor & 0xff;
1137                 evs[4] = vp->da->attr & fr_attr_mask[0];                
1138
1139                 ptr[1] += 5;
1140         }
1141         hdr_len = ptr[1];
1142
1143         len = vp2data_any(packet, original, secret, 0,
1144                           pvp, ptr + ptr[1], room - hdr_len);
1145         if (len <= 0) return len;
1146
1147         /*
1148          *      There may be more than 252 octets of data encoded in
1149          *      the attribute.  If so, move the data up in the packet,
1150          *      and copy the existing header over.  Set the "M" flag ONLY
1151          *      after copying the rest of the data.
1152          */
1153         if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1154                 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1155         }
1156
1157         ptr[1] += len;
1158         
1159 #ifndef NDEBUG
1160         if ((fr_debug_flag > 3) && fr_log_fp) {
1161                 int jump = 3;
1162
1163                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1164                 if (!vp->da->flags.long_extended) {
1165                         fprintf(fr_log_fp, "%02x  ", ptr[2]);
1166                         
1167                 } else {
1168                         fprintf(fr_log_fp, "%02x %02x  ", ptr[2], ptr[3]);
1169                         jump = 4;
1170                 }
1171
1172                 if (vp->da->flags.evs) {
1173                         fprintf(fr_log_fp, "%02x%02x%02x%02x (%u)  %02x  ",
1174                                 ptr[jump], ptr[jump + 1],
1175                                 ptr[jump + 2], ptr[jump + 3],
1176                                 ((ptr[jump + 1] << 16) |
1177                                  (ptr[jump + 2] << 8) |
1178                                  ptr[jump + 3]),
1179                                 ptr[jump + 4]);
1180                         jump += 5;
1181                 }
1182
1183                 print_hex_data(ptr + jump, len, 3);
1184         }
1185 #endif
1186
1187         return (ptr + ptr[1]) - start;
1188 }
1189
1190
1191 /**
1192  * @brief Encode a WiMAX attribute.
1193  */
1194 int rad_vp2wimax(RADIUS_PACKET const *packet,
1195                  RADIUS_PACKET const *original,
1196                  char const *secret, VALUE_PAIR const **pvp,
1197                  uint8_t *ptr, size_t room)
1198 {
1199         int len;
1200         uint32_t lvalue;
1201         int hdr_len;
1202         uint8_t *start = ptr;
1203         const VALUE_PAIR *vp = *pvp;
1204
1205         /*
1206          *      Double-check for WiMAX format.
1207          */
1208         if (!vp->da->flags.wimax) {
1209                 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1210                 return -1;
1211         }
1212
1213         /*
1214          *      Not enough room for:
1215          *              attr, len, vendor-id, vsa, vsalen, continuation
1216          */
1217         if (room < 9) return 0;
1218
1219         /*
1220          *      Build the Vendor-Specific header
1221          */
1222         ptr = start;
1223         ptr[0] = PW_VENDOR_SPECIFIC;
1224         ptr[1] = 9;
1225         lvalue = htonl(vp->da->vendor);
1226         memcpy(ptr + 2, &lvalue, 4);
1227         ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1228         ptr[7] = 3;
1229         ptr[8] = 0;             /* continuation byte */
1230
1231         hdr_len = 9;
1232
1233         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1234                           room - hdr_len);
1235         if (len <= 0) return len;
1236
1237         /*
1238          *      There may be more than 252 octets of data encoded in
1239          *      the attribute.  If so, move the data up in the packet,
1240          *      and copy the existing header over.  Set the "C" flag
1241          *      ONLY after copying the rest of the data.
1242          */
1243         if (len > (255 - ptr[1])) {
1244                 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1245         }
1246
1247         ptr[1] += len;
1248         ptr[7] += len;
1249
1250 #ifndef NDEBUG
1251         if ((fr_debug_flag > 3) && fr_log_fp) {
1252                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  %02x %02x %02x   ",
1253                        ptr[0], ptr[1],
1254                        ptr[2], ptr[3], ptr[4], ptr[5],
1255                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1256                        ptr[6], ptr[7], ptr[8]);
1257                 print_hex_data(ptr + 9, len, 3);
1258         }
1259 #endif
1260
1261         return (ptr + ptr[1]) - start;
1262 }
1263
1264 /**
1265  * @brief Encode an RFC format TLV.
1266  *
1267  *      This could be a standard attribute,
1268  *      or a TLV data type.  If it's a standard attribute, then
1269  *      vp->da->attr == attribute.  Otherwise, attribute may be
1270  *      something else.
1271  */
1272 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1273                            RADIUS_PACKET const *original,
1274                            char const *secret, VALUE_PAIR const **pvp,
1275                            unsigned int attribute, uint8_t *ptr, size_t room)
1276 {
1277         ssize_t len;
1278
1279         if (room < 2) return 0;
1280
1281         ptr[0] = attribute & 0xff;
1282         ptr[1] = 2;
1283
1284         if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1285
1286         len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1287         if (len <= 0) return len;
1288
1289         ptr[1] += len;
1290
1291 #ifndef NDEBUG
1292         if ((fr_debug_flag > 3) && fr_log_fp) {
1293                 fprintf(fr_log_fp, "\t\t%02x %02x  ", ptr[0], ptr[1]);
1294                 print_hex_data(ptr + 2, len, 3);
1295         }
1296 #endif
1297
1298         return ptr[1];
1299 }
1300
1301
1302 /**
1303  * @brief Encode a VSA which is a TLV.  If it's in the RFC format, call
1304  *      vp2attr_rfc.  Otherwise, encode it here.
1305  */
1306 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1307                            RADIUS_PACKET const *original,
1308                            char const *secret, VALUE_PAIR const **pvp,
1309                            unsigned int attribute, unsigned int vendor,
1310                            uint8_t *ptr, size_t room)
1311 {
1312         ssize_t len;
1313         DICT_VENDOR *dv;
1314         const VALUE_PAIR *vp = *pvp;
1315
1316         /*
1317          *      Unknown vendor: RFC format.
1318          *      Known vendor and RFC format: go do that.
1319          */
1320         dv = dict_vendorbyvalue(vendor);
1321         if (!dv ||
1322             (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1323                 return vp2attr_rfc(packet, original, secret, pvp,
1324                                    attribute, ptr, room);
1325         }
1326
1327         switch (dv->type) {
1328         default:
1329                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1330                                    " type %u", (unsigned) dv->type);
1331                 return -1;
1332
1333         case 4:
1334                 ptr[0] = 0;     /* attr must be 24-bit */
1335                 ptr[1] = (attribute >> 16) & 0xff;
1336                 ptr[2] = (attribute >> 8) & 0xff;
1337                 ptr[3] = attribute & 0xff;
1338                 break;
1339
1340         case 2:
1341                 ptr[0] = (attribute >> 8) & 0xff;
1342                 ptr[1] = attribute & 0xff;
1343                 break;
1344
1345         case 1:
1346                 ptr[0] = attribute & 0xff;
1347                 break;
1348         }
1349
1350         switch (dv->length) {
1351         default:
1352                 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1353                                    " length %u", (unsigned) dv->length);
1354                 return -1;
1355
1356         case 0:
1357                 break;
1358
1359         case 2:
1360                 ptr[dv->type] = 0;
1361                 ptr[dv->type + 1] = dv->type + 2;
1362                 break;
1363
1364         case 1:
1365                 ptr[dv->type] = dv->type + 1;
1366                 break;
1367
1368         }
1369
1370         if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1371                 room = 255 - (dv->type + dv->length);
1372         }
1373
1374         len = vp2data_any(packet, original, secret, 0, pvp,
1375                           ptr + dv->type + dv->length, room);
1376         if (len <= 0) return len;
1377
1378         if (dv->length) ptr[dv->type + dv->length - 1] += len;
1379
1380 #ifndef NDEBUG
1381         if ((fr_debug_flag > 3) && fr_log_fp) {
1382                 switch (dv->type) {
1383                 default:
1384                         break;
1385
1386                 case 4:
1387                         if ((fr_debug_flag > 3) && fr_log_fp)
1388                                 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1389                                         ptr[0], ptr[1], ptr[2], ptr[3]);
1390                         break;
1391                         
1392                 case 2:
1393                         if ((fr_debug_flag > 3) && fr_log_fp)
1394                                 fprintf(fr_log_fp, "\t\t%02x%02x ",
1395                                         ptr[0], ptr[1]);
1396                 break;
1397                 
1398                 case 1:
1399                         if ((fr_debug_flag > 3) && fr_log_fp)
1400                                 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1401                         break;
1402                 }
1403                 
1404                 switch (dv->length) {
1405                 default:
1406                         break;
1407
1408                 case 0:
1409                         fprintf(fr_log_fp, "  ");
1410                         break;
1411
1412                 case 1:
1413                         fprintf(fr_log_fp, "%02x  ",
1414                                 ptr[dv->type]);
1415                         break;
1416
1417                 case 2:
1418                         fprintf(fr_log_fp, "%02x%02x  ",
1419                                 ptr[dv->type], ptr[dv->type] + 1);
1420                         break;
1421                 }
1422
1423                 print_hex_data(ptr + dv->type + dv->length, len, 3);
1424         }
1425 #endif
1426
1427         return dv->type + dv->length + len;
1428 }
1429
1430
1431 /**
1432  * @brief Encode a Vendor-Specific attribute.
1433  */
1434 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1435                 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1436                 size_t room)
1437 {
1438         ssize_t len;
1439         uint32_t lvalue;
1440         const VALUE_PAIR *vp = *pvp;
1441
1442         /*
1443          *      Double-check for WiMAX format.
1444          */
1445         if (vp->da->flags.wimax) {
1446                 return rad_vp2wimax(packet, original, secret, pvp,
1447                                     ptr, room);
1448         }
1449
1450         if (vp->da->vendor > FR_MAX_VENDOR) {
1451                 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1452                 return -1;
1453         }
1454
1455         /*
1456          *      Not enough room for:
1457          *              attr, len, vendor-id
1458          */
1459         if (room < 6) return 0;
1460
1461         /*
1462          *      Build the Vendor-Specific header
1463          */
1464         ptr[0] = PW_VENDOR_SPECIFIC;
1465         ptr[1] = 6;
1466         lvalue = htonl(vp->da->vendor);
1467         memcpy(ptr + 2, &lvalue, 4);
1468
1469         if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1470
1471         len = vp2attr_vsa(packet, original, secret, pvp,
1472                           vp->da->attr, vp->da->vendor,
1473                           ptr + ptr[1], room);
1474         if (len < 0) return len;
1475
1476 #ifndef NDEBUG
1477         if ((fr_debug_flag > 3) && fr_log_fp) {
1478                 fprintf(fr_log_fp, "\t\t%02x %02x  %02x%02x%02x%02x (%u)  ",
1479                        ptr[0], ptr[1],
1480                        ptr[2], ptr[3], ptr[4], ptr[5],
1481                        (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1482                 print_hex_data(ptr + 6, len, 3);
1483         }
1484 #endif
1485
1486         ptr[1] += len;
1487
1488         return ptr[1];
1489 }
1490
1491
1492 /**
1493  * @brief Encode an RFC standard attribute 1..255
1494  */
1495 int rad_vp2rfc(RADIUS_PACKET const *packet,
1496                RADIUS_PACKET const *original,
1497                char const *secret, VALUE_PAIR const **pvp,
1498                uint8_t *ptr, size_t room)
1499 {
1500         const VALUE_PAIR *vp = *pvp;
1501
1502         if (vp->da->vendor != 0) {
1503                 fr_strerror_printf("rad_vp2rfc called with VSA");
1504                 return -1;
1505         }
1506
1507         if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1508                 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1509                 return -1;
1510         }
1511
1512         /*
1513          *      Only CUI is allowed to have zero length.
1514          *      Thank you, WiMAX!
1515          */
1516         if ((vp->length == 0) &&
1517             (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1518                 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1519                 ptr[1] = 2;
1520
1521                 *pvp = vp->next;
1522                 return 2;
1523         }
1524
1525         /*
1526          *      Message-Authenticator is hard-coded.
1527          */
1528         if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1529                 if (room < 18) return -1;
1530                 
1531                 debug_pair(vp);
1532                 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1533                 ptr[1] = 18;
1534                 memset(ptr + 2, 0, 16);
1535 #ifndef NDEBUG
1536                 if ((fr_debug_flag > 3) && fr_log_fp) {
1537                         fprintf(fr_log_fp, "\t\t50 12 ...\n");
1538                 }
1539 #endif
1540                 
1541                 *pvp = (*pvp)->next;
1542                 return 18;
1543         }
1544
1545         return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1546                            ptr, room);
1547 }
1548
1549 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1550                              RADIUS_PACKET const *original,
1551                              char const *secret, VALUE_PAIR const **pvp,
1552                              uint8_t *start, size_t room)
1553 {
1554         ssize_t len;
1555         const VALUE_PAIR *vp = *pvp;
1556
1557         if (!vp->da->flags.is_tlv) {
1558                 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1559                 return -1;
1560         }
1561
1562         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1563                 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1564                 return -1;
1565         }
1566
1567         if (room < 5) return 0;
1568
1569         /*
1570          *      Encode the first level of TLVs
1571          */
1572         start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1573         start[1] = 4;
1574         start[2] = vp->da->attr & fr_attr_mask[0];
1575         start[3] = 2;
1576
1577         len = vp2data_any(packet, original, secret, 0, pvp,
1578                           start + 4, room - 4);
1579         if (len <= 0) return len;
1580
1581         if (len > 253) {
1582                 return -1;
1583         }
1584
1585         start[1] += len;
1586         start[3] += len;
1587
1588         return start[1];
1589 }
1590
1591 /**
1592  * @brief Parse a data structure into a RADIUS attribute.
1593  */
1594 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1595                 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1596                 size_t room)
1597 {
1598         const VALUE_PAIR *vp;
1599
1600         if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1601
1602         vp = *pvp;
1603
1604         /*
1605          *      RFC format attributes take the fast path.
1606          */
1607         if (!vp->da->vendor) {
1608                 if (vp->da->attr > 255) return 0;
1609
1610                 return rad_vp2rfc(packet, original, secret, pvp,
1611                                   start, room);
1612         }
1613
1614         if (vp->da->flags.extended) {
1615                 return rad_vp2extended(packet, original, secret, pvp,
1616                                        start, room);
1617         }
1618
1619         /*
1620          *      The upper 8 bits of the vendor number are the standard
1621          *      space attribute which is a TLV.
1622          */
1623         if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1624                 return rad_vp2rfctlv(packet, original, secret, pvp,
1625                                      start, room);
1626         }
1627
1628         if (vp->da->flags.wimax) {
1629                 return rad_vp2wimax(packet, original, secret, pvp,
1630                                     start, room);
1631         }
1632
1633         return rad_vp2vsa(packet, original, secret, pvp,
1634                           start, room);
1635 }
1636
1637
1638 /**
1639  * @brief Encode a packet.
1640  */
1641 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1642                char const *secret)
1643 {
1644         radius_packet_t *hdr;
1645         uint8_t         *ptr;
1646         uint16_t        total_length;
1647         int             len;
1648         const VALUE_PAIR        *reply;
1649         char const      *what;
1650         char            ip_src_buffer[128];
1651         char            ip_dst_buffer[128];
1652
1653         /*
1654          *      A 4K packet, aligned on 64-bits.
1655          */
1656         uint64_t        data[MAX_PACKET_LEN / sizeof(uint64_t)];
1657
1658         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1659                 what = fr_packet_codes[packet->code];
1660         } else {
1661                 what = "Reply";
1662         }
1663
1664         DEBUG("Sending %s of id %d from %s port %u to %s port %u\n",
1665               what, packet->id,
1666               inet_ntop(packet->src_ipaddr.af,
1667                         &packet->src_ipaddr.ipaddr,
1668                         ip_src_buffer, sizeof(ip_src_buffer)),
1669               packet->src_port,
1670               inet_ntop(packet->dst_ipaddr.af,
1671                         &packet->dst_ipaddr.ipaddr,
1672                         ip_dst_buffer, sizeof(ip_dst_buffer)),
1673               packet->dst_port);
1674
1675         /*
1676          *      Double-check some things based on packet code.
1677          */
1678         switch (packet->code) {
1679         case PW_AUTHENTICATION_ACK:
1680         case PW_AUTHENTICATION_REJECT:
1681         case PW_ACCESS_CHALLENGE:
1682                 if (!original) {
1683                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1684                         return -1;
1685                 }
1686                 break;
1687
1688                 /*
1689                  *      These packet vectors start off as all zero.
1690                  */
1691         case PW_ACCOUNTING_REQUEST:
1692         case PW_DISCONNECT_REQUEST:
1693         case PW_COA_REQUEST:
1694                 memset(packet->vector, 0, sizeof(packet->vector));
1695                 break;
1696
1697         default:
1698                 break;
1699         }
1700
1701         /*
1702          *      Use memory on the stack, until we know how
1703          *      large the packet will be.
1704          */
1705         hdr = (radius_packet_t *) data;
1706
1707         /*
1708          *      Build standard header
1709          */
1710         hdr->code = packet->code;
1711         hdr->id = packet->id;
1712
1713         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1714
1715         total_length = AUTH_HDR_LEN;
1716
1717         /*
1718          *      Load up the configuration values for the user
1719          */
1720         ptr = hdr->data;
1721         packet->offset = 0;
1722
1723         /*
1724          *      FIXME: Loop twice over the reply list.  The first time,
1725          *      calculate the total length of data.  The second time,
1726          *      allocate the memory, and fill in the VP's.
1727          *
1728          *      Hmm... this may be slower than just doing a small
1729          *      memcpy.
1730          */
1731
1732         /*
1733          *      Loop over the reply attributes for the packet.
1734          */
1735         reply = packet->vps;
1736         while (reply) {
1737                 size_t last_len;
1738                 char const *last_name = NULL;
1739
1740                 /*
1741                  *      Ignore non-wire attributes, but allow extended
1742                  *      attributes.
1743                  */
1744                 if ((reply->da->vendor == 0) &&
1745                     ((reply->da->attr & 0xFFFF) >= 256) &&
1746                     !reply->da->flags.extended && !reply->da->flags.long_extended) {
1747 #ifndef NDEBUG
1748                         /*
1749                          *      Permit the admin to send BADLY formatted
1750                          *      attributes with a debug build.
1751                          */
1752                         if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1753                                 memcpy(ptr, reply->vp_octets, reply->length);
1754                                 len = reply->length;
1755                                 reply = reply->next;
1756                                 goto next;
1757                         }
1758 #endif
1759                         reply = reply->next;
1760                         continue;
1761                 }
1762
1763                 /*
1764                  *      Set the Message-Authenticator to the correct
1765                  *      length and initial value.
1766                  */
1767                 if (reply->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1768                         /*
1769                          *      Cache the offset to the
1770                          *      Message-Authenticator
1771                          */
1772                         packet->offset = total_length;
1773                         last_len = 16;
1774                 } else {
1775                         last_len = reply->length;
1776                 }
1777                 last_name = reply->da->name;
1778
1779                 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1780                                   ((uint8_t *) data) + sizeof(data) - ptr);
1781                 if (len < 0) return -1;
1782
1783                 /*
1784                  *      Failed to encode the attribute, likely because
1785                  *      the packet is full.
1786                  */
1787                 if (len == 0) {
1788                         if (last_len != 0) {
1789                                 DEBUG("WARNING: Failed encoding attribute %s\n", last_name);
1790                         } else {
1791                                 DEBUG("WARNING: Skipping zero-length attribute %s\n", last_name);
1792                         }
1793                 }
1794
1795 #ifndef NDEBUG
1796         next:                   /* Used only for Raw-Attribute */
1797 #endif
1798                 ptr += len;
1799                 total_length += len;
1800         } /* done looping over all attributes */
1801
1802         /*
1803          *      Fill in the rest of the fields, and copy the data over
1804          *      from the local stack to the newly allocated memory.
1805          *
1806          *      Yes, all this 'memcpy' is slow, but it means
1807          *      that we only allocate the minimum amount of
1808          *      memory for a request.
1809          */
1810         packet->data_len = total_length;
1811         packet->data = talloc_array(packet, uint8_t, packet->data_len);
1812         if (!packet->data) {
1813                 fr_strerror_printf("Out of memory");
1814                 return -1;
1815         }
1816
1817         memcpy(packet->data, hdr, packet->data_len);
1818         hdr = (radius_packet_t *) packet->data;
1819
1820         total_length = htons(total_length);
1821         memcpy(hdr->length, &total_length, sizeof(total_length));
1822
1823         return 0;
1824 }
1825
1826
1827 /**
1828  * @brief Sign a previously encoded packet.
1829  */
1830 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1831              char const *secret)
1832 {
1833         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1834
1835         /*
1836          *      It wasn't assigned an Id, this is bad!
1837          */
1838         if (packet->id < 0) {
1839                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1840                 return -1;
1841         }
1842
1843         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1844             (packet->offset < 0)) {
1845                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1846                 return -1;
1847         }
1848
1849         /*
1850          *      If there's a Message-Authenticator, update it
1851          *      now, BEFORE updating the authentication vector.
1852          */
1853         if (packet->offset > 0) {
1854                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1855
1856                 switch (packet->code) {
1857                 case PW_ACCOUNTING_RESPONSE:
1858                         if (original && original->code == PW_STATUS_SERVER) {
1859                                 goto do_ack;
1860                         }
1861
1862                 case PW_ACCOUNTING_REQUEST:
1863                 case PW_DISCONNECT_REQUEST:
1864                 case PW_DISCONNECT_ACK:
1865                 case PW_DISCONNECT_NAK:
1866                 case PW_COA_REQUEST:
1867                 case PW_COA_ACK:
1868                 case PW_COA_NAK:
1869                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1870                         break;
1871
1872                 do_ack:
1873                 case PW_AUTHENTICATION_ACK:
1874                 case PW_AUTHENTICATION_REJECT:
1875                 case PW_ACCESS_CHALLENGE:
1876                         if (!original) {
1877                                 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1878                                 return -1;
1879                         }
1880                         memcpy(hdr->vector, original->vector,
1881                                AUTH_VECTOR_LEN);
1882                         break;
1883
1884                 default:        /* others have vector already set to zero */
1885                         break;
1886
1887                 }
1888
1889                 /*
1890                  *      Set the authentication vector to zero,
1891                  *      calculate the HMAC, and put it
1892                  *      into the Message-Authenticator
1893                  *      attribute.
1894                  */
1895                 fr_hmac_md5(packet->data, packet->data_len,
1896                             (uint8_t const *) secret, strlen(secret),
1897                             calc_auth_vector);
1898                 memcpy(packet->data + packet->offset + 2,
1899                        calc_auth_vector, AUTH_VECTOR_LEN);
1900
1901                 /*
1902                  *      Copy the original request vector back
1903                  *      to the raw packet.
1904                  */
1905                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1906         }
1907
1908         /*
1909          *      Switch over the packet code, deciding how to
1910          *      sign the packet.
1911          */
1912         switch (packet->code) {
1913                 /*
1914                  *      Request packets are not signed, bur
1915                  *      have a random authentication vector.
1916                  */
1917         case PW_AUTHENTICATION_REQUEST:
1918         case PW_STATUS_SERVER:
1919                 break;
1920
1921                 /*
1922                  *      Reply packets are signed with the
1923                  *      authentication vector of the request.
1924                  */
1925         default:
1926                 {
1927                         uint8_t digest[16];
1928
1929                         FR_MD5_CTX      context;
1930                         fr_MD5Init(&context);
1931                         fr_MD5Update(&context, packet->data, packet->data_len);
1932                         fr_MD5Update(&context, (uint8_t const *) secret,
1933                                      strlen(secret));
1934                         fr_MD5Final(digest, &context);
1935
1936                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1937                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1938                         break;
1939                 }
1940         }/* switch over packet codes */
1941
1942         return 0;
1943 }
1944
1945 /**
1946  * @brief Reply to the request.  Also attach
1947  *      reply attribute value pairs and any user message provided.
1948  */
1949 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1950              char const *secret)
1951 {
1952         VALUE_PAIR              *reply;
1953         char const              *what;
1954         char                    ip_src_buffer[128];
1955         char                    ip_dst_buffer[128];
1956
1957         /*
1958          *      Maybe it's a fake packet.  Don't send it.
1959          */
1960         if (!packet || (packet->sockfd < 0)) {
1961                 return 0;
1962         }
1963
1964         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1965                 what = fr_packet_codes[packet->code];
1966         } else {
1967                 what = "Reply";
1968         }
1969
1970         /*
1971          *  First time through, allocate room for the packet
1972          */
1973         if (!packet->data) {
1974                 /*
1975                  *      Encode the packet.
1976                  */
1977                 if (rad_encode(packet, original, secret) < 0) {
1978                         return -1;
1979                 }
1980
1981                 /*
1982                  *      Re-sign it, including updating the
1983                  *      Message-Authenticator.
1984                  */
1985                 if (rad_sign(packet, original, secret) < 0) {
1986                         return -1;
1987                 }
1988
1989                 /*
1990                  *      If packet->data points to data, then we print out
1991                  *      the VP list again only for debugging.
1992                  */
1993         } else if (fr_debug_flag) {
1994                 DEBUG("Sending %s of id %d from %s port %u to %s port %u\n", what,
1995                       packet->id,
1996                       inet_ntop(packet->src_ipaddr.af,
1997                                 &packet->src_ipaddr.ipaddr,
1998                                 ip_src_buffer, sizeof(ip_src_buffer)),
1999                       packet->src_port,
2000                       inet_ntop(packet->dst_ipaddr.af,
2001                                 &packet->dst_ipaddr.ipaddr,
2002                                 ip_dst_buffer, sizeof(ip_dst_buffer)),
2003                       packet->dst_port);
2004
2005                 for (reply = packet->vps; reply; reply = reply->next) {
2006                         if ((reply->da->vendor == 0) &&
2007                             ((reply->da->attr & 0xFFFF) > 0xff)) continue;
2008                         debug_pair(reply);
2009                 }
2010         }
2011
2012 #ifndef NDEBUG
2013         if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2014 #endif
2015
2016         /*
2017          *      And send it on it's way.
2018          */
2019         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2020                           &packet->src_ipaddr, packet->src_port,
2021                           &packet->dst_ipaddr, packet->dst_port);
2022 }
2023
2024 /**
2025  * @brief Do a comparison of two authentication digests by comparing
2026  *      the FULL digest.
2027  *
2028  *      Otherwise, the server can be subject to
2029  *      timing attacks that allow attackers find a valid message
2030  *      authenticator.
2031  *
2032  *      http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2033  */
2034 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2035 {
2036         int result = 0;
2037         size_t i;
2038
2039         for (i = 0; i < length; i++) {
2040                 result |= a[i] ^ b[i];
2041         }
2042
2043         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
2044 }
2045
2046
2047 /**
2048  * @brief Validates the requesting client NAS.  Calculates the
2049  *      Request Authenticator based on the clients private key.
2050  */
2051 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2052 {
2053         uint8_t         digest[AUTH_VECTOR_LEN];
2054         FR_MD5_CTX              context;
2055
2056         /*
2057          *      Zero out the auth_vector in the received packet.
2058          *      Then append the shared secret to the received packet,
2059          *      and calculate the MD5 sum. This must be the same
2060          *      as the original MD5 sum (packet->vector).
2061          */
2062         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2063
2064         /*
2065          *  MD5(packet + secret);
2066          */
2067         fr_MD5Init(&context);
2068         fr_MD5Update(&context, packet->data, packet->data_len);
2069         fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
2070         fr_MD5Final(digest, &context);
2071
2072         /*
2073          *      Return 0 if OK, 2 if not OK.
2074          */
2075         if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2076         return 0;
2077 }
2078
2079
2080 /**
2081  * @brief Validates the requesting client NAS.  Calculates the
2082  *      Response Authenticator based on the clients private key.
2083  */
2084 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2085                             char const *secret)
2086 {
2087         uint8_t         calc_digest[AUTH_VECTOR_LEN];
2088         FR_MD5_CTX              context;
2089
2090         /*
2091          *      Very bad!
2092          */
2093         if (original == NULL) {
2094                 return 3;
2095         }
2096
2097         /*
2098          *  Copy the original vector in place.
2099          */
2100         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2101
2102         /*
2103          *  MD5(packet + secret);
2104          */
2105         fr_MD5Init(&context);
2106         fr_MD5Update(&context, packet->data, packet->data_len);
2107         fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
2108         fr_MD5Final(calc_digest, &context);
2109
2110         /*
2111          *  Copy the packet's vector back to the packet.
2112          */
2113         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2114
2115         /*
2116          *      Return 0 if OK, 2 if not OK.
2117          */
2118         if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2119         return 0;
2120 }
2121
2122
2123 /**
2124  * @brief Check if a set of RADIUS formatted TLVs are OK.
2125  */
2126 int rad_tlv_ok(uint8_t const *data, size_t length,
2127                size_t dv_type, size_t dv_length)
2128 {
2129         const uint8_t *end = data + length;
2130
2131         if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2132                 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2133                 return -1;
2134         }
2135
2136         while (data < end) {
2137                 size_t attrlen;
2138
2139                 if ((data + dv_type + dv_length) > end) {
2140                         fr_strerror_printf("Attribute header overflow");
2141                         return -1;
2142                 }
2143
2144                 switch (dv_type) {
2145                 case 4:
2146                         if ((data[0] == 0) && (data[1] == 0) &&
2147                             (data[2] == 0) && (data[3] == 0)) {
2148                         zero:
2149                                 fr_strerror_printf("Invalid attribute 0");
2150                                 return -1;
2151                         }
2152
2153                         if (data[0] != 0) {
2154                                 fr_strerror_printf("Invalid attribute > 2^24");
2155                                 return -1;
2156                         }
2157                         break;
2158
2159                 case 2:
2160                         if ((data[0] == 0) && (data[1] == 0)) goto zero;
2161                         break;
2162
2163                 case 1:
2164                         if (data[0] == 0) goto zero;
2165                         break;
2166
2167                 default:
2168                         fr_strerror_printf("Internal sanity check failed");
2169                         return -1;
2170                 }
2171
2172                 switch (dv_length) {
2173                 case 0:
2174                         return 0;
2175
2176                 case 2:
2177                         if (data[dv_type + 1] != 0) {
2178                                 fr_strerror_printf("Attribute is longer than 256 octets");
2179                                 return -1;
2180                         }
2181                         /* FALL-THROUGH */
2182                 case 1:
2183                         attrlen = data[dv_type + dv_length - 1];
2184                         break;
2185
2186
2187                 default:
2188                         fr_strerror_printf("Internal sanity check failed");
2189                         return -1;
2190                 }
2191
2192                 if (attrlen < (dv_type + dv_length)) {
2193                         fr_strerror_printf("Attribute header has invalid length");
2194                         return -1;
2195                 }
2196
2197                 if (attrlen > length) {
2198                         fr_strerror_printf("Attribute overflows container");
2199                         return -1;
2200                 }
2201
2202                 data += attrlen;
2203                 length -= attrlen;
2204         }
2205
2206         return 0;
2207 }
2208
2209
2210 /**
2211  * @brief See if the data pointed to by PTR is a valid RADIUS packet.
2212  *
2213  *      packet is not 'const * const' because we may update data_len,
2214  *      if there's more data in the UDP packet than in the RADIUS packet.
2215  */
2216 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
2217 {
2218         uint8_t                 *attr;
2219         size_t                  totallen;
2220         int                     count;
2221         radius_packet_t         *hdr;
2222         char                    host_ipaddr[128];
2223         int                     require_ma = 0;
2224         int                     seen_ma = 0;
2225         int                     num_attributes;
2226
2227         /*
2228          *      Check for packets smaller than the packet header.
2229          *
2230          *      RFC 2865, Section 3., subsection 'length' says:
2231          *
2232          *      "The minimum length is 20 ..."
2233          */
2234         if (packet->data_len < AUTH_HDR_LEN) {
2235                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2236                            inet_ntop(packet->src_ipaddr.af,
2237                                      &packet->src_ipaddr.ipaddr,
2238                                      host_ipaddr, sizeof(host_ipaddr)),
2239                                      packet->data_len, AUTH_HDR_LEN);
2240                 return 0;
2241         }
2242
2243
2244         /*
2245          *      Check for packets with mismatched size.
2246          *      i.e. We've received 128 bytes, and the packet header
2247          *      says it's 256 bytes long.
2248          */
2249         totallen = (packet->data[2] << 8) | packet->data[3];
2250         hdr = (radius_packet_t *)packet->data;
2251
2252         /*
2253          *      Code of 0 is not understood.
2254          *      Code of 16 or greate is not understood.
2255          */
2256         if ((hdr->code == 0) ||
2257             (hdr->code >= FR_MAX_PACKET_CODE)) {
2258                 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2259                            inet_ntop(packet->src_ipaddr.af,
2260                                      &packet->src_ipaddr.ipaddr,
2261                                      host_ipaddr, sizeof(host_ipaddr)),
2262                            hdr->code);
2263                 return 0;
2264         }
2265
2266         /*
2267          *      Message-Authenticator is required in Status-Server
2268          *      packets, otherwise they can be trivially forged.
2269          */
2270         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
2271
2272         /*
2273          *      It's also required if the caller asks for it.
2274          */
2275         if (flags) require_ma = 1;
2276
2277         /*
2278          *      Repeat the length checks.  This time, instead of
2279          *      looking at the data we received, look at the value
2280          *      of the 'length' field inside of the packet.
2281          *
2282          *      Check for packets smaller than the packet header.
2283          *
2284          *      RFC 2865, Section 3., subsection 'length' says:
2285          *
2286          *      "The minimum length is 20 ..."
2287          */
2288         if (totallen < AUTH_HDR_LEN) {
2289                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2290                            inet_ntop(packet->src_ipaddr.af,
2291                                      &packet->src_ipaddr.ipaddr,
2292                                      host_ipaddr, sizeof(host_ipaddr)),
2293                                      totallen, AUTH_HDR_LEN);
2294                 return 0;
2295         }
2296
2297         /*
2298          *      And again, for the value of the 'length' field.
2299          *
2300          *      RFC 2865, Section 3., subsection 'length' says:
2301          *
2302          *      " ... and maximum length is 4096."
2303          *
2304          *      HOWEVER.  This requirement is for the network layer.
2305          *      If the code gets here, we assume that a well-formed
2306          *      packet is an OK packet.
2307          *
2308          *      We allow both the UDP data length, and the RADIUS
2309          *      "length" field to contain up to 64K of data.
2310          */
2311
2312         /*
2313          *      RFC 2865, Section 3., subsection 'length' says:
2314          *
2315          *      "If the packet is shorter than the Length field
2316          *      indicates, it MUST be silently discarded."
2317          *
2318          *      i.e. No response to the NAS.
2319          */
2320         if (packet->data_len < totallen) {
2321                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2322                            inet_ntop(packet->src_ipaddr.af,
2323                                      &packet->src_ipaddr.ipaddr,
2324                                      host_ipaddr, sizeof(host_ipaddr)),
2325                                      packet->data_len, totallen);
2326                 return 0;
2327         }
2328
2329         /*
2330          *      RFC 2865, Section 3., subsection 'length' says:
2331          *
2332          *      "Octets outside the range of the Length field MUST be
2333          *      treated as padding and ignored on reception."
2334          */
2335         if (packet->data_len > totallen) {
2336                 /*
2337                  *      We're shortening the packet below, but just
2338                  *      to be paranoid, zero out the extra data.
2339                  */
2340                 memset(packet->data + totallen, 0, packet->data_len - totallen);
2341                 packet->data_len = totallen;
2342         }
2343
2344         /*
2345          *      Walk through the packet's attributes, ensuring that
2346          *      they add up EXACTLY to the size of the packet.
2347          *
2348          *      If they don't, then the attributes either under-fill
2349          *      or over-fill the packet.  Any parsing of the packet
2350          *      is impossible, and will result in unknown side effects.
2351          *
2352          *      This would ONLY happen with buggy RADIUS implementations,
2353          *      or with an intentional attack.  Either way, we do NOT want
2354          *      to be vulnerable to this problem.
2355          */
2356         attr = hdr->data;
2357         count = totallen - AUTH_HDR_LEN;
2358         num_attributes = 0;
2359
2360         while (count > 0) {
2361                 /*
2362                  *      We need at least 2 bytes to check the
2363                  *      attribute header.
2364                  */
2365                 if (count < 2) {
2366                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2367                                    inet_ntop(packet->src_ipaddr.af,
2368                                              &packet->src_ipaddr.ipaddr,
2369                                              host_ipaddr, sizeof(host_ipaddr)));
2370                         return 0;
2371                 }
2372
2373                 /*
2374                  *      Attribute number zero is NOT defined.
2375                  */
2376                 if (attr[0] == 0) {
2377                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2378                                    inet_ntop(packet->src_ipaddr.af,
2379                                              &packet->src_ipaddr.ipaddr,
2380                                              host_ipaddr, sizeof(host_ipaddr)));
2381                         return 0;
2382                 }
2383
2384                 /*
2385                  *      Attributes are at LEAST as long as the ID & length
2386                  *      fields.  Anything shorter is an invalid attribute.
2387                  */
2388                 if (attr[1] < 2) {
2389                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2390                                    inet_ntop(packet->src_ipaddr.af,
2391                                              &packet->src_ipaddr.ipaddr,
2392                                              host_ipaddr, sizeof(host_ipaddr)),
2393                                    attr[0]);
2394                         return 0;
2395                 }
2396
2397                 /*
2398                  *      If there are fewer bytes in the packet than in the
2399                  *      attribute, it's a bad packet.
2400                  */
2401                 if (count < attr[1]) {
2402                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2403                                    inet_ntop(packet->src_ipaddr.af,
2404                                              &packet->src_ipaddr.ipaddr,
2405                                              host_ipaddr, sizeof(host_ipaddr)),
2406                                            attr[0]);
2407                         return 0;
2408                 }
2409
2410                 /*
2411                  *      Sanity check the attributes for length.
2412                  */
2413                 switch (attr[0]) {
2414                 default:        /* don't do anything by default */
2415                         break;
2416
2417                         /*
2418                          *      If there's an EAP-Message, we require
2419                          *      a Message-Authenticator.
2420                          */
2421                 case PW_EAP_MESSAGE:
2422                         require_ma = 1;
2423                         break;
2424
2425                 case PW_MESSAGE_AUTHENTICATOR:
2426                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2427                                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2428                                            inet_ntop(packet->src_ipaddr.af,
2429                                                      &packet->src_ipaddr.ipaddr,
2430                                                      host_ipaddr, sizeof(host_ipaddr)),
2431                                            attr[1] - 2);
2432                                 return 0;
2433                         }
2434                         seen_ma = 1;
2435                         break;
2436                 }
2437
2438                 /*
2439                  *      FIXME: Look up the base 255 attributes in the
2440                  *      dictionary, and switch over their type.  For
2441                  *      integer/date/ip, the attribute length SHOULD
2442                  *      be 6.
2443                  */
2444                 count -= attr[1];       /* grab the attribute length */
2445                 attr += attr[1];
2446                 num_attributes++;       /* seen one more attribute */
2447         }
2448
2449         /*
2450          *      If the attributes add up to a packet, it's allowed.
2451          *
2452          *      If not, we complain, and throw the packet away.
2453          */
2454         if (count != 0) {
2455                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2456                            inet_ntop(packet->src_ipaddr.af,
2457                                      &packet->src_ipaddr.ipaddr,
2458                                      host_ipaddr, sizeof(host_ipaddr)));
2459                 return 0;
2460         }
2461
2462         /*
2463          *      If we're configured to look for a maximum number of
2464          *      attributes, and we've seen more than that maximum,
2465          *      then throw the packet away, as a possible DoS.
2466          */
2467         if ((fr_max_attributes > 0) &&
2468             (num_attributes > fr_max_attributes)) {
2469                 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2470                            inet_ntop(packet->src_ipaddr.af,
2471                                      &packet->src_ipaddr.ipaddr,
2472                                      host_ipaddr, sizeof(host_ipaddr)),
2473                            num_attributes, fr_max_attributes);
2474                 return 0;
2475         }
2476
2477         /*
2478          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2479          *
2480          *      A packet with an EAP-Message attribute MUST also have
2481          *      a Message-Authenticator attribute.
2482          *
2483          *      A Message-Authenticator all by itself is OK, though.
2484          *
2485          *      Similarly, Status-Server packets MUST contain
2486          *      Message-Authenticator attributes.
2487          */
2488         if (require_ma && ! seen_ma) {
2489                 fr_strerror_printf("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
2490                            inet_ntop(packet->src_ipaddr.af,
2491                                      &packet->src_ipaddr.ipaddr,
2492                                      host_ipaddr, sizeof(host_ipaddr)));
2493                 return 0;
2494         }
2495
2496         /*
2497          *      Fill RADIUS header fields
2498          */
2499         packet->code = hdr->code;
2500         packet->id = hdr->id;
2501         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2502
2503         return 1;
2504 }
2505
2506
2507 /**
2508  * @brief Receive UDP client requests, and fill in
2509  *      the basics of a RADIUS_PACKET structure.
2510  */
2511 RADIUS_PACKET *rad_recv(int fd, int flags)
2512 {
2513         int sock_flags = 0;
2514         ssize_t data_len;
2515         RADIUS_PACKET           *packet;
2516
2517         /*
2518          *      Allocate the new request data structure
2519          */
2520         packet = rad_alloc(NULL, 0);
2521         if (!packet) {
2522                 fr_strerror_printf("out of memory");
2523                 return NULL;
2524         }
2525
2526         if (flags & 0x02) {
2527                 sock_flags = MSG_PEEK;
2528                 flags &= ~0x02;
2529         }
2530
2531         data_len = rad_recvfrom(fd, packet, sock_flags,
2532                                 &packet->src_ipaddr, &packet->src_port,
2533                                 &packet->dst_ipaddr, &packet->dst_port);
2534
2535         /*
2536          *      Check for socket errors.
2537          */
2538         if (data_len < 0) {
2539                 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
2540                 /* packet->data is NULL */
2541                 rad_free(&packet);
2542                 return NULL;
2543         }
2544         packet->data_len = data_len; /* unsigned vs signed */
2545
2546         /*
2547          *      If the packet is too big, then rad_recvfrom did NOT
2548          *      allocate memory.  Instead, it just discarded the
2549          *      packet.
2550          */
2551         if (packet->data_len > MAX_PACKET_LEN) {
2552                 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
2553                 /* packet->data is NULL */
2554                 rad_free(&packet);
2555                 return NULL;
2556         }
2557
2558         /*
2559          *      Read no data.  Continue.
2560          *      This check is AFTER the MAX_PACKET_LEN check above, because
2561          *      if the packet is larger than MAX_PACKET_LEN, we also have
2562          *      packet->data == NULL
2563          */
2564         if ((packet->data_len == 0) || !packet->data) {
2565                 fr_strerror_printf("Empty packet: Socket is not ready.");
2566                 rad_free(&packet);
2567                 return NULL;
2568         }
2569
2570         /*
2571          *      See if it's a well-formed RADIUS packet.
2572          */
2573         if (!rad_packet_ok(packet, flags)) {
2574                 rad_free(&packet);
2575                 return NULL;
2576         }
2577
2578         /*
2579          *      Remember which socket we read the packet from.
2580          */
2581         packet->sockfd = fd;
2582
2583         /*
2584          *      FIXME: Do even more filtering by only permitting
2585          *      certain IP's.  The problem is that we don't know
2586          *      how to do this properly for all possible clients...
2587          */
2588
2589         /*
2590          *      Explicitely set the VP list to empty.
2591          */
2592         packet->vps = NULL;
2593
2594         if (fr_debug_flag) {
2595                 char host_ipaddr[128];
2596
2597                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2598                         DEBUG("rad_recv: %s packet from host %s port %d",
2599                               fr_packet_codes[packet->code],
2600                               inet_ntop(packet->src_ipaddr.af,
2601                                         &packet->src_ipaddr.ipaddr,
2602                                         host_ipaddr, sizeof(host_ipaddr)),
2603                               packet->src_port);
2604                 } else {
2605                         DEBUG("rad_recv: Packet from host %s port %d code=%d",
2606                               inet_ntop(packet->src_ipaddr.af,
2607                                         &packet->src_ipaddr.ipaddr,
2608                                         host_ipaddr, sizeof(host_ipaddr)),
2609                               packet->src_port,
2610                               packet->code);
2611                 }
2612                 DEBUG(", id=%d, length=%d\n",
2613                       packet->id, (int) packet->data_len);
2614         }
2615
2616 #ifndef NDEBUG
2617         if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2618 #endif
2619
2620         return packet;
2621 }
2622
2623
2624 /**
2625  * @brief Verify the Request/Response Authenticator
2626  *      (and Message-Authenticator if present) of a packet.
2627  */
2628 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2629                char const *secret)
2630 {
2631         uint8_t                 *ptr;
2632         int                     length;
2633         int                     attrlen;
2634
2635         if (!packet || !packet->data) return -1;
2636
2637         /*
2638          *      Before we allocate memory for the attributes, do more
2639          *      sanity checking.
2640          */
2641         ptr = packet->data + AUTH_HDR_LEN;
2642         length = packet->data_len - AUTH_HDR_LEN;
2643         while (length > 0) {
2644                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2645                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2646
2647                 attrlen = ptr[1];
2648
2649                 switch (ptr[0]) {
2650                 default:        /* don't do anything. */
2651                         break;
2652
2653                         /*
2654                          *      Note that more than one Message-Authenticator
2655                          *      attribute is invalid.
2656                          */
2657                 case PW_MESSAGE_AUTHENTICATOR:
2658                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2659                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2660
2661                         switch (packet->code) {
2662                         default:
2663                                 break;
2664
2665                         case PW_ACCOUNTING_RESPONSE:
2666                                 if (original &&
2667                                     (original->code == PW_STATUS_SERVER)) {
2668                                         goto do_ack;
2669                                 }
2670
2671                         case PW_ACCOUNTING_REQUEST:
2672                         case PW_DISCONNECT_REQUEST:
2673                         case PW_DISCONNECT_ACK:
2674                         case PW_DISCONNECT_NAK:
2675                         case PW_COA_REQUEST:
2676                         case PW_COA_ACK:
2677                         case PW_COA_NAK:
2678                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2679                                 break;
2680
2681                         do_ack:
2682                         case PW_AUTHENTICATION_ACK:
2683                         case PW_AUTHENTICATION_REJECT:
2684                         case PW_ACCESS_CHALLENGE:
2685                                 if (!original) {
2686                                         fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2687                                         return -1;
2688                                 }
2689                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2690                                 break;
2691                         }
2692
2693                         fr_hmac_md5(packet->data, packet->data_len,
2694                                     (uint8_t const *) secret, strlen(secret),
2695                                     calc_auth_vector);
2696                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2697                                    sizeof(calc_auth_vector)) != 0) {
2698                                 char buffer[32];
2699                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
2700                                            inet_ntop(packet->src_ipaddr.af,
2701                                                      &packet->src_ipaddr.ipaddr,
2702                                                      buffer, sizeof(buffer)));
2703                                 /* Silently drop packet, according to RFC 3579 */
2704                                 return -1;
2705                         } /* else the message authenticator was good */
2706
2707                         /*
2708                          *      Reinitialize Authenticators.
2709                          */
2710                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2711                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2712                         break;
2713                 } /* switch over the attributes */
2714
2715                 ptr += attrlen;
2716                 length -= attrlen;
2717         } /* loop over the packet, sanity checking the attributes */
2718
2719         /*
2720          *      It looks like a RADIUS packet, but we don't know what it is
2721          *      so can't validate the authenticators.
2722          */
2723         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2724                 char buffer[32];
2725                 fr_strerror_printf("Received Unknown packet code %d "
2726                            "from client %s port %d: Cannot validate Request/Response Authenticator.",
2727                            packet->code,
2728                            inet_ntop(packet->src_ipaddr.af,
2729                                      &packet->src_ipaddr.ipaddr,
2730                                      buffer, sizeof(buffer)),
2731                            packet->src_port);
2732                 return -1;
2733         }
2734
2735         /*
2736          *      Calculate and/or verify Request or Response Authenticator.
2737          */
2738         switch(packet->code) {
2739                 int rcode;
2740                 char buffer[32];
2741
2742                 case PW_AUTHENTICATION_REQUEST:
2743                 case PW_STATUS_SERVER:
2744                         /*
2745                          *      The authentication vector is random
2746                          *      nonsense, invented by the client.
2747                          */
2748                         break;
2749
2750                 case PW_COA_REQUEST:
2751                 case PW_DISCONNECT_REQUEST:
2752                 case PW_ACCOUNTING_REQUEST:
2753                         if (calc_acctdigest(packet, secret) > 1) {
2754                                 fr_strerror_printf("Received %s packet "
2755                                            "from client %s with invalid Request Authenticator!  (Shared secret is incorrect.)",
2756                                            fr_packet_codes[packet->code],
2757                                            inet_ntop(packet->src_ipaddr.af,
2758                                                      &packet->src_ipaddr.ipaddr,
2759                                                      buffer, sizeof(buffer)));
2760                                 return -1;
2761                         }
2762                         break;
2763
2764                         /* Verify the reply digest */
2765                 case PW_AUTHENTICATION_ACK:
2766                 case PW_AUTHENTICATION_REJECT:
2767                 case PW_ACCESS_CHALLENGE:
2768                 case PW_ACCOUNTING_RESPONSE:
2769                 case PW_DISCONNECT_ACK:
2770                 case PW_DISCONNECT_NAK:
2771                 case PW_COA_ACK:
2772                 case PW_COA_NAK:
2773                         rcode = calc_replydigest(packet, original, secret);
2774                         if (rcode > 1) {
2775                                 fr_strerror_printf("Received %s packet "
2776                                            "from home server %s port %d with invalid Response Authenticator!  (Shared secret is incorrect.)",
2777                                            fr_packet_codes[packet->code],
2778                                            inet_ntop(packet->src_ipaddr.af,
2779                                                      &packet->src_ipaddr.ipaddr,
2780                                                      buffer, sizeof(buffer)),
2781                                            packet->src_port);
2782                                 return -1;
2783                         }
2784                         break;
2785
2786                 default:
2787                         fr_strerror_printf("Received Unknown packet code %d "
2788                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2789                                    packet->code,
2790                                    inet_ntop(packet->src_ipaddr.af,
2791                                              &packet->src_ipaddr.ipaddr,
2792                                                      buffer, sizeof(buffer)),
2793                                    packet->src_port);
2794                         return -1;
2795         }
2796
2797         return 0;
2798 }
2799
2800
2801 static ssize_t data2vp(RADIUS_PACKET const *packet,
2802                        RADIUS_PACKET const *original,
2803                        char const *secret,
2804                        DICT_ATTR const *da, uint8_t const *start,
2805                        size_t const attrlen, size_t const packetlen,
2806                        VALUE_PAIR **pvp);
2807
2808 /**
2809  * @brief convert TLVs to one or more VPs
2810  */
2811 static ssize_t data2vp_tlvs(RADIUS_PACKET const *packet,
2812                             RADIUS_PACKET const *original,
2813                             char const *secret, DICT_ATTR const *da,
2814                             uint8_t const *start, size_t length,
2815                             VALUE_PAIR **pvp)
2816 {
2817         const uint8_t *data = start;
2818         const DICT_ATTR *child;
2819         VALUE_PAIR *head, **tail;
2820
2821         if (length < 3) return -1; /* type, length, value */
2822
2823         VP_HEXDUMP("tlvs", data, length);
2824
2825         if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2826
2827         head = NULL;
2828         tail = &head;
2829
2830         while (data < (start + length)) {
2831                 ssize_t tlv_len;
2832
2833                 child = dict_attrbyparent(da, data[0], da->vendor);
2834                 if (!child) {
2835                         unsigned int my_attr, my_vendor;
2836
2837                         VP_TRACE("Failed to find child %u of TLV %s\n",
2838                                  data[0], da->name);
2839
2840                         /*
2841                          *      Get child attr/vendor so that
2842                          *      we can call unknown attr.
2843                          */
2844                         my_attr = data[0];
2845                         my_vendor = da->vendor;
2846
2847                         if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2848                                 pairfree(&head);
2849                                 return -1;
2850                         }
2851
2852                         child = dict_attrunknown(my_attr, my_vendor, TRUE);
2853                         if (!child) {
2854                                 pairfree(&head);
2855                                 return -1;
2856                         }
2857                 }
2858
2859                 tlv_len = data2vp(packet, original, secret, child,
2860                                   data + 2, data[1] - 2, data[1] - 2, tail);
2861                 if (tlv_len < 0) {
2862                         pairfree(&head);
2863                         return -1;
2864                 }
2865                 tail = &((*tail)->next);
2866                 data += data[1];
2867         }
2868
2869         *pvp = head;
2870         return length;
2871 }
2872
2873 /**
2874  * @brief Convert a top-level VSA to a VP.
2875  *
2876  *      "length" can be LONGER than just this sub-vsa
2877  */
2878 static ssize_t data2vp_vsa(RADIUS_PACKET const *packet,
2879                            RADIUS_PACKET const *original,
2880                            char const *secret, DICT_VENDOR *dv,
2881                            uint8_t const *data, size_t length,
2882                            VALUE_PAIR **pvp)
2883 {
2884         unsigned int attribute;
2885         ssize_t attrlen, my_len;
2886         const DICT_ATTR *da;
2887
2888 #ifndef NDEBUG
2889         if (length <= (dv->type + dv->length)) {
2890                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2891                 return -1;
2892         }
2893 #endif  
2894
2895         switch (dv->type) {
2896         case 4:
2897                 /* data[0] must be zero */
2898                 attribute = data[1] << 16;
2899                 attribute |= data[2] << 8;
2900                 attribute |= data[3];
2901                 break;
2902
2903         case 2:
2904                 attribute = data[0] << 8;
2905                 attribute |= data[1];
2906                 break;
2907
2908         case 1:
2909                 attribute = data[0];
2910                 break;
2911
2912         default:
2913                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
2914                 return -1;
2915         }
2916
2917         switch (dv->length) {
2918         case 2:
2919                 /* data[dv->type] must be zero, from rad_tlv_ok() */
2920                 attrlen = data[dv->type + 1];
2921                 break;
2922
2923         case 1:
2924                 attrlen = data[dv->type];
2925                 break;
2926
2927         case 0:
2928                 attrlen = length;
2929                 break;
2930
2931         default:
2932                 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
2933                 return -1;
2934         }
2935
2936 #ifndef NDEBUG
2937         if (attrlen <= (ssize_t) (dv->type + dv->length)) {
2938                 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2939                 return -1;
2940         }
2941 #endif
2942
2943         /*
2944          *      See if the VSA is known.
2945          */
2946         da = dict_attrbyvalue(attribute, dv->vendorpec);
2947         if (!da) da = dict_attrunknown(attribute, dv->vendorpec, TRUE);
2948         if (!da) return -1;
2949
2950         my_len = data2vp(packet, original, secret, da,
2951                          data + dv->type + dv->length,
2952                          attrlen - (dv->type + dv->length),
2953                          attrlen - (dv->type + dv->length),
2954                          pvp);
2955         if (my_len < 0) return my_len;
2956
2957         return attrlen;
2958 }
2959
2960
2961 /**
2962  * @brief Convert a Vendor-Specific WIMAX to vps
2963  *
2964  *      Called ONLY for Vendor-Specific
2965  */
2966 static ssize_t data2vp_wimax(RADIUS_PACKET const *packet,
2967                              RADIUS_PACKET const *original,
2968                              char const *secret, uint32_t vendor,
2969                              uint8_t const *data,
2970                              size_t attrlen, size_t packetlen,
2971                              VALUE_PAIR **pvp)
2972 {
2973         ssize_t rcode;
2974         size_t fraglen;
2975         uint8_t *head, *tail;
2976         const uint8_t *frag, *end;
2977         const DICT_ATTR *child;
2978
2979         if (attrlen < 8) return -1;
2980
2981         if (((size_t) (data[5] + 4)) != attrlen) return -1;
2982
2983         child = dict_attrbyvalue(data[4], vendor);
2984         if (!child) return -1;
2985
2986         if ((data[6] & 0x80) == 0) {
2987                 rcode = data2vp(packet, original, secret, child,
2988                                 data + 7, data[5] - 3, data[5] - 3,
2989                                 pvp);
2990                 if (rcode < 0) return -1;
2991                 return 7 + rcode;
2992         }
2993
2994         /*
2995          *      Calculate the length of all of the fragments.  For
2996          *      now, they MUST be contiguous in the packet, and they
2997          *      MUST be all of the same VSA, WiMAX, and WiMAX-attr.
2998          *
2999          *      The first fragment doesn't have a RADIUS attribute
3000          *      header, so it needs to be treated a little special.
3001          */
3002         fraglen = data[5] - 3;
3003         frag = data + attrlen;
3004         end = data + packetlen;
3005
3006         while (frag < end) {
3007                 int last_frag = FALSE;
3008
3009                 if (last_frag ||
3010                     (frag[0] != PW_VENDOR_SPECIFIC) ||
3011                     (frag[1] < 9) ||                   /* too short for wimax */
3012                     ((frag + frag[1]) > end) ||         /* overflow */
3013                     (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3014                     (frag[6] != data[4]) || /* not the same wimax attr */
3015                     ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3016                         end = frag;
3017                         break;
3018                 }
3019
3020                 last_frag = ((frag[8] & 0x80) == 0);
3021
3022                 fraglen += frag[7] - 3;
3023                 frag += frag[1];
3024         }
3025
3026         head = tail = malloc(fraglen);
3027         if (!head) return -1;
3028
3029         /*
3030          *      And again, but faster and looser.
3031          *
3032          *      We copy the first fragment, followed by the rest of
3033          *      the fragments.
3034          */
3035         frag = data;
3036
3037         memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3038         tail += frag[4 + 1] - 3;
3039         frag += attrlen;        /* should be frag[1] - 7 */
3040
3041         /*
3042          *      frag now points to RADIUS attributes
3043          */
3044         do {
3045                 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3046                 tail += frag[2 + 4 + 1] - 3;
3047                 frag += frag[1];
3048         } while (frag < end);
3049
3050         VP_HEXDUMP("wimax fragments", head, fraglen);
3051
3052         rcode = data2vp(packet, original, secret, child,
3053                         head, fraglen, fraglen, pvp);
3054         free(head);
3055         if (rcode < 0) return rcode;
3056
3057         return end - data;
3058 }
3059
3060
3061 /**
3062  * @brief Convert a top-level VSA to one or more VPs
3063  */
3064 static ssize_t data2vp_vsas(RADIUS_PACKET const *packet,
3065                             RADIUS_PACKET const *original,
3066                             char const *secret, uint8_t const *data,
3067                             size_t attrlen, size_t packetlen,
3068                             VALUE_PAIR **pvp)
3069 {
3070         size_t total;
3071         ssize_t rcode;
3072         uint32_t vendor;
3073         DICT_VENDOR *dv;
3074         VALUE_PAIR *head, **tail;
3075
3076         if (attrlen > packetlen) return -1;
3077         if (attrlen < 5) return -1; /* vid, value */
3078         if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3079
3080         memcpy(&vendor, data, 4);
3081         vendor = ntohl(vendor);
3082         dv = dict_vendorbyvalue(vendor);
3083         if (!dv) return -1;
3084
3085         /*
3086          *      WiMAX craziness
3087          */
3088         if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3089                 rcode = data2vp_wimax(packet, original, secret, vendor,
3090                                       data, attrlen, packetlen, pvp);
3091                 return rcode;
3092         }
3093         
3094         /*
3095          *      VSAs should normally be in TLV format.
3096          */
3097         if (rad_tlv_ok(data + 4, attrlen - 4,
3098                        dv->type, dv->length) < 0) return -1;
3099
3100         /*
3101          *      There may be more than one VSA in the
3102          *      Vendor-Specific.  If so, loop over them all.
3103          */
3104         data += 4;
3105         attrlen -= 4;
3106         packetlen -= 4;
3107         total = 4;
3108         head = NULL;
3109         tail = &head;
3110
3111         while (attrlen > 0) {
3112                 ssize_t vsa_len;
3113                 
3114                 vsa_len = data2vp_vsa(packet, original, secret, dv,
3115                                       data, attrlen, tail);
3116                 if (vsa_len < 0) {
3117                         pairfree(&head);
3118                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3119                         return -1;
3120                 }
3121                 tail = &((*tail)->next);
3122                 data += vsa_len;
3123                 attrlen -= vsa_len;
3124                 packetlen -= vsa_len;
3125                 total += vsa_len;
3126         }
3127
3128         *pvp = head;
3129         return total;
3130 }
3131
3132
3133 /**
3134  * @brief Create any kind of VP from the attribute contents.
3135  *
3136  *      "length" is AT LEAST the length of this attribute, as we
3137  *      expect the caller to have verified the data with
3138  *      rad_packet_ok().  "length" may be up to the length of the
3139  *      packet.
3140  *
3141  * @return -1 on error, or "length".
3142  */
3143 static ssize_t data2vp(RADIUS_PACKET const *packet,
3144                        RADIUS_PACKET const *original,
3145                        char const *secret,
3146                        DICT_ATTR const *da, uint8_t const *start,
3147                        size_t const attrlen, size_t const packetlen,
3148                        VALUE_PAIR **pvp)
3149 {
3150         int tag = 0;
3151         size_t datalen;
3152         ssize_t rcode;
3153         uint32_t vendor;
3154         const DICT_ATTR *child;
3155         DICT_VENDOR *dv;
3156         VALUE_PAIR *vp;
3157         const uint8_t *data = start;
3158         uint8_t buffer[256];
3159
3160         if (!da || (attrlen > 253) || (attrlen > packetlen) ||
3161             (attrlen > 128*1024)) {
3162                 fr_strerror_printf("data2vp: invalid arguments");
3163                 return -1;
3164         }
3165
3166         VP_HEXDUMP("data2vp", start, attrlen);
3167
3168         VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3169
3170         datalen = attrlen;
3171
3172         /*
3173          *      Hacks for CUI.  The WiMAX spec says that it can be
3174          *      zero length, even though this is forbidden by the
3175          *      RADIUS specs.  So... we make a special case for it.
3176          */
3177         if (attrlen == 0) {
3178                 if (!((da->vendor == 0) &&
3179                       (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3180                         *pvp = NULL;
3181                         return 0;
3182                 }
3183
3184 #ifndef NDEBUG
3185                 /*
3186                  *      Hacks for Coverity.  Editing the dictionary
3187                  *      will break assumptions about CUI.  We know
3188                  *      this, but Coverity doesn't.
3189                  */
3190                 if (da->type != PW_TYPE_STRING) return -1;
3191 #endif
3192
3193                 data = (uint8_t const *) "";
3194                 datalen = 1;
3195                 goto alloc_cui; /* skip everything */
3196         }
3197
3198         /*
3199          *      Hacks for tags.  If the attribute is capable of
3200          *      encoding a tag, and there's room for the tag, and
3201          *      there is a tag, or it's encryted with Tunnel-Password,
3202          *      then decode the tag.
3203          */
3204         if (da->flags.has_tag && (datalen > 1) &&
3205             ((data[0] < 0x20) ||
3206              (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3207
3208                 if (da->type == PW_TYPE_STRING) {
3209                         memcpy(buffer, data + 1, datalen - 1);
3210                         tag = data[0];
3211                         datalen -= 1;
3212
3213                 } else if (da->type == PW_TYPE_INTEGER) {
3214                         memcpy(buffer, data, attrlen);
3215                         tag = buffer[0];
3216                         buffer[0] = 0;
3217
3218                 } else {
3219                         return -1; /* only string and integer can have tags */
3220                 }
3221
3222                 data = buffer;
3223         }
3224
3225         /*
3226          *      Decrypt the attribute.
3227          */
3228         if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3229                 if (data == start) memcpy(buffer, data, attrlen);
3230                 data = buffer;
3231
3232                 switch (da->flags.encrypt) { /* can't be tagged */
3233                 /*
3234                  *  User-Password
3235                  */
3236                 case FLAG_ENCRYPT_USER_PASSWORD:
3237                         if (original) {
3238                                 rad_pwdecode((char *) buffer,
3239                                              attrlen, secret,
3240                                              original->vector);
3241                         } else {
3242                                 rad_pwdecode((char *) buffer,
3243                                              attrlen, secret,
3244                                              packet->vector);
3245                         }
3246                         buffer[253] = '\0';
3247                         datalen = strlen((char *) buffer);
3248                         break;
3249
3250                 /*
3251                  *      Tunnel-Password's may go ONLY in response
3252                  *      packets.  They can have a tag, so datalen is
3253                  *      not the same as attrlen.
3254                  */
3255                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3256                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3257                                                 original ? original->vector : nullvector) < 0) {
3258                                 goto raw;
3259                         }
3260                         break;
3261
3262                 /*
3263                  *  Ascend-Send-Secret
3264                  *  Ascend-Receive-Secret
3265                  */
3266                 case FLAG_ENCRYPT_ASCEND_SECRET:
3267                         if (!original) {
3268                                 goto raw;
3269                         } else {
3270                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3271                                 make_secret(my_digest,
3272                                             original->vector,
3273                                             secret, data);
3274                                 memcpy(buffer, my_digest,
3275                                        AUTH_VECTOR_LEN );
3276                                 buffer[AUTH_VECTOR_LEN] = '\0';
3277                                 datalen = strlen((char *) buffer);
3278                         }
3279                         break;
3280
3281                 default:
3282                         break;
3283                 } /* switch over encryption flags */
3284         }
3285
3286         /*
3287          *      Double-check the length after decrypting the
3288          *      attribute.
3289          */
3290         switch (da->type) {
3291         case PW_TYPE_STRING:
3292         case PW_TYPE_OCTETS:
3293         case PW_TYPE_ABINARY:
3294                 break;
3295
3296         case PW_TYPE_INTEGER:
3297         case PW_TYPE_IPADDR:
3298         case PW_TYPE_DATE:
3299         case PW_TYPE_SIGNED:
3300                 if (datalen != 4) goto raw;
3301                 break;
3302
3303         case PW_TYPE_INTEGER64:
3304         case PW_TYPE_IFID:
3305                 if (datalen != 8) goto raw;
3306                 break;
3307
3308         case PW_TYPE_IPV6ADDR:
3309                 if (datalen != 16) goto raw;
3310                 break;
3311
3312         case PW_TYPE_IPV6PREFIX:
3313                 if ((datalen < 2) || (datalen > 18)) goto raw;
3314                 if (data[1] > 128) goto raw;
3315                 break;
3316
3317         case PW_TYPE_BYTE:
3318                 if (datalen != 1) goto raw;
3319                 break;
3320
3321         case PW_TYPE_SHORT:
3322                 if (datalen != 2) goto raw;
3323                 break;
3324
3325         case PW_TYPE_ETHERNET:
3326                 if (datalen != 6) goto raw;
3327                 break;
3328
3329         case PW_TYPE_COMBO_IP:
3330                 if (datalen == 4) {
3331                         child = dict_attrbytype(da->attr, da->vendor,
3332                                                 PW_TYPE_IPADDR);
3333                 } else if (datalen == 16) {
3334                         child = dict_attrbytype(da->attr, da->vendor,
3335                                              PW_TYPE_IPV6ADDR);
3336                 } else {
3337                         goto raw;
3338                 }
3339                 if (!child) goto raw;
3340                 da = child;     /* re-write it */
3341                 break;
3342
3343         case PW_TYPE_IPV4PREFIX:
3344                 if (datalen != 6) goto raw;
3345                 if ((data[1] & 0x3f) > 32) goto raw;
3346                 break;
3347
3348                 /*
3349                  *      The rest of the data types can cause
3350                  *      recursion!  Ask yourself, "is recursion OK?"
3351                  */
3352
3353         case PW_TYPE_EXTENDED:
3354                 if (datalen < 2) goto raw; /* etype, value */
3355
3356                 child = dict_attrbyparent(da, data[0], 0);
3357                 if (!child) goto raw;
3358
3359                 /*
3360                  *      Recurse to decode the contents, which could be
3361                  *      a TLV, IPaddr, etc.  Note that we decode only
3362                  *      the current attribute, and we ignore any extra
3363                  *      data after it.
3364                  */
3365                 rcode = data2vp(packet, original, secret, child,
3366                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3367                 if (rcode < 0) goto raw;
3368                 return 1 + rcode;
3369
3370         case PW_TYPE_LONG_EXTENDED:
3371                 if (datalen < 3) goto raw; /* etype, flags, value */
3372
3373                 child = dict_attrbyparent(da, data[0], 0);
3374                 if (!child) goto raw;
3375
3376                 /*
3377                  *      If there no more fragments, then the contents
3378                  *      have to be a well-known data type.
3379                  *
3380                  */
3381                 if ((data[1] & 0x80) == 0) {
3382                         rcode = data2vp(packet, original, secret, child,
3383                                         data + 2, attrlen - 2, attrlen - 2,
3384                                         pvp);
3385                         if (rcode < 0) goto raw;
3386                         return 2 + rcode;
3387                 }
3388
3389                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3390                 return -1;      /* TODO: fixme! */
3391
3392         case PW_TYPE_EVS:
3393                 if (datalen < 6) goto raw; /* vid, vtype, value */
3394
3395                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3396
3397                 memcpy(&vendor, data, 4);
3398                 vendor = ntohl(vendor);
3399                 dv = dict_vendorbyvalue(vendor);
3400                 if (!dv) goto raw;
3401
3402                 child = dict_attrbyparent(da, data[5], vendor);
3403                 if (!child) goto raw;
3404
3405                 rcode = data2vp(packet, original, secret, child,
3406                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3407                 if (rcode < 0) goto raw;
3408                 return 5 + rcode;
3409
3410         case PW_TYPE_TLV:
3411                 /*
3412                  *      We presume that the TLVs all fit into one
3413                  *      attribute, OR they've already been grouped
3414                  *      into a contiguous memory buffer.
3415                  */
3416                 rcode = data2vp_tlvs(packet, original, secret, da,
3417                                      data, attrlen, pvp);
3418                 if (rcode < 0) goto raw;
3419                 return rcode;
3420
3421         case PW_TYPE_VSA:
3422                 /*
3423                  *      VSAs can be WiMAX, in which case they don't
3424                  *      fit into one attribute.
3425                  */
3426                 rcode = data2vp_vsas(packet, original, secret,
3427                                      data, attrlen, packetlen, pvp);
3428                 if (rcode < 0) goto raw;
3429                 return rcode;
3430
3431         default:
3432         raw:
3433                 /*
3434                  *      Re-write the attribute to be "raw".  It is
3435                  *      therefore of type "octets", and will be
3436                  *      handled below.
3437                  */
3438                 da = dict_attrunknown(da->attr, da->vendor, TRUE);
3439                 if (!da) {
3440                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3441                         return -1;
3442                 }
3443                 tag = 0;
3444 #ifndef NDEBUG
3445                 /*
3446                  *      Fix for Coverity.
3447                  */
3448                 if (da->type != PW_TYPE_OCTETS) {
3449                         dict_attr_free(&da);
3450                         return -1;
3451                 }
3452 #endif
3453                 break;
3454         }
3455
3456         /*
3457          *      And now that we've verified the basic type
3458          *      information, decode the actual data.
3459          */
3460  alloc_cui:
3461         vp = pairalloc(NULL, da);
3462         if (!vp) return -1;
3463
3464         vp->length = datalen;
3465         vp->tag = tag;
3466
3467         switch (da->type) {
3468         case PW_TYPE_STRING:
3469                 memcpy(vp->vp_strvalue, data, vp->length);
3470                 vp->vp_strvalue[vp->length] = '\0';
3471                 break;
3472
3473         case PW_TYPE_OCTETS:
3474         case PW_TYPE_ABINARY:
3475                 memcpy(vp->vp_octets, data, vp->length);
3476                 break;
3477
3478         case PW_TYPE_BYTE:
3479                 vp->vp_integer = data[0];
3480                 break;
3481
3482
3483         case PW_TYPE_SHORT:
3484                 vp->vp_integer = (data[0] << 8) | data[1];
3485                 break;
3486
3487         case PW_TYPE_INTEGER:
3488                 memcpy(&vp->vp_integer, data, 4);
3489                 vp->vp_integer = ntohl(vp->vp_integer);
3490                 break;
3491
3492         case PW_TYPE_INTEGER64:
3493                 memcpy(&vp->vp_integer64, data, 8);
3494                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3495                 break;
3496
3497         case PW_TYPE_DATE:
3498                 memcpy(&vp->vp_date, data, 4);
3499                 vp->vp_date = ntohl(vp->vp_date);
3500                 break;
3501
3502
3503         case PW_TYPE_IPADDR:
3504                 memcpy(&vp->vp_ipaddr, data, 4);
3505                 break;
3506
3507         case PW_TYPE_IFID:
3508                 memcpy(&vp->vp_ifid, data, 8);
3509                 break;
3510
3511         case PW_TYPE_IPV6ADDR:
3512                 memcpy(&vp->vp_ipv6addr, data, 16);
3513                 break;
3514
3515         case PW_TYPE_IPV6PREFIX:
3516                 /*
3517                  *      FIXME: double-check that
3518                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
3519                  */
3520                 memcpy(&vp->vp_ipv6prefix, data, vp->length);
3521                 if (vp->length < 18) {
3522                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3523                                18 - vp->length);
3524                 }
3525                 break;
3526
3527         case PW_TYPE_IPV4PREFIX:
3528                 /* FIXME: do the same double-check as for IPv6Prefix */
3529                 memcpy(&vp->vp_ipv4prefix, buffer, sizeof(vp->vp_ipv4prefix));
3530
3531                 /*
3532                  *      /32 means "keep all bits".  Otherwise, mask
3533                  *      them out.
3534                  */
3535                 if ((data[1] & 0x3f) > 32) {
3536                         uint32_t addr, mask;
3537
3538                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3539                         mask = 1;
3540                         mask <<= (32 - (buffer[1] & 0x3f));
3541                         mask--;
3542                         mask = ~mask;
3543                         mask = htonl(mask);
3544                         addr &= mask;
3545                         memcpy(vp->vp_octets + 2, &addr, sizeof(addr));
3546                 }
3547                 break;
3548
3549         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
3550                 memcpy(&vp->vp_integer, buffer, 4);
3551                 vp->vp_integer = ntohl(vp->vp_integer);
3552                 break;
3553
3554         default:
3555                 pairfree(&vp);
3556                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3557                 return -1;
3558         }
3559
3560         *pvp = vp;
3561
3562         return attrlen;
3563 }
3564
3565
3566 /**
3567  * @brief Create a "normal" VALUE_PAIR from the given data.
3568  */
3569 ssize_t rad_attr2vp(RADIUS_PACKET const *packet,
3570                     RADIUS_PACKET const *original,
3571                     char const *secret,
3572                     uint8_t const *data, size_t length,
3573                     VALUE_PAIR **pvp)
3574 {
3575         ssize_t rcode;
3576
3577         const DICT_ATTR *da;
3578
3579         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3580                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3581                 return -1;
3582         }
3583
3584         da = dict_attrbyvalue(data[0], 0);
3585         if (!da) da = dict_attrunknown(data[0], 0, TRUE);
3586
3587         /*
3588          *      Note that we pass the entire length, not just the
3589          *      length of this attribute.  The Extended or WiMAX
3590          *      attributes may have the "continuation" bit set, and
3591          *      will thus be more than one attribute in length.
3592          */
3593         rcode = data2vp(packet, original, secret, da,
3594                         data + 2, data[1] - 2, length - 2, pvp);
3595         if (rcode < 0) return rcode;
3596
3597         return 2 + rcode;
3598 }
3599
3600
3601 /**
3602  * @brief Converts data in network byte order to a VP
3603  * @return -1 on error, or the length of the data read
3604  */
3605 ssize_t  rad_data2vp(unsigned int attribute, unsigned int vendor,
3606                      uint8_t const *data, size_t length,
3607                      VALUE_PAIR **pvp)
3608 {
3609         const DICT_ATTR *da;
3610
3611         if (!data || (length == 0) || !pvp) return -1;
3612
3613         da = dict_attrbyvalue(attribute, vendor);
3614         if (!da) da = dict_attrunknown(attribute, vendor, TRUE);
3615         if (!da) return -1;
3616
3617         return data2vp(NULL, NULL, NULL, da,
3618                        data, length, length, pvp);
3619 }
3620
3621 /**
3622  * @brief Converts vp_data to network byte order
3623  * @return -1 on error, or the length of the value
3624  */
3625 ssize_t rad_vp2data(VALUE_PAIR const *vp, uint8_t *out, size_t outlen)
3626 {
3627         size_t          len = 0;
3628         uint32_t        lvalue;
3629         uint64_t        lvalue64;
3630
3631         len = vp->length;
3632         if (outlen < len) {
3633                 fr_strerror_printf("ERROR: rad_vp2data buffer passed too small");
3634                 return -1;
3635         }
3636         
3637         /*
3638          *      Short-circuit it for long attributes.
3639          */
3640         if ((vp->da->type & PW_FLAG_LONG) != 0) goto do_raw;
3641
3642         switch(vp->da->type) {
3643                 case PW_TYPE_STRING:
3644                 case PW_TYPE_OCTETS:
3645                 case PW_TYPE_IFID:
3646                 case PW_TYPE_IPADDR:
3647                 case PW_TYPE_IPV6ADDR:
3648                 case PW_TYPE_IPV6PREFIX:
3649                 case PW_TYPE_IPV4PREFIX:
3650                 case PW_TYPE_ABINARY:
3651                 case PW_TYPE_TLV:
3652                         do_raw:
3653                         memcpy(out, vp->vp_octets, len);
3654                         break;
3655                 case PW_TYPE_BYTE:
3656                         out[0] = vp->vp_integer & 0xff;
3657                         break;
3658         
3659                 case PW_TYPE_SHORT:
3660                         out[0] = (vp->vp_integer >> 8) & 0xff;
3661                         out[1] = vp->vp_integer & 0xff;
3662                         break;
3663         
3664                 case PW_TYPE_INTEGER:
3665                         lvalue = htonl(vp->vp_integer);
3666                         memcpy(out, &lvalue, sizeof(lvalue));
3667                         break;
3668         
3669                 case PW_TYPE_INTEGER64:
3670                         lvalue64 = htonll(vp->vp_integer64);
3671                         memcpy(out, &lvalue64, sizeof(lvalue64));
3672                         break;
3673
3674                 case PW_TYPE_DATE:
3675                         lvalue = htonl(vp->vp_date);
3676                         memcpy(out, &lvalue, sizeof(lvalue));
3677                         break;
3678         
3679                 case PW_TYPE_SIGNED:
3680                 {
3681                         int32_t slvalue;
3682                         
3683                         slvalue = htonl(vp->vp_signed);
3684                         memcpy(out, &slvalue, sizeof(slvalue));
3685                         break;
3686                 }
3687                 /* unknown type: ignore it */
3688                 default:                
3689                         fr_strerror_printf("ERROR: Unknown attribute type %d",
3690                                            vp->da->type);
3691                         return -1;
3692         }
3693         
3694         return len;
3695 }
3696
3697 /**
3698  * @brief Calculate/check digest, and decode radius attributes.
3699  * @return -1 on decoding error, 0 on success
3700  */
3701 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3702                char const *secret)
3703 {
3704         int                     packet_length;
3705         int                     num_attributes;
3706         uint8_t                 *ptr;
3707         radius_packet_t         *hdr;
3708         VALUE_PAIR *head, **tail, *vp;
3709
3710         /*
3711          *      Extract attribute-value pairs
3712          */
3713         hdr = (radius_packet_t *)packet->data;
3714         ptr = hdr->data;
3715         packet_length = packet->data_len - AUTH_HDR_LEN;
3716
3717         head = NULL;
3718         tail = &head;
3719         num_attributes = 0;
3720
3721         /*
3722          *      Loop over the attributes, decoding them into VPs.
3723          */
3724         while (packet_length > 0) {
3725                 ssize_t my_len;
3726
3727                 /*
3728                  *      This may return many VPs
3729                  */
3730                 my_len = rad_attr2vp(packet, original, secret,
3731                                      ptr, packet_length, &vp);
3732                 if (my_len < 0) {
3733                         pairfree(&head);
3734                         return -1;
3735                 }
3736
3737                 *tail = vp;
3738                 while (vp) {
3739                         num_attributes++;
3740                         debug_pair(vp);
3741                         tail = &(vp->next);
3742                         vp = vp->next;
3743                 }
3744
3745                 /*
3746                  *      VSA's may not have been counted properly in
3747                  *      rad_packet_ok() above, as it is hard to count
3748                  *      then without using the dictionary.  We
3749                  *      therefore enforce the limits here, too.
3750                  */
3751                 if ((fr_max_attributes > 0) &&
3752                     (num_attributes > fr_max_attributes)) {
3753                         char host_ipaddr[128];
3754
3755                         pairfree(&head);
3756                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3757                                    inet_ntop(packet->src_ipaddr.af,
3758                                              &packet->src_ipaddr.ipaddr,
3759                                              host_ipaddr, sizeof(host_ipaddr)),
3760                                    num_attributes, fr_max_attributes);
3761                         return -1;
3762                 }
3763
3764                 ptr += my_len;
3765                 packet_length -= my_len;
3766         }
3767
3768         /*
3769          *      Merge information from the outside world into our
3770          *      random pool.
3771          */
3772         fr_rand_seed(packet->data, AUTH_HDR_LEN);
3773         
3774         /*
3775          *      There may be VP's already in the packet.  Don't
3776          *      destroy them.  Instead, add the decoded attributes to
3777          *      the tail of the list.
3778          */
3779         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
3780                 /* nothing */
3781         }
3782         *tail = head;
3783
3784         return 0;
3785 }
3786
3787
3788 /**
3789  * @brief Encode password.
3790  *
3791  *      We assume that the passwd buffer passed is big enough.
3792  *      RFC2138 says the password is max 128 chars, so the size
3793  *      of the passwd buffer must be at least 129 characters.
3794  *      Preferably it's just MAX_STRING_LEN.
3795  *
3796  *      int *pwlen is updated to the new length of the encrypted
3797  *      password - a multiple of 16 bytes.
3798  */
3799 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
3800                  uint8_t const *vector)
3801 {
3802         FR_MD5_CTX context, old;
3803         uint8_t digest[AUTH_VECTOR_LEN];
3804         int     i, n, secretlen;
3805         int     len;
3806
3807         /*
3808          *      RFC maximum is 128 bytes.
3809          *
3810          *      If length is zero, pad it out with zeros.
3811          *
3812          *      If the length isn't aligned to 16 bytes,
3813          *      zero out the extra data.
3814          */
3815         len = *pwlen;
3816
3817         if (len > 128) len = 128;
3818
3819         if (len == 0) {
3820                 memset(passwd, 0, AUTH_PASS_LEN);
3821                 len = AUTH_PASS_LEN;
3822         } else if ((len % AUTH_PASS_LEN) != 0) {
3823                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3824                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3825         }
3826         *pwlen = len;
3827
3828         /*
3829          *      Use the secret to setup the decryption digest
3830          */
3831         secretlen = strlen(secret);
3832
3833         fr_MD5Init(&context);
3834         fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
3835         old = context;          /* save intermediate work */
3836
3837         /*
3838          *      Encrypt it in place.  Don't bother checking
3839          *      len, as we've ensured above that it's OK.
3840          */
3841         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3842                 if (n == 0) {
3843                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3844                         fr_MD5Final(digest, &context);
3845                 } else {
3846                         context = old;
3847                         fr_MD5Update(&context,
3848                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
3849                                      AUTH_PASS_LEN);
3850                         fr_MD5Final(digest, &context);
3851                 }
3852
3853                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3854                         passwd[i + n] ^= digest[i];
3855                 }
3856         }
3857
3858         return 0;
3859 }
3860
3861 /**
3862  * @brief Decode password.
3863  */
3864 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
3865                  uint8_t const *vector)
3866 {
3867         FR_MD5_CTX context, old;
3868         uint8_t digest[AUTH_VECTOR_LEN];
3869         int     i;
3870         size_t  n, secretlen;
3871
3872         /*
3873          *      The RFC's say that the maximum is 128.
3874          *      The buffer we're putting it into above is 254, so
3875          *      we don't need to do any length checking.
3876          */
3877         if (pwlen > 128) pwlen = 128;
3878
3879         /*
3880          *      Catch idiots.
3881          */
3882         if (pwlen == 0) goto done;
3883
3884         /*
3885          *      Use the secret to setup the decryption digest
3886          */
3887         secretlen = strlen(secret);
3888
3889         fr_MD5Init(&context);
3890         fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
3891         old = context;          /* save intermediate work */
3892
3893         /*
3894          *      The inverse of the code above.
3895          */
3896         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3897                 if (n == 0) {
3898                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3899                         fr_MD5Final(digest, &context);
3900
3901                         context = old;
3902                         if (pwlen > AUTH_PASS_LEN) {
3903                                 fr_MD5Update(&context, (uint8_t *) passwd,
3904                                              AUTH_PASS_LEN);
3905                         }
3906                 } else {
3907                         fr_MD5Final(digest, &context);
3908
3909                         context = old;
3910                         if (pwlen > (n + AUTH_PASS_LEN)) {
3911                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
3912                                              AUTH_PASS_LEN);
3913                         }
3914                 }
3915
3916                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3917                         passwd[i + n] ^= digest[i];
3918                 }
3919         }
3920
3921  done:
3922         passwd[pwlen] = '\0';
3923         return strlen(passwd);
3924 }
3925
3926
3927 /**
3928  * @brief Encode Tunnel-Password attributes when sending them out on the wire.
3929  *
3930  *      int *pwlen is updated to the new length of the encrypted
3931  *      password - a multiple of 16 bytes.
3932  *
3933  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
3934  *      value MD5 hash.
3935  */
3936 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
3937                         uint8_t const *vector)
3938 {
3939         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3940         unsigned char   digest[AUTH_VECTOR_LEN];
3941         char*   salt;
3942         int     i, n, secretlen;
3943         unsigned len, n2;
3944
3945         len = *pwlen;
3946
3947         if (len > 127) len = 127;
3948
3949         /*
3950          * Shift the password 3 positions right to place a salt and original
3951          * length, tag will be added automatically on packet send
3952          */
3953         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3954         salt = passwd;
3955         passwd += 2;
3956         /*
3957          * save original password length as first password character;
3958          */
3959         *passwd = len;
3960         len += 1;
3961
3962
3963         /*
3964          *      Generate salt.  The RFC's say:
3965          *
3966          *      The high bit of salt[0] must be set, each salt in a
3967          *      packet should be unique, and they should be random
3968          *
3969          *      So, we set the high bit, add in a counter, and then
3970          *      add in some CSPRNG data.  should be OK..
3971          */
3972         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3973                    (fr_rand() & 0x07));
3974         salt[1] = fr_rand();
3975
3976         /*
3977          *      Padd password to multiple of AUTH_PASS_LEN bytes.
3978          */
3979         n = len % AUTH_PASS_LEN;
3980         if (n) {
3981                 n = AUTH_PASS_LEN - n;
3982                 for (; n > 0; n--, len++)
3983                         passwd[len] = 0;
3984         }
3985         /* set new password length */
3986         *pwlen = len + 2;
3987
3988         /*
3989          *      Use the secret to setup the decryption digest
3990          */
3991         secretlen = strlen(secret);
3992         memcpy(buffer, secret, secretlen);
3993
3994         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3995                 if (!n2) {
3996                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3997                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3998                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3999                 } else {
4000                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4001                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4002                 }
4003
4004                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4005                         passwd[i + n2] ^= digest[i];
4006                 }
4007         }
4008         passwd[n2] = 0;
4009         return 0;
4010 }
4011
4012 /**
4013  * @brief Decode Tunnel-Password encrypted attributes.
4014  *
4015  *      Defined in RFC-2868, this uses a two char SALT along with the
4016  *      initial intermediate value, to differentiate it from the
4017  *      above.
4018  */
4019 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4020                         uint8_t const *vector)
4021 {
4022         FR_MD5_CTX  context, old;
4023         uint8_t         digest[AUTH_VECTOR_LEN];
4024         int             secretlen;
4025         unsigned        i, n, len, reallen;
4026
4027         len = *pwlen;
4028
4029         /*
4030          *      We need at least a salt.
4031          */
4032         if (len < 2) {
4033                 fr_strerror_printf("tunnel password is too short");
4034                 return -1;
4035         }
4036
4037         /*
4038          *      There's a salt, but no password.  Or, there's a salt
4039          *      and a 'data_len' octet.  It's wrong, but at least we
4040          *      can figure out what it means: the password is empty.
4041          *
4042          *      Note that this means we ignore the 'data_len' field,
4043          *      if the attribute length tells us that there's no
4044          *      more data.  So the 'data_len' field may be wrong,
4045          *      but that's ok...
4046          */
4047         if (len <= 3) {
4048                 passwd[0] = 0;
4049                 *pwlen = 0;
4050                 return 0;
4051         }
4052
4053         len -= 2;               /* discount the salt */
4054
4055         /*
4056          *      Use the secret to setup the decryption digest
4057          */
4058         secretlen = strlen(secret);
4059
4060         fr_MD5Init(&context);
4061         fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
4062         old = context;          /* save intermediate work */
4063
4064         /*
4065          *      Set up the initial key:
4066          *
4067          *       b(1) = MD5(secret + vector + salt)
4068          */
4069         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
4070         fr_MD5Update(&context, passwd, 2);
4071
4072         reallen = 0;
4073         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4074                 int base = 0;
4075
4076                 if (n == 0) {
4077                         fr_MD5Final(digest, &context);
4078
4079                         context = old;
4080
4081                         /*
4082                          *      A quick check: decrypt the first octet
4083                          *      of the password, which is the
4084                          *      'data_len' field.  Ensure it's sane.
4085                          */
4086                         reallen = passwd[2] ^ digest[0];
4087                         if (reallen >= len) {
4088                                 fr_strerror_printf("tunnel password is too long for the attribute");
4089                                 return -1;
4090                         }
4091
4092                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
4093
4094                         base = 1;
4095                 } else {
4096                         fr_MD5Final(digest, &context);
4097
4098                         context = old;
4099                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
4100                 }
4101
4102                 for (i = base; i < AUTH_PASS_LEN; i++) {
4103                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4104                 }
4105         }
4106
4107         /*
4108          *      See make_tunnel_password, above.
4109          */
4110         if (reallen > 239) reallen = 239;
4111
4112         *pwlen = reallen;
4113         passwd[reallen] = 0;
4114
4115         return reallen;
4116 }
4117
4118 /**
4119  * @brief Encode a CHAP password
4120  *
4121  *      @bug FIXME: might not work with Ascend because
4122  *      we use vp->length, and Ascend gear likes
4123  *      to send an extra '\0' in the string!
4124  */
4125 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4126                     VALUE_PAIR *password)
4127 {
4128         int             i;
4129         uint8_t         *ptr;
4130         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4131         VALUE_PAIR      *challenge;
4132
4133         /*
4134          *      Sanity check the input parameters
4135          */
4136         if ((packet == NULL) || (password == NULL)) {
4137                 return -1;
4138         }
4139
4140         /*
4141          *      Note that the password VP can be EITHER
4142          *      a User-Password attribute (from a check-item list),
4143          *      or a CHAP-Password attribute (the client asking
4144          *      the library to encode it).
4145          */
4146
4147         i = 0;
4148         ptr = string;
4149         *ptr++ = id;
4150
4151         i++;
4152         memcpy(ptr, password->vp_strvalue, password->length);
4153         ptr += password->length;
4154         i += password->length;
4155
4156         /*
4157          *      Use Chap-Challenge pair if present,
4158          *      Request Authenticator otherwise.
4159          */
4160         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4161         if (challenge) {
4162                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4163                 i += challenge->length;
4164         } else {
4165                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4166                 i += AUTH_VECTOR_LEN;
4167         }
4168
4169         *output = id;
4170         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4171
4172         return 0;
4173 }
4174
4175
4176 /**
4177  * @brief Seed the random number generator.
4178  *
4179  *      May be called any number of times.
4180  */
4181 void fr_rand_seed(void const *data, size_t size)
4182 {
4183         uint32_t hash;
4184
4185         /*
4186          *      Ensure that the pool is initialized.
4187          */
4188         if (!fr_rand_initialized) {
4189                 int fd;
4190
4191                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4192
4193                 fd = open("/dev/urandom", O_RDONLY);
4194                 if (fd >= 0) {
4195                         size_t total;
4196                         ssize_t this;
4197
4198                         total = 0;
4199                         while (total < sizeof(fr_rand_pool.randrsl)) {
4200                                 this = read(fd, fr_rand_pool.randrsl,
4201                                             sizeof(fr_rand_pool.randrsl) - total);
4202                                 if ((this < 0) && (errno != EINTR)) break;
4203                                 if (this > 0) total += this;
4204                         }
4205                         close(fd);
4206                 } else {
4207                         fr_rand_pool.randrsl[0] = fd;
4208                         fr_rand_pool.randrsl[1] = time(NULL);
4209                         fr_rand_pool.randrsl[2] = errno;
4210                 }
4211
4212                 fr_randinit(&fr_rand_pool, 1);
4213                 fr_rand_pool.randcnt = 0;
4214                 fr_rand_initialized = 1;
4215         }
4216
4217         if (!data) return;
4218
4219         /*
4220          *      Hash the user data
4221          */
4222         hash = fr_rand();
4223         if (!hash) hash = fr_rand();
4224         hash = fr_hash_update(data, size, hash);
4225
4226         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4227 }
4228
4229
4230 /**
4231  * @brief Return a 32-bit random number.
4232  */
4233 uint32_t fr_rand(void)
4234 {
4235         uint32_t num;
4236
4237         /*
4238          *      Ensure that the pool is initialized.
4239          */
4240         if (!fr_rand_initialized) {
4241                 fr_rand_seed(NULL, 0);
4242         }
4243
4244         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4245         if (fr_rand_pool.randcnt >= 256) {
4246                 fr_rand_pool.randcnt = 0;
4247                 fr_isaac(&fr_rand_pool);
4248         }
4249
4250         return num;
4251 }
4252
4253
4254 /** Allocate a new RADIUS_PACKET
4255  *
4256  * @param ctx the context in which the packet is allocated. May be NULL if
4257  *      the packet is not associated with a REQUEST.
4258  * @param newvector if TRUE a new request authenticator will be generated.
4259  * @return a new RADIUS_PACKET or NULL on error.
4260  */
4261 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, int newvector)
4262 {
4263         RADIUS_PACKET   *rp;
4264
4265         rp = talloc_zero(ctx, RADIUS_PACKET);
4266         if (!rp) {
4267                 fr_strerror_printf("out of memory");
4268                 return NULL;
4269         }
4270         rp->id = -1;
4271         rp->offset = -1;
4272
4273         if (newvector) {
4274                 int i;
4275                 uint32_t hash, base;
4276
4277                 /*
4278                  *      Don't expose the actual contents of the random
4279                  *      pool.
4280                  */
4281                 base = fr_rand();
4282                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4283                         hash = fr_rand() ^ base;
4284                         memcpy(rp->vector + i, &hash, sizeof(hash));
4285                 }
4286         }
4287         fr_rand();              /* stir the pool again */
4288
4289         return rp;
4290 }
4291
4292 /** Allocate a new RADIUS_PACKET response
4293  *
4294  * @param ctx the context in which the packet is allocated. May be NULL if
4295  *      the packet is not associated with a REQUEST.
4296  * @param packet The request packet.
4297  * @return a new RADIUS_PACKET or NULL on error.
4298  */
4299 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4300 {
4301         RADIUS_PACKET *reply;
4302
4303         if (!packet) return NULL;
4304
4305         reply = rad_alloc(ctx, 0);
4306         if (!reply) return NULL;
4307
4308         /*
4309          *      Initialize the fields from the request.
4310          */
4311         reply->sockfd = packet->sockfd;
4312         reply->dst_ipaddr = packet->src_ipaddr;
4313         reply->src_ipaddr = packet->dst_ipaddr;
4314         reply->dst_port = packet->src_port;
4315         reply->src_port = packet->dst_port;
4316         reply->id = packet->id;
4317         reply->code = 0; /* UNKNOWN code */
4318         memcpy(reply->vector, packet->vector,
4319                sizeof(reply->vector));
4320         reply->vps = NULL;
4321         reply->data = NULL;
4322         reply->data_len = 0;
4323
4324         return reply;
4325 }
4326
4327
4328 /**
4329  * @brief Free a RADIUS_PACKET
4330  */
4331 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4332 {
4333         RADIUS_PACKET *radius_packet;
4334
4335         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4336         radius_packet = *radius_packet_ptr;
4337
4338         talloc_free(radius_packet->data); /* not really necessary... */
4339
4340         pairfree(&radius_packet->vps);
4341
4342         talloc_free(radius_packet);
4343         *radius_packet_ptr = NULL;
4344 }