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