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