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