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