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