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