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