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