ade05c5f76f6456a4a05b0d2ef4e25faa3844dd3
[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 fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
58
59 typedef struct radius_packet_t {
60   uint8_t       code;
61   uint8_t       id;
62   uint8_t       length[2];
63   uint8_t       vector[AUTH_VECTOR_LEN];
64   uint8_t       data[1];
65 } radius_packet_t;
66
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
70 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
71
72 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
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 void fr_printf_log(const char *fmt, ...)
129 {
130         va_list ap;
131
132         va_start(ap, fmt);
133         if ((fr_debug_flag == 0) || !fr_log_fp) {
134                 va_end(ap);
135                 return;
136         }
137
138         vfprintf(fr_log_fp, fmt, ap);
139         va_end(ap);
140
141         return;
142 }
143
144 void rad_print_hex(RADIUS_PACKET *packet)
145 {
146         int i;
147
148         if (!packet->data) return;
149
150         printf("  Code:\t\t%u\n", packet->data[0]);
151         printf("  Id:\t\t%u\n", packet->data[1]);
152         printf("  Length:\t%u\n", ((packet->data[2] << 8) |
153                                    (packet->data[3])));
154         printf("  Vector:\t");
155         for (i = 4; i < 20; i++) {
156                 printf("%02x", packet->data[i]);
157         }
158         printf("\n");
159
160         if (packet->data_len > 20) {
161                 int total;
162                 const uint8_t *ptr;
163                 printf("  Data:");
164
165                 total = packet->data_len - 20;
166                 ptr = packet->data + 20;
167
168                 while (total > 0) {
169                         int attrlen;
170
171                         printf("\t\t");
172                         if (total < 2) { /* too short */
173                                 printf("%02x\n", *ptr);
174                                 break;
175                         }
176
177                         if (ptr[1] > total) { /* too long */
178                                 for (i = 0; i < total; i++) {
179                                         printf("%02x ", ptr[i]);
180                                 }
181                                 break;
182                         }
183
184                         printf("%02x  %02x  ", ptr[0], ptr[1]);
185                         attrlen = ptr[1] - 2;
186                         ptr += 2;
187                         total -= 2;
188
189                         for (i = 0; i < attrlen; i++) {
190                                 if ((i > 0) && ((i & 0x0f) == 0x00))
191                                         printf("\t\t\t");
192                                 printf("%02x ", ptr[i]);
193                                 if ((i & 0x0f) == 0x0f) printf("\n");
194                         }
195
196                         if ((attrlen & 0x0f) != 0x00) printf("\n");
197
198                         ptr += attrlen;
199                         total -= attrlen;
200                 }
201         }
202         fflush(stdout);
203 }
204
205
206 /*
207  *      Wrapper for sendto which handles sendfromto, IPv6, and all
208  *      possible combinations.
209  */
210 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
211                       fr_ipaddr_t *src_ipaddr, int src_port,
212                       fr_ipaddr_t *dst_ipaddr, int dst_port)
213 {
214         int rcode;
215         struct sockaddr_storage dst;
216         socklen_t               sizeof_dst;
217
218 #ifdef WITH_UDPFROMTO
219         struct sockaddr_storage src;
220         socklen_t               sizeof_src;
221
222         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
223 #else
224         src_port = src_port;    /* -Wunused */
225 #endif
226
227         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
228                 return -1;
229         }
230
231 #ifdef WITH_UDPFROMTO
232         /*
233          *      And if they don't specify a source IP address, don't
234          *      use udpfromto.
235          */
236         if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
237             (src_ipaddr->af != AF_UNSPEC) &&
238             !fr_inaddr_any(src_ipaddr)) {
239                 rcode = sendfromto(sockfd, data, data_len, flags,
240                                    (struct sockaddr *)&src, sizeof_src,
241                                    (struct sockaddr *)&dst, sizeof_dst);
242                 goto done;
243         }
244 #else
245         src_ipaddr = src_ipaddr; /* -Wunused */
246 #endif
247
248         /*
249          *      No udpfromto, fail gracefully.
250          */
251         rcode = sendto(sockfd, data, data_len, flags,
252                        (struct sockaddr *) &dst, sizeof_dst);
253 #ifdef WITH_UDPFROMTO
254 done:
255 #endif
256         if (rcode < 0) {
257                 DEBUG("rad_send() failed: %s\n", strerror(errno));
258         }
259
260         return rcode;
261 }
262
263
264 void rad_recv_discard(int sockfd)
265 {
266         uint8_t                 header[4];
267         struct sockaddr_storage src;
268         socklen_t               sizeof_src = sizeof(src);
269
270         recvfrom(sockfd, header, sizeof(header), 0,
271                  (struct sockaddr *)&src, &sizeof_src);
272 }
273
274
275 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
276                         int *code)
277 {
278         ssize_t                 data_len, packet_len;
279         uint8_t                 header[4];
280         struct sockaddr_storage src;
281         socklen_t               sizeof_src = sizeof(src);
282
283         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
284                             (struct sockaddr *)&src, &sizeof_src);
285         if (data_len < 0) {
286                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
287                 return -1;
288         }
289
290         /*
291          *      Too little data is available, discard the packet.
292          */
293         if (data_len < 4) {
294                 recvfrom(sockfd, header, sizeof(header), 0,
295                          (struct sockaddr *)&src, &sizeof_src);
296                 return 1;
297
298         } else {                /* we got 4 bytes of data. */
299                 /*
300                  *      See how long the packet says it is.
301                  */
302                 packet_len = (header[2] * 256) + header[3];
303
304                 /*
305                  *      The length in the packet says it's less than
306                  *      a RADIUS header length: discard it.
307                  */
308                 if (packet_len < AUTH_HDR_LEN) {
309                         recvfrom(sockfd, header, sizeof(header), 0,
310                                  (struct sockaddr *)&src, &sizeof_src);
311                         return 1;
312
313                         /*
314                          *      Enforce RFC requirements, for sanity.
315                          *      Anything after 4k will be discarded.
316                          */
317                 } else if (packet_len > MAX_PACKET_LEN) {
318                         recvfrom(sockfd, header, sizeof(header), 0,
319                                  (struct sockaddr *)&src, &sizeof_src);
320                         return 1;
321                 }
322         }
323
324         /*
325          *      Convert AF.  If unknown, discard packet.
326          */
327         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
328                 recvfrom(sockfd, header, sizeof(header), 0,
329                          (struct sockaddr *)&src, &sizeof_src);
330                 return 1;
331         }
332
333         *code = header[0];
334
335         /*
336          *      The packet says it's this long, but the actual UDP
337          *      size could still be smaller.
338          */
339         return packet_len;
340 }
341
342
343 /*
344  *      wrapper for recvfrom, which handles recvfromto, IPv6, and all
345  *      possible combinations.
346  */
347 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
348                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
349                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
350 {
351         struct sockaddr_storage src;
352         struct sockaddr_storage dst;
353         socklen_t               sizeof_src = sizeof(src);
354         socklen_t               sizeof_dst = sizeof(dst);
355         ssize_t                 data_len;
356         uint8_t                 header[4];
357         void                    *buf;
358         size_t                  len;
359         int                     port;
360
361         memset(&src, 0, sizeof_src);
362         memset(&dst, 0, sizeof_dst);
363
364         /*
365          *      Get address family, etc. first, so we know if we
366          *      need to do udpfromto.
367          *
368          *      FIXME: udpfromto also does this, but it's not
369          *      a critical problem.
370          */
371         if (getsockname(sockfd, (struct sockaddr *)&dst,
372                         &sizeof_dst) < 0) return -1;
373
374         /*
375          *      Read the length of the packet, from the packet.
376          *      This lets us allocate the buffer to use for
377          *      reading the rest of the packet.
378          */
379         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
380                             (struct sockaddr *)&src, &sizeof_src);
381         if (data_len < 0) {
382                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
383                 return -1;
384         }
385
386         /*
387          *      Too little data is available, discard the packet.
388          */
389         if (data_len < 4) {
390                 recvfrom(sockfd, header, sizeof(header), flags,
391                          (struct sockaddr *)&src, &sizeof_src);
392                 return 0;
393
394         } else {                /* we got 4 bytes of data. */
395                 /*
396                  *      See how long the packet says it is.
397                  */
398                 len = (header[2] * 256) + header[3];
399
400                 /*
401                  *      The length in the packet says it's less than
402                  *      a RADIUS header length: discard it.
403                  */
404                 if (len < AUTH_HDR_LEN) {
405                         recvfrom(sockfd, header, sizeof(header), flags,
406                                  (struct sockaddr *)&src, &sizeof_src);
407                         return 0;
408
409                         /*
410                          *      Enforce RFC requirements, for sanity.
411                          *      Anything after 4k will be discarded.
412                          */
413                 } else if (len > MAX_PACKET_LEN) {
414                         recvfrom(sockfd, header, sizeof(header), flags,
415                                  (struct sockaddr *)&src, &sizeof_src);
416                         return len;
417                 }
418         }
419
420         buf = malloc(len);
421         if (!buf) return -1;
422
423         /*
424          *      Receive the packet.  The OS will discard any data in the
425          *      packet after "len" bytes.
426          */
427 #ifdef WITH_UDPFROMTO
428         if ((dst.ss_family == AF_INET) || (dst.ss_family == AF_INET6)) {
429                 data_len = recvfromto(sockfd, buf, len, flags,
430                                       (struct sockaddr *)&src, &sizeof_src,
431                                       (struct sockaddr *)&dst, &sizeof_dst);
432         } else
433 #endif
434                 /*
435                  *      No udpfromto, fail gracefully.
436                  */
437                 data_len = recvfrom(sockfd, buf, len, flags,
438                                     (struct sockaddr *)&src, &sizeof_src);
439         if (data_len < 0) {
440                 free(buf);
441                 return data_len;
442         }
443
444         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
445                 free(buf);
446                 return -1;      /* Unknown address family, Die Die Die! */
447         }
448         *src_port = port;
449
450         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
451         *dst_port = port;
452
453         /*
454          *      Different address families should never happen.
455          */
456         if (src.ss_family != dst.ss_family) {
457                 free(buf);
458                 return -1;
459         }
460
461         /*
462          *      Tell the caller about the data
463          */
464         *pbuf = buf;
465
466         return data_len;
467 }
468
469
470 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
471 /*************************************************************************
472  *
473  *      Function: make_secret
474  *
475  *      Purpose: Build an encrypted secret value to return in a reply
476  *               packet.  The secret is hidden by xoring with a MD5 digest
477  *               created from the shared secret and the authentication
478  *               vector.  We put them into MD5 in the reverse order from
479  *               that used when encrypting passwords to RADIUS.
480  *
481  *************************************************************************/
482 static void make_secret(uint8_t *digest, const uint8_t *vector,
483                         const char *secret, const uint8_t *value, size_t length)
484 {
485         FR_MD5_CTX context;
486         int             i;
487
488         fr_MD5Init(&context);
489         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
490         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
491         fr_MD5Final(digest, &context);
492
493         for ( i = 0; i < length; i++ ) {
494                 digest[i] ^= value[i];
495         }
496 }
497
498 #define MAX_PASS_LEN (128)
499 static void make_passwd(uint8_t *output, size_t *outlen,
500                         const uint8_t *input, size_t inlen,
501                         const char *secret, const uint8_t *vector)
502 {
503         FR_MD5_CTX context, old;
504         uint8_t digest[AUTH_VECTOR_LEN];
505         uint8_t passwd[MAX_PASS_LEN];
506         int     i, n;
507         int     len;
508
509         /*
510          *      If the length is zero, round it up.
511          */
512         len = inlen;
513
514         if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
515
516         memcpy(passwd, input, len);
517         if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
518
519         if (len == 0) {
520                 len = AUTH_PASS_LEN;
521         }
522
523         else if ((len & 0x0f) != 0) {
524                 len += 0x0f;
525                 len &= ~0x0f;
526         }
527         *outlen = len;
528
529         fr_MD5Init(&context);
530         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
531         old = context;
532
533         /*
534          *      Do first pass.
535          */
536         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
537
538         for (n = 0; n < len; n += AUTH_PASS_LEN) {
539                 if (n > 0) {
540                         context = old;
541                         fr_MD5Update(&context,
542                                        passwd + n - AUTH_PASS_LEN,
543                                        AUTH_PASS_LEN);
544                 }
545
546                 fr_MD5Final(digest, &context);
547                 for (i = 0; i < AUTH_PASS_LEN; i++) {
548                         passwd[i + n] ^= digest[i];
549                 }
550         }
551
552         memcpy(output, passwd, len);
553 }
554
555 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
556                                const uint8_t *input, size_t inlen, size_t room,
557                                const char *secret, const uint8_t *vector)
558 {
559         FR_MD5_CTX context, old;
560         uint8_t digest[AUTH_VECTOR_LEN];
561         size_t  i, n;
562         size_t  encrypted_len;
563
564         /*
565          *      The password gets encoded with a 1-byte "length"
566          *      field.  Ensure that it doesn't overflow.
567          */
568         if (room > 253) room = 253;
569
570         /*
571          *      Limit the maximum size of the input password.  2 bytes
572          *      are taken up by the salt, and one by the encoded
573          *      "length" field.  Note that if we have a tag, the
574          *      "room" will be 252 octets, not 253 octets.
575          */
576         if (inlen > (room - 3)) inlen = room - 3;
577
578         /*
579          *      Length of the encrypted data is the clear-text
580          *      password length plus one byte which encodes the length
581          *      of the password.  We round up to the nearest encoding
582          *      block.  Note that this can result in the encoding
583          *      length being more than 253 octets.
584          */
585         encrypted_len = inlen + 1;
586         if ((encrypted_len & 0x0f) != 0) {
587                 encrypted_len += 0x0f;
588                 encrypted_len &= ~0x0f;
589         }
590
591         /*
592          *      We need 2 octets for the salt, followed by the actual
593          *      encrypted data.
594          */
595         if (encrypted_len > (room - 2)) encrypted_len = room - 2;
596
597         *outlen = encrypted_len + 2;    /* account for the salt */
598
599         /*
600          *      Copy the password over, and zero-fill the remainder.
601          */
602         memcpy(output + 3, input, inlen);
603         memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
604
605         /*
606          *      Generate salt.  The RFCs say:
607          *
608          *      The high bit of salt[0] must be set, each salt in a
609          *      packet should be unique, and they should be random
610          *
611          *      So, we set the high bit, add in a counter, and then
612          *      add in some CSPRNG data.  should be OK..
613          */
614         output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
615                      (fr_rand() & 0x07));
616         output[1] = fr_rand();
617         output[2] = inlen;      /* length of the password string */
618
619         fr_MD5Init(&context);
620         fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
621         old = context;
622
623         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
624         fr_MD5Update(&context, &output[0], 2);
625
626         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
627                 size_t block_len;
628
629                 if (n > 0) {
630                         context = old;
631                         fr_MD5Update(&context,
632                                        output + 2 + n - AUTH_PASS_LEN,
633                                        AUTH_PASS_LEN);
634                 }
635
636                 fr_MD5Final(digest, &context);
637
638                 if ((2 + n + AUTH_PASS_LEN) < room) {
639                         block_len = AUTH_PASS_LEN;
640                 } else {
641                         block_len = room - 2 - n;
642                 }
643
644                 for (i = 0; i < block_len; i++) {
645                         output[i + 2 + n] ^= digest[i];
646                 }
647         }
648 }
649
650 /*
651  *      Returns the end of the data.
652  */
653 static uint8_t *vp2data(const RADIUS_PACKET *packet,
654                         const RADIUS_PACKET *original,
655                         const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
656                         size_t room)
657 {
658         uint32_t lvalue;
659         size_t len;
660         const uint8_t *data;
661         uint8_t array[4];
662
663         /*
664          *      Set up the default sources for the data.
665          */
666         data = vp->vp_octets;
667         len = vp->length;
668
669         switch(vp->type) {
670         case PW_TYPE_STRING:
671         case PW_TYPE_OCTETS:
672         case PW_TYPE_IFID:
673         case PW_TYPE_IPV6ADDR:
674         case PW_TYPE_IPV6PREFIX:
675         case PW_TYPE_ABINARY:
676                 /* nothing more to do */
677                 break;
678
679         case PW_TYPE_BYTE:
680                 len = 1;        /* just in case */
681                 array[0] = vp->vp_integer & 0xff;
682                 data = array;
683                 break;
684
685         case PW_TYPE_SHORT:
686                 len = 2;        /* just in case */
687                 array[0] = (vp->vp_integer >> 8) & 0xff;
688                 array[1] = vp->vp_integer & 0xff;
689                 data = array;
690                 break;
691
692         case PW_TYPE_INTEGER:
693                 len = 4;        /* just in case */
694                 lvalue = htonl(vp->vp_integer);
695                 memcpy(array, &lvalue, sizeof(lvalue));
696                 data = array;
697                 break;
698
699         case PW_TYPE_IPADDR:
700                 data = (const uint8_t *) &vp->vp_ipaddr;
701                 len = 4;        /* just in case */
702                 break;
703
704                 /*
705                  *  There are no tagged date attributes.
706                  */
707         case PW_TYPE_DATE:
708                 lvalue = htonl(vp->vp_date);
709                 data = (const uint8_t *) &lvalue;
710                 len = 4;        /* just in case */
711                 break;
712
713         case PW_TYPE_SIGNED:
714         {
715                 int32_t slvalue;
716
717                 len = 4;        /* just in case */
718                 slvalue = htonl(vp->vp_signed);
719                 memcpy(array, &slvalue, sizeof(slvalue));
720                 break;
721         }
722
723         case PW_TYPE_TLV:
724                 data = vp->vp_tlv;
725                 if (!data) {
726                         fr_strerror_printf("ERROR: Cannot encode NULL TLV");
727                         return NULL;
728                 }
729                 break;
730
731         default:                /* unknown type: ignore it */
732                 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
733                 return NULL;
734         }
735
736         /*
737          *      Bound the data to the calling size
738          */
739         if (len > room) len = room;
740
741         /*
742          *      Encrypt the various password styles
743          *
744          *      Attributes with encrypted values MUST be less than
745          *      128 bytes long.
746          */
747         if (packet) switch (vp->flags.encrypt) {
748         case FLAG_ENCRYPT_USER_PASSWORD:
749                 make_passwd(ptr, &len, data, len,
750                             secret, packet->vector);
751                 break;
752
753         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
754                 /*
755                  *      Check if there's enough room.  If there isn't,
756                  *      we discard the attribute.
757                  *
758                  *      This is ONLY a problem if we have multiple VSA's
759                  *      in one Vendor-Specific, though.
760                  */
761                 if (room < 18) return ptr;
762
763                 switch (packet->code) {
764                 case PW_AUTHENTICATION_ACK:
765                 case PW_AUTHENTICATION_REJECT:
766                 case PW_ACCESS_CHALLENGE:
767                 default:
768                         if (!original) {
769                                 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
770                                 return NULL;
771                         }
772                         make_tunnel_passwd(ptr, &len, data, len, room,
773                                            secret, original->vector);
774                         break;
775                 case PW_ACCOUNTING_REQUEST:
776                 case PW_DISCONNECT_REQUEST:
777                 case PW_COA_REQUEST:
778                         make_tunnel_passwd(ptr, &len, data, len, room,
779                                            secret, packet->vector);
780                         break;
781                 }
782                 break;
783
784                 /*
785                  *      The code above ensures that this attribute
786                  *      always fits.
787                  */
788         case FLAG_ENCRYPT_ASCEND_SECRET:
789 #ifndef NDEBUG
790                 if (data == array) return NULL;
791 #endif
792                 if (len > AUTH_VECTOR_LEN) len = AUTH_VECTOR_LEN;
793                 make_secret(ptr, packet->vector, secret, data, len);
794                 break;
795
796
797         default:
798                 /*
799                  *      Just copy the data over
800                  */
801                 memcpy(ptr, data, len);
802                 break;
803
804         } else {                /* no packet */
805                 memcpy(ptr, data, len);
806         }
807
808         return ptr + len;
809 }
810
811
812 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
813 {
814         int maxattr = 0;
815         int length;
816         unsigned int attribute;
817         uint8_t *ptr, *end;
818         VALUE_PAIR *vp, *tlv;
819
820         attribute = vps->attribute & 0xffff00ff;
821         maxattr = vps->attribute & 0x0ff;
822
823         tlv = paircreate(attribute, PW_TYPE_TLV);
824         if (!tlv) return NULL;
825
826         tlv->length = 0;
827         for (vp = vps; vp != NULL; vp = vp->next) {
828                 /*
829                  *      Group the attributes ONLY until we see a
830                  *      non-TLV attribute.
831                  */
832                 if (!vp->flags.is_tlv ||
833                     vp->flags.encoded ||
834                     (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
835                     ((vp->attribute & 0xffff00ff) != attribute) ||
836                     ((vp->attribute & 0x0000ff00) < maxattr)) {
837                         break;
838                 }
839
840                 maxattr = vp->attribute & 0xff00;
841                 tlv->length += vp->length + 2;
842         }
843
844         if (!tlv->length) {
845                 pairfree(&tlv);
846                 return NULL;
847         }
848
849         tlv->vp_tlv = malloc(tlv->length);
850         if (!tlv->vp_tlv) {
851                 pairfree(&tlv);
852                 return NULL;
853         }
854
855         ptr = tlv->vp_tlv;
856         maxattr = vps->attribute & 0x0ff;
857         for (vp = vps; vp != NULL; vp = vp->next) {
858                 if (!vp->flags.is_tlv ||
859                     vp->flags.encoded ||
860                     (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
861                     ((vp->attribute & 0xffff00ff) != attribute) ||
862                     ((vp->attribute & 0x0000ff00) < maxattr)) {
863                         break;
864                 }
865
866                 maxattr = vp->attribute & 0xff00;
867                 end = vp2data(NULL, NULL, NULL, vp, ptr + 2,
868                               tlv->vp_tlv + tlv->length - ptr);
869                 if (!end) {
870                         vp->length = ptr - vp->vp_tlv;
871                         return tlv; /* should be a more serious error... */
872                 }
873
874                 length = (end - ptr);
875                 if (length > 255) {
876                         pairfree(&tlv);
877                         return NULL;
878                 }
879
880                 /*
881                  *      Pack the attribute.
882                  */
883                 ptr[0] = (vp->attribute & 0xff00) >> 8;
884                 ptr[1] = length;
885
886                 ptr += ptr[1];
887                 vp->flags.encoded = 1;
888         }
889
890         return tlv;
891 }
892
893 /*
894  *      Pack data without any encryption.
895  *      start == start of RADIUS attribute
896  *      ptr   == continuation byte (i.e. one after length)
897  */
898 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
899                                uint8_t *ptr)
900 {
901         size_t left, piece;
902         size_t hsize = (ptr - start);
903         uint8_t *this = start;
904         const uint8_t *data;
905         uint8_t header[16];
906         
907         /*
908          *      If it's too long and marked as encrypted, ignore it.
909          */
910         if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
911                 return 0;
912         }
913         
914         memcpy(header, start, hsize);
915
916         left = vp->length;
917         
918         switch (vp->type) {
919         case PW_TYPE_TLV:
920                 data = vp->vp_tlv;
921                 break;
922
923         case PW_TYPE_OCTETS:
924         case PW_TYPE_STRING:
925                 data = vp->vp_octets;
926                 break;
927
928                 /*
929                  *      This is invalid.
930                  */
931         default:
932                 return 0;
933         }
934         
935         while (left > 0) {
936                 memcpy(this, header, hsize);
937                 ptr = this + hsize;
938                 
939                 /*
940                  *      254 to account for
941                  *      continuation flag.
942                  */
943                 if (left > (254 - hsize)) {
944                         piece = 254 - hsize;
945                         *(ptr++) = 0x80;
946                 } else {
947                         piece = left;
948                         *(ptr++) = 0x00;
949                 }
950                 
951                 memcpy(ptr, data, piece);
952                 this[1] = hsize + piece + 1;
953
954                 /*
955                  *      
956                  */
957                 this[hsize - 1] = hsize - 6 + 1 + piece;
958                 data += piece;
959                 ptr += piece;
960                 left -= piece;
961                 this = ptr;
962         }
963         
964         return (ptr - start);
965 }
966
967
968 /*
969  *      Parse a data structure into a RADIUS attribute.
970  */
971 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
972                 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
973 {
974         int             vendorcode;
975         int             len, total_length;
976         uint32_t        lvalue;
977         uint8_t         *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
978         uint8_t         *end;
979
980         ptr = start;
981         end = ptr + 255;
982         total_length = 0;
983         length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
984
985         /*
986          *      For interoperability, always put vendor attributes
987          *      into their own VSA.
988          */
989         if ((vendorcode = VENDOR(vp->attribute)) == 0) {
990                 *(ptr++) = vp->attribute & 0xFF;
991                 length_ptr = ptr;
992                 *(ptr++) = 2;
993                 total_length += 2;
994
995         } else {
996                 int vsa_tlen = 1;
997                 int vsa_llen = 1;
998                 int vsa_offset = 0;
999                 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
1000
1001                 /*
1002                  *      This must be an RFC-format attribute.  If it
1003                  *      wasn't, then the "decode" function would have
1004                  *      made a Vendor-Specific attribute (i.e. type
1005                  *      26), and we would have "vendorcode == 0" here.
1006                  */
1007                 if (dv) {
1008                         vsa_tlen = dv->type;
1009                         vsa_llen = dv->length;
1010                         if (dv->flags) vsa_offset = 1;
1011                 }
1012
1013                 /*
1014                  *      Build a VSA header.
1015                  */
1016                 *ptr++ = PW_VENDOR_SPECIFIC;
1017                 vsa_length_ptr = ptr;
1018                 *ptr++ = 6;
1019                 lvalue = htonl(vendorcode);
1020                 memcpy(ptr, &lvalue, 4);
1021                 ptr += 4;
1022                 total_length += 6;
1023
1024                 switch (vsa_tlen) {
1025                 case 1:
1026                         ptr[0] = (vp->attribute & 0xFF);
1027                         break;
1028
1029                 case 2:
1030                         ptr[0] = ((vp->attribute >> 8) & 0xFF);
1031                         ptr[1] = (vp->attribute & 0xFF);
1032                         break;
1033
1034                 case 4:
1035                         ptr[0] = 0;
1036                         ptr[1] = 0;
1037                         ptr[2] = ((vp->attribute >> 8) & 0xFF);
1038                         ptr[3] = (vp->attribute & 0xFF);
1039                         break;
1040
1041                 default:
1042                         return 0; /* silently discard it */
1043                 }
1044                 ptr += vsa_tlen;
1045
1046                 switch (vsa_llen) {
1047                 case 0:
1048                         length_ptr = vsa_length_ptr;
1049                         vsa_length_ptr = NULL;
1050                         break;
1051                 case 1:
1052                         ptr[0] = 0;
1053                         length_ptr = ptr;
1054                         break;
1055                 case 2:
1056                         ptr[0] = 0;
1057                         ptr[1] = 0;
1058                         length_ptr = ptr + 1;
1059                         break;
1060
1061                 default:
1062                         return 0; /* silently discard it */
1063                 }
1064                 ptr += vsa_llen;
1065
1066                 /*
1067                  *      Allow for some continuation.
1068                  */
1069                 if (vsa_offset) {
1070                         /*
1071                          *      Allow TLV's to be encoded, if someone
1072                          *      manages to somehow encode the sub-tlv's.
1073                          *
1074                          *      FIXME: Keep track of room in the packet!
1075                          */
1076                         if (vp->length > (((size_t) 254) - (ptr - start))) {
1077                                 return rad_vp2continuation(vp, start, ptr);
1078                         }
1079
1080                         ptr[0] = 0x00;
1081                         ptr++;
1082
1083                         /*
1084                          *      sub-TLV's can only be in one format.
1085                          */
1086                         if (vp->flags.is_tlv) {
1087                                 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1088                                 tlv_length_ptr = ptr;
1089                                 *(ptr++) = 2;
1090                                 vsa_offset += 2;
1091                         }
1092                 }
1093
1094                 total_length += vsa_tlen + vsa_llen + vsa_offset;
1095                 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1096                 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1097         }
1098
1099         /*
1100          *      Insert tags for string attributes.  They go BEFORE
1101          *      the string.
1102          */
1103         if (vp->flags.has_tag && (vp->type == PW_TYPE_STRING) &&
1104             (TAG_VALID(vp->flags.tag) ||
1105              (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
1106                 ptr[0] = vp->flags.tag;
1107                 end = vp2data(packet, original, secret, vp, ptr + 1,
1108                               (end - ptr) - 1);
1109         } else {
1110                 end = vp2data(packet, original, secret, vp, ptr,
1111                               (end - ptr));
1112         }
1113         if (!end) return -1;
1114
1115         /*
1116          *      Insert tags for integer attributes.  They go at the START
1117          *      of the integer, and over-write the first byte.
1118          */
1119         if (vp->flags.has_tag && (vp->type == PW_TYPE_INTEGER)) {
1120                 ptr[0] = vp->flags.tag;
1121         }
1122
1123         /*
1124          *      RFC 2865 section 5 says that zero-length attributes
1125          *      MUST NOT be sent.
1126          *
1127          *      ... and the WiMAX forum ignores this... because of
1128          *      one vendor.  Don't they have anything better to do
1129          *      with their time?
1130          */
1131         if ((end == ptr) &&
1132             (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1133
1134         len = (end - ptr);
1135
1136         /*
1137          *      Update the various lengths.
1138          */
1139         *length_ptr += len;
1140         if (vsa_length_ptr) *vsa_length_ptr += len;
1141         if (tlv_length_ptr) *tlv_length_ptr += len;
1142         total_length += len;
1143
1144         return total_length;    /* of attribute */
1145 }
1146
1147
1148 /*
1149  *      Encode a packet.
1150  */
1151 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1152                const char *secret)
1153 {
1154         radius_packet_t *hdr;
1155         uint8_t         *ptr;
1156         uint16_t        total_length;
1157         int             len;
1158         VALUE_PAIR      *reply;
1159         const char      *what;
1160         char            ip_buffer[128];
1161
1162         /*
1163          *      For simplicity in the following logic, we allow
1164          *      the attributes to "overflow" the 4k maximum
1165          *      RADIUS packet size, by one attribute.
1166          *
1167          *      It's uint32_t, for alignment purposes.
1168          */
1169         uint32_t        data[(MAX_PACKET_LEN + 256) / 4];
1170
1171         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1172                 what = fr_packet_codes[packet->code];
1173         } else {
1174                 what = "Reply";
1175         }
1176
1177         DEBUG("Sending %s of id %d to %s port %d\n",
1178               what, packet->id,
1179               inet_ntop(packet->dst_ipaddr.af,
1180                         &packet->dst_ipaddr.ipaddr,
1181                         ip_buffer, sizeof(ip_buffer)),
1182               packet->dst_port);
1183
1184         /*
1185          *      Double-check some things based on packet code.
1186          */
1187         switch (packet->code) {
1188         case PW_AUTHENTICATION_ACK:
1189         case PW_AUTHENTICATION_REJECT:
1190         case PW_ACCESS_CHALLENGE:
1191                 if (!original) {
1192                         fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1193                         return -1;
1194                 }
1195                 break;
1196
1197                 /*
1198                  *      These packet vectors start off as all zero.
1199                  */
1200         case PW_ACCOUNTING_REQUEST:
1201         case PW_DISCONNECT_REQUEST:
1202         case PW_COA_REQUEST:
1203                 memset(packet->vector, 0, sizeof(packet->vector));
1204                 break;
1205
1206         default:
1207                 break;
1208         }
1209
1210         /*
1211          *      Use memory on the stack, until we know how
1212          *      large the packet will be.
1213          */
1214         hdr = (radius_packet_t *) data;
1215
1216         /*
1217          *      Build standard header
1218          */
1219         hdr->code = packet->code;
1220         hdr->id = packet->id;
1221
1222         memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1223
1224         total_length = AUTH_HDR_LEN;
1225
1226         /*
1227          *      Load up the configuration values for the user
1228          */
1229         ptr = hdr->data;
1230         packet->offset = 0;
1231
1232         /*
1233          *      FIXME: Loop twice over the reply list.  The first time,
1234          *      calculate the total length of data.  The second time,
1235          *      allocate the memory, and fill in the VP's.
1236          *
1237          *      Hmm... this may be slower than just doing a small
1238          *      memcpy.
1239          */
1240
1241         /*
1242          *      Loop over the reply attributes for the packet.
1243          */
1244         for (reply = packet->vps; reply; reply = reply->next) {
1245                 /*
1246                  *      Ignore non-wire attributes
1247                  */
1248                 if ((VENDOR(reply->attribute) == 0) &&
1249                     ((reply->attribute & 0xFFFF) > 0xff)) {
1250 #ifndef NDEBUG
1251                         /*
1252                          *      Permit the admin to send BADLY formatted
1253                          *      attributes with a debug build.
1254                          */
1255                         if (reply->attribute == PW_RAW_ATTRIBUTE) {
1256                                 memcpy(ptr, reply->vp_octets, reply->length);
1257                                 len = reply->length;
1258                                 goto next;
1259                         }
1260 #endif
1261                         continue;
1262                 }
1263
1264                 /*
1265                  *      Set the Message-Authenticator to the correct
1266                  *      length and initial value.
1267                  */
1268                 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1269                         reply->length = AUTH_VECTOR_LEN;
1270                         memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1271
1272                         /*
1273                          *      Cache the offset to the
1274                          *      Message-Authenticator
1275                          */
1276                         packet->offset = total_length;
1277                 }
1278
1279                 /*
1280                  *      Print out ONLY the attributes which
1281                  *      we're sending over the wire, and print
1282                  *      them out BEFORE they're encrypted.
1283                  */
1284                 debug_pair(reply);
1285
1286                 /*
1287                  *      Print them in order, even if they were encoded
1288                  *      already.
1289                  */
1290                 len = 0;
1291                 if (reply->flags.encoded) goto next;
1292
1293                 if (reply->flags.is_tlv) {
1294                         VALUE_PAIR *tlv = rad_vp2tlv(reply);
1295                         if (tlv) {
1296                                 tlv->next = reply->next;
1297                                 reply->next = tlv;
1298                         }
1299
1300                         /*
1301                          *      The encoded flag MUST be set in reply!
1302                          */
1303                         reply = reply->next;
1304                 }
1305
1306                 len = rad_vp2attr(packet, original, secret, reply, ptr);
1307
1308                 if (len < 0) return -1;
1309
1310                 /*
1311                  *      Check that the packet is no more than 4k in
1312                  *      size, AFTER writing the attribute past the 4k
1313                  *      boundary, but BEFORE deciding to increase the
1314                  *      size of the packet. Note that the 'data'
1315                  *      buffer, above, is one attribute longer than
1316                  *      necessary, in order to permit this overflow.
1317                  */
1318                 if ((total_length + len) > MAX_PACKET_LEN) {
1319                         DEBUG("WARNING: Attributes are too long for packet.  Discarding data past %d bytes", total_length);
1320                         break;
1321                 }
1322
1323         next:
1324                 ptr += len;
1325                 total_length += len;
1326         } /* done looping over all attributes */
1327
1328         /*
1329          *      Fill in the rest of the fields, and copy the data over
1330          *      from the local stack to the newly allocated memory.
1331          *
1332          *      Yes, all this 'memcpy' is slow, but it means
1333          *      that we only allocate the minimum amount of
1334          *      memory for a request.
1335          */
1336         packet->data_len = total_length;
1337         packet->data = (uint8_t *) malloc(packet->data_len);
1338         if (!packet->data) {
1339                 fr_strerror_printf("Out of memory");
1340                 return -1;
1341         }
1342
1343         memcpy(packet->data, hdr, packet->data_len);
1344         hdr = (radius_packet_t *) packet->data;
1345
1346         total_length = htons(total_length);
1347         memcpy(hdr->length, &total_length, sizeof(total_length));
1348
1349         return 0;
1350 }
1351
1352
1353 /*
1354  *      Sign a previously encoded packet.
1355  */
1356 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1357              const char *secret)
1358 {
1359         radius_packet_t *hdr = (radius_packet_t *)packet->data;
1360
1361         /*
1362          *      It wasn't assigned an Id, this is bad!
1363          */
1364         if (packet->id < 0) {
1365                 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1366                 return -1;
1367         }
1368
1369         if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1370             (packet->offset < 0)) {
1371                 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1372                 return -1;
1373         }
1374
1375         /*
1376          *      If there's a Message-Authenticator, update it
1377          *      now, BEFORE updating the authentication vector.
1378          */
1379         if (packet->offset > 0) {
1380                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1381
1382                 switch (packet->code) {
1383                 case PW_ACCOUNTING_RESPONSE:
1384                         if (original && original->code == PW_STATUS_SERVER) {
1385                                 goto do_ack;
1386                         }
1387
1388                 case PW_ACCOUNTING_REQUEST:
1389                 case PW_DISCONNECT_REQUEST:
1390                 case PW_DISCONNECT_ACK:
1391                 case PW_DISCONNECT_NAK:
1392                 case PW_COA_REQUEST:
1393                 case PW_COA_ACK:
1394                 case PW_COA_NAK:
1395                         memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1396                         break;
1397
1398                 do_ack:
1399                 case PW_AUTHENTICATION_ACK:
1400                 case PW_AUTHENTICATION_REJECT:
1401                 case PW_ACCESS_CHALLENGE:
1402                         if (!original) {
1403                                 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1404                                 return -1;
1405                         }
1406                         memcpy(hdr->vector, original->vector,
1407                                AUTH_VECTOR_LEN);
1408                         break;
1409
1410                 default:        /* others have vector already set to zero */
1411                         break;
1412
1413                 }
1414
1415                 /*
1416                  *      Set the authentication vector to zero,
1417                  *      calculate the HMAC, and put it
1418                  *      into the Message-Authenticator
1419                  *      attribute.
1420                  */
1421                 fr_hmac_md5(packet->data, packet->data_len,
1422                             (const uint8_t *) secret, strlen(secret),
1423                             calc_auth_vector);
1424                 memcpy(packet->data + packet->offset + 2,
1425                        calc_auth_vector, AUTH_VECTOR_LEN);
1426
1427                 /*
1428                  *      Copy the original request vector back
1429                  *      to the raw packet.
1430                  */
1431                 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1432         }
1433
1434         /*
1435          *      Switch over the packet code, deciding how to
1436          *      sign the packet.
1437          */
1438         switch (packet->code) {
1439                 /*
1440                  *      Request packets are not signed, bur
1441                  *      have a random authentication vector.
1442                  */
1443         case PW_AUTHENTICATION_REQUEST:
1444         case PW_STATUS_SERVER:
1445                 break;
1446
1447                 /*
1448                  *      Reply packets are signed with the
1449                  *      authentication vector of the request.
1450                  */
1451         default:
1452                 {
1453                         uint8_t digest[16];
1454
1455                         FR_MD5_CTX      context;
1456                         fr_MD5Init(&context);
1457                         fr_MD5Update(&context, packet->data, packet->data_len);
1458                         fr_MD5Update(&context, (const uint8_t *) secret,
1459                                      strlen(secret));
1460                         fr_MD5Final(digest, &context);
1461
1462                         memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1463                         memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1464                         break;
1465                 }
1466         }/* switch over packet codes */
1467
1468         return 0;
1469 }
1470
1471 /*
1472  *      Reply to the request.  Also attach
1473  *      reply attribute value pairs and any user message provided.
1474  */
1475 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1476              const char *secret)
1477 {
1478         VALUE_PAIR              *reply;
1479         const char              *what;
1480         char                    ip_buffer[128];
1481
1482         /*
1483          *      Maybe it's a fake packet.  Don't send it.
1484          */
1485         if (!packet || (packet->sockfd < 0)) {
1486                 return 0;
1487         }
1488
1489         if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1490                 what = fr_packet_codes[packet->code];
1491         } else {
1492                 what = "Reply";
1493         }
1494
1495         /*
1496          *  First time through, allocate room for the packet
1497          */
1498         if (!packet->data) {
1499                 /*
1500                  *      Encode the packet.
1501                  */
1502                 if (rad_encode(packet, original, secret) < 0) {
1503                         return -1;
1504                 }
1505
1506                 /*
1507                  *      Re-sign it, including updating the
1508                  *      Message-Authenticator.
1509                  */
1510                 if (rad_sign(packet, original, secret) < 0) {
1511                         return -1;
1512                 }
1513
1514                 /*
1515                  *      If packet->data points to data, then we print out
1516                  *      the VP list again only for debugging.
1517                  */
1518         } else if (fr_debug_flag) {
1519                 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1520                       inet_ntop(packet->dst_ipaddr.af,
1521                                 &packet->dst_ipaddr.ipaddr,
1522                                 ip_buffer, sizeof(ip_buffer)),
1523                       packet->dst_port);
1524
1525                 for (reply = packet->vps; reply; reply = reply->next) {
1526                         if ((VENDOR(reply->attribute) == 0) &&
1527                             ((reply->attribute & 0xFFFF) > 0xff)) continue;
1528                         debug_pair(reply);
1529                 }
1530         }
1531
1532         /*
1533          *      And send it on it's way.
1534          */
1535         return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1536                           &packet->src_ipaddr, packet->src_port,
1537                           &packet->dst_ipaddr, packet->dst_port);
1538 }
1539
1540 /*
1541  *      Do a comparison of two authentication digests by comparing
1542  *      the FULL digest.  Otehrwise, the server can be subject to
1543  *      timing attacks that allow attackers find a valid message
1544  *      authenticator.
1545  *
1546  *      http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1547  */
1548 int rad_digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1549 {
1550         int result = 0;
1551         size_t i;
1552
1553         for (i = 0; i < length; i++) {
1554                 result |= a[i] ^ b[i];
1555         }
1556
1557         return result;          /* 0 is OK, !0 is !OK, just like memcmp */
1558 }
1559
1560
1561 /*
1562  *      Validates the requesting client NAS.  Calculates the
1563  *      Request Authenticator based on the clients private key.
1564  */
1565 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1566 {
1567         uint8_t         digest[AUTH_VECTOR_LEN];
1568         FR_MD5_CTX              context;
1569
1570         /*
1571          *      Zero out the auth_vector in the received packet.
1572          *      Then append the shared secret to the received packet,
1573          *      and calculate the MD5 sum. This must be the same
1574          *      as the original MD5 sum (packet->vector).
1575          */
1576         memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1577
1578         /*
1579          *  MD5(packet + secret);
1580          */
1581         fr_MD5Init(&context);
1582         fr_MD5Update(&context, packet->data, packet->data_len);
1583         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1584         fr_MD5Final(digest, &context);
1585
1586         /*
1587          *      Return 0 if OK, 2 if not OK.
1588          */
1589         if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1590         return 0;
1591 }
1592
1593
1594 /*
1595  *      Validates the requesting client NAS.  Calculates the
1596  *      Response Authenticator based on the clients private key.
1597  */
1598 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1599                             const char *secret)
1600 {
1601         uint8_t         calc_digest[AUTH_VECTOR_LEN];
1602         FR_MD5_CTX              context;
1603
1604         /*
1605          *      Very bad!
1606          */
1607         if (original == NULL) {
1608                 return 3;
1609         }
1610
1611         /*
1612          *  Copy the original vector in place.
1613          */
1614         memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1615
1616         /*
1617          *  MD5(packet + secret);
1618          */
1619         fr_MD5Init(&context);
1620         fr_MD5Update(&context, packet->data, packet->data_len);
1621         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1622         fr_MD5Final(calc_digest, &context);
1623
1624         /*
1625          *  Copy the packet's vector back to the packet.
1626          */
1627         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1628
1629         /*
1630          *      Return 0 if OK, 2 if not OK.
1631          */
1632         if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1633         return 0;
1634 }
1635
1636
1637 /*
1638  *      See if the data pointed to by PTR is a valid RADIUS packet.
1639  *
1640  *      packet is not 'const * const' because we may update data_len,
1641  *      if there's more data in the UDP packet than in the RADIUS packet.
1642  */
1643 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1644 {
1645         uint8_t                 *attr;
1646         int                     totallen;
1647         int                     count;
1648         radius_packet_t         *hdr;
1649         char                    host_ipaddr[128];
1650         int                     require_ma = 0;
1651         int                     seen_ma = 0;
1652         int                     num_attributes;
1653
1654         /*
1655          *      Check for packets smaller than the packet header.
1656          *
1657          *      RFC 2865, Section 3., subsection 'length' says:
1658          *
1659          *      "The minimum length is 20 ..."
1660          */
1661         if (packet->data_len < AUTH_HDR_LEN) {
1662                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1663                            inet_ntop(packet->src_ipaddr.af,
1664                                      &packet->src_ipaddr.ipaddr,
1665                                      host_ipaddr, sizeof(host_ipaddr)),
1666                            packet->data_len, AUTH_HDR_LEN);
1667                 return 0;
1668         }
1669
1670         /*
1671          *      RFC 2865, Section 3., subsection 'length' says:
1672          *
1673          *      " ... and maximum length is 4096."
1674          */
1675         if (packet->data_len > MAX_PACKET_LEN) {
1676                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1677                            inet_ntop(packet->src_ipaddr.af,
1678                                      &packet->src_ipaddr.ipaddr,
1679                                      host_ipaddr, sizeof(host_ipaddr)),
1680                            packet->data_len, MAX_PACKET_LEN);
1681                 return 0;
1682         }
1683
1684         /*
1685          *      Check for packets with mismatched size.
1686          *      i.e. We've received 128 bytes, and the packet header
1687          *      says it's 256 bytes long.
1688          */
1689         totallen = (packet->data[2] << 8) | packet->data[3];
1690         hdr = (radius_packet_t *)packet->data;
1691
1692         /*
1693          *      Code of 0 is not understood.
1694          *      Code of 16 or greate is not understood.
1695          */
1696         if ((hdr->code == 0) ||
1697             (hdr->code >= FR_MAX_PACKET_CODE)) {
1698                 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1699                            inet_ntop(packet->src_ipaddr.af,
1700                                      &packet->src_ipaddr.ipaddr,
1701                                      host_ipaddr, sizeof(host_ipaddr)),
1702                            hdr->code);
1703                 return 0;
1704         }
1705
1706         /*
1707          *      Message-Authenticator is required in Status-Server
1708          *      packets, otherwise they can be trivially forged.
1709          */
1710         if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1711
1712         /*
1713          *      It's also required if the caller asks for it.
1714          */
1715         if (flags) require_ma = 1;
1716
1717         /*
1718          *      Repeat the length checks.  This time, instead of
1719          *      looking at the data we received, look at the value
1720          *      of the 'length' field inside of the packet.
1721          *
1722          *      Check for packets smaller than the packet header.
1723          *
1724          *      RFC 2865, Section 3., subsection 'length' says:
1725          *
1726          *      "The minimum length is 20 ..."
1727          */
1728         if (totallen < AUTH_HDR_LEN) {
1729                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1730                            inet_ntop(packet->src_ipaddr.af,
1731                                      &packet->src_ipaddr.ipaddr,
1732                                      host_ipaddr, sizeof(host_ipaddr)),
1733                            totallen, AUTH_HDR_LEN);
1734                 return 0;
1735         }
1736
1737         /*
1738          *      And again, for the value of the 'length' field.
1739          *
1740          *      RFC 2865, Section 3., subsection 'length' says:
1741          *
1742          *      " ... and maximum length is 4096."
1743          */
1744         if (totallen > MAX_PACKET_LEN) {
1745                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1746                            inet_ntop(packet->src_ipaddr.af,
1747                                      &packet->src_ipaddr.ipaddr,
1748                                      host_ipaddr, sizeof(host_ipaddr)),
1749                            totallen, MAX_PACKET_LEN);
1750                 return 0;
1751         }
1752
1753         /*
1754          *      RFC 2865, Section 3., subsection 'length' says:
1755          *
1756          *      "If the packet is shorter than the Length field
1757          *      indicates, it MUST be silently discarded."
1758          *
1759          *      i.e. No response to the NAS.
1760          */
1761         if (packet->data_len < totallen) {
1762                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1763                            inet_ntop(packet->src_ipaddr.af,
1764                                      &packet->src_ipaddr.ipaddr,
1765                                      host_ipaddr, sizeof(host_ipaddr)),
1766                            packet->data_len, totallen);
1767                 return 0;
1768         }
1769
1770         /*
1771          *      RFC 2865, Section 3., subsection 'length' says:
1772          *
1773          *      "Octets outside the range of the Length field MUST be
1774          *      treated as padding and ignored on reception."
1775          */
1776         if (packet->data_len > totallen) {
1777                 /*
1778                  *      We're shortening the packet below, but just
1779                  *      to be paranoid, zero out the extra data.
1780                  */
1781                 memset(packet->data + totallen, 0, packet->data_len - totallen);
1782                 packet->data_len = totallen;
1783         }
1784
1785         /*
1786          *      Walk through the packet's attributes, ensuring that
1787          *      they add up EXACTLY to the size of the packet.
1788          *
1789          *      If they don't, then the attributes either under-fill
1790          *      or over-fill the packet.  Any parsing of the packet
1791          *      is impossible, and will result in unknown side effects.
1792          *
1793          *      This would ONLY happen with buggy RADIUS implementations,
1794          *      or with an intentional attack.  Either way, we do NOT want
1795          *      to be vulnerable to this problem.
1796          */
1797         attr = hdr->data;
1798         count = totallen - AUTH_HDR_LEN;
1799         num_attributes = 0;
1800
1801         while (count > 0) {
1802                 /*
1803                  *      We need at least 2 bytes to check the
1804                  *      attribute header.
1805                  */
1806                 if (count < 2) {
1807                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
1808                                    inet_ntop(packet->src_ipaddr.af,
1809                                              &packet->src_ipaddr.ipaddr,
1810                                              host_ipaddr, sizeof(host_ipaddr)));
1811                         return 0;
1812                 }
1813
1814                 /*
1815                  *      Attribute number zero is NOT defined.
1816                  */
1817                 if (attr[0] == 0) {
1818                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1819                                    inet_ntop(packet->src_ipaddr.af,
1820                                              &packet->src_ipaddr.ipaddr,
1821                                              host_ipaddr, sizeof(host_ipaddr)));
1822                         return 0;
1823                 }
1824
1825                 /*
1826                  *      Attributes are at LEAST as long as the ID & length
1827                  *      fields.  Anything shorter is an invalid attribute.
1828                  */
1829                 if (attr[1] < 2) {
1830                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
1831                                    inet_ntop(packet->src_ipaddr.af,
1832                                              &packet->src_ipaddr.ipaddr,
1833                                              host_ipaddr, sizeof(host_ipaddr)),
1834                                    attr[0]);
1835                         return 0;
1836                 }
1837
1838                 /*
1839                  *      If there are fewer bytes in the packet than in the
1840                  *      attribute, it's a bad packet.
1841                  */
1842                 if (count < attr[1]) {
1843                         fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
1844                                    inet_ntop(packet->src_ipaddr.af,
1845                                              &packet->src_ipaddr.ipaddr,
1846                                              host_ipaddr, sizeof(host_ipaddr)),
1847                                            attr[0]);
1848                         return 0;
1849                 }
1850
1851                 /*
1852                  *      Sanity check the attributes for length.
1853                  */
1854                 switch (attr[0]) {
1855                 default:        /* don't do anything by default */
1856                         break;
1857
1858                         /*
1859                          *      If there's an EAP-Message, we require
1860                          *      a Message-Authenticator.
1861                          */
1862                 case PW_EAP_MESSAGE:
1863                         require_ma = 1;
1864                         break;
1865
1866                 case PW_MESSAGE_AUTHENTICATOR:
1867                         if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1868                                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1869                                            inet_ntop(packet->src_ipaddr.af,
1870                                                      &packet->src_ipaddr.ipaddr,
1871                                                      host_ipaddr, sizeof(host_ipaddr)),
1872                                            attr[1] - 2);
1873                                 return 0;
1874                         }
1875                         seen_ma = 1;
1876                         break;
1877                 }
1878
1879                 /*
1880                  *      FIXME: Look up the base 255 attributes in the
1881                  *      dictionary, and switch over their type.  For
1882                  *      integer/date/ip, the attribute length SHOULD
1883                  *      be 6.
1884                  */
1885                 count -= attr[1];       /* grab the attribute length */
1886                 attr += attr[1];
1887                 num_attributes++;       /* seen one more attribute */
1888         }
1889
1890         /*
1891          *      If the attributes add up to a packet, it's allowed.
1892          *
1893          *      If not, we complain, and throw the packet away.
1894          */
1895         if (count != 0) {
1896                 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1897                            inet_ntop(packet->src_ipaddr.af,
1898                                      &packet->src_ipaddr.ipaddr,
1899                                      host_ipaddr, sizeof(host_ipaddr)));
1900                 return 0;
1901         }
1902
1903         /*
1904          *      If we're configured to look for a maximum number of
1905          *      attributes, and we've seen more than that maximum,
1906          *      then throw the packet away, as a possible DoS.
1907          */
1908         if ((fr_max_attributes > 0) &&
1909             (num_attributes > fr_max_attributes)) {
1910                 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1911                            inet_ntop(packet->src_ipaddr.af,
1912                                      &packet->src_ipaddr.ipaddr,
1913                                      host_ipaddr, sizeof(host_ipaddr)),
1914                            num_attributes, fr_max_attributes);
1915                 return 0;
1916         }
1917
1918         /*
1919          *      http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1920          *
1921          *      A packet with an EAP-Message attribute MUST also have
1922          *      a Message-Authenticator attribute.
1923          *
1924          *      A Message-Authenticator all by itself is OK, though.
1925          *
1926          *      Similarly, Status-Server packets MUST contain
1927          *      Message-Authenticator attributes.
1928          */
1929         if (require_ma && ! seen_ma) {
1930                 fr_strerror_printf("WARNING: Insecure packet from host %s:  Packet does not contain required Message-Authenticator attribute",
1931                            inet_ntop(packet->src_ipaddr.af,
1932                                      &packet->src_ipaddr.ipaddr,
1933                                      host_ipaddr, sizeof(host_ipaddr)));
1934                 return 0;
1935         }
1936
1937         /*
1938          *      Fill RADIUS header fields
1939          */
1940         packet->code = hdr->code;
1941         packet->id = hdr->id;
1942         memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1943
1944         return 1;
1945 }
1946
1947
1948 /*
1949  *      Receive UDP client requests, and fill in
1950  *      the basics of a RADIUS_PACKET structure.
1951  */
1952 RADIUS_PACKET *rad_recv(int fd, int flags)
1953 {
1954         int sock_flags = 0;
1955         RADIUS_PACKET           *packet;
1956
1957         /*
1958          *      Allocate the new request data structure
1959          */
1960         if ((packet = malloc(sizeof(*packet))) == NULL) {
1961                 fr_strerror_printf("out of memory");
1962                 return NULL;
1963         }
1964         memset(packet, 0, sizeof(*packet));
1965
1966         if (flags & 0x02) {
1967                 sock_flags = MSG_PEEK;
1968                 flags &= ~0x02;
1969         }
1970
1971         packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1972                                         &packet->src_ipaddr, &packet->src_port,
1973                                         &packet->dst_ipaddr, &packet->dst_port);
1974
1975         /*
1976          *      Check for socket errors.
1977          */
1978         if (packet->data_len < 0) {
1979                 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1980                 /* packet->data is NULL */
1981                 free(packet);
1982                 return NULL;
1983         }
1984
1985         /*
1986          *      If the packet is too big, then rad_recvfrom did NOT
1987          *      allocate memory.  Instead, it just discarded the
1988          *      packet.
1989          */
1990         if (packet->data_len > MAX_PACKET_LEN) {
1991                 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1992                 /* packet->data is NULL */
1993                 free(packet);
1994                 return NULL;
1995         }
1996
1997         /*
1998          *      Read no data.  Continue.
1999          *      This check is AFTER the MAX_PACKET_LEN check above, because
2000          *      if the packet is larger than MAX_PACKET_LEN, we also have
2001          *      packet->data == NULL
2002          */
2003         if ((packet->data_len == 0) || !packet->data) {
2004                 fr_strerror_printf("Empty packet: Socket is not ready.");
2005                 free(packet);
2006                 return NULL;
2007         }
2008
2009         /*
2010          *      See if it's a well-formed RADIUS packet.
2011          */
2012         if (!rad_packet_ok(packet, flags)) {
2013                 rad_free(&packet);
2014                 return NULL;
2015         }
2016
2017         /*
2018          *      Remember which socket we read the packet from.
2019          */
2020         packet->sockfd = fd;
2021
2022         /*
2023          *      FIXME: Do even more filtering by only permitting
2024          *      certain IP's.  The problem is that we don't know
2025          *      how to do this properly for all possible clients...
2026          */
2027
2028         /*
2029          *      Explicitely set the VP list to empty.
2030          */
2031         packet->vps = NULL;
2032
2033         if (fr_debug_flag) {
2034                 char host_ipaddr[128];
2035
2036                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2037                         DEBUG("rad_recv: %s packet from host %s port %d",
2038                               fr_packet_codes[packet->code],
2039                               inet_ntop(packet->src_ipaddr.af,
2040                                         &packet->src_ipaddr.ipaddr,
2041                                         host_ipaddr, sizeof(host_ipaddr)),
2042                               packet->src_port);
2043                 } else {
2044                         DEBUG("rad_recv: Packet from host %s port %d code=%d",
2045                               inet_ntop(packet->src_ipaddr.af,
2046                                         &packet->src_ipaddr.ipaddr,
2047                                         host_ipaddr, sizeof(host_ipaddr)),
2048                               packet->src_port,
2049                               packet->code);
2050                 }
2051                 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
2052         }
2053
2054         return packet;
2055 }
2056
2057
2058 /*
2059  *      Verify the Request/Response Authenticator
2060  *      (and Message-Authenticator if present) of a packet.
2061  */
2062 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2063                const char *secret)
2064 {
2065         uint8_t                 *ptr;
2066         int                     length;
2067         int                     attrlen;
2068
2069         if (!packet || !packet->data) return -1;
2070
2071         /*
2072          *      Before we allocate memory for the attributes, do more
2073          *      sanity checking.
2074          */
2075         ptr = packet->data + AUTH_HDR_LEN;
2076         length = packet->data_len - AUTH_HDR_LEN;
2077         while (length > 0) {
2078                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2079                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2080
2081                 attrlen = ptr[1];
2082
2083                 switch (ptr[0]) {
2084                 default:        /* don't do anything. */
2085                         break;
2086
2087                         /*
2088                          *      Note that more than one Message-Authenticator
2089                          *      attribute is invalid.
2090                          */
2091                 case PW_MESSAGE_AUTHENTICATOR:
2092                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2093                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2094
2095                         switch (packet->code) {
2096                         default:
2097                                 break;
2098
2099                         case PW_ACCOUNTING_RESPONSE:
2100                                 if (original &&
2101                                     (original->code == PW_STATUS_SERVER)) {
2102                                         goto do_ack;
2103                                 }
2104
2105                         case PW_ACCOUNTING_REQUEST:
2106                         case PW_DISCONNECT_REQUEST:
2107                         case PW_COA_REQUEST:
2108                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2109                                 break;
2110
2111                         do_ack:
2112                         case PW_AUTHENTICATION_ACK:
2113                         case PW_AUTHENTICATION_REJECT:
2114                         case PW_ACCESS_CHALLENGE:
2115                         case PW_DISCONNECT_ACK:
2116                         case PW_DISCONNECT_NAK:
2117                         case PW_COA_ACK:
2118                         case PW_COA_NAK:
2119                                 if (!original) {
2120                                         fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2121                                         return -1;
2122                                 }
2123                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2124                                 break;
2125                         }
2126
2127                         fr_hmac_md5(packet->data, packet->data_len,
2128                                     (const uint8_t *) secret, strlen(secret),
2129                                     calc_auth_vector);
2130                         if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2131                                    sizeof(calc_auth_vector)) != 0) {
2132                                 char buffer[32];
2133                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
2134                                            inet_ntop(packet->src_ipaddr.af,
2135                                                      &packet->src_ipaddr.ipaddr,
2136                                                      buffer, sizeof(buffer)));
2137                                 /* Silently drop packet, according to RFC 3579 */
2138                                 return -1;
2139                         } /* else the message authenticator was good */
2140
2141                         /*
2142                          *      Reinitialize Authenticators.
2143                          */
2144                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2145                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2146                         break;
2147                 } /* switch over the attributes */
2148
2149                 ptr += attrlen;
2150                 length -= attrlen;
2151         } /* loop over the packet, sanity checking the attributes */
2152
2153         /*
2154          *      It looks like a RADIUS packet, but we don't know what it is
2155          *      so can't validate the authenticators.
2156          */
2157         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2158                 char buffer[32];
2159                 fr_strerror_printf("Received Unknown packet code %d "
2160                            "from client %s port %d: Cannot validate Request/Response Authenticator.",
2161                            packet->code,
2162                            inet_ntop(packet->src_ipaddr.af,
2163                                      &packet->src_ipaddr.ipaddr,
2164                                      buffer, sizeof(buffer)),
2165                            packet->src_port);
2166                 return -1;
2167         }
2168
2169         /*
2170          *      Calculate and/or verify Request or Response Authenticator.
2171          */
2172         switch(packet->code) {
2173                 int rcode;
2174                 char buffer[32];
2175
2176                 case PW_AUTHENTICATION_REQUEST:
2177                 case PW_STATUS_SERVER:
2178                         /*
2179                          *      The authentication vector is random
2180                          *      nonsense, invented by the client.
2181                          */
2182                         break;
2183
2184                 case PW_COA_REQUEST:
2185                 case PW_DISCONNECT_REQUEST:
2186                 case PW_ACCOUNTING_REQUEST:
2187                         if (calc_acctdigest(packet, secret) > 1) {
2188                                 fr_strerror_printf("Received %s packet "
2189                                            "from client %s with invalid Request Authenticator!  (Shared secret is incorrect.)",
2190                                            fr_packet_codes[packet->code],
2191                                            inet_ntop(packet->src_ipaddr.af,
2192                                                      &packet->src_ipaddr.ipaddr,
2193                                                      buffer, sizeof(buffer)));
2194                                 return -1;
2195                         }
2196                         break;
2197
2198                         /* Verify the reply digest */
2199                 case PW_AUTHENTICATION_ACK:
2200                 case PW_AUTHENTICATION_REJECT:
2201                 case PW_ACCESS_CHALLENGE:
2202                 case PW_ACCOUNTING_RESPONSE:
2203                 case PW_DISCONNECT_ACK:
2204                 case PW_DISCONNECT_NAK:
2205                 case PW_COA_ACK:
2206                 case PW_COA_NAK:
2207                         rcode = calc_replydigest(packet, original, secret);
2208                         if (rcode > 1) {
2209                                 fr_strerror_printf("Received %s packet "
2210                                            "from home server %s port %d with invalid Response Authenticator!  (Shared secret is incorrect.)",
2211                                            fr_packet_codes[packet->code],
2212                                            inet_ntop(packet->src_ipaddr.af,
2213                                                      &packet->src_ipaddr.ipaddr,
2214                                                      buffer, sizeof(buffer)),
2215                                            packet->src_port);
2216                                 return -1;
2217                         }
2218                         break;
2219
2220                 default:
2221                         fr_strerror_printf("Received Unknown packet code %d "
2222                                    "from client %s port %d: Cannot validate Request/Response Authenticator",
2223                                    packet->code,
2224                                    inet_ntop(packet->src_ipaddr.af,
2225                                              &packet->src_ipaddr.ipaddr,
2226                                                      buffer, sizeof(buffer)),
2227                                    packet->src_port);
2228                         return -1;
2229         }
2230
2231         return 0;
2232 }
2233
2234
2235 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2236                            const RADIUS_PACKET *original,
2237                            const char *secret,
2238                            unsigned int attribute, size_t length,
2239                            const uint8_t *data, VALUE_PAIR *vp)
2240 {
2241         int offset = 0;
2242
2243         /*
2244          *      If length is greater than 253, something is SERIOUSLY
2245          *      wrong.
2246          */
2247         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2248
2249         vp->length = length;
2250         vp->operator = T_OP_EQ;
2251         vp->next = NULL;
2252
2253         /*
2254          *      Handle tags.
2255          */
2256         if (vp->flags.has_tag) {
2257                 if (TAG_VALID(data[0]) ||
2258                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2259                         /*
2260                          *      Tunnel passwords REQUIRE a tag, even
2261                          *      if don't have a valid tag.
2262                          */
2263                         vp->flags.tag = data[0];
2264
2265                         if ((vp->type == PW_TYPE_STRING) ||
2266                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
2267                 }
2268         }
2269
2270         /*
2271          *      Copy the data to be decrypted
2272          */
2273         memcpy(&vp->vp_octets[0], data + offset, length - offset);
2274         vp->length -= offset;
2275
2276         /*
2277          *      Decrypt the attribute.
2278          */
2279         if (secret) switch (vp->flags.encrypt) {
2280                 /*
2281                  *  User-Password
2282                  */
2283         case FLAG_ENCRYPT_USER_PASSWORD:
2284                 if (original) {
2285                         rad_pwdecode((char *)vp->vp_strvalue,
2286                                      vp->length, secret,
2287                                      original->vector);
2288                 } else {
2289                         rad_pwdecode((char *)vp->vp_strvalue,
2290                                      vp->length, secret,
2291                                      packet->vector);
2292                 }
2293                 if (vp->attribute == PW_USER_PASSWORD) {
2294                         vp->length = strlen(vp->vp_strvalue);
2295                 }
2296                 break;
2297
2298                 /*
2299                  *      Tunnel-Password's may go ONLY
2300                  *      in response packets.
2301                  */
2302         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2303                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length, secret,
2304                                         original ? original->vector : nullvector) < 0)
2305                         goto raw;
2306                 break;
2307
2308                 /*
2309                  *  Ascend-Send-Secret
2310                  *  Ascend-Receive-Secret
2311                  */
2312         case FLAG_ENCRYPT_ASCEND_SECRET:
2313                 if (!original) {
2314                         goto raw;
2315                 } else {
2316                         uint8_t my_digest[AUTH_VECTOR_LEN];
2317                         size_t secret_len;
2318
2319                         secret_len = length;
2320                         if (secret_len > AUTH_VECTOR_LEN) secret_len = AUTH_VECTOR_LEN;
2321
2322                         make_secret(my_digest,
2323                                     original->vector,
2324                                     secret, data, secret_len);
2325                         memcpy(vp->vp_strvalue, my_digest,
2326                                AUTH_VECTOR_LEN );
2327                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2328                         vp->length = strlen(vp->vp_strvalue);
2329                 }
2330                 break;
2331
2332         default:
2333                 break;
2334         } /* switch over encryption flags */
2335
2336
2337         switch (vp->type) {
2338         case PW_TYPE_STRING:
2339         case PW_TYPE_OCTETS:
2340         case PW_TYPE_ABINARY:
2341                 /* nothing more to do */
2342                 break;
2343
2344         case PW_TYPE_BYTE:
2345                 if (vp->length != 1) goto raw;
2346
2347                 vp->vp_integer = vp->vp_octets[0];
2348                 break;
2349
2350
2351         case PW_TYPE_SHORT:
2352                 if (vp->length != 2) goto raw;
2353
2354                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2355                 break;
2356
2357         case PW_TYPE_INTEGER:
2358                 if (vp->length != 4) goto raw;
2359
2360                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2361                 vp->vp_integer = ntohl(vp->vp_integer);
2362
2363                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2364
2365                 /*
2366                  *      Try to get named VALUEs
2367                  */
2368                 {
2369                         DICT_VALUE *dval;
2370                         dval = dict_valbyattr(vp->attribute,
2371                                               vp->vp_integer);
2372                         if (dval) {
2373                                 strlcpy(vp->vp_strvalue,
2374                                         dval->name,
2375                                         sizeof(vp->vp_strvalue));
2376                         }
2377                 }
2378                 break;
2379
2380         case PW_TYPE_DATE:
2381                 if (vp->length != 4) goto raw;
2382
2383                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2384                 vp->vp_date = ntohl(vp->vp_date);
2385                 break;
2386
2387
2388         case PW_TYPE_IPADDR:
2389                 if (vp->length != 4) goto raw;
2390
2391                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2392                 break;
2393
2394                 /*
2395                  *      IPv6 interface ID is 8 octets long.
2396                  */
2397         case PW_TYPE_IFID:
2398                 if (vp->length != 8) goto raw;
2399                 /* vp->vp_ifid == vp->vp_octets */
2400                 break;
2401
2402                 /*
2403                  *      IPv6 addresses are 16 octets long
2404                  */
2405         case PW_TYPE_IPV6ADDR:
2406                 if (vp->length != 16) goto raw;
2407                 /* vp->vp_ipv6addr == vp->vp_octets */
2408                 break;
2409
2410                 /*
2411                  *      IPv6 prefixes are 2 to 18 octets long.
2412                  *
2413                  *      RFC 3162: The first octet is unused.
2414                  *      The second is the length of the prefix
2415                  *      the rest are the prefix data.
2416                  *
2417                  *      The prefix length can have value 0 to 128.
2418                  */
2419         case PW_TYPE_IPV6PREFIX:
2420                 if (vp->length < 2 || vp->length > 18) goto raw;
2421                 if (vp->vp_octets[1] > 128) goto raw;
2422
2423                 /*
2424                  *      FIXME: double-check that
2425                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2426                  */
2427                 if (vp->length < 18) {
2428                         memset(vp->vp_octets + vp->length, 0,
2429                                18 - vp->length);
2430                 }
2431                 break;
2432
2433         case PW_TYPE_SIGNED:
2434                 if (vp->length != 4) goto raw;
2435
2436                 /*
2437                  *      Overload vp_integer for ntohl, which takes
2438                  *      uint32_t, not int32_t
2439                  */
2440                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2441                 vp->vp_integer = ntohl(vp->vp_integer);
2442                 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2443                 break;
2444
2445         case PW_TYPE_TLV:
2446                 vp->length = length;
2447                 vp->vp_tlv = malloc(length);
2448                 if (!vp->vp_tlv) {
2449                         pairfree(&vp);
2450                         fr_strerror_printf("No memory");
2451                         return NULL;
2452                 }
2453                 memcpy(vp->vp_tlv, data, length);
2454                 break;
2455
2456         case PW_TYPE_COMBO_IP:
2457                 if (vp->length == 4) {
2458                         vp->type = PW_TYPE_IPADDR;
2459                         memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2460                         break;
2461
2462                 } else if (vp->length == 16) {
2463                         vp->type = PW_TYPE_IPV6ADDR;
2464                         /* vp->vp_ipv6addr == vp->vp_octets */
2465                         break;
2466
2467                 }
2468                 /* FALL-THROUGH */
2469
2470         default:
2471         raw:
2472                 /*
2473                  *      Change the name to show the user that the
2474                  *      attribute is not of the correct format.
2475                  */
2476                 {
2477                         VALUE_PAIR *vp2;
2478
2479                         vp2 = pairalloc(NULL);
2480                         if (!vp2) {
2481                                 pairfree(&vp);
2482                                 return NULL;
2483                         }
2484                         pairfree(&vp);
2485                         vp = vp2;
2486
2487                         /*
2488                          *      This sets "vp->flags" appropriately,
2489                          *      and vp->type.
2490                          */
2491                         if (!paircreate_raw(attribute, PW_TYPE_OCTETS, vp)) {
2492                                 return NULL;
2493                         }
2494
2495                         vp->length = length;
2496                         memcpy(vp->vp_octets, data, length);
2497                 }
2498                 break;
2499         }
2500
2501         return vp;
2502 }
2503
2504 static void rad_sortvp(VALUE_PAIR **head)
2505 {
2506         int swapped;
2507         VALUE_PAIR *vp, **tail;
2508
2509         /*
2510          *      Walk over the VP's, sorting them in order.  Did I
2511          *      mention that I hate WiMAX continuations?
2512          *
2513          *      And bubble sort!  WTF is up with that?
2514          */
2515         do {
2516                 swapped = 0;
2517                 tail = head;
2518                 while (*tail) {
2519                         vp = *tail;
2520                         if (!vp->next) break;
2521
2522                         if (vp->attribute > vp->next->attribute) {
2523                                 *tail = vp->next;
2524                                 vp->next = (*tail)->next;
2525                                 (*tail)->next = vp;
2526                                 swapped = 1;
2527                         }
2528                         tail = &(vp->next);
2529                 }
2530         } while (swapped);
2531 }
2532
2533
2534 /*
2535  *      Walk the packet, looking for continuations of this attribute.
2536  *
2537  *      This is (worst-case) O(N^2) in the number of RADIUS
2538  *      attributes.  That happens only when perverse clients create
2539  *      continued attributes, AND separate the fragmented portions
2540  *      with a lot of other attributes.
2541  *
2542  *      Sane clients should put the fragments next to each other, in
2543  *      which case this is O(N), in the number of fragments.
2544  */
2545 static uint8_t *rad_coalesce(unsigned int attribute, size_t length,
2546                              uint8_t *data,
2547                              size_t packet_length, size_t *ptlv_length)
2548                              
2549 {
2550         uint32_t lvalue;
2551         size_t tlv_length = length;
2552         uint8_t *ptr, *tlv, *tlv_data;
2553
2554         for (ptr = data + length;
2555              ptr < (data + packet_length);
2556              ptr += ptr[1]) {
2557                 if ((ptr + 2) > (data + length)) return NULL;
2558
2559                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2560                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2561                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2562                         continue;
2563                 }
2564
2565                 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2566                 lvalue = ntohl(lvalue);
2567                 lvalue <<= 16;
2568                 lvalue |= ptr[2 + 4]; /* add in VSA number */
2569                 if (lvalue != attribute) continue;
2570
2571                 /*
2572                  *      If the vendor-length is too small, it's badly
2573                  *      formed, so we stop.
2574                  */
2575                 if ((ptr[2 + 4 + 1]) < 3) return NULL;
2576
2577                 /*
2578                  *      If it overflows the packet, it's bad.
2579                  */
2580                 if ((ptr + ptr[2 + 4 + 1]) > (data + packet_length)) {
2581                         return NULL;
2582                 }
2583
2584                 tlv_length += ptr[2 + 4 + 1] - 3;
2585                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2586         }
2587
2588         tlv = tlv_data = malloc(tlv_length);
2589         if (!tlv_data) return NULL;
2590
2591         memcpy(tlv, data, length);
2592         tlv += length;
2593
2594         /*
2595          *      Now we walk the list again, copying the data over to
2596          *      our newly created memory.
2597          */
2598         for (ptr = data + length;
2599              ptr < (data + packet_length);
2600              ptr += ptr[1]) {
2601                 int this_length;
2602
2603                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2604                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2605                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2606                         continue;
2607                 }
2608
2609                 memcpy(&lvalue, ptr + 2, 4);
2610                 lvalue = ntohl(lvalue);
2611                 lvalue <<= 16;
2612                 lvalue |= ptr[2 + 4];
2613                 if (lvalue != attribute) continue;
2614
2615                 /*
2616                  *      If the vendor-length is too small, it's badly
2617                  *      formed, so we stop.
2618                  */
2619                 if ((ptr[2 + 4 + 1]) < 3) break;
2620
2621                 this_length = ptr[2 + 4 + 1] - 3;
2622                 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2623                 tlv += this_length;
2624
2625                 ptr[2 + 4] = 0; /* What a hack! */
2626                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2627         }
2628
2629         *ptlv_length = tlv_length;
2630         return tlv_data;
2631 }
2632
2633 /*
2634  *      Start at the *data* portion of a continued attribute.  search
2635  *      through the rest of the attributes to find a matching one, and
2636  *      add it's contents to our contents.
2637  */
2638 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2639                                        const RADIUS_PACKET *original,
2640                                        const char *secret, int attribute,
2641                                        int length, /* CANNOT be zero */
2642                                        uint8_t *data, size_t packet_length,
2643                                        int flag, DICT_ATTR *da)
2644 {
2645         size_t tlv_length, left;
2646         uint8_t *ptr;
2647         uint8_t *tlv_data;
2648         VALUE_PAIR *vp, *head, **tail;
2649
2650         /*
2651          *      Ensure we have data that hasn't been split across
2652          *      multiple attributes.
2653          */
2654         if (flag) {
2655                 tlv_data = rad_coalesce(attribute, length,
2656                                         data, packet_length, &tlv_length);
2657                 if (!tlv_data) return NULL;
2658         } else {
2659                 tlv_data = data;
2660                 tlv_length = length;
2661         }
2662
2663         /*
2664          *      Non-TLV types cannot be continued across multiple
2665          *      attributes.  This is true even of keys that are
2666          *      encrypted with the tunnel-password method.  The spec
2667          *      says that they can be continued... but also that the
2668          *      keys are 160 bits, which means that they CANNOT be
2669          *      continued.  <sigh>
2670          *
2671          *      Note that we don't check "flag" here.  The calling
2672          *      code ensures that 
2673          */
2674         if (!da || (da->type != PW_TYPE_TLV)) {
2675         not_well_formed:
2676                 if (tlv_data == data) { /* true if we had 'goto' */
2677                         tlv_data = malloc(tlv_length);
2678                         if (!tlv_data) return NULL;
2679                         memcpy(tlv_data, data, tlv_length);
2680                 }
2681                 
2682                 vp = paircreate(attribute, PW_TYPE_OCTETS);
2683                 if (!vp) {
2684                         free(tlv_data);
2685                         return NULL;
2686                 }
2687                         
2688                 vp->type = PW_TYPE_TLV;
2689                 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2690                 vp->flags.has_tag = 0;
2691                 vp->flags.is_tlv = 0;
2692                 vp->vp_tlv = tlv_data;
2693                 vp->length = tlv_length;
2694                 return vp;
2695         } /* else it WAS a TLV, go decode the sub-tlv's */
2696
2697         /*
2698          *      Now (sigh) we walk over the TLV, seeing if it is
2699          *      well-formed.
2700          */
2701         left = tlv_length;
2702         for (ptr = tlv_data;
2703              ptr != (tlv_data + tlv_length);
2704              ptr += ptr[1]) {
2705                 if ((left < 2) ||
2706                     (ptr[1] < 2) ||
2707                     (ptr[1] > left)) {
2708                         goto not_well_formed;
2709                 }
2710                 left -= ptr[1];
2711         }
2712
2713         /*
2714          *      Now we walk over the TLV *again*, creating sub-tlv's.
2715          */
2716         head = NULL;
2717         tail = &head;
2718
2719         for (ptr = tlv_data;
2720              ptr != (tlv_data + tlv_length);
2721              ptr += ptr[1]) {
2722                 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2723                 if (!vp) {
2724                         pairfree(&head);
2725                         goto not_well_formed;
2726                 }
2727
2728                 vp = data2vp(packet, original, secret,
2729                              ptr[0], ptr[1] - 2, ptr + 2, vp);
2730                 if (!vp) {      /* called frees vp */
2731                         pairfree(&head);
2732                         goto not_well_formed;
2733                 }
2734
2735                 *tail = vp;
2736                 tail = &(vp->next);
2737         }
2738
2739         /*
2740          *      TLV's MAY be continued, but sometimes they're not.
2741          */
2742         if (tlv_data != data) free(tlv_data);
2743
2744         if (head && head->next) rad_sortvp(&head);
2745
2746         return head;
2747 }
2748
2749
2750 /*
2751  *      Parse a RADIUS attribute into a data structure.
2752  */
2753 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2754                         const char *secret, int attribute, int length,
2755                         const uint8_t *data)
2756 {
2757         VALUE_PAIR *vp;
2758
2759         vp = paircreate(attribute, PW_TYPE_OCTETS);
2760         if (!vp) return NULL;
2761
2762         return data2vp(packet, original, secret, attribute, length, data, vp);
2763 }
2764
2765 /**
2766  *      Converts vp_data to network byte order
2767  *      Returns:
2768  *              -1 on error, or the length of the value
2769  */
2770 ssize_t rad_vp2data(const VALUE_PAIR *vp, uint8_t *out, size_t outlen)
2771 {
2772         size_t          len = 0;
2773         uint32_t        lvalue;
2774
2775         len = vp->length;
2776         if (outlen < len) {
2777                 fr_strerror_printf("ERROR: rad_vp2data buffer passed too small");
2778                 return -1;
2779         }
2780         
2781         switch(vp->type) {
2782                 case PW_TYPE_STRING:
2783                 case PW_TYPE_OCTETS:
2784                 case PW_TYPE_IFID:
2785                 case PW_TYPE_IPADDR:
2786                 case PW_TYPE_IPV6ADDR:
2787                 case PW_TYPE_IPV6PREFIX:
2788                 case PW_TYPE_ABINARY:
2789                 case PW_TYPE_TLV:
2790                         memcpy(out, vp->vp_octets, len);
2791                         break;
2792                 case PW_TYPE_BYTE:
2793                         out[0] = vp->vp_integer & 0xff;
2794                         break;
2795         
2796                 case PW_TYPE_SHORT:
2797                         out[0] = (vp->vp_integer >> 8) & 0xff;
2798                         out[1] = vp->vp_integer & 0xff;
2799                         break;
2800         
2801                 case PW_TYPE_INTEGER:
2802                         lvalue = htonl(vp->vp_integer);
2803                         memcpy(out, &lvalue, sizeof(lvalue));
2804                         break;
2805
2806                 case PW_TYPE_DATE:
2807                         lvalue = htonl(vp->vp_date);
2808                         memcpy(out, &lvalue, sizeof(lvalue));
2809                         break;
2810         
2811                 case PW_TYPE_SIGNED:
2812                 {
2813                         int32_t slvalue;
2814                         
2815                         slvalue = htonl(vp->vp_signed);
2816                         memcpy(out, &slvalue, sizeof(slvalue));
2817                         break;
2818                 }
2819                 /* unknown type: ignore it */
2820                 default:                
2821                         fr_strerror_printf("ERROR: Unknown attribute type %d",
2822                                            vp->type);
2823                         return -1;
2824         }
2825         
2826         return len;
2827 }
2828
2829 /*
2830  *      Calculate/check digest, and decode radius attributes.
2831  *      Returns:
2832  *      -1 on decoding error
2833  *      0 on success
2834  */
2835 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2836                const char *secret)
2837 {
2838         uint32_t                lvalue;
2839         uint32_t                vendorcode;
2840         VALUE_PAIR              **tail;
2841         VALUE_PAIR              *pair;
2842         uint8_t                 *ptr, *vsa_ptr;
2843         int                     packet_length;
2844         int                     attribute;
2845         int                     attrlen;
2846         int                     vendorlen;
2847         radius_packet_t         *hdr;
2848         int                     vsa_tlen, vsa_llen, vsa_offset;
2849         DICT_VENDOR             *dv = NULL;
2850         int                     num_attributes = 0;
2851
2852         /*
2853          *      Extract attribute-value pairs
2854          */
2855         hdr = (radius_packet_t *)packet->data;
2856         ptr = hdr->data;
2857         packet_length = packet->data_len - AUTH_HDR_LEN;
2858
2859         /*
2860          *      There may be VP's already in the packet.  Don't
2861          *      destroy them.
2862          */
2863         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2864                 /* nothing */
2865         }
2866
2867         vendorcode = 0;
2868         vendorlen  = 0;
2869         vsa_tlen = vsa_llen = 1;
2870         vsa_offset = 0;
2871
2872         /*
2873          *      We have to read at least two bytes.
2874          *
2875          *      rad_recv() above ensures that this is OK.
2876          */
2877         while (packet_length > 0) {
2878                 attribute = -1;
2879                 attrlen = -1;
2880
2881                 /*
2882                  *      Normal attribute, handle it like normal.
2883                  */
2884                 if (vendorcode == 0) {
2885                         /*
2886                          *      No room to read attr/length,
2887                          *      or bad attribute, or attribute is
2888                          *      too short, or attribute is too long,
2889                          *      stop processing the packet.
2890                          */
2891                         if ((packet_length < 2) ||
2892                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2893                             (ptr[1] > packet_length)) break;
2894
2895                         attribute = *ptr++;
2896                         attrlen   = *ptr++;
2897
2898                         attrlen -= 2;
2899                         packet_length  -= 2;
2900
2901                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2902
2903                         /*
2904                          *      No vendor code, or ONLY vendor code.
2905                          */
2906                         if (attrlen <= 4) goto create_pair;
2907
2908                         vendorlen = 0;
2909                 }
2910
2911                 /*
2912                  *      Handle Vendor-Specific
2913                  */
2914                 if (vendorlen == 0) {
2915                         uint8_t *subptr;
2916                         int sublen;
2917                         int myvendor;
2918
2919                         /*
2920                          *      attrlen was checked above.
2921                          */
2922                         memcpy(&lvalue, ptr, 4);
2923                         myvendor = ntohl(lvalue);
2924
2925                         /*
2926                          *      Zero isn't allowed.
2927                          */
2928                         if (myvendor == 0) goto create_pair;
2929
2930                         /*
2931                          *      This is an implementation issue.
2932                          *      We currently pack vendor into the upper
2933                          *      16 bits of a 32-bit attribute number,
2934                          *      so we can't handle vendor numbers larger
2935                          *      than 16 bits.
2936                          */
2937                         if (myvendor > 65535) goto create_pair;
2938
2939                         vsa_tlen = vsa_llen = 1;
2940                         vsa_offset = 0;
2941                         dv = dict_vendorbyvalue(myvendor);
2942                         if (dv) {
2943                                 vsa_tlen = dv->type;
2944                                 vsa_llen = dv->length;
2945                                 if (dv->flags) vsa_offset = 1;
2946                         }
2947
2948                         /*
2949                          *      Sweep through the list of VSA's,
2950                          *      seeing if they exactly fill the
2951                          *      outer Vendor-Specific attribute.
2952                          *
2953                          *      If not, create a raw Vendor-Specific.
2954                          */
2955                         subptr = ptr + 4;
2956                         sublen = attrlen - 4;
2957
2958                         /*
2959                          *      See if we can parse it.
2960                          */
2961                         do {
2962                                 int myattr = 0;
2963
2964                                 /*
2965                                  *      Not enough room for one more
2966                                  *      attribute.  Die!
2967                                  */
2968                                 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2969
2970                                 /*
2971                                  *      Ensure that the attribute number
2972                                  *      is OK.
2973                                  */
2974                                 switch (vsa_tlen) {
2975                                 case 1:
2976                                         myattr = subptr[0];
2977                                         break;
2978
2979                                 case 2:
2980                                         myattr = (subptr[0] << 8) | subptr[1];
2981                                         break;
2982
2983                                 case 4:
2984                                         if ((subptr[0] != 0) ||
2985                                             (subptr[1] != 0)) goto create_pair;
2986
2987                                         myattr = (subptr[2] << 8) | subptr[3];
2988                                         break;
2989
2990                                         /*
2991                                          *      Our dictionary is broken.
2992                                          */
2993                                 default:
2994                                         goto create_pair;
2995                                 }
2996
2997                                 switch (vsa_llen) {
2998                                 case 0:
2999                                         attribute = (myvendor << 16) | myattr;
3000                                         ptr += 4 + vsa_tlen;
3001                                         attrlen -= (4 + vsa_tlen);
3002                                         packet_length -= 4 + vsa_tlen;
3003                                         goto create_pair;
3004
3005                                 case 1:
3006                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
3007                                                 goto create_pair;
3008
3009                                         if (subptr[vsa_tlen] > sublen)
3010                                                 goto create_pair;
3011
3012                                         /*
3013                                          *      WiMAX: 0bCrrrrrrr
3014                                          *      Reserved bits MUST be
3015                                          *      zero.
3016                                          */
3017                                         if (vsa_offset &&
3018                                             ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
3019                                                 goto create_pair;
3020
3021                                         sublen -= subptr[vsa_tlen];
3022                                         subptr += subptr[vsa_tlen];
3023                                         break;
3024
3025                                 case 2:
3026                                         if (subptr[vsa_tlen] != 0) goto create_pair;
3027                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
3028                                                 goto create_pair;
3029                                         if (subptr[vsa_tlen + 1] > sublen)
3030                                                 goto create_pair;
3031                                         sublen -= subptr[vsa_tlen + 1];
3032                                         subptr += subptr[vsa_tlen + 1];
3033                                         break;
3034
3035                                         /*
3036                                          *      Our dictionaries are
3037                                          *      broken.
3038                                          */
3039                                 default:
3040                                         goto create_pair;
3041                                 }
3042                         } while (sublen > 0);
3043
3044                         vendorcode = myvendor;
3045                         vendorlen = attrlen - 4;
3046                         packet_length -= 4;
3047
3048                         ptr += 4;
3049                 }
3050
3051                 /*
3052                  *      attrlen is the length of this attribute.
3053                  *      total_len is the length of the encompassing
3054                  *      attribute.
3055                  */
3056                 switch (vsa_tlen) {
3057                 case 1:
3058                         attribute = ptr[0];
3059                         break;
3060
3061                 case 2:
3062                         attribute = (ptr[0] << 8) | ptr[1];
3063                         break;
3064
3065                 default:        /* can't hit this. */
3066                         return -1;
3067                 }
3068                 attribute |= (vendorcode << 16);
3069                 vsa_ptr = ptr;
3070                 ptr += vsa_tlen;
3071
3072                 switch (vsa_llen) {
3073                 case 1:
3074                         attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
3075                         break;
3076
3077                 case 2:
3078                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
3079                         break;
3080
3081                 default:        /* can't hit this. */
3082                         return -1;
3083                 }
3084
3085                 ptr += vsa_llen + vsa_offset;
3086                 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
3087                 if (vendorlen == 0) vendorcode = 0;
3088                 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
3089
3090                 /*
3091                  *      Ignore VSAs that have no data.
3092                  */
3093                 if (attrlen == 0) goto next;
3094
3095                 /*
3096                  *      WiMAX attributes of type 0 are ignored.  They
3097                  *      are a secret flag to us that the attribute has
3098                  *      already been dealt with.
3099                  */
3100                 if (attribute == 0x60b50000) goto next;
3101
3102                 if (vsa_offset) {
3103                         DICT_ATTR *da;
3104
3105                         da = dict_attrbyvalue(attribute);
3106
3107                         /*
3108                          *      If it's NOT continued, AND we know
3109                          *      about it, AND it's not a TLV, we can
3110                          *      create a normal pair.
3111                          */
3112                         if (((vsa_ptr[2] & 0x80) == 0) &&
3113                             da && (da->type != PW_TYPE_TLV)) goto create_pair;
3114
3115                         /*
3116                          *      Else it IS continued, or it's a TLV.
3117                          *      Go do a lot of work to find the stuff.
3118                          */
3119                         pair = rad_continuation2vp(packet, original, secret,
3120                                                    attribute, attrlen, ptr,
3121                                                    packet_length,
3122                                                    ((vsa_ptr[2] & 0x80) != 0),
3123                                                    da);
3124                         goto created_pair;
3125                 }
3126
3127                 /*
3128                  *      Create the attribute, setting the default type
3129                  *      to 'octets'.  If the type in the dictionary
3130                  *      is different, then the dictionary type will
3131                  *      over-ride this one.
3132                  *
3133                  *      If the attribute has no data, then discard it.
3134                  *
3135                  *      Unless it's CUI.  Damn you, CUI!
3136                  */
3137         create_pair:
3138                 if (!attrlen &&
3139                     (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
3140
3141                 pair = rad_attr2vp(packet, original, secret,
3142                                    attribute, attrlen, ptr);
3143                 if (!pair) {
3144                         pairfree(&packet->vps);
3145                         fr_strerror_printf("out of memory");
3146                         return -1;
3147                 }
3148
3149         created_pair:
3150                 *tail = pair;
3151                 while (pair) {
3152                         num_attributes++;
3153                         debug_pair(pair);
3154                         tail = &pair->next;
3155                         pair = pair->next;
3156                 }
3157
3158                 /*
3159                  *      VSA's may not have been counted properly in
3160                  *      rad_packet_ok() above, as it is hard to count
3161                  *      then without using the dictionary.  We
3162                  *      therefore enforce the limits here, too.
3163                  */
3164                 if ((fr_max_attributes > 0) &&
3165                     (num_attributes > fr_max_attributes)) {
3166                         char host_ipaddr[128];
3167
3168                         pairfree(&packet->vps);
3169                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3170                                    inet_ntop(packet->src_ipaddr.af,
3171                                              &packet->src_ipaddr.ipaddr,
3172                                              host_ipaddr, sizeof(host_ipaddr)),
3173                                    num_attributes, fr_max_attributes);
3174                         return -1;
3175                 }
3176
3177         next:
3178                 ptr += attrlen;
3179                 packet_length -= attrlen;
3180         }
3181
3182         /*
3183          *      Merge information from the outside world into our
3184          *      random pool.
3185          */
3186         fr_rand_seed(packet->data, AUTH_HDR_LEN);
3187
3188         return 0;
3189 }
3190
3191
3192 /*
3193  *      Encode password.
3194  *
3195  *      We assume that the passwd buffer passed is big enough.
3196  *      RFC2138 says the password is max 128 chars, so the size
3197  *      of the passwd buffer must be at least 129 characters.
3198  *      Preferably it's just MAX_STRING_LEN.
3199  *
3200  *      int *pwlen is updated to the new length of the encrypted
3201  *      password - a multiple of 16 bytes.
3202  */
3203 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3204                  const uint8_t *vector)
3205 {
3206         FR_MD5_CTX context, old;
3207         uint8_t digest[AUTH_VECTOR_LEN];
3208         int     i, n, secretlen;
3209         int     len;
3210
3211         /*
3212          *      RFC maximum is 128 bytes.
3213          *
3214          *      If length is zero, pad it out with zeros.
3215          *
3216          *      If the length isn't aligned to 16 bytes,
3217          *      zero out the extra data.
3218          */
3219         len = *pwlen;
3220
3221         if (len > 128) len = 128;
3222
3223         if (len == 0) {
3224                 memset(passwd, 0, AUTH_PASS_LEN);
3225                 len = AUTH_PASS_LEN;
3226         } else if ((len % AUTH_PASS_LEN) != 0) {
3227                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3228                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3229         }
3230         *pwlen = len;
3231
3232         /*
3233          *      Use the secret to setup the decryption digest
3234          */
3235         secretlen = strlen(secret);
3236
3237         fr_MD5Init(&context);
3238         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3239         old = context;          /* save intermediate work */
3240
3241         /*
3242          *      Encrypt it in place.  Don't bother checking
3243          *      len, as we've ensured above that it's OK.
3244          */
3245         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3246                 if (n == 0) {
3247                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3248                         fr_MD5Final(digest, &context);
3249                 } else {
3250                         context = old;
3251                         fr_MD5Update(&context,
3252                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
3253                                      AUTH_PASS_LEN);
3254                         fr_MD5Final(digest, &context);
3255                 }
3256
3257                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3258                         passwd[i + n] ^= digest[i];
3259                 }
3260         }
3261
3262         return 0;
3263 }
3264
3265 /*
3266  *      Decode password.
3267  */
3268 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3269                  const uint8_t *vector)
3270 {
3271         FR_MD5_CTX context, old;
3272         uint8_t digest[AUTH_VECTOR_LEN];
3273         int     i;
3274         size_t  n, secretlen;
3275
3276         /*
3277          *      The RFC's say that the maximum is 128.
3278          *      The buffer we're putting it into above is 254, so
3279          *      we don't need to do any length checking.
3280          */
3281         if (pwlen > 128) pwlen = 128;
3282
3283         /*
3284          *      Catch idiots.
3285          */
3286         if (pwlen == 0) goto done;
3287
3288         /*
3289          *      Use the secret to setup the decryption digest
3290          */
3291         secretlen = strlen(secret);
3292
3293         fr_MD5Init(&context);
3294         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3295         old = context;          /* save intermediate work */
3296
3297         /*
3298          *      The inverse of the code above.
3299          */
3300         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3301                 if (n == 0) {
3302                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3303                         fr_MD5Final(digest, &context);
3304
3305                         context = old;
3306                         if (pwlen > AUTH_PASS_LEN) {
3307                                 fr_MD5Update(&context, (uint8_t *) passwd,
3308                                              AUTH_PASS_LEN);
3309                         }
3310                 } else {
3311                         fr_MD5Final(digest, &context);
3312
3313                         context = old;
3314                         if (pwlen > (n + AUTH_PASS_LEN)) {
3315                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
3316                                              AUTH_PASS_LEN);
3317                         }
3318                 }
3319
3320                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3321                         passwd[i + n] ^= digest[i];
3322                 }
3323         }
3324
3325  done:
3326         passwd[pwlen] = '\0';
3327         return strlen(passwd);
3328 }
3329
3330
3331 /*
3332  *      Encode Tunnel-Password attributes when sending them out on the wire.
3333  *
3334  *      int *pwlen is updated to the new length of the encrypted
3335  *      password - a multiple of 16 bytes.
3336  *
3337  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
3338  *      value MD5 hash.
3339  */
3340 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3341                         const uint8_t *vector)
3342 {
3343         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3344         unsigned char   digest[AUTH_VECTOR_LEN];
3345         char*   salt;
3346         int     i, n, secretlen;
3347         unsigned len, n2;
3348
3349         len = *pwlen;
3350
3351         if (len > 127) len = 127;
3352
3353         /*
3354          * Shift the password 3 positions right to place a salt and original
3355          * length, tag will be added automatically on packet send
3356          */
3357         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3358         salt = passwd;
3359         passwd += 2;
3360         /*
3361          * save original password length as first password character;
3362          */
3363         *passwd = len;
3364         len += 1;
3365
3366
3367         /*
3368          *      Generate salt.  The RFC's say:
3369          *
3370          *      The high bit of salt[0] must be set, each salt in a
3371          *      packet should be unique, and they should be random
3372          *
3373          *      So, we set the high bit, add in a counter, and then
3374          *      add in some CSPRNG data.  should be OK..
3375          */
3376         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3377                    (fr_rand() & 0x07));
3378         salt[1] = fr_rand();
3379
3380         /*
3381          *      Padd password to multiple of AUTH_PASS_LEN bytes.
3382          */
3383         n = len % AUTH_PASS_LEN;
3384         if (n) {
3385                 n = AUTH_PASS_LEN - n;
3386                 for (; n > 0; n--, len++)
3387                         passwd[len] = 0;
3388         }
3389         /* set new password length */
3390         *pwlen = len + 2;
3391
3392         /*
3393          *      Use the secret to setup the decryption digest
3394          */
3395         secretlen = strlen(secret);
3396         memcpy(buffer, secret, secretlen);
3397
3398         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3399                 if (!n2) {
3400                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3401                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3402                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3403                 } else {
3404                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3405                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3406                 }
3407
3408                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3409                         passwd[i + n2] ^= digest[i];
3410                 }
3411         }
3412         passwd[n2] = 0;
3413         return 0;
3414 }
3415
3416 /*
3417  *      Decode Tunnel-Password encrypted attributes.
3418  *
3419  *      Defined in RFC-2868, this uses a two char SALT along with the
3420  *      initial intermediate value, to differentiate it from the
3421  *      above.
3422  */
3423 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3424                         const uint8_t *vector)
3425 {
3426         FR_MD5_CTX  context, old;
3427         uint8_t         digest[AUTH_VECTOR_LEN];
3428         int             secretlen;
3429         size_t          i, n, encrypted_len, reallen;
3430
3431         encrypted_len = *pwlen;
3432
3433         /*
3434          *      We need at least a salt.
3435          */
3436         if (encrypted_len < 2) {
3437                 fr_strerror_printf("tunnel password is too short");
3438                 return -1;
3439         }
3440
3441         /*
3442          *      There's a salt, but no password.  Or, there's a salt
3443          *      and a 'data_len' octet.  It's wrong, but at least we
3444          *      can figure out what it means: the password is empty.
3445          *
3446          *      Note that this means we ignore the 'data_len' field,
3447          *      if the attribute length tells us that there's no
3448          *      more data.  So the 'data_len' field may be wrong,
3449          *      but that's ok...
3450          */
3451         if (encrypted_len <= 3) {
3452                 passwd[0] = 0;
3453                 *pwlen = 0;
3454                 return 0;
3455         }
3456
3457         encrypted_len -= 2;             /* discount the salt */
3458
3459         /*
3460          *      Use the secret to setup the decryption digest
3461          */
3462         secretlen = strlen(secret);
3463
3464         fr_MD5Init(&context);
3465         fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
3466         old = context;          /* save intermediate work */
3467
3468         /*
3469          *      Set up the initial key:
3470          *
3471          *       b(1) = MD5(secret + vector + salt)
3472          */
3473         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3474         fr_MD5Update(&context, passwd, 2);
3475
3476         reallen = 0;
3477         for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
3478                 size_t base;
3479                 size_t block_len = AUTH_PASS_LEN;
3480
3481                 /*
3482                  *      Ensure we don't overflow the input on MD5
3483                  */
3484                 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
3485                         block_len = *pwlen - n - 2;
3486                 }
3487
3488                 if (n == 0) {
3489                         base = 1;
3490
3491                         fr_MD5Final(digest, &context);
3492
3493                         context = old;
3494
3495                         /*
3496                          *      A quick check: decrypt the first octet
3497                          *      of the password, which is the
3498                          *      'data_len' field.  Ensure it's sane.
3499                          */
3500                         reallen = passwd[2] ^ digest[0];
3501                         if (reallen > encrypted_len) {
3502                                 fr_strerror_printf("tunnel password is too long for the attribute");
3503                                 return -1;
3504                         }
3505
3506                         fr_MD5Update(&context, passwd + 2, block_len);
3507
3508                 } else {
3509                         base = 0;
3510
3511                         fr_MD5Final(digest, &context);
3512
3513                         context = old;
3514                         fr_MD5Update(&context, passwd + n + 2, block_len);
3515                 }
3516
3517                 for (i = base; i < block_len; i++) {
3518                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3519                 }
3520         }
3521
3522         *pwlen = reallen;
3523         passwd[reallen] = 0;
3524
3525         return reallen;
3526 }
3527
3528 /*
3529  *      Encode a CHAP password
3530  *
3531  *      FIXME: might not work with Ascend because
3532  *      we use vp->length, and Ascend gear likes
3533  *      to send an extra '\0' in the string!
3534  */
3535 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3536                     VALUE_PAIR *password)
3537 {
3538         int             i;
3539         uint8_t         *ptr;
3540         uint8_t         string[MAX_STRING_LEN * 2 + 1];
3541         VALUE_PAIR      *challenge;
3542
3543         /*
3544          *      Sanity check the input parameters
3545          */
3546         if ((packet == NULL) || (password == NULL)) {
3547                 return -1;
3548         }
3549
3550         /*
3551          *      Note that the password VP can be EITHER
3552          *      a User-Password attribute (from a check-item list),
3553          *      or a CHAP-Password attribute (the client asking
3554          *      the library to encode it).
3555          */
3556
3557         i = 0;
3558         ptr = string;
3559         *ptr++ = id;
3560
3561         i++;
3562         memcpy(ptr, password->vp_strvalue, password->length);
3563         ptr += password->length;
3564         i += password->length;
3565
3566         /*
3567          *      Use Chap-Challenge pair if present,
3568          *      Request Authenticator otherwise.
3569          */
3570         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3571         if (challenge) {
3572                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3573                 i += challenge->length;
3574         } else {
3575                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3576                 i += AUTH_VECTOR_LEN;
3577         }
3578
3579         *output = id;
3580         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3581
3582         return 0;
3583 }
3584
3585
3586 /*
3587  *      Seed the random number generator.
3588  *
3589  *      May be called any number of times.
3590  */
3591 void fr_rand_seed(const void *data, size_t size)
3592 {
3593         uint32_t hash;
3594
3595         /*
3596          *      Ensure that the pool is initialized.
3597          */
3598         if (!fr_rand_initialized) {
3599                 int fd;
3600
3601                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3602
3603                 fd = open("/dev/urandom", O_RDONLY);
3604                 if (fd >= 0) {
3605                         size_t total;
3606                         ssize_t this;
3607
3608                         total = this = 0;
3609                         while (total < sizeof(fr_rand_pool.randrsl)) {
3610                                 this = read(fd, fr_rand_pool.randrsl,
3611                                             sizeof(fr_rand_pool.randrsl) - total);
3612                                 if ((this < 0) && (errno != EINTR)) break;
3613                                 if (this > 0) total += this;
3614                         }
3615                         close(fd);
3616                 } else {
3617                         fr_rand_pool.randrsl[0] = fd;
3618                         fr_rand_pool.randrsl[1] = time(NULL);
3619                         fr_rand_pool.randrsl[2] = errno;
3620                 }
3621
3622                 fr_randinit(&fr_rand_pool, 1);
3623                 fr_rand_pool.randcnt = 0;
3624                 fr_rand_initialized = 1;
3625         }
3626
3627         if (!data) return;
3628
3629         /*
3630          *      Hash the user data
3631          */
3632         hash = fr_rand();
3633         if (!hash) hash = fr_rand();
3634         hash = fr_hash_update(data, size, hash);
3635
3636         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3637 }
3638
3639
3640 /*
3641  *      Return a 32-bit random number.
3642  */
3643 uint32_t fr_rand(void)
3644 {
3645         uint32_t num;
3646
3647         /*
3648          *      Ensure that the pool is initialized.
3649          */
3650         if (!fr_rand_initialized) {
3651                 fr_rand_seed(NULL, 0);
3652         }
3653
3654         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3655         if (fr_rand_pool.randcnt >= 256) {
3656                 fr_rand_pool.randcnt = 0;
3657                 fr_isaac(&fr_rand_pool);
3658         }
3659
3660         return num;
3661 }
3662
3663
3664 /*
3665  *      Allocate a new RADIUS_PACKET
3666  */
3667 RADIUS_PACKET *rad_alloc(int newvector)
3668 {
3669         RADIUS_PACKET   *rp;
3670
3671         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3672                 fr_strerror_printf("out of memory");
3673                 return NULL;
3674         }
3675         memset(rp, 0, sizeof(*rp));
3676         rp->id = -1;
3677         rp->offset = -1;
3678
3679         if (newvector) {
3680                 int i;
3681                 uint32_t hash, base;
3682
3683                 /*
3684                  *      Don't expose the actual contents of the random
3685                  *      pool.
3686                  */
3687                 base = fr_rand();
3688                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3689                         hash = fr_rand() ^ base;
3690                         memcpy(rp->vector + i, &hash, sizeof(hash));
3691                 }
3692         }
3693         fr_rand();              /* stir the pool again */
3694
3695         return rp;
3696 }
3697
3698 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3699 {
3700         RADIUS_PACKET *reply;
3701
3702         if (!packet) return NULL;
3703
3704         reply = rad_alloc(0);
3705         if (!reply) return NULL;
3706
3707         /*
3708          *      Initialize the fields from the request.
3709          */
3710         reply->sockfd = packet->sockfd;
3711         reply->dst_ipaddr = packet->src_ipaddr;
3712         reply->src_ipaddr = packet->dst_ipaddr;
3713         reply->dst_port = packet->src_port;
3714         reply->src_port = packet->dst_port;
3715         reply->id = packet->id;
3716         reply->code = 0; /* UNKNOWN code */
3717         memcpy(reply->vector, packet->vector,
3718                sizeof(reply->vector));
3719         reply->vps = NULL;
3720         reply->data = NULL;
3721         reply->data_len = 0;
3722
3723         return reply;
3724 }
3725
3726
3727 /*
3728  *      Free a RADIUS_PACKET
3729  */
3730 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3731 {
3732         RADIUS_PACKET *radius_packet;
3733
3734         if (!radius_packet_ptr || !*radius_packet_ptr) return;
3735         radius_packet = *radius_packet_ptr;
3736
3737         free(radius_packet->data);
3738
3739         pairfree(&radius_packet->vps);
3740
3741         free(radius_packet);
3742
3743         *radius_packet_ptr = NULL;
3744 }