Shorten passwords from the end. Fixes #1013
[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
3454                         /*
3455                          *      Take off trailing zeros from the END.
3456                          *      This allows passwords to have zeros in
3457                          *      the middle of a field.
3458                          *
3459                          *      However, if the password has a zero at
3460                          *      the end, it will get mashed by this
3461                          *      code.  There's really no way around
3462                          *      that.
3463                          */
3464                         while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3465                         break;
3466
3467                 /*
3468                  *      Tunnel-Password's may go ONLY in response
3469                  *      packets.  They can have a tag, so datalen is
3470                  *      not the same as attrlen.
3471                  */
3472                 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3473                         if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3474                                                 original ? original->vector : nullvector) < 0) {
3475                                 goto raw;
3476                         }
3477                         break;
3478
3479                 /*
3480                  *  Ascend-Send-Secret
3481                  *  Ascend-Receive-Secret
3482                  */
3483                 case FLAG_ENCRYPT_ASCEND_SECRET:
3484                         if (!original) {
3485                                 goto raw;
3486                         } else {
3487                                 uint8_t my_digest[AUTH_VECTOR_LEN];
3488                                 make_secret(my_digest,
3489                                             original->vector,
3490                                             secret, data);
3491                                 memcpy(buffer, my_digest,
3492                                        AUTH_VECTOR_LEN );
3493                                 buffer[AUTH_VECTOR_LEN] = '\0';
3494                                 datalen = strlen((char *) buffer);
3495                         }
3496                         break;
3497
3498                 default:
3499                         break;
3500                 } /* switch over encryption flags */
3501         }
3502
3503         /*
3504          *      Double-check the length after decrypting the
3505          *      attribute.
3506          */
3507         VP_TRACE("data2vp: type %u\n", da->type);
3508         switch (da->type) {
3509         case PW_TYPE_STRING:
3510         case PW_TYPE_OCTETS:
3511                 break;
3512
3513         case PW_TYPE_ABINARY:
3514                 if (datalen > sizeof(vp->vp_filter)) goto raw;
3515                 break;
3516
3517         case PW_TYPE_INTEGER:
3518         case PW_TYPE_IPV4_ADDR:
3519         case PW_TYPE_DATE:
3520         case PW_TYPE_SIGNED:
3521                 if (datalen != 4) goto raw;
3522                 break;
3523
3524         case PW_TYPE_INTEGER64:
3525         case PW_TYPE_IFID:
3526                 if (datalen != 8) goto raw;
3527                 break;
3528
3529         case PW_TYPE_IPV6_ADDR:
3530                 if (datalen != 16) goto raw;
3531                 break;
3532
3533         case PW_TYPE_IPV6_PREFIX:
3534                 if ((datalen < 2) || (datalen > 18)) goto raw;
3535                 if (data[1] > 128) goto raw;
3536                 break;
3537
3538         case PW_TYPE_BYTE:
3539                 if (datalen != 1) goto raw;
3540                 break;
3541
3542         case PW_TYPE_SHORT:
3543                 if (datalen != 2) goto raw;
3544                 break;
3545
3546         case PW_TYPE_ETHERNET:
3547                 if (datalen != 6) goto raw;
3548                 break;
3549
3550         case PW_TYPE_COMBO_IP_ADDR:
3551                 if (datalen == 4) {
3552                         child = dict_attrbytype(da->attr, da->vendor,
3553                                                 PW_TYPE_IPV4_ADDR);
3554                 } else if (datalen == 16) {
3555                         child = dict_attrbytype(da->attr, da->vendor,
3556                                              PW_TYPE_IPV6_ADDR);
3557                 } else {
3558                         goto raw;
3559                 }
3560                 if (!child) goto raw;
3561                 da = child;     /* re-write it */
3562                 break;
3563
3564         case PW_TYPE_IPV4_PREFIX:
3565                 if (datalen != 6) goto raw;
3566                 if ((data[1] & 0x3f) > 32) goto raw;
3567                 break;
3568
3569                 /*
3570                  *      The rest of the data types can cause
3571                  *      recursion!  Ask yourself, "is recursion OK?"
3572                  */
3573
3574         case PW_TYPE_EXTENDED:
3575                 if (datalen < 2) goto raw; /* etype, value */
3576
3577                 child = dict_attrbyparent(da, data[0], 0);
3578                 if (!child) goto raw;
3579
3580                 /*
3581                  *      Recurse to decode the contents, which could be
3582                  *      a TLV, IPaddr, etc.  Note that we decode only
3583                  *      the current attribute, and we ignore any extra
3584                  *      data after it.
3585                  */
3586                 rcode = data2vp(ctx, packet, original, secret, child,
3587                                 data + 1, attrlen - 1, attrlen - 1, pvp);
3588                 if (rcode < 0) goto raw;
3589                 return 1 + rcode;
3590
3591         case PW_TYPE_LONG_EXTENDED:
3592                 if (datalen < 3) goto raw; /* etype, flags, value */
3593
3594                 child = dict_attrbyparent(da, data[0], 0);
3595                 if (!child) {
3596                         if ((data[0] != PW_VENDOR_SPECIFIC) ||
3597                             (datalen < (3 + 4 + 1))) {
3598                                 /* da->attr < 255, da->vendor == 0 */
3599                                 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3600                         } else {
3601                                 /*
3602                                  *      Try to find the VSA.
3603                                  */
3604                                 memcpy(&vendor, data + 3, 4);
3605                                 vendor = ntohl(vendor);
3606
3607                                 if (vendor == 0) goto raw;
3608
3609                                 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3610                         }
3611
3612                         if (!child) {
3613                                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3614                                 return -1;
3615                         }
3616                 }
3617
3618                 /*
3619                  *      If there no more fragments, then the contents
3620                  *      have to be a well-known data type.
3621                  *
3622                  */
3623                 if ((data[1] & 0x80) == 0) {
3624                         rcode = data2vp(ctx, packet, original, secret, child,
3625                                         data + 2, attrlen - 2, attrlen - 2,
3626                                         pvp);
3627                         if (rcode < 0) goto raw;
3628                         return 2 + rcode;
3629                 }
3630
3631                 /*
3632                  *      This requires a whole lot more work.
3633                  */
3634                 return data2vp_extended(ctx, packet, original, secret, child,
3635                                         start, attrlen, packetlen, pvp);
3636
3637         case PW_TYPE_EVS:
3638                 if (datalen < 6) goto raw; /* vid, vtype, value */
3639
3640                 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3641
3642                 memcpy(&vendor, data, 4);
3643                 vendor = ntohl(vendor);
3644                 dv = dict_vendorbyvalue(vendor);
3645                 if (!dv) {
3646                         child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3647                 } else {
3648                         child = dict_attrbyparent(da, data[4], vendor);
3649                         if (!child) {
3650                                 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3651                         }
3652                 }
3653                 if (!child) goto raw;
3654
3655                 rcode = data2vp(ctx, packet, original, secret, child,
3656                                 data + 5, attrlen - 5, attrlen - 5, pvp);
3657                 if (rcode < 0) goto raw;
3658                 return 5 + rcode;
3659
3660         case PW_TYPE_TLV:
3661                 /*
3662                  *      We presume that the TLVs all fit into one
3663                  *      attribute, OR they've already been grouped
3664                  *      into a contiguous memory buffer.
3665                  */
3666                 rcode = data2vp_tlvs(ctx, packet, original, secret, da,
3667                                      data, attrlen, pvp);
3668                 if (rcode < 0) goto raw;
3669                 return rcode;
3670
3671         case PW_TYPE_VSA:
3672                 /*
3673                  *      VSAs can be WiMAX, in which case they don't
3674                  *      fit into one attribute.
3675                  */
3676                 rcode = data2vp_vsas(ctx, packet, original, secret,
3677                                      data, attrlen, packetlen, pvp);
3678                 if (rcode < 0) goto raw;
3679                 return rcode;
3680
3681         default:
3682         raw:
3683                 /*
3684                  *      Re-write the attribute to be "raw".  It is
3685                  *      therefore of type "octets", and will be
3686                  *      handled below.
3687                  */
3688                 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3689                 if (!da) {
3690                         fr_strerror_printf("Internal sanity check %d", __LINE__);
3691                         return -1;
3692                 }
3693                 tag = TAG_NONE;
3694 #ifndef NDEBUG
3695                 /*
3696                  *      Fix for Coverity.
3697                  */
3698                 if (da->type != PW_TYPE_OCTETS) {
3699                         dict_attr_free(&da);
3700                         return -1;
3701                 }
3702 #endif
3703                 break;
3704         }
3705
3706         /*
3707          *      And now that we've verified the basic type
3708          *      information, decode the actual data.
3709          */
3710  alloc_cui:
3711         vp = pairalloc(ctx, da);
3712         if (!vp) return -1;
3713
3714         vp->vp_length = datalen;
3715         vp->tag = tag;
3716
3717         switch (da->type) {
3718         case PW_TYPE_STRING:
3719                 p = talloc_array(vp, char, vp->vp_length + 1);
3720                 memcpy(p, data, vp->vp_length);
3721                 p[vp->vp_length] = '\0';
3722                 vp->vp_strvalue = p;
3723                 break;
3724
3725         case PW_TYPE_OCTETS:
3726                 pairmemcpy(vp, data, vp->vp_length);
3727                 break;
3728
3729         case PW_TYPE_ABINARY:
3730                 if (vp->vp_length > sizeof(vp->vp_filter)) {
3731                         vp->vp_length = sizeof(vp->vp_filter);
3732                 }
3733                 memcpy(vp->vp_filter, data, vp->vp_length);
3734                 break;
3735
3736         case PW_TYPE_BYTE:
3737                 vp->vp_byte = data[0];
3738                 break;
3739
3740         case PW_TYPE_SHORT:
3741                 vp->vp_short = (data[0] << 8) | data[1];
3742                 break;
3743
3744         case PW_TYPE_INTEGER:
3745                 memcpy(&vp->vp_integer, data, 4);
3746                 vp->vp_integer = ntohl(vp->vp_integer);
3747                 break;
3748
3749         case PW_TYPE_INTEGER64:
3750                 memcpy(&vp->vp_integer64, data, 8);
3751                 vp->vp_integer64 = ntohll(vp->vp_integer64);
3752                 break;
3753
3754         case PW_TYPE_DATE:
3755                 memcpy(&vp->vp_date, data, 4);
3756                 vp->vp_date = ntohl(vp->vp_date);
3757                 break;
3758
3759         case PW_TYPE_ETHERNET:
3760                 memcpy(vp->vp_ether, data, 6);
3761                 break;
3762
3763         case PW_TYPE_IPV4_ADDR:
3764                 memcpy(&vp->vp_ipaddr, data, 4);
3765                 break;
3766
3767         case PW_TYPE_IFID:
3768                 memcpy(vp->vp_ifid, data, 8);
3769                 break;
3770
3771         case PW_TYPE_IPV6_ADDR:
3772                 memcpy(&vp->vp_ipv6addr, data, 16);
3773                 break;
3774
3775         case PW_TYPE_IPV6_PREFIX:
3776                 /*
3777                  *      FIXME: double-check that
3778                  *      (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3779                  */
3780                 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3781                 if (vp->vp_length < 18) {
3782                         memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3783                                18 - vp->vp_length);
3784                 }
3785                 break;
3786
3787         case PW_TYPE_IPV4_PREFIX:
3788                 /* FIXME: do the same double-check as for IPv6Prefix */
3789                 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3790
3791                 /*
3792                  *      /32 means "keep all bits".  Otherwise, mask
3793                  *      them out.
3794                  */
3795                 if ((data[1] & 0x3f) > 32) {
3796                         uint32_t addr, mask;
3797
3798                         memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3799                         mask = 1;
3800                         mask <<= (32 - (data[1] & 0x3f));
3801                         mask--;
3802                         mask = ~mask;
3803                         mask = htonl(mask);
3804                         addr &= mask;
3805                         memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3806                 }
3807                 break;
3808
3809         case PW_TYPE_SIGNED:    /* overloaded with vp_integer */
3810                 memcpy(&vp->vp_integer, buffer, 4);
3811                 vp->vp_integer = ntohl(vp->vp_integer);
3812                 break;
3813
3814         default:
3815                 pairfree(&vp);
3816                 fr_strerror_printf("Internal sanity check %d", __LINE__);
3817                 return -1;
3818         }
3819         vp->type = VT_DATA;
3820         *pvp = vp;
3821
3822         return attrlen;
3823 }
3824
3825
3826 /** Create a "normal" VALUE_PAIR from the given data
3827  *
3828  */
3829 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3830                     RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3831                     char const *secret,
3832                     uint8_t const *data, size_t length,
3833                     VALUE_PAIR **pvp)
3834 {
3835         ssize_t rcode;
3836
3837         DICT_ATTR const *da;
3838
3839         if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3840                 fr_strerror_printf("rad_attr2vp: Insufficient data");
3841                 return -1;
3842         }
3843
3844         da = dict_attrbyvalue(data[0], 0);
3845         if (!da) {
3846                 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3847                 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3848         }
3849         if (!da) return -1;
3850
3851         /*
3852          *      Pass the entire thing to the decoding function
3853          */
3854         if (da->flags.concat) {
3855                 VP_TRACE("attr2vp: concat attribute\n");
3856                 return data2vp_concat(ctx, da, data, length, pvp);
3857         }
3858
3859         /*
3860          *      Note that we pass the entire length, not just the
3861          *      length of this attribute.  The Extended or WiMAX
3862          *      attributes may have the "continuation" bit set, and
3863          *      will thus be more than one attribute in length.
3864          */
3865         rcode = data2vp(ctx, packet, original, secret, da,
3866                         data + 2, data[1] - 2, length - 2, pvp);
3867         if (rcode < 0) return rcode;
3868
3869         return 2 + rcode;
3870 }
3871
3872 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3873
3874 /** Converts vp_data to network byte order
3875  *
3876  * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3877  * in an architecture independent format.
3878  *
3879  * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3880  * as the source VALUE_PAIR is not freed.
3881  *
3882  * @param out where to write the pointer to the value.
3883  * @param vp to get the value from.
3884  * @return -1 on error, or the length of the value
3885  */
3886 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3887 {
3888         uint8_t         *buffer;
3889         uint32_t        lvalue;
3890         uint64_t        lvalue64;
3891
3892         *out = NULL;
3893
3894         buffer = fr_thread_local_init(rad_vp2data_buff, free);
3895         if (!buffer) {
3896                 int ret;
3897
3898                 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3899                 if (!buffer) {
3900                         fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3901                         return -1;
3902                 }
3903
3904                 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3905                 if (ret != 0) {
3906                         fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3907                         free(buffer);
3908                         return -1;
3909                 }
3910         }
3911
3912         VERIFY_VP(vp);
3913
3914         switch (vp->da->type) {
3915         case PW_TYPE_STRING:
3916         case PW_TYPE_OCTETS:
3917         case PW_TYPE_TLV:
3918                 memcpy(out, &vp->data.ptr, sizeof(*out));
3919                 break;
3920
3921         /*
3922          *      All of these values are at the same location.
3923          */
3924         case PW_TYPE_IFID:
3925         case PW_TYPE_IPV4_ADDR:
3926         case PW_TYPE_IPV6_ADDR:
3927         case PW_TYPE_IPV6_PREFIX:
3928         case PW_TYPE_IPV4_PREFIX:
3929         case PW_TYPE_ABINARY:
3930         case PW_TYPE_ETHERNET:
3931         case PW_TYPE_COMBO_IP_ADDR:
3932         case PW_TYPE_COMBO_IP_PREFIX:
3933         {
3934                 void const *p = &vp->data;
3935                 memcpy(out, &p, sizeof(*out));
3936                 break;
3937         }
3938
3939         case PW_TYPE_BOOLEAN:
3940                 buffer[0] = vp->vp_byte & 0x01;
3941                 *out = buffer;
3942                 break;
3943
3944         case PW_TYPE_BYTE:
3945                 buffer[0] = vp->vp_byte & 0xff;
3946                 *out = buffer;
3947                 break;
3948
3949         case PW_TYPE_SHORT:
3950                 buffer[0] = (vp->vp_short >> 8) & 0xff;
3951                 buffer[1] = vp->vp_short & 0xff;
3952                 *out = buffer;
3953                 break;
3954
3955         case PW_TYPE_INTEGER:
3956                 lvalue = htonl(vp->vp_integer);
3957                 memcpy(buffer, &lvalue, sizeof(lvalue));
3958                 *out = buffer;
3959                 break;
3960
3961         case PW_TYPE_INTEGER64:
3962                 lvalue64 = htonll(vp->vp_integer64);
3963                 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3964                 *out = buffer;
3965                 break;
3966
3967         case PW_TYPE_DATE:
3968                 lvalue = htonl(vp->vp_date);
3969                 memcpy(buffer, &lvalue, sizeof(lvalue));
3970                 *out = buffer;
3971                 break;
3972
3973         case PW_TYPE_SIGNED:
3974         {
3975                 int32_t slvalue = htonl(vp->vp_signed);
3976                 memcpy(buffer, &slvalue, sizeof(slvalue));
3977                 *out = buffer;
3978                 break;
3979         }
3980
3981         case PW_TYPE_INVALID:
3982         case PW_TYPE_EXTENDED:
3983         case PW_TYPE_LONG_EXTENDED:
3984         case PW_TYPE_EVS:
3985         case PW_TYPE_VSA:
3986         case PW_TYPE_TIMEVAL:
3987         case PW_TYPE_MAX:
3988                 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
3989                 return -1;
3990
3991         /* Don't add default */
3992         }
3993
3994         return vp->vp_length;
3995 }
3996
3997 /** Calculate/check digest, and decode radius attributes
3998  *
3999  * @return -1 on decoding error, 0 on success
4000  */
4001 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4002                char const *secret)
4003 {
4004         int                     packet_length;
4005         uint32_t                num_attributes;
4006         uint8_t                 *ptr;
4007         radius_packet_t         *hdr;
4008         VALUE_PAIR *head, **tail, *vp;
4009
4010         /*
4011          *      Extract attribute-value pairs
4012          */
4013         hdr = (radius_packet_t *)packet->data;
4014         ptr = hdr->data;
4015         packet_length = packet->data_len - RADIUS_HDR_LEN;
4016
4017         head = NULL;
4018         tail = &head;
4019         num_attributes = 0;
4020
4021         /*
4022          *      Loop over the attributes, decoding them into VPs.
4023          */
4024         while (packet_length > 0) {
4025                 ssize_t my_len;
4026
4027                 /*
4028                  *      This may return many VPs
4029                  */
4030                 my_len = rad_attr2vp(packet, packet, original, secret,
4031                                      ptr, packet_length, &vp);
4032                 if (my_len < 0) {
4033                         pairfree(&head);
4034                         return -1;
4035                 }
4036
4037                 *tail = vp;
4038                 while (vp) {
4039                         num_attributes++;
4040                         tail = &(vp->next);
4041                         vp = vp->next;
4042                 }
4043
4044                 /*
4045                  *      VSA's may not have been counted properly in
4046                  *      rad_packet_ok() above, as it is hard to count
4047                  *      then without using the dictionary.  We
4048                  *      therefore enforce the limits here, too.
4049                  */
4050                 if ((fr_max_attributes > 0) &&
4051                     (num_attributes > fr_max_attributes)) {
4052                         char host_ipaddr[128];
4053
4054                         pairfree(&head);
4055                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4056                                    inet_ntop(packet->src_ipaddr.af,
4057                                              &packet->src_ipaddr.ipaddr,
4058                                              host_ipaddr, sizeof(host_ipaddr)),
4059                                    num_attributes, fr_max_attributes);
4060                         return -1;
4061                 }
4062
4063                 ptr += my_len;
4064                 packet_length -= my_len;
4065         }
4066
4067         /*
4068          *      Merge information from the outside world into our
4069          *      random pool.
4070          */
4071         fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4072
4073         /*
4074          *      There may be VP's already in the packet.  Don't
4075          *      destroy them.  Instead, add the decoded attributes to
4076          *      the tail of the list.
4077          */
4078         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4079                 /* nothing */
4080         }
4081         *tail = head;
4082
4083         return 0;
4084 }
4085
4086
4087 /** Encode password
4088  *
4089  * We assume that the passwd buffer passed is big enough.
4090  * RFC2138 says the password is max 128 chars, so the size
4091  * of the passwd buffer must be at least 129 characters.
4092  * Preferably it's just MAX_STRING_LEN.
4093  *
4094  * int *pwlen is updated to the new length of the encrypted
4095  * password - a multiple of 16 bytes.
4096  */
4097 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4098                  uint8_t const *vector)
4099 {
4100         FR_MD5_CTX context, old;
4101         uint8_t digest[AUTH_VECTOR_LEN];
4102         int     i, n, secretlen;
4103         int     len;
4104
4105         /*
4106          *      RFC maximum is 128 bytes.
4107          *
4108          *      If length is zero, pad it out with zeros.
4109          *
4110          *      If the length isn't aligned to 16 bytes,
4111          *      zero out the extra data.
4112          */
4113         len = *pwlen;
4114
4115         if (len > 128) len = 128;
4116
4117         if (len == 0) {
4118                 memset(passwd, 0, AUTH_PASS_LEN);
4119                 len = AUTH_PASS_LEN;
4120         } else if ((len % AUTH_PASS_LEN) != 0) {
4121                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4122                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4123         }
4124         *pwlen = len;
4125
4126         /*
4127          *      Use the secret to setup the decryption digest
4128          */
4129         secretlen = strlen(secret);
4130
4131         fr_md5_init(&context);
4132         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4133         old = context;          /* save intermediate work */
4134
4135         /*
4136          *      Encrypt it in place.  Don't bother checking
4137          *      len, as we've ensured above that it's OK.
4138          */
4139         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4140                 if (n == 0) {
4141                         fr_md5_update(&context, vector, AUTH_PASS_LEN);
4142                         fr_md5_final(digest, &context);
4143                 } else {
4144                         context = old;
4145                         fr_md5_update(&context,
4146                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
4147                                      AUTH_PASS_LEN);
4148                         fr_md5_final(digest, &context);
4149                 }
4150
4151                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4152                         passwd[i + n] ^= digest[i];
4153                 }
4154         }
4155
4156         return 0;
4157 }
4158
4159 /** Decode password
4160  *
4161  */
4162 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4163                  uint8_t const *vector)
4164 {
4165         FR_MD5_CTX context, old;
4166         uint8_t digest[AUTH_VECTOR_LEN];
4167         int     i;
4168         size_t  n, secretlen;
4169
4170         /*
4171          *      The RFC's say that the maximum is 128.
4172          *      The buffer we're putting it into above is 254, so
4173          *      we don't need to do any length checking.
4174          */
4175         if (pwlen > 128) pwlen = 128;
4176
4177         /*
4178          *      Catch idiots.
4179          */
4180         if (pwlen == 0) goto done;
4181
4182         /*
4183          *      Use the secret to setup the decryption digest
4184          */
4185         secretlen = strlen(secret);
4186
4187         fr_md5_init(&context);
4188         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4189         old = context;          /* save intermediate work */
4190
4191         /*
4192          *      The inverse of the code above.
4193          */
4194         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4195                 if (n == 0) {
4196                         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4197                         fr_md5_final(digest, &context);
4198
4199                         context = old;
4200                         if (pwlen > AUTH_PASS_LEN) {
4201                                 fr_md5_update(&context, (uint8_t *) passwd,
4202                                              AUTH_PASS_LEN);
4203                         }
4204                 } else {
4205                         fr_md5_final(digest, &context);
4206
4207                         context = old;
4208                         if (pwlen > (n + AUTH_PASS_LEN)) {
4209                                 fr_md5_update(&context, (uint8_t *) passwd + n,
4210                                              AUTH_PASS_LEN);
4211                         }
4212                 }
4213
4214                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4215                         passwd[i + n] ^= digest[i];
4216                 }
4217         }
4218
4219  done:
4220         passwd[pwlen] = '\0';
4221         return strlen(passwd);
4222 }
4223
4224
4225 /** Encode Tunnel-Password attributes when sending them out on the wire
4226  *
4227  * int *pwlen is updated to the new length of the encrypted
4228  * password - a multiple of 16 bytes.
4229  *
4230  * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4231  * value MD5 hash.
4232  */
4233 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4234                         uint8_t const *vector)
4235 {
4236         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4237         unsigned char   digest[AUTH_VECTOR_LEN];
4238         char*   salt;
4239         int     i, n, secretlen;
4240         unsigned len, n2;
4241
4242         len = *pwlen;
4243
4244         if (len > 127) len = 127;
4245
4246         /*
4247          * Shift the password 3 positions right to place a salt and original
4248          * length, tag will be added automatically on packet send
4249          */
4250         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4251         salt = passwd;
4252         passwd += 2;
4253         /*
4254          * save original password length as first password character;
4255          */
4256         *passwd = len;
4257         len += 1;
4258
4259
4260         /*
4261          *      Generate salt.  The RFC's say:
4262          *
4263          *      The high bit of salt[0] must be set, each salt in a
4264          *      packet should be unique, and they should be random
4265          *
4266          *      So, we set the high bit, add in a counter, and then
4267          *      add in some CSPRNG data.  should be OK..
4268          */
4269         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4270                    (fr_rand() & 0x07));
4271         salt[1] = fr_rand();
4272
4273         /*
4274          *      Padd password to multiple of AUTH_PASS_LEN bytes.
4275          */
4276         n = len % AUTH_PASS_LEN;
4277         if (n) {
4278                 n = AUTH_PASS_LEN - n;
4279                 for (; n > 0; n--, len++)
4280                         passwd[len] = 0;
4281         }
4282         /* set new password length */
4283         *pwlen = len + 2;
4284
4285         /*
4286          *      Use the secret to setup the decryption digest
4287          */
4288         secretlen = strlen(secret);
4289         memcpy(buffer, secret, secretlen);
4290
4291         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4292                 if (!n2) {
4293                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4294                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4295                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4296                 } else {
4297                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4298                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4299                 }
4300
4301                 for (i = 0; i < AUTH_PASS_LEN; i++) {
4302                         passwd[i + n2] ^= digest[i];
4303                 }
4304         }
4305         passwd[n2] = 0;
4306         return 0;
4307 }
4308
4309 /** Decode Tunnel-Password encrypted attributes
4310  *
4311  * Defined in RFC-2868, this uses a two char SALT along with the
4312  * initial intermediate value, to differentiate it from the
4313  * above.
4314  */
4315 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4316                         uint8_t const *vector)
4317 {
4318         FR_MD5_CTX  context, old;
4319         uint8_t         digest[AUTH_VECTOR_LEN];
4320         int             secretlen;
4321         unsigned        i, n, len, reallen;
4322
4323         len = *pwlen;
4324
4325         /*
4326          *      We need at least a salt.
4327          */
4328         if (len < 2) {
4329                 fr_strerror_printf("tunnel password is too short");
4330                 return -1;
4331         }
4332
4333         /*
4334          *      There's a salt, but no password.  Or, there's a salt
4335          *      and a 'data_len' octet.  It's wrong, but at least we
4336          *      can figure out what it means: the password is empty.
4337          *
4338          *      Note that this means we ignore the 'data_len' field,
4339          *      if the attribute length tells us that there's no
4340          *      more data.  So the 'data_len' field may be wrong,
4341          *      but that's ok...
4342          */
4343         if (len <= 3) {
4344                 passwd[0] = 0;
4345                 *pwlen = 0;
4346                 return 0;
4347         }
4348
4349         len -= 2;               /* discount the salt */
4350
4351         /*
4352          *      Use the secret to setup the decryption digest
4353          */
4354         secretlen = strlen(secret);
4355
4356         fr_md5_init(&context);
4357         fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4358         old = context;          /* save intermediate work */
4359
4360         /*
4361          *      Set up the initial key:
4362          *
4363          *       b(1) = MD5(secret + vector + salt)
4364          */
4365         fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4366         fr_md5_update(&context, passwd, 2);
4367
4368         reallen = 0;
4369         for (n = 0; n < len; n += AUTH_PASS_LEN) {
4370                 int base = 0;
4371
4372                 if (n == 0) {
4373                         fr_md5_final(digest, &context);
4374
4375                         context = old;
4376
4377                         /*
4378                          *      A quick check: decrypt the first octet
4379                          *      of the password, which is the
4380                          *      'data_len' field.  Ensure it's sane.
4381                          */
4382                         reallen = passwd[2] ^ digest[0];
4383                         if (reallen >= len) {
4384                                 fr_strerror_printf("tunnel password is too long for the attribute");
4385                                 return -1;
4386                         }
4387
4388                         fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4389
4390                         base = 1;
4391                 } else {
4392                         fr_md5_final(digest, &context);
4393
4394                         context = old;
4395                         fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4396                 }
4397
4398                 for (i = base; i < AUTH_PASS_LEN; i++) {
4399                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4400                 }
4401         }
4402
4403         /*
4404          *      See make_tunnel_password, above.
4405          */
4406         if (reallen > 239) reallen = 239;
4407
4408         *pwlen = reallen;
4409         passwd[reallen] = 0;
4410
4411         return reallen;
4412 }
4413
4414 /** Encode a CHAP password
4415  *
4416  * @bug FIXME: might not work with Ascend because
4417  * we use vp->vp_length, and Ascend gear likes
4418  * to send an extra '\0' in the string!
4419  */
4420 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4421                     VALUE_PAIR *password)
4422 {
4423         int             i;
4424         uint8_t         *ptr;
4425         uint8_t         string[MAX_STRING_LEN * 2 + 1];
4426         VALUE_PAIR      *challenge;
4427
4428         /*
4429          *      Sanity check the input parameters
4430          */
4431         if ((packet == NULL) || (password == NULL)) {
4432                 return -1;
4433         }
4434
4435         /*
4436          *      Note that the password VP can be EITHER
4437          *      a User-Password attribute (from a check-item list),
4438          *      or a CHAP-Password attribute (the client asking
4439          *      the library to encode it).
4440          */
4441
4442         i = 0;
4443         ptr = string;
4444         *ptr++ = id;
4445
4446         i++;
4447         memcpy(ptr, password->vp_strvalue, password->vp_length);
4448         ptr += password->vp_length;
4449         i += password->vp_length;
4450
4451         /*
4452          *      Use Chap-Challenge pair if present,
4453          *      Request Authenticator otherwise.
4454          */
4455         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4456         if (challenge) {
4457                 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4458                 i += challenge->vp_length;
4459         } else {
4460                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4461                 i += AUTH_VECTOR_LEN;
4462         }
4463
4464         *output = id;
4465         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4466
4467         return 0;
4468 }
4469
4470
4471 /** Seed the random number generator
4472  *
4473  * May be called any number of times.
4474  */
4475 void fr_rand_seed(void const *data, size_t size)
4476 {
4477         uint32_t hash;
4478
4479         /*
4480          *      Ensure that the pool is initialized.
4481          */
4482         if (!fr_rand_initialized) {
4483                 int fd;
4484
4485                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4486
4487                 fd = open("/dev/urandom", O_RDONLY);
4488                 if (fd >= 0) {
4489                         size_t total;
4490                         ssize_t this;
4491
4492                         total = 0;
4493                         while (total < sizeof(fr_rand_pool.randrsl)) {
4494                                 this = read(fd, fr_rand_pool.randrsl,
4495                                             sizeof(fr_rand_pool.randrsl) - total);
4496                                 if ((this < 0) && (errno != EINTR)) break;
4497                                 if (this > 0) total += this;
4498                         }
4499                         close(fd);
4500                 } else {
4501                         fr_rand_pool.randrsl[0] = fd;
4502                         fr_rand_pool.randrsl[1] = time(NULL);
4503                         fr_rand_pool.randrsl[2] = errno;
4504                 }
4505
4506                 fr_randinit(&fr_rand_pool, 1);
4507                 fr_rand_pool.randcnt = 0;
4508                 fr_rand_initialized = 1;
4509         }
4510
4511         if (!data) return;
4512
4513         /*
4514          *      Hash the user data
4515          */
4516         hash = fr_rand();
4517         if (!hash) hash = fr_rand();
4518         hash = fr_hash_update(data, size, hash);
4519
4520         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4521 }
4522
4523
4524 /** Return a 32-bit random number
4525  *
4526  */
4527 uint32_t fr_rand(void)
4528 {
4529         uint32_t num;
4530
4531         /*
4532          *      Ensure that the pool is initialized.
4533          */
4534         if (!fr_rand_initialized) {
4535                 fr_rand_seed(NULL, 0);
4536         }
4537
4538         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4539         if (fr_rand_pool.randcnt >= 256) {
4540                 fr_rand_pool.randcnt = 0;
4541                 fr_isaac(&fr_rand_pool);
4542         }
4543
4544         return num;
4545 }
4546
4547
4548 /** Allocate a new RADIUS_PACKET
4549  *
4550  * @param ctx the context in which the packet is allocated. May be NULL if
4551  *      the packet is not associated with a REQUEST.
4552  * @param new_vector if true a new request authenticator will be generated.
4553  * @return a new RADIUS_PACKET or NULL on error.
4554  */
4555 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4556 {
4557         RADIUS_PACKET   *rp;
4558
4559         rp = talloc_zero(ctx, RADIUS_PACKET);
4560         if (!rp) {
4561                 fr_strerror_printf("out of memory");
4562                 return NULL;
4563         }
4564         rp->id = -1;
4565         rp->offset = -1;
4566
4567         if (new_vector) {
4568                 int i;
4569                 uint32_t hash, base;
4570
4571                 /*
4572                  *      Don't expose the actual contents of the random
4573                  *      pool.
4574                  */
4575                 base = fr_rand();
4576                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4577                         hash = fr_rand() ^ base;
4578                         memcpy(rp->vector + i, &hash, sizeof(hash));
4579                 }
4580         }
4581         fr_rand();              /* stir the pool again */
4582
4583         return rp;
4584 }
4585
4586 /** Allocate a new RADIUS_PACKET response
4587  *
4588  * @param ctx the context in which the packet is allocated. May be NULL if
4589  *      the packet is not associated with a REQUEST.
4590  * @param packet The request packet.
4591  * @return a new RADIUS_PACKET or NULL on error.
4592  */
4593 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4594 {
4595         RADIUS_PACKET *reply;
4596
4597         if (!packet) return NULL;
4598
4599         reply = rad_alloc(ctx, false);
4600         if (!reply) return NULL;
4601
4602         /*
4603          *      Initialize the fields from the request.
4604          */
4605         reply->sockfd = packet->sockfd;
4606         reply->dst_ipaddr = packet->src_ipaddr;
4607         reply->src_ipaddr = packet->dst_ipaddr;
4608         reply->dst_port = packet->src_port;
4609         reply->src_port = packet->dst_port;
4610         reply->id = packet->id;
4611         reply->code = 0; /* UNKNOWN code */
4612         memcpy(reply->vector, packet->vector,
4613                sizeof(reply->vector));
4614         reply->vps = NULL;
4615         reply->data = NULL;
4616         reply->data_len = 0;
4617
4618 #ifdef WITH_TCP
4619         reply->proto = packet->proto;
4620 #endif
4621         return reply;
4622 }
4623
4624
4625 /** Free a RADIUS_PACKET
4626  *
4627  */
4628 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4629 {
4630         RADIUS_PACKET *radius_packet;
4631
4632         if (!radius_packet_ptr || !*radius_packet_ptr) return;
4633         radius_packet = *radius_packet_ptr;
4634
4635         VERIFY_PACKET(radius_packet);
4636
4637         pairfree(&radius_packet->vps);
4638
4639         talloc_free(radius_packet);
4640         *radius_packet_ptr = NULL;
4641 }
4642
4643 /** Duplicate a RADIUS_PACKET
4644  *
4645  * @param ctx the context in which the packet is allocated. May be NULL if
4646  *      the packet is not associated with a REQUEST.
4647  * @param in The packet to copy
4648  * @return a new RADIUS_PACKET or NULL on error.
4649  */
4650 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4651 {
4652         RADIUS_PACKET *out;
4653
4654         out = rad_alloc(ctx, false);
4655         if (!out) return NULL;
4656
4657         /*
4658          *      Bootstrap by copying everything.
4659          */
4660         memcpy(out, in, sizeof(*out));
4661
4662         /*
4663          *      Then reset necessary fields
4664          */
4665         out->sockfd = -1;
4666
4667         out->data = NULL;
4668         out->data_len = 0;
4669
4670         out->vps = paircopy(out, in->vps);
4671         out->offset = 0;
4672
4673         return out;
4674 }