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