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