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