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