Fixed compiler warnings so it now builds with -Werror
[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 librad_max_attributes = 0;
57
58 typedef struct radius_packet_t {
59   uint8_t       code;
60   uint8_t       id;
61   uint8_t       length[2];
62   uint8_t       vector[AUTH_VECTOR_LEN];
63   uint8_t       data[1];
64 } radius_packet_t;
65
66 static fr_randctx fr_rand_pool; /* across multiple calls */
67 static int fr_rand_initialized = 0;
68 static unsigned int salt_offset = 0;
69
70
71 #define MAX_PACKET_CODE (52)
72 static const char *packet_codes[] = {
73   "",
74   "Access-Request",
75   "Access-Accept",
76   "Access-Reject",
77   "Accounting-Request",
78   "Accounting-Response",
79   "Accounting-Status",
80   "Password-Request",
81   "Password-Accept",
82   "Password-Reject",
83   "Accounting-Message",
84   "Access-Challenge",
85   "Status-Server",
86   "Status-Client",
87   "14",
88   "15",
89   "16",
90   "17",
91   "18",
92   "19",
93   "20",
94   "Resource-Free-Request",
95   "Resource-Free-Response",
96   "Resource-Query-Request",
97   "Resource-Query-Response",
98   "Alternate-Resource-Reclaim-Request",
99   "NAS-Reboot-Request",
100   "NAS-Reboot-Response",
101   "28",
102   "Next-Passcode",
103   "New-Pin",
104   "Terminate-Session",
105   "Password-Expired",
106   "Event-Request",
107   "Event-Response",
108   "35",
109   "36",
110   "37",
111   "38",
112   "39",
113   "Disconnect-Request",
114   "Disconnect-ACK",
115   "Disconnect-NAK",
116   "CoA-Request",
117   "CoA-ACK",
118   "CoA-NAK",
119   "46",
120   "47",
121   "48",
122   "49",
123   "IP-Address-Allocate",
124   "IP-Address-Release"
125 };
126
127
128 /*
129  *      Wrapper for sendto which handles sendfromto, IPv6, and all
130  *      possible combinations.
131  */
132 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
133                       fr_ipaddr_t *src_ipaddr, int src_port,
134                       fr_ipaddr_t *dst_ipaddr, int dst_port)
135 {
136         struct sockaddr_storage dst;
137         socklen_t               sizeof_dst = sizeof(dst);
138
139 #ifdef WITH_UDPFROMTO
140         struct sockaddr_storage src;
141         socklen_t               sizeof_src = sizeof(src);
142
143         memset(&src, 0, sizeof(src));
144 #endif
145         memset(&dst, 0, sizeof(dst));
146
147         /*
148          *      IPv4 is supported.
149          */
150         if (dst_ipaddr->af == AF_INET) {
151                 struct sockaddr_in      *s4;
152
153                 s4 = (struct sockaddr_in *)&dst;
154                 sizeof_dst = sizeof(struct sockaddr_in);
155
156                 s4->sin_family = AF_INET;
157                 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
158                 s4->sin_port = htons(dst_port);
159
160 #ifdef WITH_UDPFROMTO
161                 s4 = (struct sockaddr_in *)&src;
162                 sizeof_src = sizeof(struct sockaddr_in);
163
164                 s4->sin_family = AF_INET;
165                 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
166                 s4->sin_port = htons(src_port);
167 #else
168                 src_port = src_port; /* -Wunused */
169 #endif
170
171         /*
172          *      IPv6 MAY be supported.
173          */
174 #ifdef HAVE_STRUCT_SOCKADDR_IN6
175         } else if (dst_ipaddr->af == AF_INET6) {
176                 struct sockaddr_in6     *s6;
177
178                 s6 = (struct sockaddr_in6 *)&dst;
179                 sizeof_dst = sizeof(struct sockaddr_in6);
180
181                 s6->sin6_family = AF_INET6;
182                 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
183                 s6->sin6_port = htons(dst_port);
184
185 #ifdef WITH_UDPFROMTO
186                 return -1;      /* UDPFROMTO && IPv6 are not supported */
187 #if 0
188                 s6 = (struct sockaddr_in6 *)&src;
189                 sizeof_src = sizeof(struct sockaddr_in6);
190
191                 s6->sin6_family = AF_INET6;
192                 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
193 #endif /* #if 0 */
194 #endif /* WITH_UDPFROMTO */
195 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
196         } else return -1;   /* Unknown address family, Die Die Die! */
197
198 #ifdef WITH_UDPFROMTO
199         /*
200          *      Only IPv4 is supported for udpfromto.
201          *
202          *      And if they don't specify a source IP address, don't
203          *      use udpfromto.
204          */
205         if ((dst_ipaddr->af == AF_INET) ||
206             (src_ipaddr->af != AF_UNSPEC)) {
207                 return sendfromto(sockfd, data, data_len, flags,
208                                   (struct sockaddr *)&src, sizeof_src,
209                                   (struct sockaddr *)&dst, sizeof_dst);
210         }
211 #else
212         src_ipaddr = src_ipaddr; /* -Wunused */
213 #endif
214
215         /*
216          *      No udpfromto, OR an IPv6 socket, fail gracefully.
217          */
218         return sendto(sockfd, data, data_len, flags,
219                       (struct sockaddr *)&dst, sizeof_dst);
220 }
221
222
223 void rad_recv_discard(int sockfd)
224 {
225         uint8_t                 header[4];
226         struct sockaddr_storage src;
227         socklen_t               sizeof_src = sizeof(src);
228
229         recvfrom(sockfd, header, sizeof(header), 0,
230                  (struct sockaddr *)&src, &sizeof_src);
231 }
232
233
234 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
235                         int *code)
236 {
237         ssize_t                 data_len, packet_len;
238         uint8_t                 header[4];
239         struct sockaddr_storage src;
240         socklen_t               sizeof_src = sizeof(src);
241
242         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
243                             (struct sockaddr *)&src, &sizeof_src);
244         if (data_len < 0) {
245                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
246                 return -1;
247         }
248
249         /*
250          *      Too little data is available, discard the packet.
251          */
252         if (data_len < 4) {
253                 recvfrom(sockfd, header, sizeof(header), 0,
254                          (struct sockaddr *)&src, &sizeof_src);
255                 return 1;
256
257         } else {                /* we got 4 bytes of data. */
258                 /*
259                  *      See how long the packet says it is.
260                  */
261                 packet_len = (header[2] * 256) + header[3];
262
263                 /*
264                  *      The length in the packet says it's less than
265                  *      a RADIUS header length: discard it.
266                  */
267                 if (packet_len < AUTH_HDR_LEN) {
268                         recvfrom(sockfd, header, sizeof(header), 0,
269                                  (struct sockaddr *)&src, &sizeof_src);
270                         return 1;
271
272                         /*
273                          *      Enforce RFC requirements, for sanity.
274                          *      Anything after 4k will be discarded.
275                          */
276                 } else if (packet_len > MAX_PACKET_LEN) {
277                         recvfrom(sockfd, header, sizeof(header), 0,
278                                  (struct sockaddr *)&src, &sizeof_src);
279                         return 1;
280                 }
281         }
282
283         if (src.ss_family == AF_INET) {
284                 struct sockaddr_in      *s4;
285
286                 s4 = (struct sockaddr_in *)&src;
287                 src_ipaddr->af = AF_INET;
288                 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
289                 *src_port = ntohs(s4->sin_port);
290
291 #ifdef HAVE_STRUCT_SOCKADDR_IN6
292         } else if (src.ss_family == AF_INET6) {
293                 struct sockaddr_in6     *s6;
294
295                 s6 = (struct sockaddr_in6 *)&src;
296                 src_ipaddr->af = AF_INET6;
297                 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
298                 *src_port = ntohs(s6->sin6_port);
299
300 #endif
301         } else {
302                 recvfrom(sockfd, header, sizeof(header), 0,
303                          (struct sockaddr *)&src, &sizeof_src);
304                 return 1;
305         }
306
307         *code = header[0];
308
309         /*
310          *      The packet says it's this long, but the actual UDP
311          *      size could still be smaller.
312          */
313         return packet_len;
314 }
315
316
317 /*
318  *      wrapper for recvfrom, which handles recvfromto, IPv6, and all
319  *      possible combinations.
320  */
321 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
322                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
323                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
324 {
325         struct sockaddr_storage src;
326         struct sockaddr_storage dst;
327         socklen_t               sizeof_src = sizeof(src);
328         socklen_t               sizeof_dst = sizeof(dst);
329         ssize_t                 data_len;
330         uint8_t                 header[4];
331         void                    *buf;
332         size_t                  len;
333
334         memset(&src, 0, sizeof_src);
335         memset(&dst, 0, sizeof_dst);
336
337         /*
338          *      Get address family, etc. first, so we know if we
339          *      need to do udpfromto.
340          *
341          *      FIXME: udpfromto also does this, but it's not
342          *      a critical problem.
343          */
344         if (getsockname(sockfd, (struct sockaddr *)&dst,
345                         &sizeof_dst) < 0) return -1;
346
347         /*
348          *      Read the length of the packet, from the packet.
349          *      This lets us allocate the buffer to use for
350          *      reading the rest of the packet.
351          */
352         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
353                             (struct sockaddr *)&src, &sizeof_src);
354         if (data_len < 0) {
355                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
356                 return -1;
357         }
358
359         /*
360          *      Too little data is available, discard the packet.
361          */
362         if (data_len < 4) {
363                 recvfrom(sockfd, header, sizeof(header), flags,
364                          (struct sockaddr *)&src, &sizeof_src);
365                 return 0;
366
367         } else {                /* we got 4 bytes of data. */
368                 /*
369                  *      See how long the packet says it is.
370                  */
371                 len = (header[2] * 256) + header[3];
372
373                 /*
374                  *      The length in the packet says it's less than
375                  *      a RADIUS header length: discard it.
376                  */
377                 if (len < AUTH_HDR_LEN) {
378                         recvfrom(sockfd, header, sizeof(header), flags,
379                                  (struct sockaddr *)&src, &sizeof_src);
380                         return 0;
381
382                         /*
383                          *      Enforce RFC requirements, for sanity.
384                          *      Anything after 4k will be discarded.
385                          */
386                 } else if (len > MAX_PACKET_LEN) {
387                         recvfrom(sockfd, header, sizeof(header), flags,
388                                  (struct sockaddr *)&src, &sizeof_src);
389                         return len;
390                 }
391         }
392
393         buf = malloc(len);
394         if (!buf) return -1;
395
396         /*
397          *      Receive the packet.  The OS will discard any data in the
398          *      packet after "len" bytes.
399          */
400 #ifdef WITH_UDPFROMTO
401         if (dst.ss_family == AF_INET) {
402                 data_len = recvfromto(sockfd, buf, len, flags,
403                                       (struct sockaddr *)&src, &sizeof_src,
404                                       (struct sockaddr *)&dst, &sizeof_dst);
405         } else
406 #endif
407                 /*
408                  *      No udpfromto, OR an IPv6 socket.  Fail gracefully.
409                  */
410                 data_len = recvfrom(sockfd, buf, len, flags,
411                                     (struct sockaddr *)&src, &sizeof_src);
412         if (data_len < 0) {
413                 free(buf);
414                 return data_len;
415         }
416
417         /*
418          *      Check address families, and update src/dst ports, etc.
419          */
420         if (src.ss_family == AF_INET) {
421                 struct sockaddr_in      *s4;
422
423                 s4 = (struct sockaddr_in *)&src;
424                 src_ipaddr->af = AF_INET;
425                 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
426                 *src_port = ntohs(s4->sin_port);
427
428                 s4 = (struct sockaddr_in *)&dst;
429                 dst_ipaddr->af = AF_INET;
430                 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
431                 *dst_port = ntohs(s4->sin_port);
432
433 #ifdef HAVE_STRUCT_SOCKADDR_IN6
434         } else if (src.ss_family == AF_INET6) {
435                 struct sockaddr_in6     *s6;
436
437                 s6 = (struct sockaddr_in6 *)&src;
438                 src_ipaddr->af = AF_INET6;
439                 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
440                 *src_port = ntohs(s6->sin6_port);
441
442                 s6 = (struct sockaddr_in6 *)&dst;
443                 dst_ipaddr->af = AF_INET6;
444                 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
445                 *dst_port = ntohs(s6->sin6_port);
446 #endif
447         } else {
448                 free(buf);
449                 return -1;      /* Unknown address family, Die Die Die! */
450         }
451
452         /*
453          *      Different address families should never happen.
454          */
455         if (src.ss_family != dst.ss_family) {
456                 free(buf);
457                 return -1;
458         }
459
460         /*
461          *      Tell the caller about the data
462          */
463         *pbuf = buf;
464
465         return data_len;
466 }
467
468
469 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
470 /*************************************************************************
471  *
472  *      Function: make_secret
473  *
474  *      Purpose: Build an encrypted secret value to return in a reply
475  *               packet.  The secret is hidden by xoring with a MD5 digest
476  *               created from the shared secret and the authentication
477  *               vector.  We put them into MD5 in the reverse order from
478  *               that used when encrypting passwords to RADIUS.
479  *
480  *************************************************************************/
481 static void make_secret(uint8_t *digest, const uint8_t *vector,
482                         const char *secret, const uint8_t *value)
483 {
484         FR_MD5_CTX context;
485         int             i;
486
487         fr_MD5Init(&context);
488         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
489         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
490         fr_MD5Final(digest, &context);
491
492         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
493                 digest[i] ^= value[i];
494         }
495 }
496
497 #define MAX_PASS_LEN (128)
498 static void make_passwd(uint8_t *output, int *outlen,
499                         const uint8_t *input, int inlen,
500                         const char *secret, const uint8_t *vector)
501 {
502         FR_MD5_CTX context, old;
503         uint8_t digest[AUTH_VECTOR_LEN];
504         uint8_t passwd[MAX_PASS_LEN];
505         int     i, n;
506         int     len;
507
508         /*
509          *      If the length is zero, round it up.
510          */
511         len = inlen;
512         if (len == 0) {
513                 len = AUTH_PASS_LEN;
514         }
515         else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
516
517         else if ((len & 0x0f) != 0) {
518                 len += 0x0f;
519                 len &= ~0x0f;
520         }
521         *outlen = len;
522
523         memcpy(passwd, input, len);
524         memset(passwd + len, 0, sizeof(passwd) - len);
525
526         fr_MD5Init(&context);
527         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
528         old = context;
529
530         /*
531          *      Do first pass.
532          */
533         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
534
535         for (n = 0; n < len; n += AUTH_PASS_LEN) {
536                 if (n > 0) {
537                         context = old;
538                         fr_MD5Update(&context,
539                                        passwd + n - AUTH_PASS_LEN,
540                                        AUTH_PASS_LEN);
541                 }
542
543                 fr_MD5Final(digest, &context);
544                 for (i = 0; i < AUTH_PASS_LEN; i++) {
545                         passwd[i + n] ^= digest[i];
546                 }
547         }
548
549         memcpy(output, passwd, len);
550 }
551
552 static void make_tunnel_passwd(uint8_t *output, int *outlen,
553                                const uint8_t *input, int inlen, int room,
554                                const char *secret, const uint8_t *vector)
555 {
556         FR_MD5_CTX context, old;
557         uint8_t digest[AUTH_VECTOR_LEN];
558         uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
559         int     i, n;
560         int     len;
561
562         /*
563          *      Be paranoid.
564          */
565         if (room > 253) room = 253;
566
567         /*
568          *      Account for 2 bytes of the salt, and round the room
569          *      available down to the nearest multiple of 16.  Then,
570          *      subtract one from that to account for the length byte,
571          *      and the resulting number is the upper bound on the data
572          *      to copy.
573          *
574          *      We could short-cut this calculation just be forcing
575          *      inlen to be no more than 239.  It would work for all
576          *      VSA's, as we don't pack multiple VSA's into one
577          *      attribute.
578          *
579          *      However, this calculation is more general, if a little
580          *      complex.  And it will work in the future for all possible
581          *      kinds of weird attribute packing.
582          */
583         room -= 2;
584         room -= (room & 0x0f);
585         room--;
586
587         if (inlen > room) inlen = room;
588
589         /*
590          *      Length of the encrypted data is password length plus
591          *      one byte for the length of the password.
592          */
593         len = inlen + 1;
594         if ((len & 0x0f) != 0) {
595                 len += 0x0f;
596                 len &= ~0x0f;
597         }
598         *outlen = len + 2;      /* account for the salt */
599
600         /*
601          *      Copy the password over.
602          */
603         memcpy(passwd + 3, input, inlen);
604         memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
605
606         /*
607          *      Generate salt.  The RFC's say:
608          *
609          *      The high bit of salt[0] must be set, each salt in a
610          *      packet should be unique, and they should be random
611          *
612          *      So, we set the high bit, add in a counter, and then
613          *      add in some CSPRNG data.  should be OK..
614          */
615         passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
616                      (fr_rand() & 0x07));
617         passwd[1] = fr_rand();
618         passwd[2] = inlen;      /* length of the password string */
619
620         fr_MD5Init(&context);
621         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
622         old = context;
623
624         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
625         fr_MD5Update(&context, &passwd[0], 2);
626
627         for (n = 0; n < len; n += AUTH_PASS_LEN) {
628                 if (n > 0) {
629                         context = old;
630                         fr_MD5Update(&context,
631                                        passwd + 2 + n - AUTH_PASS_LEN,
632                                        AUTH_PASS_LEN);
633                 }
634
635                 fr_MD5Final(digest, &context);
636                 for (i = 0; i < AUTH_PASS_LEN; i++) {
637                         passwd[i + 2 + n] ^= digest[i];
638                 }
639         }
640         memcpy(output, passwd, len + 2);
641 }
642
643
644 /*
645  *      Parse a data structure into a RADIUS attribute.
646  */
647 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
648                 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
649 {
650         int             vendorcode;
651         int             offset, len, total_length;
652         uint32_t        lvalue;
653         uint8_t         *length_ptr, *vsa_length_ptr;
654         const uint8_t   *data = NULL;
655         uint8_t         array[4];
656
657         vendorcode = total_length = 0;
658         length_ptr = vsa_length_ptr = NULL;
659
660         /*
661          *      For interoperability, always put vendor attributes
662          *      into their own VSA.
663          */
664         if ((vendorcode = VENDOR(vp->attribute)) == 0) {
665                 *(ptr++) = vp->attribute & 0xFF;
666                 length_ptr = ptr;
667                 *(ptr++) = 2;
668                 total_length += 2;
669
670         } else {
671                 int vsa_tlen = 1;
672                 int vsa_llen = 1;
673                 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
674
675                 /*
676                  *      This must be an RFC-format attribute.  If it
677                  *      wasn't, then the "decode" function would have
678                  *      made a Vendor-Specific attribute (i.e. type
679                  *      26), and we would have "vendorcode == 0" here.
680                  */
681                 if (dv) {
682                         vsa_tlen = dv->type;
683                         vsa_llen = dv->length;
684                 }
685
686                 /*
687                  *      Build a VSA header.
688                  */
689                 *ptr++ = PW_VENDOR_SPECIFIC;
690                 vsa_length_ptr = ptr;
691                 *ptr++ = 6;
692                 lvalue = htonl(vendorcode);
693                 memcpy(ptr, &lvalue, 4);
694                 ptr += 4;
695                 total_length += 6;
696
697                 switch (vsa_tlen) {
698                 case 1:
699                         ptr[0] = (vp->attribute & 0xFF);
700                         break;
701
702                 case 2:
703                         ptr[0] = ((vp->attribute >> 8) & 0xFF);
704                         ptr[1] = (vp->attribute & 0xFF);
705                         break;
706
707                 case 4:
708                         ptr[0] = 0;
709                         ptr[1] = 0;
710                         ptr[2] = ((vp->attribute >> 8) & 0xFF);
711                         ptr[3] = (vp->attribute & 0xFF);
712                         break;
713
714                 default:
715                         return 0; /* silently discard it */
716                 }
717                 ptr += vsa_tlen;
718
719                 switch (vsa_llen) {
720                 case 0:
721                         length_ptr = vsa_length_ptr;
722                         vsa_length_ptr = NULL;
723                         break;
724                 case 1:
725                         ptr[0] = 0;
726                         length_ptr = ptr;
727                         break;
728                 case 2:
729                         ptr[0] = 0;
730                         ptr[1] = 0;
731                         length_ptr = ptr + 1;
732                         break;
733
734                 default:
735                         return 0; /* silently discard it */
736                 }
737                 ptr += vsa_llen;
738
739                 total_length += vsa_tlen + vsa_llen;
740                 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
741                 *length_ptr += vsa_tlen + vsa_llen;
742         }
743
744         offset = 0;
745         if (vp->flags.has_tag) {
746                 if (TAG_VALID(vp->flags.tag)) {
747                         ptr[0] = vp->flags.tag & 0xff;
748                         offset = 1;
749
750                 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
751                         /*
752                          *      Tunnel passwords REQUIRE a tag, even
753                          *      if don't have a valid tag.
754                          */
755                         ptr[0] = 0;
756                         offset = 1;
757                 } /* else don't write a tag */
758         } /* else the attribute doesn't have a tag */
759
760         /*
761          *      Set up the default sources for the data.
762          */
763         data = vp->vp_octets;
764         len = vp->length;
765
766         switch(vp->type) {
767         case PW_TYPE_STRING:
768         case PW_TYPE_OCTETS:
769         case PW_TYPE_IFID:
770         case PW_TYPE_IPV6ADDR:
771         case PW_TYPE_IPV6PREFIX:
772         case PW_TYPE_ABINARY:
773                 /* nothing more to do */
774                 break;
775
776         case PW_TYPE_BYTE:
777                 len = 1;        /* just in case */
778                 array[0] = vp->vp_integer & 0xff;
779                 data = array;
780                 offset = 0;
781                 break;
782
783
784         case PW_TYPE_SHORT:
785                 len = 2;        /* just in case */
786                 array[0] = (vp->vp_integer >> 8) & 0xff;
787                 array[1] = vp->vp_integer & 0xff;
788                 data = array;
789                 offset = 0;
790                 break;
791
792         case PW_TYPE_INTEGER:
793                 len = 4;        /* just in case */
794                 lvalue = htonl(vp->vp_integer);
795                 memcpy(array, &lvalue, sizeof(lvalue));
796
797                 /*
798                  *      Perhaps discard the first octet.
799                  */
800                 data = &array[offset];
801                 len -= offset;
802                 break;
803
804         case PW_TYPE_IPADDR:
805                 data = (const uint8_t *) &vp->vp_ipaddr;
806                 len = 4;        /* just in case */
807                 break;
808
809                 /*
810                  *  There are no tagged date attributes.
811                  */
812         case PW_TYPE_DATE:
813                 lvalue = htonl(vp->vp_date);
814                 data = (const uint8_t *) &lvalue;
815                 len = 4;        /* just in case */
816                 break;
817
818         default:                /* unknown type: ignore it */
819                 librad_log("ERROR: Unknown attribute type %d", vp->type);
820                 return -1;
821         }
822
823         /*
824          *      Bound the data to 255 bytes.
825          */
826         if (len + offset + total_length > 255) {
827                 len = 255 - offset - total_length;
828         }
829
830         /*
831          *      Encrypt the various password styles
832          *
833          *      Attributes with encrypted values MUST be less than
834          *      128 bytes long.
835          */
836         switch (vp->flags.encrypt) {
837         case FLAG_ENCRYPT_USER_PASSWORD:
838                 make_passwd(ptr + offset, &len,
839                             data, len,
840                             secret, packet->vector);
841                 break;
842
843         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
844                 if (!original) {
845                         librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
846                         return -1;
847                 }
848
849                 /*
850                  *      Check if 255 - offset - total_length is less
851                  *      than 18.  If so, we can't fit the data into
852                  *      the available space, and we discard the
853                  *      attribute.
854                  *
855                  *      This is ONLY a problem if we have multiple VSA's
856                  *      in one Vendor-Specific, though.
857                  */
858                 if ((255 - offset - total_length) < 18) return 0;
859
860                 make_tunnel_passwd(ptr + offset, &len,
861                                    data, len, 255 - offset - total_length,
862                                    secret, original->vector);
863                 break;
864
865                 /*
866                  *      The code above ensures that this attribute
867                  *      always fits.
868                  */
869         case FLAG_ENCRYPT_ASCEND_SECRET:
870                 make_secret(ptr + offset, packet->vector,
871                             secret, data);
872                 len = AUTH_VECTOR_LEN;
873                 break;
874
875
876         default:
877                 /*
878                  *      Just copy the data over
879                  */
880                 memcpy(ptr + offset, data, len);
881                 break;
882         } /* switch over encryption flags */
883
884         /*
885          *      Account for the tag (if any).
886          */
887         len += offset;
888
889         /*
890          *      RFC 2865 section 5 says that zero-length attributes
891          *      MUST NOT be sent.
892          */
893         if (len == 0) return 0;
894
895         /*
896          *      Update the various lengths.
897          */
898         *length_ptr += len;
899         if (vsa_length_ptr) *vsa_length_ptr += len;
900         ptr += len;
901         total_length += len;
902
903         return total_length;    /* of attribute */
904 }
905
906
907 /*
908  *      Encode a packet.
909  */
910 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
911                const char *secret)
912 {
913         radius_packet_t *hdr;
914         uint8_t         *ptr;
915         uint16_t        total_length;
916         int             len;
917         VALUE_PAIR      *reply;
918         const char      *what;
919         char            ip_buffer[128];
920
921         /*
922          *      For simplicity in the following logic, we allow
923          *      the attributes to "overflow" the 4k maximum
924          *      RADIUS packet size, by one attribute.
925          *
926          *      It's uint32_t, for alignment purposes.
927          */
928         uint32_t        data[(MAX_PACKET_LEN + 256) / 4];
929
930         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
931                 what = packet_codes[packet->code];
932         } else {
933                 what = "Reply";
934         }
935
936         DEBUG("Sending %s of id %d to %s port %d\n",
937               what, packet->id,
938               inet_ntop(packet->dst_ipaddr.af,
939                         &packet->dst_ipaddr.ipaddr,
940                         ip_buffer, sizeof(ip_buffer)),
941               packet->dst_port);
942
943         /*
944          *      Double-check some things based on packet code.
945          */
946         switch (packet->code) {
947         case PW_AUTHENTICATION_ACK:
948         case PW_AUTHENTICATION_REJECT:
949         case PW_ACCESS_CHALLENGE:
950                 if (!original) {
951                         librad_log("ERROR: Cannot sign response packet without a request packet.");
952                         return -1;
953                 }
954                 break;
955
956                 /*
957                  *      These packet vectors start off as all zero.
958                  */
959         case PW_ACCOUNTING_REQUEST:
960         case PW_DISCONNECT_REQUEST:
961         case PW_COA_REQUEST:
962                 memset(packet->vector, 0, sizeof(packet->vector));
963                 break;
964
965         default:
966                 break;
967         }
968
969         /*
970          *      Use memory on the stack, until we know how
971          *      large the packet will be.
972          */
973         hdr = (radius_packet_t *) data;
974
975         /*
976          *      Build standard header
977          */
978         hdr->code = packet->code;
979         hdr->id = packet->id;
980
981         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
982
983         total_length = AUTH_HDR_LEN;
984
985         /*
986          *      Load up the configuration values for the user
987          */
988         ptr = hdr->data;
989         packet->offset = 0;
990
991         /*
992          *      FIXME: Loop twice over the reply list.  The first time,
993          *      calculate the total length of data.  The second time,
994          *      allocate the memory, and fill in the VP's.
995          *
996          *      Hmm... this may be slower than just doing a small
997          *      memcpy.
998          */
999
1000         /*
1001          *      Loop over the reply attributes for the packet.
1002          */
1003         for (reply = packet->vps; reply; reply = reply->next) {
1004                 /*
1005                  *      Ignore non-wire attributes
1006                  */
1007                 if ((VENDOR(reply->attribute) == 0) &&
1008                     ((reply->attribute & 0xFFFF) > 0xff)) {
1009                         continue;
1010                 }
1011
1012                 /*
1013                  *      Set the Message-Authenticator to the correct
1014                  *      length and initial value.
1015                  */
1016                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1017                         reply->length = AUTH_VECTOR_LEN;
1018                         memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1019
1020                         /*
1021                          *      Cache the offset to the
1022                          *      Message-Authenticator
1023                          */
1024                         packet->offset = total_length;
1025                 }
1026
1027                 /*
1028                  *      Print out ONLY the attributes which
1029                  *      we're sending over the wire, and print
1030                  *      them out BEFORE they're encrypted.
1031                  */
1032                 debug_pair(reply);
1033
1034                 len = rad_vp2attr(packet, original, secret, reply, ptr);
1035
1036                 if (len < 0) return -1;
1037
1038                 /*
1039                  *      Check that the packet is no more than 4k in
1040                  *      size, AFTER writing the attribute past the 4k
1041                  *      boundary, but BEFORE deciding to increase the
1042                  *      size of the packet. Note that the 'data'
1043                  *      buffer, above, is one attribute longer than
1044                  *      necessary, in order to permit this overflow.
1045                  */
1046                 if ((total_length + len) > MAX_PACKET_LEN) {
1047                         break;
1048                 }
1049
1050                 ptr += len;
1051                 total_length += len;
1052         } /* done looping over all attributes */
1053
1054         /*
1055          *      Fill in the rest of the fields, and copy the data over
1056          *      from the local stack to the newly allocated memory.
1057          *
1058          *      Yes, all this 'memcpy' is slow, but it means
1059          *      that we only allocate the minimum amount of
1060          *      memory for a request.
1061          */
1062         packet->data_len = total_length;
1063         packet->data = (uint8_t *) malloc(packet->data_len);
1064         if (!packet->data) {
1065                 librad_log("Out of memory");
1066                 return -1;
1067         }
1068
1069         memcpy(packet->data, data, packet->data_len);
1070         hdr = (radius_packet_t *) packet->data;
1071
1072         total_length = htons(total_length);
1073         memcpy(hdr->length, &total_length, sizeof(total_length));
1074
1075         return 0;
1076 }
1077
1078
1079 /*
1080  *      Sign a previously encoded packet.
1081  */
1082 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1083              const char *secret)
1084 {
1085         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1086
1087         /*
1088          *      It wasn't assigned an Id, this is bad!
1089          */
1090         if (packet->id < 0) {
1091                 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1092                 return -1;
1093         }
1094
1095         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1096             (packet->offset < 0)) {
1097                 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1098                 return -1;
1099         }
1100
1101         /*
1102          *      If there's a Message-Authenticator, update it
1103          *      now, BEFORE updating the authentication vector.
1104          */
1105         if (packet->offset > 0) {
1106                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1107
1108                 switch (packet->code) {
1109                 case PW_ACCOUNTING_REQUEST:
1110                 case PW_ACCOUNTING_RESPONSE:
1111                 case PW_DISCONNECT_REQUEST:
1112                 case PW_DISCONNECT_ACK:
1113                 case PW_DISCONNECT_NAK:
1114                 case PW_COA_REQUEST:
1115                 case PW_COA_ACK:
1116                 case PW_COA_NAK:
1117                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1118                         break;
1119
1120                 case PW_AUTHENTICATION_ACK:
1121                 case PW_AUTHENTICATION_REJECT:
1122                 case PW_ACCESS_CHALLENGE:
1123                         if (!original) {
1124                                 librad_log("ERROR: Cannot sign response packet without a request packet.");
1125                                 return -1;
1126                         }
1127                         memcpy(hdr->vector, original->vector,
1128                                AUTH_VECTOR_LEN);
1129                         break;
1130
1131                 default:        /* others have vector already set to zero */
1132                         break;
1133
1134                 }
1135
1136                 /*
1137                  *      Set the authentication vector to zero,
1138                  *      calculate the signature, and put it
1139                  *      into the Message-Authenticator
1140                  *      attribute.
1141                  */
1142                 fr_hmac_md5(packet->data, packet->data_len,
1143                             (const uint8_t *) secret, strlen(secret),
1144                             calc_auth_vector);
1145                 memcpy(packet->data + packet->offset + 2,
1146                        calc_auth_vector, AUTH_VECTOR_LEN);
1147
1148                 /*
1149                  *      Copy the original request vector back
1150                  *      to the raw packet.
1151                  */
1152                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1153         }
1154
1155         /*
1156          *      Switch over the packet code, deciding how to
1157          *      sign the packet.
1158          */
1159         switch (packet->code) {
1160                 /*
1161                  *      Request packets are not signed, bur
1162                  *      have a random authentication vector.
1163                  */
1164         case PW_AUTHENTICATION_REQUEST:
1165         case PW_STATUS_SERVER:
1166                 break;
1167
1168                 /*
1169                  *      Reply packets are signed with the
1170                  *      authentication vector of the request.
1171                  */
1172         default:
1173                 {
1174                         uint8_t digest[16];
1175
1176                         FR_MD5_CTX      context;
1177                         fr_MD5Init(&context);
1178                         fr_MD5Update(&context, packet->data, packet->data_len);
1179                         fr_MD5Update(&context, (const uint8_t *) secret,
1180                                      strlen(secret));
1181                         fr_MD5Final(digest, &context);
1182
1183                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1184                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1185                         break;
1186                 }
1187         }/* switch over packet codes */
1188
1189         return 0;
1190 }
1191
1192 /*
1193  *      Reply to the request.  Also attach
1194  *      reply attribute value pairs and any user message provided.
1195  */
1196 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1197              const char *secret)
1198 {
1199         VALUE_PAIR              *reply;
1200         const char              *what;
1201         char                    ip_buffer[128];
1202
1203         /*
1204          *      Maybe it's a fake packet.  Don't send it.
1205          */
1206         if (!packet || (packet->sockfd < 0)) {
1207                 return 0;
1208         }
1209
1210         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1211                 what = packet_codes[packet->code];
1212         } else {
1213                 what = "Reply";
1214         }
1215
1216         /*
1217          *  First time through, allocate room for the packet
1218          */
1219         if (!packet->data) {
1220                 /*
1221                  *      Encode the packet.
1222                  */
1223                 if (rad_encode(packet, original, secret) < 0) {
1224                         return -1;
1225                 }
1226
1227                 /*
1228                  *      Re-sign it, including updating the
1229                  *      Message-Authenticator.
1230                  */
1231                 if (rad_sign(packet, original, secret) < 0) {
1232                         return -1;
1233                 }
1234
1235                 /*
1236                  *      If packet->data points to data, then we print out
1237                  *      the VP list again only for debugging.
1238                  */
1239         } else if (librad_debug) {
1240                 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1241                       inet_ntop(packet->dst_ipaddr.af,
1242                                 &packet->dst_ipaddr.ipaddr,
1243                                 ip_buffer, sizeof(ip_buffer)),
1244                       packet->dst_port);
1245
1246                 for (reply = packet->vps; reply; reply = reply->next) {
1247                         /* FIXME: ignore attributes > 0xff */
1248                         debug_pair(reply);
1249                 }
1250         }
1251
1252         /*
1253          *      And send it on it's way.
1254          */
1255         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1256                           &packet->src_ipaddr, packet->src_port,
1257                           &packet->dst_ipaddr, packet->dst_port);
1258 }
1259
1260
1261 /*
1262  *      Validates the requesting client NAS.  Calculates the
1263  *      signature based on the clients private key.
1264  */
1265 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1266 {
1267         uint8_t         digest[AUTH_VECTOR_LEN];
1268         FR_MD5_CTX              context;
1269
1270         /*
1271          *      Zero out the auth_vector in the received packet.
1272          *      Then append the shared secret to the received packet,
1273          *      and calculate the MD5 sum. This must be the same
1274          *      as the original MD5 sum (packet->vector).
1275          */
1276         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1277
1278         /*
1279          *  MD5(packet + secret);
1280          */
1281         fr_MD5Init(&context);
1282         fr_MD5Update(&context, packet->data, packet->data_len);
1283         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1284         fr_MD5Final(digest, &context);
1285
1286         /*
1287          *      Return 0 if OK, 2 if not OK.
1288          */
1289         if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1290         return 0;
1291 }
1292
1293
1294 /*
1295  *      Validates the requesting client NAS.  Calculates the
1296  *      signature based on the clients private key.
1297  */
1298 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1299                             const char *secret)
1300 {
1301         uint8_t         calc_digest[AUTH_VECTOR_LEN];
1302         FR_MD5_CTX              context;
1303
1304         /*
1305          *      Very bad!
1306          */
1307         if (original == NULL) {
1308                 return 3;
1309         }
1310
1311         /*
1312          *  Copy the original vector in place.
1313          */
1314         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1315
1316         /*
1317          *  MD5(packet + secret);
1318          */
1319         fr_MD5Init(&context);
1320         fr_MD5Update(&context, packet->data, packet->data_len);
1321         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1322         fr_MD5Final(calc_digest, &context);
1323
1324         /*
1325          *  Copy the packet's vector back to the packet.
1326          */
1327         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1328
1329         /*
1330          *      Return 0 if OK, 2 if not OK.
1331          */
1332         if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1333         return 0;
1334 }
1335
1336
1337 /*
1338  *      See if the data pointed to by PTR is a valid RADIUS packet.
1339  *
1340  *      packet is not 'const * const' because we may update data_len,
1341  *      if there's more data in the UDP packet than in the RADIUS packet.
1342  */
1343 int rad_packet_ok(RADIUS_PACKET *packet)
1344 {
1345         uint8_t                 *attr;
1346         int                     totallen;
1347         int                     count;
1348         radius_packet_t         *hdr;
1349         char                    host_ipaddr[128];
1350         int                     require_ma = 0;
1351         int                     seen_ma = 0;
1352         int                     num_attributes;
1353
1354         /*
1355          *      Check for packets smaller than the packet header.
1356          *
1357          *      RFC 2865, Section 3., subsection 'length' says:
1358          *
1359          *      "The minimum length is 20 ..."
1360          */
1361         if (packet->data_len < AUTH_HDR_LEN) {
1362                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1363                            inet_ntop(packet->src_ipaddr.af,
1364                                      &packet->src_ipaddr.ipaddr,
1365                                      host_ipaddr, sizeof(host_ipaddr)),
1366                            packet->data_len, AUTH_HDR_LEN);
1367                 return 0;
1368         }
1369
1370         /*
1371          *      RFC 2865, Section 3., subsection 'length' says:
1372          *
1373          *      " ... and maximum length is 4096."
1374          */
1375         if (packet->data_len > MAX_PACKET_LEN) {
1376                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1377                            inet_ntop(packet->src_ipaddr.af,
1378                                      &packet->src_ipaddr.ipaddr,
1379                                      host_ipaddr, sizeof(host_ipaddr)),
1380                            packet->data_len, MAX_PACKET_LEN);
1381                 return 0;
1382         }
1383
1384         /*
1385          *      Check for packets with mismatched size.
1386          *      i.e. We've received 128 bytes, and the packet header
1387          *      says it's 256 bytes long.
1388          */
1389         totallen = (packet->data[2] << 8) | packet->data[3];
1390         hdr = (radius_packet_t *)packet->data;
1391
1392         /*
1393          *      Code of 0 is not understood.
1394          *      Code of 16 or greate is not understood.
1395          */
1396         if ((hdr->code == 0) ||
1397             (hdr->code >= MAX_PACKET_CODE)) {
1398                 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1399                            inet_ntop(packet->src_ipaddr.af,
1400                                      &packet->src_ipaddr.ipaddr,
1401                                      host_ipaddr, sizeof(host_ipaddr)),
1402                            hdr->code);
1403                 return 0;
1404         }
1405
1406         /*
1407          *      Message-Authenticator is required in Status-Server
1408          *      packets, otherwise they can be trivially forged.
1409          */
1410         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1411
1412         /*
1413          *      Repeat the length checks.  This time, instead of
1414          *      looking at the data we received, look at the value
1415          *      of the 'length' field inside of the packet.
1416          *
1417          *      Check for packets smaller than the packet header.
1418          *
1419          *      RFC 2865, Section 3., subsection 'length' says:
1420          *
1421          *      "The minimum length is 20 ..."
1422          */
1423         if (totallen < AUTH_HDR_LEN) {
1424                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1425                            inet_ntop(packet->src_ipaddr.af,
1426                                      &packet->src_ipaddr.ipaddr,
1427                                      host_ipaddr, sizeof(host_ipaddr)),
1428                            totallen, AUTH_HDR_LEN);
1429                 return 0;
1430         }
1431
1432         /*
1433          *      And again, for the value of the 'length' field.
1434          *
1435          *      RFC 2865, Section 3., subsection 'length' says:
1436          *
1437          *      " ... and maximum length is 4096."
1438          */
1439         if (totallen > MAX_PACKET_LEN) {
1440                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1441                            inet_ntop(packet->src_ipaddr.af,
1442                                      &packet->src_ipaddr.ipaddr,
1443                                      host_ipaddr, sizeof(host_ipaddr)),
1444                            totallen, MAX_PACKET_LEN);
1445                 return 0;
1446         }
1447
1448         /*
1449          *      RFC 2865, Section 3., subsection 'length' says:
1450          *
1451          *      "If the packet is shorter than the Length field
1452          *      indicates, it MUST be silently discarded."
1453          *
1454          *      i.e. No response to the NAS.
1455          */
1456         if (packet->data_len < totallen) {
1457                 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1458                            inet_ntop(packet->src_ipaddr.af,
1459                                      &packet->src_ipaddr.ipaddr,
1460                                      host_ipaddr, sizeof(host_ipaddr)),
1461                            packet->data_len, totallen);
1462                 return 0;
1463         }
1464
1465         /*
1466          *      RFC 2865, Section 3., subsection 'length' says:
1467          *
1468          *      "Octets outside the range of the Length field MUST be
1469          *      treated as padding and ignored on reception."
1470          */
1471         if (packet->data_len > totallen) {
1472                 /*
1473                  *      We're shortening the packet below, but just
1474                  *      to be paranoid, zero out the extra data.
1475                  */
1476                 memset(packet->data + totallen, 0, packet->data_len - totallen);
1477                 packet->data_len = totallen;
1478         }
1479
1480         /*
1481          *      Walk through the packet's attributes, ensuring that
1482          *      they add up EXACTLY to the size of the packet.
1483          *
1484          *      If they don't, then the attributes either under-fill
1485          *      or over-fill the packet.  Any parsing of the packet
1486          *      is impossible, and will result in unknown side effects.
1487          *
1488          *      This would ONLY happen with buggy RADIUS implementations,
1489          *      or with an intentional attack.  Either way, we do NOT want
1490          *      to be vulnerable to this problem.
1491          */
1492         attr = hdr->data;
1493         count = totallen - AUTH_HDR_LEN;
1494         num_attributes = 0;
1495
1496         while (count > 0) {
1497                 /*
1498                  *      Attribute number zero is NOT defined.
1499                  */
1500                 if (attr[0] == 0) {
1501                         librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1502                                    inet_ntop(packet->src_ipaddr.af,
1503                                              &packet->src_ipaddr.ipaddr,
1504                                              host_ipaddr, sizeof(host_ipaddr)));
1505                         return 0;
1506                 }
1507
1508                 /*
1509                  *      Attributes are at LEAST as long as the ID & length
1510                  *      fields.  Anything shorter is an invalid attribute.
1511                  */
1512                 if (attr[1] < 2) {
1513                         librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1514                                    inet_ntop(packet->src_ipaddr.af,
1515                                              &packet->src_ipaddr.ipaddr,
1516                                              host_ipaddr, sizeof(host_ipaddr)),
1517                                    attr[0]);
1518                         return 0;
1519                 }
1520
1521                 /*
1522                  *      Sanity check the attributes for length.
1523                  */
1524                 switch (attr[0]) {
1525                 default:        /* don't do anything by default */
1526                         break;
1527
1528                         /*
1529                          *      If there's an EAP-Message, we require
1530                          *      a Message-Authenticator.
1531                          */
1532                 case PW_EAP_MESSAGE:
1533                         require_ma = 1;
1534                         break;
1535
1536                 case PW_MESSAGE_AUTHENTICATOR:
1537                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1538                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1539                                            inet_ntop(packet->src_ipaddr.af,
1540                                                      &packet->src_ipaddr.ipaddr,
1541                                                      host_ipaddr, sizeof(host_ipaddr)),
1542                                            attr[1] - 2);
1543                                 return 0;
1544                         }
1545                         seen_ma = 1;
1546                         break;
1547                 }
1548
1549                 /*
1550                  *      FIXME: Look up the base 255 attributes in the
1551                  *      dictionary, and switch over their type.  For
1552                  *      integer/date/ip, the attribute length SHOULD
1553                  *      be 6.
1554                  */
1555                 count -= attr[1];       /* grab the attribute length */
1556                 attr += attr[1];
1557                 num_attributes++;       /* seen one more attribute */
1558         }
1559
1560         /*
1561          *      If the attributes add up to a packet, it's allowed.
1562          *
1563          *      If not, we complain, and throw the packet away.
1564          */
1565         if (count != 0) {
1566                 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1567                            inet_ntop(packet->src_ipaddr.af,
1568                                      &packet->src_ipaddr.ipaddr,
1569                                      host_ipaddr, sizeof(host_ipaddr)));
1570                 return 0;
1571         }
1572
1573         /*
1574          *      If we're configured to look for a maximum number of
1575          *      attributes, and we've seen more than that maximum,
1576          *      then throw the packet away, as a possible DoS.
1577          */
1578         if ((librad_max_attributes > 0) &&
1579             (num_attributes > librad_max_attributes)) {
1580                 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1581                            inet_ntop(packet->src_ipaddr.af,
1582                                      &packet->src_ipaddr.ipaddr,
1583                                      host_ipaddr, sizeof(host_ipaddr)),
1584                            num_attributes, librad_max_attributes);
1585                 return 0;
1586         }
1587
1588         /*
1589          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1590          *
1591          *      A packet with an EAP-Message attribute MUST also have
1592          *      a Message-Authenticator attribute.
1593          *
1594          *      A Message-Authenticator all by itself is OK, though.
1595          *
1596          *      Similarly, Status-Server packets MUST contain
1597          *      Message-Authenticator attributes.
1598          */
1599         if (require_ma && ! seen_ma) {
1600                 librad_log("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1601                            inet_ntop(packet->src_ipaddr.af,
1602                                      &packet->src_ipaddr.ipaddr,
1603                                      host_ipaddr, sizeof(host_ipaddr)));
1604                 return 0;
1605         }
1606
1607         /*
1608          *      Fill RADIUS header fields
1609          */
1610         packet->code = hdr->code;
1611         packet->id = hdr->id;
1612         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1613
1614         return 1;
1615 }
1616
1617
1618 /*
1619  *      Receive UDP client requests, and fill in
1620  *      the basics of a RADIUS_PACKET structure.
1621  */
1622 RADIUS_PACKET *rad_recv(int fd)
1623 {
1624         RADIUS_PACKET           *packet;
1625
1626         /*
1627          *      Allocate the new request data structure
1628          */
1629         if ((packet = malloc(sizeof(*packet))) == NULL) {
1630                 librad_log("out of memory");
1631                 return NULL;
1632         }
1633         memset(packet, 0, sizeof(*packet));
1634
1635         packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1636                                         &packet->src_ipaddr, &packet->src_port,
1637                                         &packet->dst_ipaddr, &packet->dst_port);
1638
1639         /*
1640          *      Check for socket errors.
1641          */
1642         if (packet->data_len < 0) {
1643                 librad_log("Error receiving packet: %s", strerror(errno));
1644                 /* packet->data is NULL */
1645                 free(packet);
1646                 return NULL;
1647         }
1648
1649         /*
1650          *      If the packet is too big, then rad_recvfrom did NOT
1651          *      allocate memory.  Instead, it just discarded the
1652          *      packet.
1653          */
1654         if (packet->data_len > MAX_PACKET_LEN) {
1655                 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1656                 /* packet->data is NULL */
1657                 free(packet);
1658                 return NULL;
1659         }
1660
1661         /*
1662          *      Read no data.  Continue.
1663          *      This check is AFTER the MAX_PACKET_LEN check above, because
1664          *      if the packet is larger than MAX_PACKET_LEN, we also have
1665          *      packet->data == NULL
1666          */
1667         if ((packet->data_len == 0) || !packet->data) {
1668                 librad_log("No data.");
1669                 free(packet);
1670                 return NULL;
1671         }
1672
1673         /*
1674          *      See if it's a well-formed RADIUS packet.
1675          */
1676         if (!rad_packet_ok(packet)) {
1677                 rad_free(&packet);
1678                 return NULL;
1679         }
1680
1681         /*
1682          *      Remember which socket we read the packet from.
1683          */
1684         packet->sockfd = fd;
1685
1686         /*
1687          *      FIXME: Do even more filtering by only permitting
1688          *      certain IP's.  The problem is that we don't know
1689          *      how to do this properly for all possible clients...
1690          */
1691
1692         /*
1693          *      Explicitely set the VP list to empty.
1694          */
1695         packet->vps = NULL;
1696
1697         if (librad_debug) {
1698                 char host_ipaddr[128];
1699
1700                 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1701                         printf("rad_recv: %s packet from host %s port %d",
1702                                packet_codes[packet->code],
1703                                inet_ntop(packet->src_ipaddr.af,
1704                                          &packet->src_ipaddr.ipaddr,
1705                                          host_ipaddr, sizeof(host_ipaddr)),
1706                                packet->src_port);
1707                 } else {
1708                         printf("rad_recv: Packet from host %s port %d code=%d",
1709                                inet_ntop(packet->src_ipaddr.af,
1710                                          &packet->src_ipaddr.ipaddr,
1711                                          host_ipaddr, sizeof(host_ipaddr)),
1712                                packet->src_port,
1713                                packet->code);
1714                 }
1715                 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1716         }
1717
1718         return packet;
1719 }
1720
1721
1722 /*
1723  *      Verify the signature of a packet.
1724  */
1725 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1726                const char *secret)
1727 {
1728         uint8_t                 *ptr;
1729         int                     length;
1730         int                     attrlen;
1731
1732         if (!packet || !packet->data) return -1;
1733
1734         /*
1735          *      Before we allocate memory for the attributes, do more
1736          *      sanity checking.
1737          */
1738         ptr = packet->data + AUTH_HDR_LEN;
1739         length = packet->data_len - AUTH_HDR_LEN;
1740         while (length > 0) {
1741                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1742                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1743
1744                 attrlen = ptr[1];
1745
1746                 switch (ptr[0]) {
1747                 default:        /* don't do anything. */
1748                         break;
1749
1750                         /*
1751                          *      Note that more than one Message-Authenticator
1752                          *      attribute is invalid.
1753                          */
1754                 case PW_MESSAGE_AUTHENTICATOR:
1755                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1756                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1757
1758                         switch (packet->code) {
1759                         default:
1760                                 break;
1761
1762                         case PW_ACCOUNTING_REQUEST:
1763                         case PW_ACCOUNTING_RESPONSE:
1764                         case PW_DISCONNECT_REQUEST:
1765                         case PW_DISCONNECT_ACK:
1766                         case PW_DISCONNECT_NAK:
1767                         case PW_COA_REQUEST:
1768                         case PW_COA_ACK:
1769                         case PW_COA_NAK:
1770                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1771                                 break;
1772
1773                         case PW_AUTHENTICATION_ACK:
1774                         case PW_AUTHENTICATION_REJECT:
1775                         case PW_ACCESS_CHALLENGE:
1776                                 if (!original) {
1777                                         librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1778                                         return -1;
1779                                 }
1780                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1781                                 break;
1782                         }
1783
1784                         fr_hmac_md5(packet->data, packet->data_len,
1785                                     (const uint8_t *) secret, strlen(secret),
1786                                     calc_auth_vector);
1787                         if (memcmp(calc_auth_vector, msg_auth_vector,
1788                                    sizeof(calc_auth_vector)) != 0) {
1789                                 char buffer[32];
1790                                 librad_log("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1791                                            inet_ntop(packet->src_ipaddr.af,
1792                                                      &packet->src_ipaddr.ipaddr,
1793                                                      buffer, sizeof(buffer)));
1794                                 /* Silently drop packet, according to RFC 3579 */
1795                                 return -1;
1796                         } /* else the message authenticator was good */
1797
1798                         /*
1799                          *      Reinitialize Authenticators.
1800                          */
1801                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1802                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1803                         break;
1804                 } /* switch over the attributes */
1805
1806                 ptr += attrlen;
1807                 length -= attrlen;
1808         } /* loop over the packet, sanity checking the attributes */
1809
1810         /*
1811          *      It looks like a RADIUS packet, but we can't validate
1812          *      the signature.
1813          */
1814         if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1815                 char buffer[32];
1816                 librad_log("Received Unknown packet code %d"
1817                            "from client %s port %d: Cannot validate signature",
1818                            packet->code,
1819                            inet_ntop(packet->src_ipaddr.af,
1820                                      &packet->src_ipaddr.ipaddr,
1821                                      buffer, sizeof(buffer)),
1822                            packet->src_port);
1823                 return -1;
1824         }
1825
1826         /*
1827          *      Calculate and/or verify digest.
1828          */
1829         switch(packet->code) {
1830                 int rcode;
1831                 char buffer[32];
1832
1833                 case PW_AUTHENTICATION_REQUEST:
1834                 case PW_STATUS_SERVER:
1835                 case PW_DISCONNECT_REQUEST:
1836                         /*
1837                          *      The authentication vector is random
1838                          *      nonsense, invented by the client.
1839                          */
1840                         break;
1841
1842                 case PW_ACCOUNTING_REQUEST:
1843                         if (calc_acctdigest(packet, secret) > 1) {
1844                                 librad_log("Received Accounting-Request packet "
1845                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
1846                                            inet_ntop(packet->src_ipaddr.af,
1847                                                      &packet->src_ipaddr.ipaddr,
1848                                                      buffer, sizeof(buffer)));
1849                                 return -1;
1850                         }
1851                         break;
1852
1853                         /* Verify the reply digest */
1854                 case PW_AUTHENTICATION_ACK:
1855                 case PW_AUTHENTICATION_REJECT:
1856                 case PW_ACCESS_CHALLENGE:
1857                 case PW_ACCOUNTING_RESPONSE:
1858                 case PW_DISCONNECT_ACK:
1859                 case PW_DISCONNECT_NAK:
1860                 case PW_COA_ACK:
1861                 case PW_COA_NAK:
1862                         rcode = calc_replydigest(packet, original, secret);
1863                         if (rcode > 1) {
1864                                 librad_log("Received %s packet "
1865                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
1866                                            packet_codes[packet->code],
1867                                            inet_ntop(packet->src_ipaddr.af,
1868                                                      &packet->src_ipaddr.ipaddr,
1869                                                      buffer, sizeof(buffer)),
1870                                            packet->src_port,
1871                                            rcode);
1872                                 return -1;
1873                         }
1874                         break;
1875
1876                 default:
1877                         librad_log("Received Unknown packet code %d"
1878                                    "from client %s port %d: Cannot validate signature",
1879                                    packet->code,
1880                                    inet_ntop(packet->src_ipaddr.af,
1881                                              &packet->src_ipaddr.ipaddr,
1882                                                      buffer, sizeof(buffer)),
1883                                    packet->src_port);
1884                         return -1;
1885         }
1886
1887         return 0;
1888 }
1889
1890
1891 /*
1892  *      Parse a RADIUS attribute into a data structure.
1893  */
1894 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1895                         const char *secret, int attribute, int length,
1896                         const uint8_t *data)
1897 {
1898         int offset = 0;
1899         VALUE_PAIR *vp;
1900
1901         if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1902                 return NULL;
1903         }
1904
1905         /*
1906          *      If length is greater than 253, something is SERIOUSLY
1907          *      wrong.
1908          */
1909         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1910
1911         vp->length = length;
1912         vp->operator = T_OP_EQ;
1913         vp->next = NULL;
1914
1915         /*
1916          *      Handle tags.
1917          */
1918         if (vp->flags.has_tag) {
1919                 if (TAG_VALID(data[0]) ||
1920                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1921                         /*
1922                          *      Tunnel passwords REQUIRE a tag, even
1923                          *      if don't have a valid tag.
1924                          */
1925                         vp->flags.tag = data[0];
1926
1927                         if ((vp->type == PW_TYPE_STRING) ||
1928                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
1929                 }
1930         }
1931
1932         /*
1933          *      Copy the data to be decrypted
1934          */
1935         memcpy(&vp->vp_octets[0], data + offset, length - offset);
1936         vp->length -= offset;
1937
1938         /*
1939          *      Decrypt the attribute.
1940          */
1941         switch (vp->flags.encrypt) {
1942                 /*
1943                  *  User-Password
1944                  */
1945         case FLAG_ENCRYPT_USER_PASSWORD:
1946                 if (original) {
1947                         rad_pwdecode((char *)vp->vp_strvalue,
1948                                      vp->length, secret,
1949                                      original->vector);
1950                 } else {
1951                         rad_pwdecode((char *)vp->vp_strvalue,
1952                                      vp->length, secret,
1953                                      packet->vector);
1954                 }
1955                 if (vp->attribute == PW_USER_PASSWORD) {
1956                         vp->length = strlen(vp->vp_strvalue);
1957                 }
1958                 break;
1959
1960                 /*
1961                  *      Tunnel-Password's may go ONLY
1962                  *      in response packets.
1963                  */
1964         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1965                 if (!original) goto raw;
1966
1967                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1968                                         secret, original->vector) < 0) {
1969                         goto raw;
1970                 }
1971                 break;
1972
1973                 /*
1974                  *  Ascend-Send-Secret
1975                  *  Ascend-Receive-Secret
1976                  */
1977         case FLAG_ENCRYPT_ASCEND_SECRET:
1978                 if (!original) {
1979                         goto raw;
1980                 } else {
1981                         uint8_t my_digest[AUTH_VECTOR_LEN];
1982                         make_secret(my_digest,
1983                                     original->vector,
1984                                     secret, data);
1985                         memcpy(vp->vp_strvalue, my_digest,
1986                                AUTH_VECTOR_LEN );
1987                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1988                         vp->length = strlen(vp->vp_strvalue);
1989                 }
1990                 break;
1991
1992         default:
1993                 break;
1994         } /* switch over encryption flags */
1995
1996
1997         switch (vp->type) {
1998         case PW_TYPE_STRING:
1999         case PW_TYPE_OCTETS:
2000         case PW_TYPE_ABINARY:
2001                 /* nothing more to do */
2002                 break;
2003
2004         case PW_TYPE_BYTE:
2005                 if (vp->length != 1) goto raw;
2006
2007                 vp->vp_integer = vp->vp_octets[0];
2008                 break;
2009
2010
2011         case PW_TYPE_SHORT:
2012                 if (vp->length != 2) goto raw;
2013
2014                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2015                 break;
2016
2017         case PW_TYPE_INTEGER:
2018                 if (vp->length != 4) goto raw;
2019
2020                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2021                 vp->vp_integer = ntohl(vp->vp_integer);
2022
2023                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2024
2025                 /*
2026                  *      Try to get named VALUEs
2027                  */
2028                 {
2029                         DICT_VALUE *dval;
2030                         dval = dict_valbyattr(vp->attribute,
2031                                               vp->vp_integer);
2032                         if (dval) {
2033                                 strlcpy(vp->vp_strvalue,
2034                                         dval->name,
2035                                         sizeof(vp->vp_strvalue));
2036                         }
2037                 }
2038                 break;
2039
2040         case PW_TYPE_DATE:
2041                 if (vp->length != 4) goto raw;
2042
2043                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2044                 vp->vp_date = ntohl(vp->vp_date);
2045                 break;
2046
2047
2048         case PW_TYPE_IPADDR:
2049                 if (vp->length != 4) goto raw;
2050
2051                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2052                 break;
2053
2054                 /*
2055                  *      IPv6 interface ID is 8 octets long.
2056                  */
2057         case PW_TYPE_IFID:
2058                 if (vp->length != 8) goto raw;
2059                 /* vp->vp_ifid == vp->vp_octets */
2060                 break;
2061
2062                 /*
2063                  *      IPv6 addresses are 16 octets long
2064                  */
2065         case PW_TYPE_IPV6ADDR:
2066                 if (vp->length != 16) goto raw;
2067                 /* vp->vp_ipv6addr == vp->vp_octets */
2068                 break;
2069
2070                 /*
2071                  *      IPv6 prefixes are 2 to 18 octets long.
2072                  *
2073                  *      RFC 3162: The first octet is unused.
2074                  *      The second is the length of the prefix
2075                  *      the rest are the prefix data.
2076                  *
2077                  *      The prefix length can have value 0 to 128.
2078                  */
2079         case PW_TYPE_IPV6PREFIX:
2080                 if (vp->length < 2 || vp->length > 18) goto raw;
2081                 if (vp->vp_octets[1] > 128) goto raw;
2082
2083                 /*
2084                  *      FIXME: double-check that
2085                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2086                  */
2087                 if (vp->length < 18) {
2088                         memset(vp->vp_octets + vp->length, 0,
2089                                18 - vp->length);
2090                 }
2091                 break;
2092
2093         default:
2094         raw:
2095                 vp->type = PW_TYPE_OCTETS;
2096                 vp->length = length;
2097                 memcpy(vp->vp_octets, data, length);
2098
2099
2100                 /*
2101                  *      Ensure there's no encryption or tag stuff,
2102                  *      we just pass the attribute as-is.
2103                  */
2104                 memset(&vp->flags, 0, sizeof(vp->flags));
2105         }
2106
2107         return vp;
2108 }
2109
2110
2111 /*
2112  *      Calculate/check digest, and decode radius attributes.
2113  *      Returns:
2114  *      -1 on decoding error
2115  *      0 on success
2116  */
2117 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2118                const char *secret)
2119 {
2120         uint32_t                lvalue;
2121         uint32_t                vendorcode;
2122         VALUE_PAIR              **tail;
2123         VALUE_PAIR              *pair;
2124         uint8_t                 *ptr;
2125         int                     packet_length;
2126         int                     attribute;
2127         int                     attrlen;
2128         int                     vendorlen;
2129         radius_packet_t         *hdr;
2130         int                     vsa_tlen, vsa_llen;
2131         DICT_VENDOR             *dv = NULL;
2132         int                     num_attributes = 0;
2133
2134         /*
2135          *      Extract attribute-value pairs
2136          */
2137         hdr = (radius_packet_t *)packet->data;
2138         ptr = hdr->data;
2139         packet_length = packet->data_len - AUTH_HDR_LEN;
2140
2141         /*
2142          *      There may be VP's already in the packet.  Don't
2143          *      destroy them.
2144          */
2145         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2146                 /* nothing */
2147         }
2148
2149         vendorcode = 0;
2150         vendorlen  = 0;
2151         vsa_tlen = vsa_llen = 1;
2152
2153         /*
2154          *      We have to read at least two bytes.
2155          *
2156          *      rad_recv() above ensures that this is OK.
2157          */
2158         while (packet_length > 0) {
2159                 attribute = -1;
2160                 attrlen = -1;
2161
2162                 /*
2163                  *      Normal attribute, handle it like normal.
2164                  */
2165                 if (vendorcode == 0) {
2166                         /*
2167                          *      No room to read attr/length,
2168                          *      or bad attribute, or attribute is
2169                          *      too short, or attribute is too long,
2170                          *      stop processing the packet.
2171                          */
2172                         if ((packet_length < 2) ||
2173                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2174                             (ptr[1] > packet_length)) break;
2175
2176                         attribute = *ptr++;
2177                         attrlen   = *ptr++;
2178
2179                         attrlen -= 2;
2180                         packet_length  -= 2;
2181
2182                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2183
2184                         /*
2185                          *      No vendor code, or ONLY vendor code.
2186                          */
2187                         if (attrlen <= 4) goto create_pair;
2188
2189                         vendorlen = 0;
2190                 }
2191
2192                 /*
2193                  *      Handle Vendor-Specific
2194                  */
2195                 if (vendorlen == 0) {
2196                         uint8_t *subptr;
2197                         int sublen;
2198                         int myvendor;
2199
2200                         /*
2201                          *      attrlen was checked above.
2202                          */
2203                         memcpy(&lvalue, ptr, 4);
2204                         myvendor = ntohl(lvalue);
2205
2206                         /*
2207                          *      Zero isn't allowed.
2208                          */
2209                         if (myvendor == 0) goto create_pair;
2210
2211                         /*
2212                          *      This is an implementation issue.
2213                          *      We currently pack vendor into the upper
2214                          *      16 bits of a 32-bit attribute number,
2215                          *      so we can't handle vendor numbers larger
2216                          *      than 16 bits.
2217                          */
2218                         if (myvendor > 65535) goto create_pair;
2219
2220                         vsa_tlen = vsa_llen = 1;
2221                         dv = dict_vendorbyvalue(myvendor);
2222                         if (dv) {
2223                                 vsa_tlen = dv->type;
2224                                 vsa_llen = dv->length;
2225                         }
2226
2227                         /*
2228                          *      Sweep through the list of VSA's,
2229                          *      seeing if they exactly fill the
2230                          *      outer Vendor-Specific attribute.
2231                          *
2232                          *      If not, create a raw Vendor-Specific.
2233                          */
2234                         subptr = ptr + 4;
2235                         sublen = attrlen - 4;
2236
2237                         /*
2238                          *      See if we can parse it.
2239                          */
2240                         do {
2241                                 int myattr = 0;
2242
2243                                 /*
2244                                  *      Don't have a type, it's bad.
2245                                  */
2246                                 if (sublen < vsa_tlen) goto create_pair;
2247
2248                                 /*
2249                                  *      Ensure that the attribute number
2250                                  *      is OK.
2251                                  */
2252                                 switch (vsa_tlen) {
2253                                 case 1:
2254                                         myattr = subptr[0];
2255                                         break;
2256
2257                                 case 2:
2258                                         myattr = (subptr[0] << 8) | subptr[1];
2259                                         break;
2260
2261                                 case 4:
2262                                         if ((subptr[0] != 0) ||
2263                                             (subptr[1] != 0)) goto create_pair;
2264
2265                                         myattr = (subptr[2] << 8) | subptr[3];
2266                                         break;
2267
2268                                         /*
2269                                          *      Our dictionary is broken.
2270                                          */
2271                                 default:
2272                                         goto create_pair;
2273                                 }
2274
2275                                 /*
2276                                  *      Not enough room for one more
2277                                  *      attribute.  Die!
2278                                  */
2279                                 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2280                                 switch (vsa_llen) {
2281                                 case 0:
2282                                         attribute = (myvendor << 16) | myattr;
2283                                         ptr += 4 + vsa_tlen;
2284                                         attrlen -= (4 + vsa_tlen);
2285                                         packet_length -= 4 + vsa_tlen;
2286                                         goto create_pair;
2287
2288                                 case 1:
2289                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2290                                                 goto create_pair;
2291
2292                                         if (subptr[vsa_tlen] > sublen)
2293                                                 goto create_pair;
2294                                         sublen -= subptr[vsa_tlen];
2295                                         subptr += subptr[vsa_tlen];
2296                                         break;
2297
2298                                 case 2:
2299                                         if (subptr[vsa_tlen] != 0) goto create_pair;
2300                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2301                                                 goto create_pair;
2302                                         if (subptr[vsa_tlen + 1] > sublen)
2303                                                 goto create_pair;
2304                                         sublen -= subptr[vsa_tlen + 1];
2305                                         subptr += subptr[vsa_tlen + 1];
2306                                         break;
2307
2308                                         /*
2309                                          *      Our dictionaries are
2310                                          *      broken.
2311                                          */
2312                                 default:
2313                                         goto create_pair;
2314                                 }
2315                         } while (sublen > 0);
2316
2317                         vendorcode = myvendor;
2318                         vendorlen = attrlen - 4;
2319                         packet_length -= 4;
2320
2321                         ptr += 4;
2322                 }
2323
2324                 /*
2325                  *      attrlen is the length of this attribute.
2326                  *      total_len is the length of the encompassing
2327                  *      attribute.
2328                  */
2329                 switch (vsa_tlen) {
2330                 case 1:
2331                         attribute = ptr[0];
2332                         break;
2333
2334                 case 2:
2335                         attribute = (ptr[0] << 8) | ptr[1];
2336                         break;
2337
2338                 default:        /* can't hit this. */
2339                         return -1;
2340                 }
2341                 attribute |= (vendorcode << 16);
2342                 ptr += vsa_tlen;
2343
2344                 switch (vsa_llen) {
2345                 case 1:
2346                         attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2347                         break;
2348
2349                 case 2:
2350                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2351                         break;
2352
2353                 default:        /* can't hit this. */
2354                         return -1;
2355                 }
2356                 ptr += vsa_llen;
2357                 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2358                 if (vendorlen == 0) vendorcode = 0;
2359                 packet_length -= (vsa_tlen + vsa_llen);
2360
2361                 /*
2362                  *      Create the attribute, setting the default type
2363                  *      to 'octets'.  If the type in the dictionary
2364                  *      is different, then the dictionary type will
2365                  *      over-ride this one.
2366                  */
2367         create_pair:
2368                 pair = rad_attr2vp(packet, original, secret,
2369                                    attribute, attrlen, ptr);
2370                 if (!pair) {
2371                         pairfree(&packet->vps);
2372                         librad_log("out of memory");
2373                         return -1;
2374                 }
2375
2376                 *tail = pair;
2377                 while (pair) {
2378                         num_attributes++;
2379                         debug_pair(pair);
2380                         tail = &pair->next;
2381                         pair = pair->next;
2382                 }
2383
2384                 /*
2385                  *      VSA's may not have been counted properly in
2386                  *      rad_packet_ok() above, as it is hard to count
2387                  *      then without using the dictionary.  We
2388                  *      therefore enforce the limits here, too.
2389                  */
2390                 if ((librad_max_attributes > 0) &&
2391                     (num_attributes > librad_max_attributes)) {
2392                         char host_ipaddr[128];
2393
2394                         pairfree(&packet->vps);
2395                         librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2396                                    inet_ntop(packet->src_ipaddr.af,
2397                                              &packet->src_ipaddr.ipaddr,
2398                                              host_ipaddr, sizeof(host_ipaddr)),
2399                                    num_attributes, librad_max_attributes);
2400                         return -1;
2401                 }
2402
2403                 ptr += attrlen;
2404                 packet_length -= attrlen;
2405         }
2406
2407         /*
2408          *      Merge information from the outside world into our
2409          *      random pool.
2410          */
2411         fr_rand_seed(packet->data, AUTH_HDR_LEN);
2412
2413         return 0;
2414 }
2415
2416
2417 /*
2418  *      Encode password.
2419  *
2420  *      We assume that the passwd buffer passed is big enough.
2421  *      RFC2138 says the password is max 128 chars, so the size
2422  *      of the passwd buffer must be at least 129 characters.
2423  *      Preferably it's just MAX_STRING_LEN.
2424  *
2425  *      int *pwlen is updated to the new length of the encrypted
2426  *      password - a multiple of 16 bytes.
2427  */
2428 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2429                  const uint8_t *vector)
2430 {
2431         FR_MD5_CTX context, old;
2432         uint8_t digest[AUTH_VECTOR_LEN];
2433         int     i, n, secretlen;
2434         int     len;
2435
2436         /*
2437          *      RFC maximum is 128 bytes.
2438          *
2439          *      If length is zero, pad it out with zeros.
2440          *
2441          *      If the length isn't aligned to 16 bytes,
2442          *      zero out the extra data.
2443          */
2444         len = *pwlen;
2445
2446         if (len > 128) len = 128;
2447
2448         if (len == 0) {
2449                 memset(passwd, 0, AUTH_PASS_LEN);
2450                 len = AUTH_PASS_LEN;
2451         } else if ((len % AUTH_PASS_LEN) != 0) {
2452                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2453                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2454         }
2455         *pwlen = len;
2456
2457         /*
2458          *      Use the secret to setup the decryption digest
2459          */
2460         secretlen = strlen(secret);
2461
2462         fr_MD5Init(&context);
2463         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2464         old = context;          /* save intermediate work */
2465
2466         /*
2467          *      Encrypt it in place.  Don't bother checking
2468          *      len, as we've ensured above that it's OK.
2469          */
2470         for (n = 0; n < len; n += AUTH_PASS_LEN) {
2471                 if (n == 0) {
2472                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2473                         fr_MD5Final(digest, &context);
2474                 } else {
2475                         context = old;
2476                         fr_MD5Update(&context,
2477                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
2478                                      AUTH_PASS_LEN);
2479                         fr_MD5Final(digest, &context);
2480                 }
2481
2482                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2483                         passwd[i + n] ^= digest[i];
2484                 }
2485         }
2486
2487         return 0;
2488 }
2489
2490 /*
2491  *      Decode password.
2492  */
2493 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2494                  const uint8_t *vector)
2495 {
2496         FR_MD5_CTX context, old;
2497         uint8_t digest[AUTH_VECTOR_LEN];
2498         int     i, n, secretlen;
2499
2500         /*
2501          *      The RFC's say that the maximum is 128.
2502          *      The buffer we're putting it into above is 254, so
2503          *      we don't need to do any length checking.
2504          */
2505         if (pwlen > 128) pwlen = 128;
2506
2507         /*
2508          *      Catch idiots.
2509          */
2510         if (pwlen == 0) goto done;
2511
2512         /*
2513          *      Use the secret to setup the decryption digest
2514          */
2515         secretlen = strlen(secret);
2516
2517         fr_MD5Init(&context);
2518         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2519         old = context;          /* save intermediate work */
2520
2521         /*
2522          *      The inverse of the code above.
2523          */
2524         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2525                 if (n == 0) {
2526                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2527                         fr_MD5Final(digest, &context);
2528
2529                         context = old;
2530                         if (pwlen > AUTH_PASS_LEN) {
2531                                 fr_MD5Update(&context, (uint8_t *) passwd,
2532                                              AUTH_PASS_LEN);
2533                         }
2534                 } else {
2535                         fr_MD5Final(digest, &context);
2536
2537                         context = old;
2538                         if (pwlen > (n + AUTH_PASS_LEN)) {
2539                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
2540                                              AUTH_PASS_LEN);
2541                         }
2542                 }
2543
2544                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2545                         passwd[i + n] ^= digest[i];
2546                 }
2547         }
2548
2549  done:
2550         passwd[pwlen] = '\0';
2551         return strlen(passwd);
2552 }
2553
2554
2555 /*
2556  *      Encode Tunnel-Password attributes when sending them out on the wire.
2557  *
2558  *      int *pwlen is updated to the new length of the encrypted
2559  *      password - a multiple of 16 bytes.
2560  *
2561  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
2562  *      value MD5 hash.
2563  */
2564 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2565                         const uint8_t *vector)
2566 {
2567         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2568         unsigned char   digest[AUTH_VECTOR_LEN];
2569         char*   salt;
2570         int     i, n, secretlen;
2571         unsigned len, n2;
2572
2573         len = *pwlen;
2574
2575         if (len > 127) len = 127;
2576
2577         /*
2578          * Shift the password 3 positions right to place a salt and original
2579          * length, tag will be added automatically on packet send
2580          */
2581         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2582         salt = passwd;
2583         passwd += 2;
2584         /*
2585          * save original password length as first password character;
2586          */
2587         *passwd = len;
2588         len += 1;
2589
2590
2591         /*
2592          *      Generate salt.  The RFC's say:
2593          *
2594          *      The high bit of salt[0] must be set, each salt in a
2595          *      packet should be unique, and they should be random
2596          *
2597          *      So, we set the high bit, add in a counter, and then
2598          *      add in some CSPRNG data.  should be OK..
2599          */
2600         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2601                    (fr_rand() & 0x07));
2602         salt[1] = fr_rand();
2603
2604         /*
2605          *      Padd password to multiple of AUTH_PASS_LEN bytes.
2606          */
2607         n = len % AUTH_PASS_LEN;
2608         if (n) {
2609                 n = AUTH_PASS_LEN - n;
2610                 for (; n > 0; n--, len++)
2611                         passwd[len] = 0;
2612         }
2613         /* set new password length */
2614         *pwlen = len + 2;
2615
2616         /*
2617          *      Use the secret to setup the decryption digest
2618          */
2619         secretlen = strlen(secret);
2620         memcpy(buffer, secret, secretlen);
2621
2622         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2623                 if (!n2) {
2624                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2625                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2626                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2627                 } else {
2628                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2629                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2630                 }
2631
2632                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2633                         passwd[i + n2] ^= digest[i];
2634                 }
2635         }
2636         passwd[n2] = 0;
2637         return 0;
2638 }
2639
2640 /*
2641  *      Decode Tunnel-Password encrypted attributes.
2642  *
2643  *      Defined in RFC-2868, this uses a two char SALT along with the
2644  *      initial intermediate value, to differentiate it from the
2645  *      above.
2646  */
2647 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2648                         const uint8_t *vector)
2649 {
2650         FR_MD5_CTX  context, old;
2651         uint8_t         digest[AUTH_VECTOR_LEN];
2652         int             secretlen;
2653         unsigned        i, n, len, reallen;
2654
2655         len = *pwlen;
2656
2657         /*
2658          *      We need at least a salt.
2659          */
2660         if (len < 2) {
2661                 librad_log("tunnel password is too short");
2662                 return -1;
2663         }
2664
2665         /*
2666          *      There's a salt, but no password.  Or, there's a salt
2667          *      and a 'data_len' octet.  It's wrong, but at least we
2668          *      can figure out what it means: the password is empty.
2669          *
2670          *      Note that this means we ignore the 'data_len' field,
2671          *      if the attribute length tells us that there's no
2672          *      more data.  So the 'data_len' field may be wrong,
2673          *      but that's ok...
2674          */
2675         if (len <= 3) {
2676                 passwd[0] = 0;
2677                 *pwlen = 0;
2678                 return 0;
2679         }
2680
2681         len -= 2;               /* discount the salt */
2682
2683         /*
2684          *      Use the secret to setup the decryption digest
2685          */
2686         secretlen = strlen(secret);
2687
2688         fr_MD5Init(&context);
2689         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2690         old = context;          /* save intermediate work */
2691
2692         /*
2693          *      Set up the initial key:
2694          *
2695          *       b(1) = MD5(secret + vector + salt)
2696          */
2697         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2698         fr_MD5Update(&context, passwd, 2);
2699
2700         reallen = 0;
2701         for (n = 0; n < len; n += AUTH_PASS_LEN) {
2702                 int base = 0;
2703
2704                 if (n == 0) {
2705                         fr_MD5Final(digest, &context);
2706
2707                         context = old;
2708
2709                         /*
2710                          *      A quick check: decrypt the first octet
2711                          *      of the password, which is the
2712                          *      'data_len' field.  Ensure it's sane.
2713                          */
2714                         reallen = passwd[2] ^ digest[0];
2715                         if (reallen >= len) {
2716                                 librad_log("tunnel password is too long for the attribute");
2717                                 return -1;
2718                         }
2719
2720                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2721
2722                         base = 1;
2723                 } else {
2724                         fr_MD5Final(digest, &context);
2725
2726                         context = old;
2727                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2728                 }
2729
2730                 for (i = base; i < AUTH_PASS_LEN; i++) {
2731                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2732                 }
2733         }
2734
2735         /*
2736          *      See make_tunnel_password, above.
2737          */
2738         if (reallen > 239) reallen = 239;
2739
2740         *pwlen = reallen;
2741         passwd[reallen] = 0;
2742
2743         return reallen;
2744 }
2745
2746 /*
2747  *      Encode a CHAP password
2748  *
2749  *      FIXME: might not work with Ascend because
2750  *      we use vp->length, and Ascend gear likes
2751  *      to send an extra '\0' in the string!
2752  */
2753 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2754                     VALUE_PAIR *password)
2755 {
2756         int             i;
2757         uint8_t         *ptr;
2758         uint8_t         string[MAX_STRING_LEN * 2 + 1];
2759         VALUE_PAIR      *challenge;
2760
2761         /*
2762          *      Sanity check the input parameters
2763          */
2764         if ((packet == NULL) || (password == NULL)) {
2765                 return -1;
2766         }
2767
2768         /*
2769          *      Note that the password VP can be EITHER
2770          *      a User-Password attribute (from a check-item list),
2771          *      or a CHAP-Password attribute (the client asking
2772          *      the library to encode it).
2773          */
2774
2775         i = 0;
2776         ptr = string;
2777         *ptr++ = id;
2778
2779         i++;
2780         memcpy(ptr, password->vp_strvalue, password->length);
2781         ptr += password->length;
2782         i += password->length;
2783
2784         /*
2785          *      Use Chap-Challenge pair if present,
2786          *      Request-Authenticator otherwise.
2787          */
2788         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2789         if (challenge) {
2790                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2791                 i += challenge->length;
2792         } else {
2793                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2794                 i += AUTH_VECTOR_LEN;
2795         }
2796
2797         *output = id;
2798         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2799
2800         return 0;
2801 }
2802
2803
2804 /*
2805  *      Seed the random number generator.
2806  *
2807  *      May be called any number of times.
2808  */
2809 void fr_rand_seed(const void *data, size_t size)
2810 {
2811         uint32_t hash;
2812
2813         /*
2814          *      Ensure that the pool is initialized.
2815          */
2816         if (!fr_rand_initialized) {
2817                 int fd;
2818
2819                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2820
2821                 fd = open("/dev/urandom", O_RDONLY);
2822                 if (fd >= 0) {
2823                         size_t total;
2824                         ssize_t this;
2825
2826                         total = this = 0;
2827                         while (total < sizeof(fr_rand_pool.randrsl)) {
2828                                 this = read(fd, fr_rand_pool.randrsl,
2829                                             sizeof(fr_rand_pool.randrsl) - total);
2830                                 if ((this < 0) && (errno != EINTR)) break;
2831                                 if (this > 0) total += this;
2832                         }
2833                         close(fd);
2834                 } else {
2835                         fr_rand_pool.randrsl[0] = fd;
2836                         fr_rand_pool.randrsl[1] = time(NULL);
2837                         fr_rand_pool.randrsl[2] = errno;
2838                 }
2839
2840                 fr_randinit(&fr_rand_pool, 1);
2841                 fr_rand_pool.randcnt = 0;
2842                 fr_rand_initialized = 1;
2843         }
2844
2845         if (!data) return;
2846
2847         /*
2848          *      Hash the user data
2849          */
2850         hash = fr_rand();
2851         if (!hash) hash = fr_rand();
2852         hash = fr_hash_update(data, size, hash);
2853
2854         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2855 }
2856
2857
2858 /*
2859  *      Return a 32-bit random number.
2860  */
2861 uint32_t fr_rand(void)
2862 {
2863         uint32_t num;
2864
2865         /*
2866          *      Ensure that the pool is initialized.
2867          */
2868         if (!fr_rand_initialized) {
2869                 fr_rand_seed(NULL, 0);
2870         }
2871
2872         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2873         if (fr_rand_pool.randcnt == 256) {
2874                 fr_rand_pool.randcnt = 0;
2875                 fr_isaac(&fr_rand_pool);
2876         }
2877
2878         return num;
2879 }
2880
2881
2882 /*
2883  *      Allocate a new RADIUS_PACKET
2884  */
2885 RADIUS_PACKET *rad_alloc(int newvector)
2886 {
2887         RADIUS_PACKET   *rp;
2888
2889         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2890                 librad_log("out of memory");
2891                 return NULL;
2892         }
2893         memset(rp, 0, sizeof(*rp));
2894         rp->id = -1;
2895         rp->offset = -1;
2896
2897         if (newvector) {
2898                 int i;
2899                 uint32_t hash, base;
2900
2901                 /*
2902                  *      Don't expose the actual contents of the random
2903                  *      pool.
2904                  */
2905                 base = fr_rand();
2906                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2907                         hash = fr_rand() ^ base;
2908                         memcpy(rp->vector + i, &hash, sizeof(hash));
2909                 }
2910         }
2911         fr_rand();              /* stir the pool again */
2912
2913         return rp;
2914 }
2915
2916 /*
2917  *      Free a RADIUS_PACKET
2918  */
2919 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2920 {
2921         RADIUS_PACKET *radius_packet;
2922
2923         if (!radius_packet_ptr || !*radius_packet_ptr) return;
2924         radius_packet = *radius_packet_ptr;
2925
2926         free(radius_packet->data);
2927
2928         pairfree(&radius_packet->vps);
2929
2930         free(radius_packet);
2931
2932         *radius_packet_ptr = NULL;
2933 }