92c2305a76578c0c8a54eb7d18fc5df2bd5afe56
[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                 /*
845                  *      Check if 255 - offset - total_length is less
846                  *      than 18.  If so, we can't fit the data into
847                  *      the available space, and we discard the
848                  *      attribute.
849                  *
850                  *      This is ONLY a problem if we have multiple VSA's
851                  *      in one Vendor-Specific, though.
852                  */
853                 if ((255 - offset - total_length) < 18) return 0;
854
855                 switch (packet->code) {
856                 case PW_AUTHENTICATION_ACK:
857                 case PW_AUTHENTICATION_REJECT:
858                 case PW_ACCESS_CHALLENGE:
859                 default:
860                         if (!original) {
861                                 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
862                                 return -1;
863                         }
864                         make_tunnel_passwd(ptr + offset, &len,
865                                            data, len, 255 - offset - total_length,
866                                            secret, original->vector);
867                         break;
868                 case PW_ACCOUNTING_REQUEST:
869                 case PW_DISCONNECT_REQUEST:
870                 case PW_COA_REQUEST:
871                         make_tunnel_passwd(ptr + offset, &len,
872                                            data, len, 255 - offset - total_length,
873                                            secret, packet->vector);
874                         break;
875                 }
876                 break;
877
878                 /*
879                  *      The code above ensures that this attribute
880                  *      always fits.
881                  */
882         case FLAG_ENCRYPT_ASCEND_SECRET:
883                 make_secret(ptr + offset, packet->vector,
884                             secret, data);
885                 len = AUTH_VECTOR_LEN;
886                 break;
887
888
889         default:
890                 /*
891                  *      Just copy the data over
892                  */
893                 memcpy(ptr + offset, data, len);
894                 break;
895         } /* switch over encryption flags */
896
897         /*
898          *      Account for the tag (if any).
899          */
900         len += offset;
901
902         /*
903          *      RFC 2865 section 5 says that zero-length attributes
904          *      MUST NOT be sent.
905          */
906         if (len == 0) return 0;
907
908         /*
909          *      Update the various lengths.
910          */
911         *length_ptr += len;
912         if (vsa_length_ptr) *vsa_length_ptr += len;
913         ptr += len;
914         total_length += len;
915
916         return total_length;    /* of attribute */
917 }
918
919
920 /*
921  *      Encode a packet.
922  */
923 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
924                const char *secret)
925 {
926         radius_packet_t *hdr;
927         uint8_t         *ptr;
928         uint16_t        total_length;
929         int             len;
930         VALUE_PAIR      *reply;
931         const char      *what;
932         char            ip_buffer[128];
933
934         /*
935          *      For simplicity in the following logic, we allow
936          *      the attributes to "overflow" the 4k maximum
937          *      RADIUS packet size, by one attribute.
938          *
939          *      It's uint32_t, for alignment purposes.
940          */
941         uint32_t        data[(MAX_PACKET_LEN + 256) / 4];
942
943         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
944                 what = packet_codes[packet->code];
945         } else {
946                 what = "Reply";
947         }
948
949         DEBUG("Sending %s of id %d to %s port %d\n",
950               what, packet->id,
951               inet_ntop(packet->dst_ipaddr.af,
952                         &packet->dst_ipaddr.ipaddr,
953                         ip_buffer, sizeof(ip_buffer)),
954               packet->dst_port);
955
956         /*
957          *      Double-check some things based on packet code.
958          */
959         switch (packet->code) {
960         case PW_AUTHENTICATION_ACK:
961         case PW_AUTHENTICATION_REJECT:
962         case PW_ACCESS_CHALLENGE:
963                 if (!original) {
964                         librad_log("ERROR: Cannot sign response packet without a request packet.");
965                         return -1;
966                 }
967                 break;
968
969                 /*
970                  *      These packet vectors start off as all zero.
971                  */
972         case PW_ACCOUNTING_REQUEST:
973         case PW_DISCONNECT_REQUEST:
974         case PW_COA_REQUEST:
975                 memset(packet->vector, 0, sizeof(packet->vector));
976                 break;
977
978         default:
979                 break;
980         }
981
982         /*
983          *      Use memory on the stack, until we know how
984          *      large the packet will be.
985          */
986         hdr = (radius_packet_t *) data;
987
988         /*
989          *      Build standard header
990          */
991         hdr->code = packet->code;
992         hdr->id = packet->id;
993
994         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
995
996         total_length = AUTH_HDR_LEN;
997
998         /*
999          *      Load up the configuration values for the user
1000          */
1001         ptr = hdr->data;
1002         packet->offset = 0;
1003
1004         /*
1005          *      FIXME: Loop twice over the reply list.  The first time,
1006          *      calculate the total length of data.  The second time,
1007          *      allocate the memory, and fill in the VP's.
1008          *
1009          *      Hmm... this may be slower than just doing a small
1010          *      memcpy.
1011          */
1012
1013         /*
1014          *      Loop over the reply attributes for the packet.
1015          */
1016         for (reply = packet->vps; reply; reply = reply->next) {
1017                 /*
1018                  *      Ignore non-wire attributes
1019                  */
1020                 if ((VENDOR(reply->attribute) == 0) &&
1021                     ((reply->attribute & 0xFFFF) > 0xff)) {
1022 #ifndef NDEBUG
1023                         /*
1024                          *      Permit the admin to send BADLY formatted
1025                          *      attributes with a debug build.
1026                          */
1027                         if (reply->attribute == PW_RAW_ATTRIBUTE) {
1028                                 memcpy(ptr, reply->vp_octets, reply->length);
1029                                 len = reply->length;
1030                                 goto next;
1031                         }
1032 #endif
1033                         continue;
1034                 }
1035
1036                 /*
1037                  *      Set the Message-Authenticator to the correct
1038                  *      length and initial value.
1039                  */
1040                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1041                         reply->length = AUTH_VECTOR_LEN;
1042                         memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1043
1044                         /*
1045                          *      Cache the offset to the
1046                          *      Message-Authenticator
1047                          */
1048                         packet->offset = total_length;
1049                 }
1050
1051                 /*
1052                  *      Print out ONLY the attributes which
1053                  *      we're sending over the wire, and print
1054                  *      them out BEFORE they're encrypted.
1055                  */
1056                 debug_pair(reply);
1057
1058                 len = rad_vp2attr(packet, original, secret, reply, ptr);
1059
1060                 if (len < 0) return -1;
1061
1062                 /*
1063                  *      Check that the packet is no more than 4k in
1064                  *      size, AFTER writing the attribute past the 4k
1065                  *      boundary, but BEFORE deciding to increase the
1066                  *      size of the packet. Note that the 'data'
1067                  *      buffer, above, is one attribute longer than
1068                  *      necessary, in order to permit this overflow.
1069                  */
1070                 if ((total_length + len) > MAX_PACKET_LEN) {
1071                         break;
1072                 }
1073
1074         next:
1075                 ptr += len;
1076                 total_length += len;
1077         } /* done looping over all attributes */
1078
1079         /*
1080          *      Fill in the rest of the fields, and copy the data over
1081          *      from the local stack to the newly allocated memory.
1082          *
1083          *      Yes, all this 'memcpy' is slow, but it means
1084          *      that we only allocate the minimum amount of
1085          *      memory for a request.
1086          */
1087         packet->data_len = total_length;
1088         packet->data = (uint8_t *) malloc(packet->data_len);
1089         if (!packet->data) {
1090                 librad_log("Out of memory");
1091                 return -1;
1092         }
1093
1094         memcpy(packet->data, data, packet->data_len);
1095         hdr = (radius_packet_t *) packet->data;
1096
1097         total_length = htons(total_length);
1098         memcpy(hdr->length, &total_length, sizeof(total_length));
1099
1100         return 0;
1101 }
1102
1103
1104 /*
1105  *      Sign a previously encoded packet.
1106  */
1107 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1108              const char *secret)
1109 {
1110         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1111
1112         /*
1113          *      It wasn't assigned an Id, this is bad!
1114          */
1115         if (packet->id < 0) {
1116                 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1117                 return -1;
1118         }
1119
1120         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1121             (packet->offset < 0)) {
1122                 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1123                 return -1;
1124         }
1125
1126         /*
1127          *      If there's a Message-Authenticator, update it
1128          *      now, BEFORE updating the authentication vector.
1129          */
1130         if (packet->offset > 0) {
1131                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1132
1133                 switch (packet->code) {
1134                 case PW_ACCOUNTING_REQUEST:
1135                 case PW_ACCOUNTING_RESPONSE:
1136                 case PW_DISCONNECT_REQUEST:
1137                 case PW_DISCONNECT_ACK:
1138                 case PW_DISCONNECT_NAK:
1139                 case PW_COA_REQUEST:
1140                 case PW_COA_ACK:
1141                 case PW_COA_NAK:
1142                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1143                         break;
1144
1145                 case PW_AUTHENTICATION_ACK:
1146                 case PW_AUTHENTICATION_REJECT:
1147                 case PW_ACCESS_CHALLENGE:
1148                         if (!original) {
1149                                 librad_log("ERROR: Cannot sign response packet without a request packet.");
1150                                 return -1;
1151                         }
1152                         memcpy(hdr->vector, original->vector,
1153                                AUTH_VECTOR_LEN);
1154                         break;
1155
1156                 default:        /* others have vector already set to zero */
1157                         break;
1158
1159                 }
1160
1161                 /*
1162                  *      Set the authentication vector to zero,
1163                  *      calculate the signature, and put it
1164                  *      into the Message-Authenticator
1165                  *      attribute.
1166                  */
1167                 fr_hmac_md5(packet->data, packet->data_len,
1168                             (const uint8_t *) secret, strlen(secret),
1169                             calc_auth_vector);
1170                 memcpy(packet->data + packet->offset + 2,
1171                        calc_auth_vector, AUTH_VECTOR_LEN);
1172
1173                 /*
1174                  *      Copy the original request vector back
1175                  *      to the raw packet.
1176                  */
1177                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1178         }
1179
1180         /*
1181          *      Switch over the packet code, deciding how to
1182          *      sign the packet.
1183          */
1184         switch (packet->code) {
1185                 /*
1186                  *      Request packets are not signed, bur
1187                  *      have a random authentication vector.
1188                  */
1189         case PW_AUTHENTICATION_REQUEST:
1190         case PW_STATUS_SERVER:
1191                 break;
1192
1193                 /*
1194                  *      Reply packets are signed with the
1195                  *      authentication vector of the request.
1196                  */
1197         default:
1198                 {
1199                         uint8_t digest[16];
1200
1201                         FR_MD5_CTX      context;
1202                         fr_MD5Init(&context);
1203                         fr_MD5Update(&context, packet->data, packet->data_len);
1204                         fr_MD5Update(&context, (const uint8_t *) secret,
1205                                      strlen(secret));
1206                         fr_MD5Final(digest, &context);
1207
1208                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1209                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1210                         break;
1211                 }
1212         }/* switch over packet codes */
1213
1214         return 0;
1215 }
1216
1217 /*
1218  *      Reply to the request.  Also attach
1219  *      reply attribute value pairs and any user message provided.
1220  */
1221 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1222              const char *secret)
1223 {
1224         VALUE_PAIR              *reply;
1225         const char              *what;
1226         char                    ip_buffer[128];
1227
1228         /*
1229          *      Maybe it's a fake packet.  Don't send it.
1230          */
1231         if (!packet || (packet->sockfd < 0)) {
1232                 return 0;
1233         }
1234
1235         if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1236                 what = packet_codes[packet->code];
1237         } else {
1238                 what = "Reply";
1239         }
1240
1241         /*
1242          *  First time through, allocate room for the packet
1243          */
1244         if (!packet->data) {
1245                 /*
1246                  *      Encode the packet.
1247                  */
1248                 if (rad_encode(packet, original, secret) < 0) {
1249                         return -1;
1250                 }
1251
1252                 /*
1253                  *      Re-sign it, including updating the
1254                  *      Message-Authenticator.
1255                  */
1256                 if (rad_sign(packet, original, secret) < 0) {
1257                         return -1;
1258                 }
1259
1260                 /*
1261                  *      If packet->data points to data, then we print out
1262                  *      the VP list again only for debugging.
1263                  */
1264         } else if (librad_debug) {
1265                 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1266                       inet_ntop(packet->dst_ipaddr.af,
1267                                 &packet->dst_ipaddr.ipaddr,
1268                                 ip_buffer, sizeof(ip_buffer)),
1269                       packet->dst_port);
1270
1271                 for (reply = packet->vps; reply; reply = reply->next) {
1272                         if ((VENDOR(reply->attribute) == 0) &&
1273                             ((reply->attribute & 0xFFFF) > 0xff)) continue;
1274                         debug_pair(reply);
1275                 }
1276         }
1277
1278         /*
1279          *      And send it on it's way.
1280          */
1281         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1282                           &packet->src_ipaddr, packet->src_port,
1283                           &packet->dst_ipaddr, packet->dst_port);
1284 }
1285
1286
1287 /*
1288  *      Validates the requesting client NAS.  Calculates the
1289  *      signature based on the clients private key.
1290  */
1291 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1292 {
1293         uint8_t         digest[AUTH_VECTOR_LEN];
1294         FR_MD5_CTX              context;
1295
1296         /*
1297          *      Zero out the auth_vector in the received packet.
1298          *      Then append the shared secret to the received packet,
1299          *      and calculate the MD5 sum. This must be the same
1300          *      as the original MD5 sum (packet->vector).
1301          */
1302         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1303
1304         /*
1305          *  MD5(packet + secret);
1306          */
1307         fr_MD5Init(&context);
1308         fr_MD5Update(&context, packet->data, packet->data_len);
1309         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1310         fr_MD5Final(digest, &context);
1311
1312         /*
1313          *      Return 0 if OK, 2 if not OK.
1314          */
1315         if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1316         return 0;
1317 }
1318
1319
1320 /*
1321  *      Validates the requesting client NAS.  Calculates the
1322  *      signature based on the clients private key.
1323  */
1324 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1325                             const char *secret)
1326 {
1327         uint8_t         calc_digest[AUTH_VECTOR_LEN];
1328         FR_MD5_CTX              context;
1329
1330         /*
1331          *      Very bad!
1332          */
1333         if (original == NULL) {
1334                 return 3;
1335         }
1336
1337         /*
1338          *  Copy the original vector in place.
1339          */
1340         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1341
1342         /*
1343          *  MD5(packet + secret);
1344          */
1345         fr_MD5Init(&context);
1346         fr_MD5Update(&context, packet->data, packet->data_len);
1347         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1348         fr_MD5Final(calc_digest, &context);
1349
1350         /*
1351          *  Copy the packet's vector back to the packet.
1352          */
1353         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1354
1355         /*
1356          *      Return 0 if OK, 2 if not OK.
1357          */
1358         if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1359         return 0;
1360 }
1361
1362
1363 /*
1364  *      See if the data pointed to by PTR is a valid RADIUS packet.
1365  *
1366  *      packet is not 'const * const' because we may update data_len,
1367  *      if there's more data in the UDP packet than in the RADIUS packet.
1368  */
1369 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1370 {
1371         uint8_t                 *attr;
1372         int                     totallen;
1373         int                     count;
1374         radius_packet_t         *hdr;
1375         char                    host_ipaddr[128];
1376         int                     require_ma = 0;
1377         int                     seen_ma = 0;
1378         int                     num_attributes;
1379
1380         /*
1381          *      Check for packets smaller than the packet header.
1382          *
1383          *      RFC 2865, Section 3., subsection 'length' says:
1384          *
1385          *      "The minimum length is 20 ..."
1386          */
1387         if (packet->data_len < AUTH_HDR_LEN) {
1388                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1389                            inet_ntop(packet->src_ipaddr.af,
1390                                      &packet->src_ipaddr.ipaddr,
1391                                      host_ipaddr, sizeof(host_ipaddr)),
1392                            packet->data_len, AUTH_HDR_LEN);
1393                 return 0;
1394         }
1395
1396         /*
1397          *      RFC 2865, Section 3., subsection 'length' says:
1398          *
1399          *      " ... and maximum length is 4096."
1400          */
1401         if (packet->data_len > MAX_PACKET_LEN) {
1402                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1403                            inet_ntop(packet->src_ipaddr.af,
1404                                      &packet->src_ipaddr.ipaddr,
1405                                      host_ipaddr, sizeof(host_ipaddr)),
1406                            packet->data_len, MAX_PACKET_LEN);
1407                 return 0;
1408         }
1409
1410         /*
1411          *      Check for packets with mismatched size.
1412          *      i.e. We've received 128 bytes, and the packet header
1413          *      says it's 256 bytes long.
1414          */
1415         totallen = (packet->data[2] << 8) | packet->data[3];
1416         hdr = (radius_packet_t *)packet->data;
1417
1418         /*
1419          *      Code of 0 is not understood.
1420          *      Code of 16 or greate is not understood.
1421          */
1422         if ((hdr->code == 0) ||
1423             (hdr->code >= MAX_PACKET_CODE)) {
1424                 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1425                            inet_ntop(packet->src_ipaddr.af,
1426                                      &packet->src_ipaddr.ipaddr,
1427                                      host_ipaddr, sizeof(host_ipaddr)),
1428                            hdr->code);
1429                 return 0;
1430         }
1431
1432         /*
1433          *      Message-Authenticator is required in Status-Server
1434          *      packets, otherwise they can be trivially forged.
1435          */
1436         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1437
1438         /*
1439          *      It's also required if the caller asks for it.
1440          */
1441         if (flags) require_ma = 1;
1442
1443         /*
1444          *      Repeat the length checks.  This time, instead of
1445          *      looking at the data we received, look at the value
1446          *      of the 'length' field inside of the packet.
1447          *
1448          *      Check for packets smaller than the packet header.
1449          *
1450          *      RFC 2865, Section 3., subsection 'length' says:
1451          *
1452          *      "The minimum length is 20 ..."
1453          */
1454         if (totallen < AUTH_HDR_LEN) {
1455                 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1456                            inet_ntop(packet->src_ipaddr.af,
1457                                      &packet->src_ipaddr.ipaddr,
1458                                      host_ipaddr, sizeof(host_ipaddr)),
1459                            totallen, AUTH_HDR_LEN);
1460                 return 0;
1461         }
1462
1463         /*
1464          *      And again, for the value of the 'length' field.
1465          *
1466          *      RFC 2865, Section 3., subsection 'length' says:
1467          *
1468          *      " ... and maximum length is 4096."
1469          */
1470         if (totallen > MAX_PACKET_LEN) {
1471                 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1472                            inet_ntop(packet->src_ipaddr.af,
1473                                      &packet->src_ipaddr.ipaddr,
1474                                      host_ipaddr, sizeof(host_ipaddr)),
1475                            totallen, MAX_PACKET_LEN);
1476                 return 0;
1477         }
1478
1479         /*
1480          *      RFC 2865, Section 3., subsection 'length' says:
1481          *
1482          *      "If the packet is shorter than the Length field
1483          *      indicates, it MUST be silently discarded."
1484          *
1485          *      i.e. No response to the NAS.
1486          */
1487         if (packet->data_len < totallen) {
1488                 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1489                            inet_ntop(packet->src_ipaddr.af,
1490                                      &packet->src_ipaddr.ipaddr,
1491                                      host_ipaddr, sizeof(host_ipaddr)),
1492                            packet->data_len, totallen);
1493                 return 0;
1494         }
1495
1496         /*
1497          *      RFC 2865, Section 3., subsection 'length' says:
1498          *
1499          *      "Octets outside the range of the Length field MUST be
1500          *      treated as padding and ignored on reception."
1501          */
1502         if (packet->data_len > totallen) {
1503                 /*
1504                  *      We're shortening the packet below, but just
1505                  *      to be paranoid, zero out the extra data.
1506                  */
1507                 memset(packet->data + totallen, 0, packet->data_len - totallen);
1508                 packet->data_len = totallen;
1509         }
1510
1511         /*
1512          *      Walk through the packet's attributes, ensuring that
1513          *      they add up EXACTLY to the size of the packet.
1514          *
1515          *      If they don't, then the attributes either under-fill
1516          *      or over-fill the packet.  Any parsing of the packet
1517          *      is impossible, and will result in unknown side effects.
1518          *
1519          *      This would ONLY happen with buggy RADIUS implementations,
1520          *      or with an intentional attack.  Either way, we do NOT want
1521          *      to be vulnerable to this problem.
1522          */
1523         attr = hdr->data;
1524         count = totallen - AUTH_HDR_LEN;
1525         num_attributes = 0;
1526
1527         while (count > 0) {
1528                 /*
1529                  *      Attribute number zero is NOT defined.
1530                  */
1531                 if (attr[0] == 0) {
1532                         librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1533                                    inet_ntop(packet->src_ipaddr.af,
1534                                              &packet->src_ipaddr.ipaddr,
1535                                              host_ipaddr, sizeof(host_ipaddr)));
1536                         return 0;
1537                 }
1538
1539                 /*
1540                  *      Attributes are at LEAST as long as the ID & length
1541                  *      fields.  Anything shorter is an invalid attribute.
1542                  */
1543                 if (attr[1] < 2) {
1544                         librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1545                                    inet_ntop(packet->src_ipaddr.af,
1546                                              &packet->src_ipaddr.ipaddr,
1547                                              host_ipaddr, sizeof(host_ipaddr)),
1548                                    attr[0]);
1549                         return 0;
1550                 }
1551
1552                 /*
1553                  *      Sanity check the attributes for length.
1554                  */
1555                 switch (attr[0]) {
1556                 default:        /* don't do anything by default */
1557                         break;
1558
1559                         /*
1560                          *      If there's an EAP-Message, we require
1561                          *      a Message-Authenticator.
1562                          */
1563                 case PW_EAP_MESSAGE:
1564                         require_ma = 1;
1565                         break;
1566
1567                 case PW_MESSAGE_AUTHENTICATOR:
1568                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1569                                 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1570                                            inet_ntop(packet->src_ipaddr.af,
1571                                                      &packet->src_ipaddr.ipaddr,
1572                                                      host_ipaddr, sizeof(host_ipaddr)),
1573                                            attr[1] - 2);
1574                                 return 0;
1575                         }
1576                         seen_ma = 1;
1577                         break;
1578                 }
1579
1580                 /*
1581                  *      FIXME: Look up the base 255 attributes in the
1582                  *      dictionary, and switch over their type.  For
1583                  *      integer/date/ip, the attribute length SHOULD
1584                  *      be 6.
1585                  */
1586                 count -= attr[1];       /* grab the attribute length */
1587                 attr += attr[1];
1588                 num_attributes++;       /* seen one more attribute */
1589         }
1590
1591         /*
1592          *      If the attributes add up to a packet, it's allowed.
1593          *
1594          *      If not, we complain, and throw the packet away.
1595          */
1596         if (count != 0) {
1597                 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1598                            inet_ntop(packet->src_ipaddr.af,
1599                                      &packet->src_ipaddr.ipaddr,
1600                                      host_ipaddr, sizeof(host_ipaddr)));
1601                 return 0;
1602         }
1603
1604         /*
1605          *      If we're configured to look for a maximum number of
1606          *      attributes, and we've seen more than that maximum,
1607          *      then throw the packet away, as a possible DoS.
1608          */
1609         if ((librad_max_attributes > 0) &&
1610             (num_attributes > librad_max_attributes)) {
1611                 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1612                            inet_ntop(packet->src_ipaddr.af,
1613                                      &packet->src_ipaddr.ipaddr,
1614                                      host_ipaddr, sizeof(host_ipaddr)),
1615                            num_attributes, librad_max_attributes);
1616                 return 0;
1617         }
1618
1619         /*
1620          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1621          *
1622          *      A packet with an EAP-Message attribute MUST also have
1623          *      a Message-Authenticator attribute.
1624          *
1625          *      A Message-Authenticator all by itself is OK, though.
1626          *
1627          *      Similarly, Status-Server packets MUST contain
1628          *      Message-Authenticator attributes.
1629          */
1630         if (require_ma && ! seen_ma) {
1631                 librad_log("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1632                            inet_ntop(packet->src_ipaddr.af,
1633                                      &packet->src_ipaddr.ipaddr,
1634                                      host_ipaddr, sizeof(host_ipaddr)));
1635                 return 0;
1636         }
1637
1638         /*
1639          *      Fill RADIUS header fields
1640          */
1641         packet->code = hdr->code;
1642         packet->id = hdr->id;
1643         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1644
1645         return 1;
1646 }
1647
1648
1649 /*
1650  *      Receive UDP client requests, and fill in
1651  *      the basics of a RADIUS_PACKET structure.
1652  */
1653 RADIUS_PACKET *rad_recv(int fd, int flags)
1654 {
1655         RADIUS_PACKET           *packet;
1656
1657         /*
1658          *      Allocate the new request data structure
1659          */
1660         if ((packet = malloc(sizeof(*packet))) == NULL) {
1661                 librad_log("out of memory");
1662                 return NULL;
1663         }
1664         memset(packet, 0, sizeof(*packet));
1665
1666         packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1667                                         &packet->src_ipaddr, &packet->src_port,
1668                                         &packet->dst_ipaddr, &packet->dst_port);
1669
1670         /*
1671          *      Check for socket errors.
1672          */
1673         if (packet->data_len < 0) {
1674                 librad_log("Error receiving packet: %s", strerror(errno));
1675                 /* packet->data is NULL */
1676                 free(packet);
1677                 return NULL;
1678         }
1679
1680         /*
1681          *      If the packet is too big, then rad_recvfrom did NOT
1682          *      allocate memory.  Instead, it just discarded the
1683          *      packet.
1684          */
1685         if (packet->data_len > MAX_PACKET_LEN) {
1686                 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1687                 /* packet->data is NULL */
1688                 free(packet);
1689                 return NULL;
1690         }
1691
1692         /*
1693          *      Read no data.  Continue.
1694          *      This check is AFTER the MAX_PACKET_LEN check above, because
1695          *      if the packet is larger than MAX_PACKET_LEN, we also have
1696          *      packet->data == NULL
1697          */
1698         if ((packet->data_len == 0) || !packet->data) {
1699                 librad_log("Empty packet: Socket is not ready.");
1700                 free(packet);
1701                 return NULL;
1702         }
1703
1704         /*
1705          *      See if it's a well-formed RADIUS packet.
1706          */
1707         if (!rad_packet_ok(packet, flags)) {
1708                 rad_free(&packet);
1709                 return NULL;
1710         }
1711
1712         /*
1713          *      Remember which socket we read the packet from.
1714          */
1715         packet->sockfd = fd;
1716
1717         /*
1718          *      FIXME: Do even more filtering by only permitting
1719          *      certain IP's.  The problem is that we don't know
1720          *      how to do this properly for all possible clients...
1721          */
1722
1723         /*
1724          *      Explicitely set the VP list to empty.
1725          */
1726         packet->vps = NULL;
1727
1728         if (librad_debug) {
1729                 char host_ipaddr[128];
1730
1731                 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1732                         printf("rad_recv: %s packet from host %s port %d",
1733                                packet_codes[packet->code],
1734                                inet_ntop(packet->src_ipaddr.af,
1735                                          &packet->src_ipaddr.ipaddr,
1736                                          host_ipaddr, sizeof(host_ipaddr)),
1737                                packet->src_port);
1738                 } else {
1739                         printf("rad_recv: Packet from host %s port %d code=%d",
1740                                inet_ntop(packet->src_ipaddr.af,
1741                                          &packet->src_ipaddr.ipaddr,
1742                                          host_ipaddr, sizeof(host_ipaddr)),
1743                                packet->src_port,
1744                                packet->code);
1745                 }
1746                 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1747         }
1748
1749         return packet;
1750 }
1751
1752
1753 /*
1754  *      Verify the signature of a packet.
1755  */
1756 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1757                const char *secret)
1758 {
1759         uint8_t                 *ptr;
1760         int                     length;
1761         int                     attrlen;
1762
1763         if (!packet || !packet->data) return -1;
1764
1765         /*
1766          *      Before we allocate memory for the attributes, do more
1767          *      sanity checking.
1768          */
1769         ptr = packet->data + AUTH_HDR_LEN;
1770         length = packet->data_len - AUTH_HDR_LEN;
1771         while (length > 0) {
1772                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1773                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1774
1775                 attrlen = ptr[1];
1776
1777                 switch (ptr[0]) {
1778                 default:        /* don't do anything. */
1779                         break;
1780
1781                         /*
1782                          *      Note that more than one Message-Authenticator
1783                          *      attribute is invalid.
1784                          */
1785                 case PW_MESSAGE_AUTHENTICATOR:
1786                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1787                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1788
1789                         switch (packet->code) {
1790                         default:
1791                                 break;
1792
1793                         case PW_ACCOUNTING_REQUEST:
1794                         case PW_ACCOUNTING_RESPONSE:
1795                         case PW_DISCONNECT_REQUEST:
1796                         case PW_DISCONNECT_ACK:
1797                         case PW_DISCONNECT_NAK:
1798                         case PW_COA_REQUEST:
1799                         case PW_COA_ACK:
1800                         case PW_COA_NAK:
1801                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1802                                 break;
1803
1804                         case PW_AUTHENTICATION_ACK:
1805                         case PW_AUTHENTICATION_REJECT:
1806                         case PW_ACCESS_CHALLENGE:
1807                                 if (!original) {
1808                                         librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1809                                         return -1;
1810                                 }
1811                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1812                                 break;
1813                         }
1814
1815                         fr_hmac_md5(packet->data, packet->data_len,
1816                                     (const uint8_t *) secret, strlen(secret),
1817                                     calc_auth_vector);
1818                         if (memcmp(calc_auth_vector, msg_auth_vector,
1819                                    sizeof(calc_auth_vector)) != 0) {
1820                                 char buffer[32];
1821                                 librad_log("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1822                                            inet_ntop(packet->src_ipaddr.af,
1823                                                      &packet->src_ipaddr.ipaddr,
1824                                                      buffer, sizeof(buffer)));
1825                                 /* Silently drop packet, according to RFC 3579 */
1826                                 return -1;
1827                         } /* else the message authenticator was good */
1828
1829                         /*
1830                          *      Reinitialize Authenticators.
1831                          */
1832                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1833                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1834                         break;
1835                 } /* switch over the attributes */
1836
1837                 ptr += attrlen;
1838                 length -= attrlen;
1839         } /* loop over the packet, sanity checking the attributes */
1840
1841         /*
1842          *      It looks like a RADIUS packet, but we can't validate
1843          *      the signature.
1844          */
1845         if ((packet->code == 0) || (packet->code >= MAX_PACKET_CODE)) {
1846                 char buffer[32];
1847                 librad_log("Received Unknown packet code %d "
1848                            "from client %s port %d: Cannot validate signature.",
1849                            packet->code,
1850                            inet_ntop(packet->src_ipaddr.af,
1851                                      &packet->src_ipaddr.ipaddr,
1852                                      buffer, sizeof(buffer)),
1853                            packet->src_port);
1854                 return -1;
1855         }
1856
1857         /*
1858          *      Calculate and/or verify digest.
1859          */
1860         switch(packet->code) {
1861                 int rcode;
1862                 char buffer[32];
1863
1864                 case PW_AUTHENTICATION_REQUEST:
1865                 case PW_STATUS_SERVER:
1866                         /*
1867                          *      The authentication vector is random
1868                          *      nonsense, invented by the client.
1869                          */
1870                         break;
1871
1872                 case PW_COA_REQUEST:
1873                 case PW_DISCONNECT_REQUEST:
1874                 case PW_ACCOUNTING_REQUEST:
1875                         if (calc_acctdigest(packet, secret) > 1) {
1876                                 librad_log("Received %s packet "
1877                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
1878                                            packet_codes[packet->code],
1879                                            inet_ntop(packet->src_ipaddr.af,
1880                                                      &packet->src_ipaddr.ipaddr,
1881                                                      buffer, sizeof(buffer)));
1882                                 return -1;
1883                         }
1884                         break;
1885
1886                         /* Verify the reply digest */
1887                 case PW_AUTHENTICATION_ACK:
1888                 case PW_AUTHENTICATION_REJECT:
1889                 case PW_ACCESS_CHALLENGE:
1890                 case PW_ACCOUNTING_RESPONSE:
1891                 case PW_DISCONNECT_ACK:
1892                 case PW_DISCONNECT_NAK:
1893                 case PW_COA_ACK:
1894                 case PW_COA_NAK:
1895                         rcode = calc_replydigest(packet, original, secret);
1896                         if (rcode > 1) {
1897                                 librad_log("Received %s packet "
1898                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
1899                                            packet_codes[packet->code],
1900                                            inet_ntop(packet->src_ipaddr.af,
1901                                                      &packet->src_ipaddr.ipaddr,
1902                                                      buffer, sizeof(buffer)),
1903                                            packet->src_port,
1904                                            rcode);
1905                                 return -1;
1906                         }
1907                         break;
1908
1909                 default:
1910                         librad_log("Received Unknown packet code %d "
1911                                    "from client %s port %d: Cannot validate signature",
1912                                    packet->code,
1913                                    inet_ntop(packet->src_ipaddr.af,
1914                                              &packet->src_ipaddr.ipaddr,
1915                                                      buffer, sizeof(buffer)),
1916                                    packet->src_port);
1917                         return -1;
1918         }
1919
1920         return 0;
1921 }
1922
1923
1924 /*
1925  *      Parse a RADIUS attribute into a data structure.
1926  */
1927 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1928                         const char *secret, int attribute, int length,
1929                         const uint8_t *data)
1930 {
1931         int offset = 0;
1932         VALUE_PAIR *vp;
1933
1934         if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1935                 return NULL;
1936         }
1937
1938         /*
1939          *      If length is greater than 253, something is SERIOUSLY
1940          *      wrong.
1941          */
1942         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1943
1944         vp->length = length;
1945         vp->operator = T_OP_EQ;
1946         vp->next = NULL;
1947
1948         /*
1949          *      Handle tags.
1950          */
1951         if (vp->flags.has_tag) {
1952                 if (TAG_VALID(data[0]) ||
1953                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1954                         /*
1955                          *      Tunnel passwords REQUIRE a tag, even
1956                          *      if don't have a valid tag.
1957                          */
1958                         vp->flags.tag = data[0];
1959
1960                         if ((vp->type == PW_TYPE_STRING) ||
1961                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
1962                 }
1963         }
1964
1965         /*
1966          *      Copy the data to be decrypted
1967          */
1968         memcpy(&vp->vp_octets[0], data + offset, length - offset);
1969         vp->length -= offset;
1970
1971         /*
1972          *      Decrypt the attribute.
1973          */
1974         switch (vp->flags.encrypt) {
1975                 /*
1976                  *  User-Password
1977                  */
1978         case FLAG_ENCRYPT_USER_PASSWORD:
1979                 if (original) {
1980                         rad_pwdecode((char *)vp->vp_strvalue,
1981                                      vp->length, secret,
1982                                      original->vector);
1983                 } else {
1984                         rad_pwdecode((char *)vp->vp_strvalue,
1985                                      vp->length, secret,
1986                                      packet->vector);
1987                 }
1988                 if (vp->attribute == PW_USER_PASSWORD) {
1989                         vp->length = strlen(vp->vp_strvalue);
1990                 }
1991                 break;
1992
1993                 /*
1994                  *      Tunnel-Password's may go ONLY
1995                  *      in response packets.
1996                  */
1997         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1998                 if (!original) goto raw;
1999
2000                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2001                                         secret, original->vector) < 0) {
2002                         goto raw;
2003                 }
2004                 break;
2005
2006                 /*
2007                  *  Ascend-Send-Secret
2008                  *  Ascend-Receive-Secret
2009                  */
2010         case FLAG_ENCRYPT_ASCEND_SECRET:
2011                 if (!original) {
2012                         goto raw;
2013                 } else {
2014                         uint8_t my_digest[AUTH_VECTOR_LEN];
2015                         make_secret(my_digest,
2016                                     original->vector,
2017                                     secret, data);
2018                         memcpy(vp->vp_strvalue, my_digest,
2019                                AUTH_VECTOR_LEN );
2020                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2021                         vp->length = strlen(vp->vp_strvalue);
2022                 }
2023                 break;
2024
2025         default:
2026                 break;
2027         } /* switch over encryption flags */
2028
2029
2030         switch (vp->type) {
2031         case PW_TYPE_STRING:
2032         case PW_TYPE_OCTETS:
2033         case PW_TYPE_ABINARY:
2034                 /* nothing more to do */
2035                 break;
2036
2037         case PW_TYPE_BYTE:
2038                 if (vp->length != 1) goto raw;
2039
2040                 vp->vp_integer = vp->vp_octets[0];
2041                 break;
2042
2043
2044         case PW_TYPE_SHORT:
2045                 if (vp->length != 2) goto raw;
2046
2047                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2048                 break;
2049
2050         case PW_TYPE_INTEGER:
2051                 if (vp->length != 4) goto raw;
2052
2053                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2054                 vp->vp_integer = ntohl(vp->vp_integer);
2055
2056                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2057
2058                 /*
2059                  *      Try to get named VALUEs
2060                  */
2061                 {
2062                         DICT_VALUE *dval;
2063                         dval = dict_valbyattr(vp->attribute,
2064                                               vp->vp_integer);
2065                         if (dval) {
2066                                 strlcpy(vp->vp_strvalue,
2067                                         dval->name,
2068                                         sizeof(vp->vp_strvalue));
2069                         }
2070                 }
2071                 break;
2072
2073         case PW_TYPE_DATE:
2074                 if (vp->length != 4) goto raw;
2075
2076                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2077                 vp->vp_date = ntohl(vp->vp_date);
2078                 break;
2079
2080
2081         case PW_TYPE_IPADDR:
2082                 if (vp->length != 4) goto raw;
2083
2084                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2085                 break;
2086
2087                 /*
2088                  *      IPv6 interface ID is 8 octets long.
2089                  */
2090         case PW_TYPE_IFID:
2091                 if (vp->length != 8) goto raw;
2092                 /* vp->vp_ifid == vp->vp_octets */
2093                 break;
2094
2095                 /*
2096                  *      IPv6 addresses are 16 octets long
2097                  */
2098         case PW_TYPE_IPV6ADDR:
2099                 if (vp->length != 16) goto raw;
2100                 /* vp->vp_ipv6addr == vp->vp_octets */
2101                 break;
2102
2103                 /*
2104                  *      IPv6 prefixes are 2 to 18 octets long.
2105                  *
2106                  *      RFC 3162: The first octet is unused.
2107                  *      The second is the length of the prefix
2108                  *      the rest are the prefix data.
2109                  *
2110                  *      The prefix length can have value 0 to 128.
2111                  */
2112         case PW_TYPE_IPV6PREFIX:
2113                 if (vp->length < 2 || vp->length > 18) goto raw;
2114                 if (vp->vp_octets[1] > 128) goto raw;
2115
2116                 /*
2117                  *      FIXME: double-check that
2118                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2119                  */
2120                 if (vp->length < 18) {
2121                         memset(vp->vp_octets + vp->length, 0,
2122                                18 - vp->length);
2123                 }
2124                 break;
2125
2126         default:
2127         raw:
2128                 vp->type = PW_TYPE_OCTETS;
2129                 vp->length = length;
2130                 memcpy(vp->vp_octets, data, length);
2131
2132
2133                 /*
2134                  *      Ensure there's no encryption or tag stuff,
2135                  *      we just pass the attribute as-is.
2136                  */
2137                 memset(&vp->flags, 0, sizeof(vp->flags));
2138         }
2139
2140         return vp;
2141 }
2142
2143
2144 /*
2145  *      Calculate/check digest, and decode radius attributes.
2146  *      Returns:
2147  *      -1 on decoding error
2148  *      0 on success
2149  */
2150 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2151                const char *secret)
2152 {
2153         uint32_t                lvalue;
2154         uint32_t                vendorcode;
2155         VALUE_PAIR              **tail;
2156         VALUE_PAIR              *pair;
2157         uint8_t                 *ptr;
2158         int                     packet_length;
2159         int                     attribute;
2160         int                     attrlen;
2161         int                     vendorlen;
2162         radius_packet_t         *hdr;
2163         int                     vsa_tlen, vsa_llen;
2164         DICT_VENDOR             *dv = NULL;
2165         int                     num_attributes = 0;
2166
2167         /*
2168          *      Extract attribute-value pairs
2169          */
2170         hdr = (radius_packet_t *)packet->data;
2171         ptr = hdr->data;
2172         packet_length = packet->data_len - AUTH_HDR_LEN;
2173
2174         /*
2175          *      There may be VP's already in the packet.  Don't
2176          *      destroy them.
2177          */
2178         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2179                 /* nothing */
2180         }
2181
2182         vendorcode = 0;
2183         vendorlen  = 0;
2184         vsa_tlen = vsa_llen = 1;
2185
2186         /*
2187          *      We have to read at least two bytes.
2188          *
2189          *      rad_recv() above ensures that this is OK.
2190          */
2191         while (packet_length > 0) {
2192                 attribute = -1;
2193                 attrlen = -1;
2194
2195                 /*
2196                  *      Normal attribute, handle it like normal.
2197                  */
2198                 if (vendorcode == 0) {
2199                         /*
2200                          *      No room to read attr/length,
2201                          *      or bad attribute, or attribute is
2202                          *      too short, or attribute is too long,
2203                          *      stop processing the packet.
2204                          */
2205                         if ((packet_length < 2) ||
2206                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2207                             (ptr[1] > packet_length)) break;
2208
2209                         attribute = *ptr++;
2210                         attrlen   = *ptr++;
2211
2212                         attrlen -= 2;
2213                         packet_length  -= 2;
2214
2215                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2216
2217                         /*
2218                          *      No vendor code, or ONLY vendor code.
2219                          */
2220                         if (attrlen <= 4) goto create_pair;
2221
2222                         vendorlen = 0;
2223                 }
2224
2225                 /*
2226                  *      Handle Vendor-Specific
2227                  */
2228                 if (vendorlen == 0) {
2229                         uint8_t *subptr;
2230                         int sublen;
2231                         int myvendor;
2232
2233                         /*
2234                          *      attrlen was checked above.
2235                          */
2236                         memcpy(&lvalue, ptr, 4);
2237                         myvendor = ntohl(lvalue);
2238
2239                         /*
2240                          *      Zero isn't allowed.
2241                          */
2242                         if (myvendor == 0) goto create_pair;
2243
2244                         /*
2245                          *      This is an implementation issue.
2246                          *      We currently pack vendor into the upper
2247                          *      16 bits of a 32-bit attribute number,
2248                          *      so we can't handle vendor numbers larger
2249                          *      than 16 bits.
2250                          */
2251                         if (myvendor > 65535) goto create_pair;
2252
2253                         vsa_tlen = vsa_llen = 1;
2254                         dv = dict_vendorbyvalue(myvendor);
2255                         if (dv) {
2256                                 vsa_tlen = dv->type;
2257                                 vsa_llen = dv->length;
2258                         }
2259
2260                         /*
2261                          *      Sweep through the list of VSA's,
2262                          *      seeing if they exactly fill the
2263                          *      outer Vendor-Specific attribute.
2264                          *
2265                          *      If not, create a raw Vendor-Specific.
2266                          */
2267                         subptr = ptr + 4;
2268                         sublen = attrlen - 4;
2269
2270                         /*
2271                          *      See if we can parse it.
2272                          */
2273                         do {
2274                                 int myattr = 0;
2275
2276                                 /*
2277                                  *      Don't have a type, it's bad.
2278                                  */
2279                                 if (sublen < vsa_tlen) goto create_pair;
2280
2281                                 /*
2282                                  *      Ensure that the attribute number
2283                                  *      is OK.
2284                                  */
2285                                 switch (vsa_tlen) {
2286                                 case 1:
2287                                         myattr = subptr[0];
2288                                         break;
2289
2290                                 case 2:
2291                                         myattr = (subptr[0] << 8) | subptr[1];
2292                                         break;
2293
2294                                 case 4:
2295                                         if ((subptr[0] != 0) ||
2296                                             (subptr[1] != 0)) goto create_pair;
2297
2298                                         myattr = (subptr[2] << 8) | subptr[3];
2299                                         break;
2300
2301                                         /*
2302                                          *      Our dictionary is broken.
2303                                          */
2304                                 default:
2305                                         goto create_pair;
2306                                 }
2307
2308                                 /*
2309                                  *      Not enough room for one more
2310                                  *      attribute.  Die!
2311                                  */
2312                                 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2313                                 switch (vsa_llen) {
2314                                 case 0:
2315                                         attribute = (myvendor << 16) | myattr;
2316                                         ptr += 4 + vsa_tlen;
2317                                         attrlen -= (4 + vsa_tlen);
2318                                         packet_length -= 4 + vsa_tlen;
2319                                         goto create_pair;
2320
2321                                 case 1:
2322                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2323                                                 goto create_pair;
2324
2325                                         if (subptr[vsa_tlen] > sublen)
2326                                                 goto create_pair;
2327                                         sublen -= subptr[vsa_tlen];
2328                                         subptr += subptr[vsa_tlen];
2329                                         break;
2330
2331                                 case 2:
2332                                         if (subptr[vsa_tlen] != 0) goto create_pair;
2333                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2334                                                 goto create_pair;
2335                                         if (subptr[vsa_tlen + 1] > sublen)
2336                                                 goto create_pair;
2337                                         sublen -= subptr[vsa_tlen + 1];
2338                                         subptr += subptr[vsa_tlen + 1];
2339                                         break;
2340
2341                                         /*
2342                                          *      Our dictionaries are
2343                                          *      broken.
2344                                          */
2345                                 default:
2346                                         goto create_pair;
2347                                 }
2348                         } while (sublen > 0);
2349
2350                         vendorcode = myvendor;
2351                         vendorlen = attrlen - 4;
2352                         packet_length -= 4;
2353
2354                         ptr += 4;
2355                 }
2356
2357                 /*
2358                  *      attrlen is the length of this attribute.
2359                  *      total_len is the length of the encompassing
2360                  *      attribute.
2361                  */
2362                 switch (vsa_tlen) {
2363                 case 1:
2364                         attribute = ptr[0];
2365                         break;
2366
2367                 case 2:
2368                         attribute = (ptr[0] << 8) | ptr[1];
2369                         break;
2370
2371                 default:        /* can't hit this. */
2372                         return -1;
2373                 }
2374                 attribute |= (vendorcode << 16);
2375                 ptr += vsa_tlen;
2376
2377                 switch (vsa_llen) {
2378                 case 1:
2379                         attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2380                         break;
2381
2382                 case 2:
2383                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2384                         break;
2385
2386                 default:        /* can't hit this. */
2387                         return -1;
2388                 }
2389                 ptr += vsa_llen;
2390                 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2391                 if (vendorlen == 0) vendorcode = 0;
2392                 packet_length -= (vsa_tlen + vsa_llen);
2393
2394                 /*
2395                  *      Create the attribute, setting the default type
2396                  *      to 'octets'.  If the type in the dictionary
2397                  *      is different, then the dictionary type will
2398                  *      over-ride this one.
2399                  *
2400                  *      If the attribute has no data, then discard it.
2401                  */
2402         create_pair:
2403                 if (!attrlen) goto next;
2404
2405                 pair = rad_attr2vp(packet, original, secret,
2406                                    attribute, attrlen, ptr);
2407                 if (!pair) {
2408                         pairfree(&packet->vps);
2409                         librad_log("out of memory");
2410                         return -1;
2411                 }
2412
2413                 *tail = pair;
2414                 while (pair) {
2415                         num_attributes++;
2416                         debug_pair(pair);
2417                         tail = &pair->next;
2418                         pair = pair->next;
2419                 }
2420
2421                 /*
2422                  *      VSA's may not have been counted properly in
2423                  *      rad_packet_ok() above, as it is hard to count
2424                  *      then without using the dictionary.  We
2425                  *      therefore enforce the limits here, too.
2426                  */
2427                 if ((librad_max_attributes > 0) &&
2428                     (num_attributes > librad_max_attributes)) {
2429                         char host_ipaddr[128];
2430
2431                         pairfree(&packet->vps);
2432                         librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2433                                    inet_ntop(packet->src_ipaddr.af,
2434                                              &packet->src_ipaddr.ipaddr,
2435                                              host_ipaddr, sizeof(host_ipaddr)),
2436                                    num_attributes, librad_max_attributes);
2437                         return -1;
2438                 }
2439
2440                     next:
2441                 ptr += attrlen;
2442                 packet_length -= attrlen;
2443         }
2444
2445         /*
2446          *      Merge information from the outside world into our
2447          *      random pool.
2448          */
2449         fr_rand_seed(packet->data, AUTH_HDR_LEN);
2450
2451         return 0;
2452 }
2453
2454
2455 /*
2456  *      Encode password.
2457  *
2458  *      We assume that the passwd buffer passed is big enough.
2459  *      RFC2138 says the password is max 128 chars, so the size
2460  *      of the passwd buffer must be at least 129 characters.
2461  *      Preferably it's just MAX_STRING_LEN.
2462  *
2463  *      int *pwlen is updated to the new length of the encrypted
2464  *      password - a multiple of 16 bytes.
2465  */
2466 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2467                  const uint8_t *vector)
2468 {
2469         FR_MD5_CTX context, old;
2470         uint8_t digest[AUTH_VECTOR_LEN];
2471         int     i, n, secretlen;
2472         int     len;
2473
2474         /*
2475          *      RFC maximum is 128 bytes.
2476          *
2477          *      If length is zero, pad it out with zeros.
2478          *
2479          *      If the length isn't aligned to 16 bytes,
2480          *      zero out the extra data.
2481          */
2482         len = *pwlen;
2483
2484         if (len > 128) len = 128;
2485
2486         if (len == 0) {
2487                 memset(passwd, 0, AUTH_PASS_LEN);
2488                 len = AUTH_PASS_LEN;
2489         } else if ((len % AUTH_PASS_LEN) != 0) {
2490                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2491                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2492         }
2493         *pwlen = len;
2494
2495         /*
2496          *      Use the secret to setup the decryption digest
2497          */
2498         secretlen = strlen(secret);
2499
2500         fr_MD5Init(&context);
2501         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2502         old = context;          /* save intermediate work */
2503
2504         /*
2505          *      Encrypt it in place.  Don't bother checking
2506          *      len, as we've ensured above that it's OK.
2507          */
2508         for (n = 0; n < len; n += AUTH_PASS_LEN) {
2509                 if (n == 0) {
2510                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2511                         fr_MD5Final(digest, &context);
2512                 } else {
2513                         context = old;
2514                         fr_MD5Update(&context,
2515                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
2516                                      AUTH_PASS_LEN);
2517                         fr_MD5Final(digest, &context);
2518                 }
2519
2520                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2521                         passwd[i + n] ^= digest[i];
2522                 }
2523         }
2524
2525         return 0;
2526 }
2527
2528 /*
2529  *      Decode password.
2530  */
2531 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
2532                  const uint8_t *vector)
2533 {
2534         FR_MD5_CTX context, old;
2535         uint8_t digest[AUTH_VECTOR_LEN];
2536         int     i;
2537         size_t  n, secretlen;
2538
2539         /*
2540          *      The RFC's say that the maximum is 128.
2541          *      The buffer we're putting it into above is 254, so
2542          *      we don't need to do any length checking.
2543          */
2544         if (pwlen > 128) pwlen = 128;
2545
2546         /*
2547          *      Catch idiots.
2548          */
2549         if (pwlen == 0) goto done;
2550
2551         /*
2552          *      Use the secret to setup the decryption digest
2553          */
2554         secretlen = strlen(secret);
2555
2556         fr_MD5Init(&context);
2557         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2558         old = context;          /* save intermediate work */
2559
2560         /*
2561          *      The inverse of the code above.
2562          */
2563         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2564                 if (n == 0) {
2565                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2566                         fr_MD5Final(digest, &context);
2567
2568                         context = old;
2569                         if (pwlen > AUTH_PASS_LEN) {
2570                                 fr_MD5Update(&context, (uint8_t *) passwd,
2571                                              AUTH_PASS_LEN);
2572                         }
2573                 } else {
2574                         fr_MD5Final(digest, &context);
2575
2576                         context = old;
2577                         if (pwlen > (n + AUTH_PASS_LEN)) {
2578                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
2579                                              AUTH_PASS_LEN);
2580                         }
2581                 }
2582
2583                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2584                         passwd[i + n] ^= digest[i];
2585                 }
2586         }
2587
2588  done:
2589         passwd[pwlen] = '\0';
2590         return strlen(passwd);
2591 }
2592
2593
2594 /*
2595  *      Encode Tunnel-Password attributes when sending them out on the wire.
2596  *
2597  *      int *pwlen is updated to the new length of the encrypted
2598  *      password - a multiple of 16 bytes.
2599  *
2600  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
2601  *      value MD5 hash.
2602  */
2603 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
2604                         const uint8_t *vector)
2605 {
2606         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2607         unsigned char   digest[AUTH_VECTOR_LEN];
2608         char*   salt;
2609         int     i, n, secretlen;
2610         unsigned len, n2;
2611
2612         len = *pwlen;
2613
2614         if (len > 127) len = 127;
2615
2616         /*
2617          * Shift the password 3 positions right to place a salt and original
2618          * length, tag will be added automatically on packet send
2619          */
2620         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2621         salt = passwd;
2622         passwd += 2;
2623         /*
2624          * save original password length as first password character;
2625          */
2626         *passwd = len;
2627         len += 1;
2628
2629
2630         /*
2631          *      Generate salt.  The RFC's say:
2632          *
2633          *      The high bit of salt[0] must be set, each salt in a
2634          *      packet should be unique, and they should be random
2635          *
2636          *      So, we set the high bit, add in a counter, and then
2637          *      add in some CSPRNG data.  should be OK..
2638          */
2639         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2640                    (fr_rand() & 0x07));
2641         salt[1] = fr_rand();
2642
2643         /*
2644          *      Padd password to multiple of AUTH_PASS_LEN bytes.
2645          */
2646         n = len % AUTH_PASS_LEN;
2647         if (n) {
2648                 n = AUTH_PASS_LEN - n;
2649                 for (; n > 0; n--, len++)
2650                         passwd[len] = 0;
2651         }
2652         /* set new password length */
2653         *pwlen = len + 2;
2654
2655         /*
2656          *      Use the secret to setup the decryption digest
2657          */
2658         secretlen = strlen(secret);
2659         memcpy(buffer, secret, secretlen);
2660
2661         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2662                 if (!n2) {
2663                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2664                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2665                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2666                 } else {
2667                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2668                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2669                 }
2670
2671                 for (i = 0; i < AUTH_PASS_LEN; i++) {
2672                         passwd[i + n2] ^= digest[i];
2673                 }
2674         }
2675         passwd[n2] = 0;
2676         return 0;
2677 }
2678
2679 /*
2680  *      Decode Tunnel-Password encrypted attributes.
2681  *
2682  *      Defined in RFC-2868, this uses a two char SALT along with the
2683  *      initial intermediate value, to differentiate it from the
2684  *      above.
2685  */
2686 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
2687                         const uint8_t *vector)
2688 {
2689         FR_MD5_CTX  context, old;
2690         uint8_t         digest[AUTH_VECTOR_LEN];
2691         int             secretlen;
2692         unsigned        i, n, len, reallen;
2693
2694         len = *pwlen;
2695
2696         /*
2697          *      We need at least a salt.
2698          */
2699         if (len < 2) {
2700                 librad_log("tunnel password is too short");
2701                 return -1;
2702         }
2703
2704         /*
2705          *      There's a salt, but no password.  Or, there's a salt
2706          *      and a 'data_len' octet.  It's wrong, but at least we
2707          *      can figure out what it means: the password is empty.
2708          *
2709          *      Note that this means we ignore the 'data_len' field,
2710          *      if the attribute length tells us that there's no
2711          *      more data.  So the 'data_len' field may be wrong,
2712          *      but that's ok...
2713          */
2714         if (len <= 3) {
2715                 passwd[0] = 0;
2716                 *pwlen = 0;
2717                 return 0;
2718         }
2719
2720         len -= 2;               /* discount the salt */
2721
2722         /*
2723          *      Use the secret to setup the decryption digest
2724          */
2725         secretlen = strlen(secret);
2726
2727         fr_MD5Init(&context);
2728         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2729         old = context;          /* save intermediate work */
2730
2731         /*
2732          *      Set up the initial key:
2733          *
2734          *       b(1) = MD5(secret + vector + salt)
2735          */
2736         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2737         fr_MD5Update(&context, passwd, 2);
2738
2739         reallen = 0;
2740         for (n = 0; n < len; n += AUTH_PASS_LEN) {
2741                 int base = 0;
2742
2743                 if (n == 0) {
2744                         fr_MD5Final(digest, &context);
2745
2746                         context = old;
2747
2748                         /*
2749                          *      A quick check: decrypt the first octet
2750                          *      of the password, which is the
2751                          *      'data_len' field.  Ensure it's sane.
2752                          */
2753                         reallen = passwd[2] ^ digest[0];
2754                         if (reallen >= len) {
2755                                 librad_log("tunnel password is too long for the attribute");
2756                                 return -1;
2757                         }
2758
2759                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2760
2761                         base = 1;
2762                 } else {
2763                         fr_MD5Final(digest, &context);
2764
2765                         context = old;
2766                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2767                 }
2768
2769                 for (i = base; i < AUTH_PASS_LEN; i++) {
2770                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2771                 }
2772         }
2773
2774         /*
2775          *      See make_tunnel_password, above.
2776          */
2777         if (reallen > 239) reallen = 239;
2778
2779         *pwlen = reallen;
2780         passwd[reallen] = 0;
2781
2782         return reallen;
2783 }
2784
2785 /*
2786  *      Encode a CHAP password
2787  *
2788  *      FIXME: might not work with Ascend because
2789  *      we use vp->length, and Ascend gear likes
2790  *      to send an extra '\0' in the string!
2791  */
2792 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2793                     VALUE_PAIR *password)
2794 {
2795         int             i;
2796         uint8_t         *ptr;
2797         uint8_t         string[MAX_STRING_LEN * 2 + 1];
2798         VALUE_PAIR      *challenge;
2799
2800         /*
2801          *      Sanity check the input parameters
2802          */
2803         if ((packet == NULL) || (password == NULL)) {
2804                 return -1;
2805         }
2806
2807         /*
2808          *      Note that the password VP can be EITHER
2809          *      a User-Password attribute (from a check-item list),
2810          *      or a CHAP-Password attribute (the client asking
2811          *      the library to encode it).
2812          */
2813
2814         i = 0;
2815         ptr = string;
2816         *ptr++ = id;
2817
2818         i++;
2819         memcpy(ptr, password->vp_strvalue, password->length);
2820         ptr += password->length;
2821         i += password->length;
2822
2823         /*
2824          *      Use Chap-Challenge pair if present,
2825          *      Request-Authenticator otherwise.
2826          */
2827         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2828         if (challenge) {
2829                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2830                 i += challenge->length;
2831         } else {
2832                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2833                 i += AUTH_VECTOR_LEN;
2834         }
2835
2836         *output = id;
2837         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2838
2839         return 0;
2840 }
2841
2842
2843 /*
2844  *      Seed the random number generator.
2845  *
2846  *      May be called any number of times.
2847  */
2848 void fr_rand_seed(const void *data, size_t size)
2849 {
2850         uint32_t hash;
2851
2852         /*
2853          *      Ensure that the pool is initialized.
2854          */
2855         if (!fr_rand_initialized) {
2856                 int fd;
2857
2858                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2859
2860                 fd = open("/dev/urandom", O_RDONLY);
2861                 if (fd >= 0) {
2862                         size_t total;
2863                         ssize_t this;
2864
2865                         total = this = 0;
2866                         while (total < sizeof(fr_rand_pool.randrsl)) {
2867                                 this = read(fd, fr_rand_pool.randrsl,
2868                                             sizeof(fr_rand_pool.randrsl) - total);
2869                                 if ((this < 0) && (errno != EINTR)) break;
2870                                 if (this > 0) total += this;
2871                         }
2872                         close(fd);
2873                 } else {
2874                         fr_rand_pool.randrsl[0] = fd;
2875                         fr_rand_pool.randrsl[1] = time(NULL);
2876                         fr_rand_pool.randrsl[2] = errno;
2877                 }
2878
2879                 fr_randinit(&fr_rand_pool, 1);
2880                 fr_rand_pool.randcnt = 0;
2881                 fr_rand_initialized = 1;
2882         }
2883
2884         if (!data) return;
2885
2886         /*
2887          *      Hash the user data
2888          */
2889         hash = fr_rand();
2890         if (!hash) hash = fr_rand();
2891         hash = fr_hash_update(data, size, hash);
2892
2893         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2894 }
2895
2896
2897 /*
2898  *      Return a 32-bit random number.
2899  */
2900 uint32_t fr_rand(void)
2901 {
2902         uint32_t num;
2903
2904         /*
2905          *      Ensure that the pool is initialized.
2906          */
2907         if (!fr_rand_initialized) {
2908                 fr_rand_seed(NULL, 0);
2909         }
2910
2911         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2912         if (fr_rand_pool.randcnt == 256) {
2913                 fr_rand_pool.randcnt = 0;
2914                 fr_isaac(&fr_rand_pool);
2915         }
2916
2917         return num;
2918 }
2919
2920
2921 /*
2922  *      Allocate a new RADIUS_PACKET
2923  */
2924 RADIUS_PACKET *rad_alloc(int newvector)
2925 {
2926         RADIUS_PACKET   *rp;
2927
2928         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2929                 librad_log("out of memory");
2930                 return NULL;
2931         }
2932         memset(rp, 0, sizeof(*rp));
2933         rp->id = -1;
2934         rp->offset = -1;
2935
2936         if (newvector) {
2937                 int i;
2938                 uint32_t hash, base;
2939
2940                 /*
2941                  *      Don't expose the actual contents of the random
2942                  *      pool.
2943                  */
2944                 base = fr_rand();
2945                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2946                         hash = fr_rand() ^ base;
2947                         memcpy(rp->vector + i, &hash, sizeof(hash));
2948                 }
2949         }
2950         fr_rand();              /* stir the pool again */
2951
2952         return rp;
2953 }
2954
2955 /*
2956  *      Free a RADIUS_PACKET
2957  */
2958 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2959 {
2960         RADIUS_PACKET *radius_packet;
2961
2962         if (!radius_packet_ptr || !*radius_packet_ptr) return;
2963         radius_packet = *radius_packet_ptr;
2964
2965         free(radius_packet->data);
2966
2967         pairfree(&radius_packet->vps);
2968
2969         free(radius_packet);
2970
2971         *radius_packet_ptr = NULL;
2972 }