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