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