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