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