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