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