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