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