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