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