Fixe typo
[freeradius.git] / src / lib / radius.c
1 /*
2  * radius.c     Functions to send/receive radius packets.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  *   Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000-2003,2006  The FreeRADIUS server project
21  */
22
23 #include        <freeradius-devel/ident.h>
24 RCSID("$Id$")
25
26 #include        <freeradius-devel/libradius.h>
27 #include        <freeradius-devel/md5.h>
28
29 #include        <fcntl.h>
30 #include        <ctype.h>
31
32 #ifdef WITH_UDPFROMTO
33 #include        <freeradius-devel/udpfromto.h>
34 #endif
35
36 #ifdef HAVE_MALLOC_H
37 #include        <malloc.h>
38 #endif
39
40 /*
41  *  The RFC says 4096 octets max, and most packets are less than 256.
42  */
43 #define MAX_PACKET_LEN 4096
44
45 /*
46  *      The maximum number of attributes which we allow in an incoming
47  *      request.  If there are more attributes than this, the request
48  *      is rejected.
49  *
50  *      This helps to minimize the potential for a DoS, when an
51  *      attacker spoofs Access-Request packets, which don't have a
52  *      Message-Authenticator attribute.  This means that the packet
53  *      is unsigned, and the attacker can use resources on the server,
54  *      even if the end request is rejected.
55  */
56 int fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
58
59 typedef struct radius_packet_t {
60   uint8_t       code;
61   uint8_t       id;
62   uint8_t       length[2];
63   uint8_t       vector[AUTH_VECTOR_LEN];
64   uint8_t       data[1];
65 } radius_packet_t;
66
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
70
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
72   "",
73   "Access-Request",
74   "Access-Accept",
75   "Access-Reject",
76   "Accounting-Request",
77   "Accounting-Response",
78   "Accounting-Status",
79   "Password-Request",
80   "Password-Accept",
81   "Password-Reject",
82   "Accounting-Message",
83   "Access-Challenge",
84   "Status-Server",
85   "Status-Client",
86   "14",
87   "15",
88   "16",
89   "17",
90   "18",
91   "19",
92   "20",
93   "Resource-Free-Request",
94   "Resource-Free-Response",
95   "Resource-Query-Request",
96   "Resource-Query-Response",
97   "Alternate-Resource-Reclaim-Request",
98   "NAS-Reboot-Request",
99   "NAS-Reboot-Response",
100   "28",
101   "Next-Passcode",
102   "New-Pin",
103   "Terminate-Session",
104   "Password-Expired",
105   "Event-Request",
106   "Event-Response",
107   "35",
108   "36",
109   "37",
110   "38",
111   "39",
112   "Disconnect-Request",
113   "Disconnect-ACK",
114   "Disconnect-NAK",
115   "CoA-Request",
116   "CoA-ACK",
117   "CoA-NAK",
118   "46",
119   "47",
120   "48",
121   "49",
122   "IP-Address-Allocate",
123   "IP-Address-Release"
124 };
125
126
127 void fr_printf_log(const char *fmt, ...)
128 {
129         va_list ap;
130
131         va_start(ap, fmt);
132         if ((fr_debug_flag == 0) || !fr_log_fp) {
133                 va_end(ap);
134                 return;
135         }
136
137         vfprintf(fr_log_fp, fmt, ap);
138         va_end(ap);
139
140         return;
141 }
142
143 /*
144  *      Wrapper for sendto which handles sendfromto, IPv6, and all
145  *      possible combinations.
146  */
147 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
148                       fr_ipaddr_t *src_ipaddr, int src_port,
149                       fr_ipaddr_t *dst_ipaddr, int dst_port)
150 {
151         struct sockaddr_storage dst;
152         socklen_t               sizeof_dst;
153
154 #ifdef WITH_UDPFROMTO
155         struct sockaddr_storage src;
156         socklen_t               sizeof_src;
157
158         fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
159 #else
160         src_port = src_port;    /* -Wunused */
161 #endif
162
163         if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
164                 return -1;
165         }
166
167 #ifdef WITH_UDPFROMTO
168         /*
169          *      Only IPv4 is supported for udpfromto.
170          *
171          *      And if they don't specify a source IP address, don't
172          *      use udpfromto.
173          */
174         if ((dst_ipaddr->af == AF_INET) ||
175             (src_ipaddr->af != AF_UNSPEC)) {
176                 return sendfromto(sockfd, data, data_len, flags,
177                                   (struct sockaddr *)&src, sizeof_src,
178                                   (struct sockaddr *)&dst, sizeof_dst);
179         }
180 #else
181         src_ipaddr = src_ipaddr; /* -Wunused */
182 #endif
183
184         /*
185          *      No udpfromto, OR an IPv6 socket, fail gracefully.
186          */
187         return sendto(sockfd, data, data_len, flags,
188                       (struct sockaddr *) &dst, sizeof_dst);
189 }
190
191
192 void rad_recv_discard(int sockfd)
193 {
194         uint8_t                 header[4];
195         struct sockaddr_storage src;
196         socklen_t               sizeof_src = sizeof(src);
197
198         recvfrom(sockfd, header, sizeof(header), 0,
199                  (struct sockaddr *)&src, &sizeof_src);
200 }
201
202
203 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
204                         int *code)
205 {
206         ssize_t                 data_len, packet_len;
207         uint8_t                 header[4];
208         struct sockaddr_storage src;
209         socklen_t               sizeof_src = sizeof(src);
210
211         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
212                             (struct sockaddr *)&src, &sizeof_src);
213         if (data_len < 0) {
214                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
215                 return -1;
216         }
217
218         /*
219          *      Too little data is available, discard the packet.
220          */
221         if (data_len < 4) {
222                 recvfrom(sockfd, header, sizeof(header), 0,
223                          (struct sockaddr *)&src, &sizeof_src);
224                 return 1;
225
226         } else {                /* we got 4 bytes of data. */
227                 /*
228                  *      See how long the packet says it is.
229                  */
230                 packet_len = (header[2] * 256) + header[3];
231
232                 /*
233                  *      The length in the packet says it's less than
234                  *      a RADIUS header length: discard it.
235                  */
236                 if (packet_len < AUTH_HDR_LEN) {
237                         recvfrom(sockfd, header, sizeof(header), 0,
238                                  (struct sockaddr *)&src, &sizeof_src);
239                         return 1;
240
241                         /*
242                          *      Enforce RFC requirements, for sanity.
243                          *      Anything after 4k will be discarded.
244                          */
245                 } else if (packet_len > MAX_PACKET_LEN) {
246                         recvfrom(sockfd, header, sizeof(header), 0,
247                                  (struct sockaddr *)&src, &sizeof_src);
248                         return 1;
249                 }
250         }
251
252         /*
253          *      Convert AF.  If unknown, discard packet.
254          */
255         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
256                 recvfrom(sockfd, header, sizeof(header), 0,
257                          (struct sockaddr *)&src, &sizeof_src);
258                 return 1;
259         }
260
261         *code = header[0];
262
263         /*
264          *      The packet says it's this long, but the actual UDP
265          *      size could still be smaller.
266          */
267         return packet_len;
268 }
269
270
271 /*
272  *      wrapper for recvfrom, which handles recvfromto, IPv6, and all
273  *      possible combinations.
274  */
275 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
276                             fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
277                             fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
278 {
279         struct sockaddr_storage src;
280         struct sockaddr_storage dst;
281         socklen_t               sizeof_src = sizeof(src);
282         socklen_t               sizeof_dst = sizeof(dst);
283         ssize_t                 data_len;
284         uint8_t                 header[4];
285         void                    *buf;
286         size_t                  len;
287         int                     port;
288
289         memset(&src, 0, sizeof_src);
290         memset(&dst, 0, sizeof_dst);
291
292         /*
293          *      Get address family, etc. first, so we know if we
294          *      need to do udpfromto.
295          *
296          *      FIXME: udpfromto also does this, but it's not
297          *      a critical problem.
298          */
299         if (getsockname(sockfd, (struct sockaddr *)&dst,
300                         &sizeof_dst) < 0) return -1;
301
302         /*
303          *      Read the length of the packet, from the packet.
304          *      This lets us allocate the buffer to use for
305          *      reading the rest of the packet.
306          */
307         data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
308                             (struct sockaddr *)&src, &sizeof_src);
309         if (data_len < 0) {
310                 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
311                 return -1;
312         }
313
314         /*
315          *      Too little data is available, discard the packet.
316          */
317         if (data_len < 4) {
318                 recvfrom(sockfd, header, sizeof(header), flags,
319                          (struct sockaddr *)&src, &sizeof_src);
320                 return 0;
321
322         } else {                /* we got 4 bytes of data. */
323                 /*
324                  *      See how long the packet says it is.
325                  */
326                 len = (header[2] * 256) + header[3];
327
328                 /*
329                  *      The length in the packet says it's less than
330                  *      a RADIUS header length: discard it.
331                  */
332                 if (len < AUTH_HDR_LEN) {
333                         recvfrom(sockfd, header, sizeof(header), flags,
334                                  (struct sockaddr *)&src, &sizeof_src);
335                         return 0;
336
337                         /*
338                          *      Enforce RFC requirements, for sanity.
339                          *      Anything after 4k will be discarded.
340                          */
341                 } else if (len > MAX_PACKET_LEN) {
342                         recvfrom(sockfd, header, sizeof(header), flags,
343                                  (struct sockaddr *)&src, &sizeof_src);
344                         return len;
345                 }
346         }
347
348         buf = malloc(len);
349         if (!buf) return -1;
350
351         /*
352          *      Receive the packet.  The OS will discard any data in the
353          *      packet after "len" bytes.
354          */
355 #ifdef WITH_UDPFROMTO
356         if (dst.ss_family == AF_INET) {
357                 data_len = recvfromto(sockfd, buf, len, flags,
358                                       (struct sockaddr *)&src, &sizeof_src,
359                                       (struct sockaddr *)&dst, &sizeof_dst);
360         } else
361 #endif
362                 /*
363                  *      No udpfromto, OR an IPv6 socket.  Fail gracefully.
364                  */
365                 data_len = recvfrom(sockfd, buf, len, flags,
366                                     (struct sockaddr *)&src, &sizeof_src);
367         if (data_len < 0) {
368                 free(buf);
369                 return data_len;
370         }
371
372         if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
373                 free(buf);
374                 return -1;      /* Unknown address family, Die Die Die! */
375         }
376         *src_port = port;
377
378         fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
379         *dst_port = port;
380
381         /*
382          *      Different address families should never happen.
383          */
384         if (src.ss_family != dst.ss_family) {
385                 free(buf);
386                 return -1;
387         }
388
389         /*
390          *      Tell the caller about the data
391          */
392         *pbuf = buf;
393
394         return data_len;
395 }
396
397
398 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
399 /*************************************************************************
400  *
401  *      Function: make_secret
402  *
403  *      Purpose: Build an encrypted secret value to return in a reply
404  *               packet.  The secret is hidden by xoring with a MD5 digest
405  *               created from the shared secret and the authentication
406  *               vector.  We put them into MD5 in the reverse order from
407  *               that used when encrypting passwords to RADIUS.
408  *
409  *************************************************************************/
410 static void make_secret(uint8_t *digest, const uint8_t *vector,
411                         const char *secret, const uint8_t *value)
412 {
413         FR_MD5_CTX context;
414         int             i;
415
416         fr_MD5Init(&context);
417         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
418         fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
419         fr_MD5Final(digest, &context);
420
421         for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
422                 digest[i] ^= value[i];
423         }
424 }
425
426 #define MAX_PASS_LEN (128)
427 static void make_passwd(uint8_t *output, int *outlen,
428                         const uint8_t *input, int inlen,
429                         const char *secret, const uint8_t *vector)
430 {
431         FR_MD5_CTX context, old;
432         uint8_t digest[AUTH_VECTOR_LEN];
433         uint8_t passwd[MAX_PASS_LEN];
434         int     i, n;
435         int     len;
436
437         /*
438          *      If the length is zero, round it up.
439          */
440         len = inlen;
441
442         if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
443
444         memcpy(passwd, input, len);
445         memset(passwd + len, 0, sizeof(passwd) - len);
446
447         if (len == 0) {
448                 len = AUTH_PASS_LEN;
449         }
450
451         else if ((len & 0x0f) != 0) {
452                 len += 0x0f;
453                 len &= ~0x0f;
454         }
455         *outlen = 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 < FR_MAX_PACKET_CODE)) {
1092                 what = fr_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 < FR_MAX_PACKET_CODE)) {
1404                 what = fr_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 >= FR_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         int sock_flags = 0;
1824         RADIUS_PACKET           *packet;
1825
1826         /*
1827          *      Allocate the new request data structure
1828          */
1829         if ((packet = malloc(sizeof(*packet))) == NULL) {
1830                 fr_strerror_printf("out of memory");
1831                 return NULL;
1832         }
1833         memset(packet, 0, sizeof(*packet));
1834
1835         if (flags & 0x02) {
1836                 sock_flags = MSG_PEEK;
1837                 flags &= ~0x02;
1838         }
1839
1840         packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1841                                         &packet->src_ipaddr, &packet->src_port,
1842                                         &packet->dst_ipaddr, &packet->dst_port);
1843
1844         /*
1845          *      Check for socket errors.
1846          */
1847         if (packet->data_len < 0) {
1848                 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1849                 /* packet->data is NULL */
1850                 free(packet);
1851                 return NULL;
1852         }
1853
1854         /*
1855          *      If the packet is too big, then rad_recvfrom did NOT
1856          *      allocate memory.  Instead, it just discarded the
1857          *      packet.
1858          */
1859         if (packet->data_len > MAX_PACKET_LEN) {
1860                 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1861                 /* packet->data is NULL */
1862                 free(packet);
1863                 return NULL;
1864         }
1865
1866         /*
1867          *      Read no data.  Continue.
1868          *      This check is AFTER the MAX_PACKET_LEN check above, because
1869          *      if the packet is larger than MAX_PACKET_LEN, we also have
1870          *      packet->data == NULL
1871          */
1872         if ((packet->data_len == 0) || !packet->data) {
1873                 fr_strerror_printf("Empty packet: Socket is not ready.");
1874                 free(packet);
1875                 return NULL;
1876         }
1877
1878         /*
1879          *      See if it's a well-formed RADIUS packet.
1880          */
1881         if (!rad_packet_ok(packet, flags)) {
1882                 rad_free(&packet);
1883                 return NULL;
1884         }
1885
1886         /*
1887          *      Remember which socket we read the packet from.
1888          */
1889         packet->sockfd = fd;
1890
1891         /*
1892          *      FIXME: Do even more filtering by only permitting
1893          *      certain IP's.  The problem is that we don't know
1894          *      how to do this properly for all possible clients...
1895          */
1896
1897         /*
1898          *      Explicitely set the VP list to empty.
1899          */
1900         packet->vps = NULL;
1901
1902         if (fr_debug_flag) {
1903                 char host_ipaddr[128];
1904
1905                 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1906                         DEBUG("rad_recv: %s packet from host %s port %d",
1907                               fr_packet_codes[packet->code],
1908                               inet_ntop(packet->src_ipaddr.af,
1909                                         &packet->src_ipaddr.ipaddr,
1910                                         host_ipaddr, sizeof(host_ipaddr)),
1911                               packet->src_port);
1912                 } else {
1913                         DEBUG("rad_recv: Packet from host %s port %d code=%d",
1914                               inet_ntop(packet->src_ipaddr.af,
1915                                         &packet->src_ipaddr.ipaddr,
1916                                         host_ipaddr, sizeof(host_ipaddr)),
1917                               packet->src_port,
1918                               packet->code);
1919                 }
1920                 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1921         }
1922
1923         return packet;
1924 }
1925
1926
1927 /*
1928  *      Verify the signature of a packet.
1929  */
1930 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1931                const char *secret)
1932 {
1933         uint8_t                 *ptr;
1934         int                     length;
1935         int                     attrlen;
1936
1937         if (!packet || !packet->data) return -1;
1938
1939         /*
1940          *      Before we allocate memory for the attributes, do more
1941          *      sanity checking.
1942          */
1943         ptr = packet->data + AUTH_HDR_LEN;
1944         length = packet->data_len - AUTH_HDR_LEN;
1945         while (length > 0) {
1946                 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1947                 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1948
1949                 attrlen = ptr[1];
1950
1951                 switch (ptr[0]) {
1952                 default:        /* don't do anything. */
1953                         break;
1954
1955                         /*
1956                          *      Note that more than one Message-Authenticator
1957                          *      attribute is invalid.
1958                          */
1959                 case PW_MESSAGE_AUTHENTICATOR:
1960                         memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1961                         memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1962
1963                         switch (packet->code) {
1964                         default:
1965                                 break;
1966
1967                         case PW_ACCOUNTING_REQUEST:
1968                         case PW_ACCOUNTING_RESPONSE:
1969                         case PW_DISCONNECT_REQUEST:
1970                         case PW_DISCONNECT_ACK:
1971                         case PW_DISCONNECT_NAK:
1972                         case PW_COA_REQUEST:
1973                         case PW_COA_ACK:
1974                         case PW_COA_NAK:
1975                                 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1976                                 break;
1977
1978                         case PW_AUTHENTICATION_ACK:
1979                         case PW_AUTHENTICATION_REJECT:
1980                         case PW_ACCESS_CHALLENGE:
1981                                 if (!original) {
1982                                         fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1983                                         return -1;
1984                                 }
1985                                 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1986                                 break;
1987                         }
1988
1989                         fr_hmac_md5(packet->data, packet->data_len,
1990                                     (const uint8_t *) secret, strlen(secret),
1991                                     calc_auth_vector);
1992                         if (memcmp(calc_auth_vector, msg_auth_vector,
1993                                    sizeof(calc_auth_vector)) != 0) {
1994                                 char buffer[32];
1995                                 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator!  (Shared secret is incorrect.)",
1996                                            inet_ntop(packet->src_ipaddr.af,
1997                                                      &packet->src_ipaddr.ipaddr,
1998                                                      buffer, sizeof(buffer)));
1999                                 /* Silently drop packet, according to RFC 3579 */
2000                                 return -1;
2001                         } /* else the message authenticator was good */
2002
2003                         /*
2004                          *      Reinitialize Authenticators.
2005                          */
2006                         memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2007                         memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2008                         break;
2009                 } /* switch over the attributes */
2010
2011                 ptr += attrlen;
2012                 length -= attrlen;
2013         } /* loop over the packet, sanity checking the attributes */
2014
2015         /*
2016          *      It looks like a RADIUS packet, but we can't validate
2017          *      the signature.
2018          */
2019         if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2020                 char buffer[32];
2021                 fr_strerror_printf("Received Unknown packet code %d "
2022                            "from client %s port %d: Cannot validate signature.",
2023                            packet->code,
2024                            inet_ntop(packet->src_ipaddr.af,
2025                                      &packet->src_ipaddr.ipaddr,
2026                                      buffer, sizeof(buffer)),
2027                            packet->src_port);
2028                 return -1;
2029         }
2030
2031         /*
2032          *      Calculate and/or verify digest.
2033          */
2034         switch(packet->code) {
2035                 int rcode;
2036                 char buffer[32];
2037
2038                 case PW_AUTHENTICATION_REQUEST:
2039                 case PW_STATUS_SERVER:
2040                         /*
2041                          *      The authentication vector is random
2042                          *      nonsense, invented by the client.
2043                          */
2044                         break;
2045
2046                 case PW_COA_REQUEST:
2047                 case PW_DISCONNECT_REQUEST:
2048                 case PW_ACCOUNTING_REQUEST:
2049                         if (calc_acctdigest(packet, secret) > 1) {
2050                                 fr_strerror_printf("Received %s packet "
2051                                            "from %s with invalid signature!  (Shared secret is incorrect.)",
2052                                            fr_packet_codes[packet->code],
2053                                            inet_ntop(packet->src_ipaddr.af,
2054                                                      &packet->src_ipaddr.ipaddr,
2055                                                      buffer, sizeof(buffer)));
2056                                 return -1;
2057                         }
2058                         break;
2059
2060                         /* Verify the reply digest */
2061                 case PW_AUTHENTICATION_ACK:
2062                 case PW_AUTHENTICATION_REJECT:
2063                 case PW_ACCESS_CHALLENGE:
2064                 case PW_ACCOUNTING_RESPONSE:
2065                 case PW_DISCONNECT_ACK:
2066                 case PW_DISCONNECT_NAK:
2067                 case PW_COA_ACK:
2068                 case PW_COA_NAK:
2069                         rcode = calc_replydigest(packet, original, secret);
2070                         if (rcode > 1) {
2071                                 fr_strerror_printf("Received %s packet "
2072                                            "from client %s port %d with invalid signature (err=%d)!  (Shared secret is incorrect.)",
2073                                            fr_packet_codes[packet->code],
2074                                            inet_ntop(packet->src_ipaddr.af,
2075                                                      &packet->src_ipaddr.ipaddr,
2076                                                      buffer, sizeof(buffer)),
2077                                            packet->src_port,
2078                                            rcode);
2079                                 return -1;
2080                         }
2081                         break;
2082
2083                 default:
2084                         fr_strerror_printf("Received Unknown packet code %d "
2085                                    "from client %s port %d: Cannot validate signature",
2086                                    packet->code,
2087                                    inet_ntop(packet->src_ipaddr.af,
2088                                              &packet->src_ipaddr.ipaddr,
2089                                                      buffer, sizeof(buffer)),
2090                                    packet->src_port);
2091                         return -1;
2092         }
2093
2094         return 0;
2095 }
2096
2097
2098 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2099                            const RADIUS_PACKET *original,
2100                            const char *secret, int attribute, int length,
2101                            const uint8_t *data, VALUE_PAIR *vp)
2102 {
2103         int offset = 0;
2104
2105         /*
2106          *      If length is greater than 253, something is SERIOUSLY
2107          *      wrong.
2108          */
2109         if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2110
2111         vp->length = length;
2112         vp->operator = T_OP_EQ;
2113         vp->next = NULL;
2114
2115         /*
2116          *      Handle tags.
2117          */
2118         if (vp->flags.has_tag) {
2119                 if (TAG_VALID(data[0]) ||
2120                     (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2121                         /*
2122                          *      Tunnel passwords REQUIRE a tag, even
2123                          *      if don't have a valid tag.
2124                          */
2125                         vp->flags.tag = data[0];
2126
2127                         if ((vp->type == PW_TYPE_STRING) ||
2128                             (vp->type == PW_TYPE_OCTETS)) offset = 1;
2129                 }
2130         }
2131
2132         /*
2133          *      Copy the data to be decrypted
2134          */
2135         memcpy(&vp->vp_octets[0], data + offset, length - offset);
2136         vp->length -= offset;
2137
2138         /*
2139          *      Decrypt the attribute.
2140          */
2141         switch (vp->flags.encrypt) {
2142                 /*
2143                  *  User-Password
2144                  */
2145         case FLAG_ENCRYPT_USER_PASSWORD:
2146                 if (original) {
2147                         rad_pwdecode((char *)vp->vp_strvalue,
2148                                      vp->length, secret,
2149                                      original->vector);
2150                 } else {
2151                         rad_pwdecode((char *)vp->vp_strvalue,
2152                                      vp->length, secret,
2153                                      packet->vector);
2154                 }
2155                 if (vp->attribute == PW_USER_PASSWORD) {
2156                         vp->length = strlen(vp->vp_strvalue);
2157                 }
2158                 break;
2159
2160                 /*
2161                  *      Tunnel-Password's may go ONLY
2162                  *      in response packets.
2163                  */
2164         case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2165                 if (!original) goto raw;
2166
2167                 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2168                                         secret, original->vector) < 0) {
2169                         goto raw;
2170                 }
2171                 break;
2172
2173                 /*
2174                  *  Ascend-Send-Secret
2175                  *  Ascend-Receive-Secret
2176                  */
2177         case FLAG_ENCRYPT_ASCEND_SECRET:
2178                 if (!original) {
2179                         goto raw;
2180                 } else {
2181                         uint8_t my_digest[AUTH_VECTOR_LEN];
2182                         make_secret(my_digest,
2183                                     original->vector,
2184                                     secret, data);
2185                         memcpy(vp->vp_strvalue, my_digest,
2186                                AUTH_VECTOR_LEN );
2187                         vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2188                         vp->length = strlen(vp->vp_strvalue);
2189                 }
2190                 break;
2191
2192         default:
2193                 break;
2194         } /* switch over encryption flags */
2195
2196
2197         switch (vp->type) {
2198         case PW_TYPE_STRING:
2199         case PW_TYPE_OCTETS:
2200         case PW_TYPE_ABINARY:
2201                 /* nothing more to do */
2202                 break;
2203
2204         case PW_TYPE_BYTE:
2205                 if (vp->length != 1) goto raw;
2206
2207                 vp->vp_integer = vp->vp_octets[0];
2208                 break;
2209
2210
2211         case PW_TYPE_SHORT:
2212                 if (vp->length != 2) goto raw;
2213
2214                 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2215                 break;
2216
2217         case PW_TYPE_INTEGER:
2218                 if (vp->length != 4) goto raw;
2219
2220                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2221                 vp->vp_integer = ntohl(vp->vp_integer);
2222
2223                 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2224
2225                 /*
2226                  *      Try to get named VALUEs
2227                  */
2228                 {
2229                         DICT_VALUE *dval;
2230                         dval = dict_valbyattr(vp->attribute,
2231                                               vp->vp_integer);
2232                         if (dval) {
2233                                 strlcpy(vp->vp_strvalue,
2234                                         dval->name,
2235                                         sizeof(vp->vp_strvalue));
2236                         }
2237                 }
2238                 break;
2239
2240         case PW_TYPE_DATE:
2241                 if (vp->length != 4) goto raw;
2242
2243                 memcpy(&vp->vp_date, vp->vp_octets, 4);
2244                 vp->vp_date = ntohl(vp->vp_date);
2245                 break;
2246
2247
2248         case PW_TYPE_IPADDR:
2249                 if (vp->length != 4) goto raw;
2250
2251                 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2252                 break;
2253
2254                 /*
2255                  *      IPv6 interface ID is 8 octets long.
2256                  */
2257         case PW_TYPE_IFID:
2258                 if (vp->length != 8) goto raw;
2259                 /* vp->vp_ifid == vp->vp_octets */
2260                 break;
2261
2262                 /*
2263                  *      IPv6 addresses are 16 octets long
2264                  */
2265         case PW_TYPE_IPV6ADDR:
2266                 if (vp->length != 16) goto raw;
2267                 /* vp->vp_ipv6addr == vp->vp_octets */
2268                 break;
2269
2270                 /*
2271                  *      IPv6 prefixes are 2 to 18 octets long.
2272                  *
2273                  *      RFC 3162: The first octet is unused.
2274                  *      The second is the length of the prefix
2275                  *      the rest are the prefix data.
2276                  *
2277                  *      The prefix length can have value 0 to 128.
2278                  */
2279         case PW_TYPE_IPV6PREFIX:
2280                 if (vp->length < 2 || vp->length > 18) goto raw;
2281                 if (vp->vp_octets[1] > 128) goto raw;
2282
2283                 /*
2284                  *      FIXME: double-check that
2285                  *      (vp->vp_octets[1] >> 3) matches vp->length + 2
2286                  */
2287                 if (vp->length < 18) {
2288                         memset(vp->vp_octets + vp->length, 0,
2289                                18 - vp->length);
2290                 }
2291                 break;
2292
2293         case PW_TYPE_SIGNED:
2294                 if (vp->length != 4) goto raw;
2295
2296                 /*
2297                  *      Overload vp_integer for ntohl, which takes
2298                  *      uint32_t, not int32_t
2299                  */
2300                 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2301                 vp->vp_integer = ntohl(vp->vp_integer);
2302                 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2303                 break;
2304
2305         case PW_TYPE_TLV:
2306                 vp->length = length;
2307                 vp->vp_tlv = malloc(length);
2308                 if (!vp->vp_tlv) {
2309                         pairfree(&vp);
2310                         fr_strerror_printf("No memory");
2311                         return NULL;
2312                 }
2313                 memcpy(vp->vp_tlv, data, length);
2314                 break;
2315
2316         case PW_TYPE_COMBO_IP:
2317                 if (vp->length == 4) {
2318                         vp->type = PW_TYPE_IPADDR;
2319                         memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2320                         break;
2321
2322                 } else if (vp->length == 16) {
2323                         vp->type = PW_TYPE_IPV6ADDR;
2324                         /* vp->vp_ipv6addr == vp->vp_octets */
2325                         break;
2326
2327                 }
2328                 /* FALL-THROUGH */
2329
2330         default:
2331         raw:
2332                 vp->type = PW_TYPE_OCTETS;
2333                 vp->length = length;
2334                 memcpy(vp->vp_octets, data, length);
2335
2336
2337                 /*
2338                  *      Ensure there's no encryption or tag stuff,
2339                  *      we just pass the attribute as-is.
2340                  */
2341                 memset(&vp->flags, 0, sizeof(vp->flags));
2342         }
2343
2344         return vp;
2345 }
2346
2347 static void rad_sortvp(VALUE_PAIR **head)
2348 {
2349         int swapped;
2350         VALUE_PAIR *vp, **tail;
2351
2352         /*
2353          *      Walk over the VP's, sorting them in order.  Did I
2354          *      mention that I hate WiMAX continuations?
2355          *
2356          *      And bubble sort!  WTF is up with that?
2357          */
2358         do {
2359                 swapped = 0;
2360                 tail = head;
2361                 while (*tail) {
2362                         vp = *tail;
2363                         if (!vp->next) break;
2364
2365                         if (vp->attribute > vp->next->attribute) {
2366                                 *tail = vp->next;
2367                                 vp->next = (*tail)->next;
2368                                 (*tail)->next = vp;
2369                                 swapped = 1;
2370                         }
2371                         tail = &(vp->next);
2372                 }
2373         } while (swapped);
2374 }
2375
2376
2377 /*
2378  *      Walk the packet, looking for continuations of this attribute.
2379  *
2380  *      This is (worst-case) O(N^2) in the number of RADIUS
2381  *      attributes.  That happens only when perverse clients create
2382  *      continued attributes, AND separate the fragmented portions
2383  *      with a lot of other attributes.
2384  *
2385  *      Sane clients should put the fragments next to each other, in
2386  *      which case this is O(N), in the number of fragments.
2387  */
2388 static uint8_t *rad_coalesce(int attribute, size_t length, uint8_t *data,
2389                              size_t packet_length, size_t *ptlv_length)
2390                              
2391 {
2392         uint32_t lvalue;
2393         size_t tlv_length = length;
2394         uint8_t *ptr, *tlv, *tlv_data;
2395
2396         for (ptr = data + length;
2397              ptr != (data + packet_length);
2398              ptr += ptr[1]) {
2399                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2400                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2401                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2402                         continue;
2403                 }
2404
2405                 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2406                 lvalue = ntohl(lvalue);
2407                 lvalue <<= 16;
2408                 lvalue |= ptr[2 + 4]; /* add in VSA number */
2409                 if (lvalue != attribute) continue;
2410
2411                 /*
2412                  *      If the vendor-length is too small, it's badly
2413                  *      formed, so we stop.
2414                  */
2415                 if ((ptr[2 + 4 + 1]) < 3) break;
2416
2417                 tlv_length += ptr[2 + 4 + 1] - 3;
2418                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2419         }
2420
2421         tlv = tlv_data = malloc(tlv_length);
2422         if (!tlv_data) return NULL;
2423
2424         memcpy(tlv, data, length);
2425         tlv += length;
2426
2427         /*
2428          *      Now we walk the list again, copying the data over to
2429          *      our newly created memory.
2430          */
2431         for (ptr = data + length;
2432              ptr != (data + packet_length);
2433              ptr += ptr[1]) {
2434                 int this_length;
2435
2436                 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2437                     (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2438                     (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2439                         continue;
2440                 }
2441
2442                 memcpy(&lvalue, ptr + 2, 4);
2443                 lvalue = ntohl(lvalue);
2444                 lvalue <<= 16;
2445                 lvalue |= ptr[2 + 4];
2446                 if (lvalue != attribute) continue;
2447
2448                 /*
2449                  *      If the vendor-length is too small, it's badly
2450                  *      formed, so we stop.
2451                  */
2452                 if ((ptr[2 + 4 + 1]) < 3) break;
2453
2454                 this_length = ptr[2 + 4 + 1] - 3;
2455                 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2456                 tlv += this_length;
2457
2458                 ptr[2 + 4] = 0; /* What a hack! */
2459                 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2460         }
2461
2462         *ptlv_length = tlv_length;
2463         return tlv_data;
2464 }
2465
2466 /*
2467  *      Start at the *data* portion of a continued attribute.  search
2468  *      through the rest of the attributes to find a matching one, and
2469  *      add it's contents to our contents.
2470  */
2471 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2472                                        const RADIUS_PACKET *original,
2473                                        const char *secret, int attribute,
2474                                        int length, /* CANNOT be zero */
2475                                        uint8_t *data, size_t packet_length,
2476                                        int flag, DICT_ATTR *da)
2477 {
2478         size_t tlv_length, left;
2479         uint8_t *ptr;
2480         uint8_t *tlv_data;
2481         VALUE_PAIR *vp, *head, **tail;
2482
2483         /*
2484          *      Ensure we have data that hasn't been split across
2485          *      multiple attributes.
2486          */
2487         if (flag) {
2488                 tlv_data = rad_coalesce(attribute, length,
2489                                         data, packet_length, &tlv_length);
2490                 if (!tlv_data) return NULL;
2491         } else {
2492                 tlv_data = data;
2493                 tlv_length = length;
2494         }
2495
2496         /*
2497          *      Non-TLV types cannot be continued across multiple
2498          *      attributes.  This is true even of keys that are
2499          *      encrypted with the tunnel-password method.  The spec
2500          *      says that they can be continued... but also that the
2501          *      keys are 160 bits, which means that they CANNOT be
2502          *      continued.  <sigh>
2503          *
2504          *      Note that we don't check "flag" here.  The calling
2505          *      code ensures that 
2506          */
2507         if (da->type != PW_TYPE_TLV) {
2508         not_well_formed:
2509                 if (tlv_data == data) { /* true if we had 'goto' */
2510                         tlv_data = malloc(tlv_length);
2511                         if (!tlv_data) return NULL;
2512                         memcpy(tlv_data, data, tlv_length);
2513                 }
2514                 
2515                 vp = paircreate(attribute, PW_TYPE_OCTETS);
2516                 if (!vp) return NULL;
2517                         
2518                 vp->type = PW_TYPE_TLV;
2519                 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2520                 vp->flags.has_tag = 0;
2521                 vp->flags.is_tlv = 0;
2522                 vp->vp_tlv = tlv_data;
2523                 vp->length = tlv_length;
2524                 return vp;
2525         } /* else it WAS a TLV, go decode the sub-tlv's */
2526
2527         /*
2528          *      Now (sigh) we walk over the TLV, seeing if it is
2529          *      well-formed.
2530          */
2531         left = tlv_length;
2532         for (ptr = tlv_data;
2533              ptr != (tlv_data + tlv_length);
2534              ptr += ptr[1]) {
2535                 if ((left < 2) ||
2536                     (ptr[1] < 2) ||
2537                     (ptr[1] > left)) {
2538                         goto not_well_formed;
2539                 }
2540                 left -= ptr[1];
2541         }
2542
2543         /*
2544          *      Now we walk over the TLV *again*, creating sub-tlv's.
2545          */
2546         head = NULL;
2547         tail = &head;
2548
2549         for (ptr = tlv_data;
2550              ptr != (tlv_data + tlv_length);
2551              ptr += ptr[1]) {
2552                 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2553                 if (!vp) {
2554                         pairfree(&head);
2555                         goto not_well_formed;
2556                 }
2557
2558                 if (!data2vp(packet, original, secret,
2559                              ptr[0], ptr[1] - 2, ptr + 2, vp)) {
2560                         pairfree(&head);
2561                         goto not_well_formed;
2562                 }
2563
2564                 *tail = vp;
2565                 tail = &(vp->next);
2566         }
2567
2568         /*
2569          *      TLV's MAY be continued, but sometimes they're not.
2570          */
2571         if (tlv_data != data) free(tlv_data);
2572
2573         if (head->next) rad_sortvp(&head);
2574
2575         return head;
2576 }
2577
2578
2579 /*
2580  *      Parse a RADIUS attribute into a data structure.
2581  */
2582 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2583                         const char *secret, int attribute, int length,
2584                         const uint8_t *data)
2585 {
2586         VALUE_PAIR *vp;
2587
2588         vp = paircreate(attribute, PW_TYPE_OCTETS);
2589         if (!vp) return NULL;
2590
2591         return data2vp(packet, original, secret, attribute, length, data, vp);
2592 }
2593
2594
2595 /*
2596  *      Calculate/check digest, and decode radius attributes.
2597  *      Returns:
2598  *      -1 on decoding error
2599  *      0 on success
2600  */
2601 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2602                const char *secret)
2603 {
2604         uint32_t                lvalue;
2605         uint32_t                vendorcode;
2606         VALUE_PAIR              **tail;
2607         VALUE_PAIR              *pair;
2608         uint8_t                 *ptr, *vsa_ptr;
2609         int                     packet_length;
2610         int                     attribute;
2611         int                     attrlen;
2612         int                     vendorlen;
2613         radius_packet_t         *hdr;
2614         int                     vsa_tlen, vsa_llen, vsa_offset;
2615         DICT_VENDOR             *dv = NULL;
2616         int                     num_attributes = 0;
2617
2618         /*
2619          *      Extract attribute-value pairs
2620          */
2621         hdr = (radius_packet_t *)packet->data;
2622         ptr = hdr->data;
2623         packet_length = packet->data_len - AUTH_HDR_LEN;
2624
2625         /*
2626          *      There may be VP's already in the packet.  Don't
2627          *      destroy them.
2628          */
2629         for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2630                 /* nothing */
2631         }
2632
2633         vendorcode = 0;
2634         vendorlen  = 0;
2635         vsa_tlen = vsa_llen = 1;
2636         vsa_offset = 0;
2637
2638         /*
2639          *      We have to read at least two bytes.
2640          *
2641          *      rad_recv() above ensures that this is OK.
2642          */
2643         while (packet_length > 0) {
2644                 attribute = -1;
2645                 attrlen = -1;
2646
2647                 /*
2648                  *      Normal attribute, handle it like normal.
2649                  */
2650                 if (vendorcode == 0) {
2651                         /*
2652                          *      No room to read attr/length,
2653                          *      or bad attribute, or attribute is
2654                          *      too short, or attribute is too long,
2655                          *      stop processing the packet.
2656                          */
2657                         if ((packet_length < 2) ||
2658                             (ptr[0] == 0) ||  (ptr[1] < 2) ||
2659                             (ptr[1] > packet_length)) break;
2660
2661                         attribute = *ptr++;
2662                         attrlen   = *ptr++;
2663
2664                         attrlen -= 2;
2665                         packet_length  -= 2;
2666
2667                         if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2668
2669                         /*
2670                          *      No vendor code, or ONLY vendor code.
2671                          */
2672                         if (attrlen <= 4) goto create_pair;
2673
2674                         vendorlen = 0;
2675                 }
2676
2677                 /*
2678                  *      Handle Vendor-Specific
2679                  */
2680                 if (vendorlen == 0) {
2681                         uint8_t *subptr;
2682                         int sublen;
2683                         int myvendor;
2684
2685                         /*
2686                          *      attrlen was checked above.
2687                          */
2688                         memcpy(&lvalue, ptr, 4);
2689                         myvendor = ntohl(lvalue);
2690
2691                         /*
2692                          *      Zero isn't allowed.
2693                          */
2694                         if (myvendor == 0) goto create_pair;
2695
2696                         /*
2697                          *      This is an implementation issue.
2698                          *      We currently pack vendor into the upper
2699                          *      16 bits of a 32-bit attribute number,
2700                          *      so we can't handle vendor numbers larger
2701                          *      than 16 bits.
2702                          */
2703                         if (myvendor > 65535) goto create_pair;
2704
2705                         vsa_tlen = vsa_llen = 1;
2706                         vsa_offset = 0;
2707                         dv = dict_vendorbyvalue(myvendor);
2708                         if (dv) {
2709                                 vsa_tlen = dv->type;
2710                                 vsa_llen = dv->length;
2711                                 if (dv->flags) vsa_offset = 1;
2712                         }
2713
2714                         /*
2715                          *      Sweep through the list of VSA's,
2716                          *      seeing if they exactly fill the
2717                          *      outer Vendor-Specific attribute.
2718                          *
2719                          *      If not, create a raw Vendor-Specific.
2720                          */
2721                         subptr = ptr + 4;
2722                         sublen = attrlen - 4;
2723
2724                         /*
2725                          *      See if we can parse it.
2726                          */
2727                         do {
2728                                 int myattr = 0;
2729
2730                                 /*
2731                                  *      Not enough room for one more
2732                                  *      attribute.  Die!
2733                                  */
2734                                 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2735
2736                                 /*
2737                                  *      Ensure that the attribute number
2738                                  *      is OK.
2739                                  */
2740                                 switch (vsa_tlen) {
2741                                 case 1:
2742                                         myattr = subptr[0];
2743                                         break;
2744
2745                                 case 2:
2746                                         myattr = (subptr[0] << 8) | subptr[1];
2747                                         break;
2748
2749                                 case 4:
2750                                         if ((subptr[0] != 0) ||
2751                                             (subptr[1] != 0)) goto create_pair;
2752
2753                                         myattr = (subptr[2] << 8) | subptr[3];
2754                                         break;
2755
2756                                         /*
2757                                          *      Our dictionary is broken.
2758                                          */
2759                                 default:
2760                                         goto create_pair;
2761                                 }
2762
2763                                 switch (vsa_llen) {
2764                                 case 0:
2765                                         attribute = (myvendor << 16) | myattr;
2766                                         ptr += 4 + vsa_tlen;
2767                                         attrlen -= (4 + vsa_tlen);
2768                                         packet_length -= 4 + vsa_tlen;
2769                                         goto create_pair;
2770
2771                                 case 1:
2772                                         if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2773                                                 goto create_pair;
2774
2775                                         if (subptr[vsa_tlen] > sublen)
2776                                                 goto create_pair;
2777
2778                                         /*
2779                                          *      WiMAX: 0bCrrrrrrr
2780                                          *      Reserved bits MUST be
2781                                          *      zero.
2782                                          */
2783                                         if (vsa_offset &&
2784                                             ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2785                                                 goto create_pair;
2786
2787                                         sublen -= subptr[vsa_tlen];
2788                                         subptr += subptr[vsa_tlen];
2789                                         break;
2790
2791                                 case 2:
2792                                         if (subptr[vsa_tlen] != 0) goto create_pair;
2793                                         if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2794                                                 goto create_pair;
2795                                         if (subptr[vsa_tlen + 1] > sublen)
2796                                                 goto create_pair;
2797                                         sublen -= subptr[vsa_tlen + 1];
2798                                         subptr += subptr[vsa_tlen + 1];
2799                                         break;
2800
2801                                         /*
2802                                          *      Our dictionaries are
2803                                          *      broken.
2804                                          */
2805                                 default:
2806                                         goto create_pair;
2807                                 }
2808                         } while (sublen > 0);
2809
2810                         vendorcode = myvendor;
2811                         vendorlen = attrlen - 4;
2812                         packet_length -= 4;
2813
2814                         ptr += 4;
2815                 }
2816
2817                 /*
2818                  *      attrlen is the length of this attribute.
2819                  *      total_len is the length of the encompassing
2820                  *      attribute.
2821                  */
2822                 switch (vsa_tlen) {
2823                 case 1:
2824                         attribute = ptr[0];
2825                         break;
2826
2827                 case 2:
2828                         attribute = (ptr[0] << 8) | ptr[1];
2829                         break;
2830
2831                 default:        /* can't hit this. */
2832                         return -1;
2833                 }
2834                 attribute |= (vendorcode << 16);
2835                 vsa_ptr = ptr;
2836                 ptr += vsa_tlen;
2837
2838                 switch (vsa_llen) {
2839                 case 1:
2840                         attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2841                         break;
2842
2843                 case 2:
2844                         attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2845                         break;
2846
2847                 default:        /* can't hit this. */
2848                         return -1;
2849                 }
2850
2851                 ptr += vsa_llen + vsa_offset;
2852                 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2853                 if (vendorlen == 0) vendorcode = 0;
2854                 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2855
2856                 /*
2857                  *      Ignore VSAs that have no data.
2858                  */
2859                 if (attrlen == 0) goto next;
2860
2861                 /*
2862                  *      WiMAX attributes of type 0 are ignored.  They
2863                  *      are a secret flag to us that the attribute has
2864                  *      already been dealt with.
2865                  */
2866                 if (attribute == 0x60b50000) goto next;
2867
2868                 if (vsa_offset) {
2869                         DICT_ATTR *da;
2870
2871                         da = dict_attrbyvalue(attribute);
2872
2873                         /*
2874                          *      If it's NOT continued, AND we know
2875                          *      about it, AND it's not a TLV, we can
2876                          *      create a normal pair.
2877                          */
2878                         if (((vsa_ptr[2] & 0x80) == 0) &&
2879                             da && (da->type != PW_TYPE_TLV)) goto create_pair;
2880
2881                         /*
2882                          *      Else it IS continued, or it's a TLV.
2883                          *      Go do a lot of work to find the stuff.
2884                          */
2885                         pair = rad_continuation2vp(packet, original, secret,
2886                                                    attribute, attrlen, ptr,
2887                                                    packet_length,
2888                                                    ((vsa_ptr[2] & 0x80) != 0),
2889                                                    da);
2890                         goto created_pair;
2891                 }
2892
2893                 /*
2894                  *      Create the attribute, setting the default type
2895                  *      to 'octets'.  If the type in the dictionary
2896                  *      is different, then the dictionary type will
2897                  *      over-ride this one.
2898                  *
2899                  *      If the attribute has no data, then discard it.
2900                  *
2901                  *      Unless it's CUI.  Damn you, CUI!
2902                  */
2903         create_pair:
2904                 if (!attrlen &&
2905                     (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2906
2907                 pair = rad_attr2vp(packet, original, secret,
2908                                    attribute, attrlen, ptr);
2909                 if (!pair) {
2910                         pairfree(&packet->vps);
2911                         fr_strerror_printf("out of memory");
2912                         return -1;
2913                 }
2914
2915         created_pair:
2916                 *tail = pair;
2917                 while (pair) {
2918                         num_attributes++;
2919                         debug_pair(pair);
2920                         tail = &pair->next;
2921                         pair = pair->next;
2922                 }
2923
2924                 /*
2925                  *      VSA's may not have been counted properly in
2926                  *      rad_packet_ok() above, as it is hard to count
2927                  *      then without using the dictionary.  We
2928                  *      therefore enforce the limits here, too.
2929                  */
2930                 if ((fr_max_attributes > 0) &&
2931                     (num_attributes > fr_max_attributes)) {
2932                         char host_ipaddr[128];
2933
2934                         pairfree(&packet->vps);
2935                         fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2936                                    inet_ntop(packet->src_ipaddr.af,
2937                                              &packet->src_ipaddr.ipaddr,
2938                                              host_ipaddr, sizeof(host_ipaddr)),
2939                                    num_attributes, fr_max_attributes);
2940                         return -1;
2941                 }
2942
2943         next:
2944                 ptr += attrlen;
2945                 packet_length -= attrlen;
2946         }
2947
2948         /*
2949          *      Merge information from the outside world into our
2950          *      random pool.
2951          */
2952         fr_rand_seed(packet->data, AUTH_HDR_LEN);
2953
2954         return 0;
2955 }
2956
2957
2958 /*
2959  *      Encode password.
2960  *
2961  *      We assume that the passwd buffer passed is big enough.
2962  *      RFC2138 says the password is max 128 chars, so the size
2963  *      of the passwd buffer must be at least 129 characters.
2964  *      Preferably it's just MAX_STRING_LEN.
2965  *
2966  *      int *pwlen is updated to the new length of the encrypted
2967  *      password - a multiple of 16 bytes.
2968  */
2969 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2970                  const uint8_t *vector)
2971 {
2972         FR_MD5_CTX context, old;
2973         uint8_t digest[AUTH_VECTOR_LEN];
2974         int     i, n, secretlen;
2975         int     len;
2976
2977         /*
2978          *      RFC maximum is 128 bytes.
2979          *
2980          *      If length is zero, pad it out with zeros.
2981          *
2982          *      If the length isn't aligned to 16 bytes,
2983          *      zero out the extra data.
2984          */
2985         len = *pwlen;
2986
2987         if (len > 128) len = 128;
2988
2989         if (len == 0) {
2990                 memset(passwd, 0, AUTH_PASS_LEN);
2991                 len = AUTH_PASS_LEN;
2992         } else if ((len % AUTH_PASS_LEN) != 0) {
2993                 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2994                 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2995         }
2996         *pwlen = len;
2997
2998         /*
2999          *      Use the secret to setup the decryption digest
3000          */
3001         secretlen = strlen(secret);
3002
3003         fr_MD5Init(&context);
3004         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3005         old = context;          /* save intermediate work */
3006
3007         /*
3008          *      Encrypt it in place.  Don't bother checking
3009          *      len, as we've ensured above that it's OK.
3010          */
3011         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3012                 if (n == 0) {
3013                         fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3014                         fr_MD5Final(digest, &context);
3015                 } else {
3016                         context = old;
3017                         fr_MD5Update(&context,
3018                                      (uint8_t *) passwd + n - AUTH_PASS_LEN,
3019                                      AUTH_PASS_LEN);
3020                         fr_MD5Final(digest, &context);
3021                 }
3022
3023                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3024                         passwd[i + n] ^= digest[i];
3025                 }
3026         }
3027
3028         return 0;
3029 }
3030
3031 /*
3032  *      Decode password.
3033  */
3034 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3035                  const uint8_t *vector)
3036 {
3037         FR_MD5_CTX context, old;
3038         uint8_t digest[AUTH_VECTOR_LEN];
3039         int     i;
3040         size_t  n, secretlen;
3041
3042         /*
3043          *      The RFC's say that the maximum is 128.
3044          *      The buffer we're putting it into above is 254, so
3045          *      we don't need to do any length checking.
3046          */
3047         if (pwlen > 128) pwlen = 128;
3048
3049         /*
3050          *      Catch idiots.
3051          */
3052         if (pwlen == 0) goto done;
3053
3054         /*
3055          *      Use the secret to setup the decryption digest
3056          */
3057         secretlen = strlen(secret);
3058
3059         fr_MD5Init(&context);
3060         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3061         old = context;          /* save intermediate work */
3062
3063         /*
3064          *      The inverse of the code above.
3065          */
3066         for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3067                 if (n == 0) {
3068                         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3069                         fr_MD5Final(digest, &context);
3070
3071                         context = old;
3072                         if (pwlen > AUTH_PASS_LEN) {
3073                                 fr_MD5Update(&context, (uint8_t *) passwd,
3074                                              AUTH_PASS_LEN);
3075                         }
3076                 } else {
3077                         fr_MD5Final(digest, &context);
3078
3079                         context = old;
3080                         if (pwlen > (n + AUTH_PASS_LEN)) {
3081                                 fr_MD5Update(&context, (uint8_t *) passwd + n,
3082                                              AUTH_PASS_LEN);
3083                         }
3084                 }
3085
3086                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3087                         passwd[i + n] ^= digest[i];
3088                 }
3089         }
3090
3091  done:
3092         passwd[pwlen] = '\0';
3093         return strlen(passwd);
3094 }
3095
3096
3097 /*
3098  *      Encode Tunnel-Password attributes when sending them out on the wire.
3099  *
3100  *      int *pwlen is updated to the new length of the encrypted
3101  *      password - a multiple of 16 bytes.
3102  *
3103  *      This is per RFC-2868 which adds a two char SALT to the initial intermediate
3104  *      value MD5 hash.
3105  */
3106 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3107                         const uint8_t *vector)
3108 {
3109         uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3110         unsigned char   digest[AUTH_VECTOR_LEN];
3111         char*   salt;
3112         int     i, n, secretlen;
3113         unsigned len, n2;
3114
3115         len = *pwlen;
3116
3117         if (len > 127) len = 127;
3118
3119         /*
3120          * Shift the password 3 positions right to place a salt and original
3121          * length, tag will be added automatically on packet send
3122          */
3123         for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3124         salt = passwd;
3125         passwd += 2;
3126         /*
3127          * save original password length as first password character;
3128          */
3129         *passwd = len;
3130         len += 1;
3131
3132
3133         /*
3134          *      Generate salt.  The RFC's say:
3135          *
3136          *      The high bit of salt[0] must be set, each salt in a
3137          *      packet should be unique, and they should be random
3138          *
3139          *      So, we set the high bit, add in a counter, and then
3140          *      add in some CSPRNG data.  should be OK..
3141          */
3142         salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3143                    (fr_rand() & 0x07));
3144         salt[1] = fr_rand();
3145
3146         /*
3147          *      Padd password to multiple of AUTH_PASS_LEN bytes.
3148          */
3149         n = len % AUTH_PASS_LEN;
3150         if (n) {
3151                 n = AUTH_PASS_LEN - n;
3152                 for (; n > 0; n--, len++)
3153                         passwd[len] = 0;
3154         }
3155         /* set new password length */
3156         *pwlen = len + 2;
3157
3158         /*
3159          *      Use the secret to setup the decryption digest
3160          */
3161         secretlen = strlen(secret);
3162         memcpy(buffer, secret, secretlen);
3163
3164         for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3165                 if (!n2) {
3166                         memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3167                         memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3168                         fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3169                 } else {
3170                         memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3171                         fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3172                 }
3173
3174                 for (i = 0; i < AUTH_PASS_LEN; i++) {
3175                         passwd[i + n2] ^= digest[i];
3176                 }
3177         }
3178         passwd[n2] = 0;
3179         return 0;
3180 }
3181
3182 /*
3183  *      Decode Tunnel-Password encrypted attributes.
3184  *
3185  *      Defined in RFC-2868, this uses a two char SALT along with the
3186  *      initial intermediate value, to differentiate it from the
3187  *      above.
3188  */
3189 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3190                         const uint8_t *vector)
3191 {
3192         FR_MD5_CTX  context, old;
3193         uint8_t         digest[AUTH_VECTOR_LEN];
3194         int             secretlen;
3195         unsigned        i, n, len, reallen;
3196
3197         len = *pwlen;
3198
3199         /*
3200          *      We need at least a salt.
3201          */
3202         if (len < 2) {
3203                 fr_strerror_printf("tunnel password is too short");
3204                 return -1;
3205         }
3206
3207         /*
3208          *      There's a salt, but no password.  Or, there's a salt
3209          *      and a 'data_len' octet.  It's wrong, but at least we
3210          *      can figure out what it means: the password is empty.
3211          *
3212          *      Note that this means we ignore the 'data_len' field,
3213          *      if the attribute length tells us that there's no
3214          *      more data.  So the 'data_len' field may be wrong,
3215          *      but that's ok...
3216          */
3217         if (len <= 3) {
3218                 passwd[0] = 0;
3219                 *pwlen = 0;
3220                 return 0;
3221         }
3222
3223         len -= 2;               /* discount the salt */
3224
3225         /*
3226          *      Use the secret to setup the decryption digest
3227          */
3228         secretlen = strlen(secret);
3229
3230         fr_MD5Init(&context);
3231         fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3232         old = context;          /* save intermediate work */
3233
3234         /*
3235          *      Set up the initial key:
3236          *
3237          *       b(1) = MD5(secret + vector + salt)
3238          */
3239         fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3240         fr_MD5Update(&context, passwd, 2);
3241
3242         reallen = 0;
3243         for (n = 0; n < len; n += AUTH_PASS_LEN) {
3244                 int base = 0;
3245
3246                 if (n == 0) {
3247                         fr_MD5Final(digest, &context);
3248
3249                         context = old;
3250
3251                         /*
3252                          *      A quick check: decrypt the first octet
3253                          *      of the password, which is the
3254                          *      'data_len' field.  Ensure it's sane.
3255                          */
3256                         reallen = passwd[2] ^ digest[0];
3257                         if (reallen >= len) {
3258                                 fr_strerror_printf("tunnel password is too long for the attribute");
3259                                 return -1;
3260                         }
3261
3262                         fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3263
3264                         base = 1;
3265                 } else {
3266                         fr_MD5Final(digest, &context);
3267
3268                         context = old;
3269                         fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3270                 }
3271
3272                 for (i = base; i < AUTH_PASS_LEN; i++) {
3273                         passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3274                 }
3275         }
3276
3277         /*
3278          *      See make_tunnel_password, above.
3279          */
3280         if (reallen > 239) reallen = 239;
3281
3282         *pwlen = reallen;
3283         passwd[reallen] = 0;
3284
3285         return reallen;
3286 }
3287
3288 /*
3289  *      Encode a CHAP password
3290  *
3291  *      FIXME: might not work with Ascend because
3292  *      we use vp->length, and Ascend gear likes
3293  *      to send an extra '\0' in the string!
3294  */
3295 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3296                     VALUE_PAIR *password)
3297 {
3298         int             i;
3299         uint8_t         *ptr;
3300         uint8_t         string[MAX_STRING_LEN * 2 + 1];
3301         VALUE_PAIR      *challenge;
3302
3303         /*
3304          *      Sanity check the input parameters
3305          */
3306         if ((packet == NULL) || (password == NULL)) {
3307                 return -1;
3308         }
3309
3310         /*
3311          *      Note that the password VP can be EITHER
3312          *      a User-Password attribute (from a check-item list),
3313          *      or a CHAP-Password attribute (the client asking
3314          *      the library to encode it).
3315          */
3316
3317         i = 0;
3318         ptr = string;
3319         *ptr++ = id;
3320
3321         i++;
3322         memcpy(ptr, password->vp_strvalue, password->length);
3323         ptr += password->length;
3324         i += password->length;
3325
3326         /*
3327          *      Use Chap-Challenge pair if present,
3328          *      Request-Authenticator otherwise.
3329          */
3330         challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3331         if (challenge) {
3332                 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3333                 i += challenge->length;
3334         } else {
3335                 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3336                 i += AUTH_VECTOR_LEN;
3337         }
3338
3339         *output = id;
3340         fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3341
3342         return 0;
3343 }
3344
3345
3346 /*
3347  *      Seed the random number generator.
3348  *
3349  *      May be called any number of times.
3350  */
3351 void fr_rand_seed(const void *data, size_t size)
3352 {
3353         uint32_t hash;
3354
3355         /*
3356          *      Ensure that the pool is initialized.
3357          */
3358         if (!fr_rand_initialized) {
3359                 int fd;
3360
3361                 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3362
3363                 fd = open("/dev/urandom", O_RDONLY);
3364                 if (fd >= 0) {
3365                         size_t total;
3366                         ssize_t this;
3367
3368                         total = this = 0;
3369                         while (total < sizeof(fr_rand_pool.randrsl)) {
3370                                 this = read(fd, fr_rand_pool.randrsl,
3371                                             sizeof(fr_rand_pool.randrsl) - total);
3372                                 if ((this < 0) && (errno != EINTR)) break;
3373                                 if (this > 0) total += this;
3374                         }
3375                         close(fd);
3376                 } else {
3377                         fr_rand_pool.randrsl[0] = fd;
3378                         fr_rand_pool.randrsl[1] = time(NULL);
3379                         fr_rand_pool.randrsl[2] = errno;
3380                 }
3381
3382                 fr_randinit(&fr_rand_pool, 1);
3383                 fr_rand_pool.randcnt = 0;
3384                 fr_rand_initialized = 1;
3385         }
3386
3387         if (!data) return;
3388
3389         /*
3390          *      Hash the user data
3391          */
3392         hash = fr_rand();
3393         if (!hash) hash = fr_rand();
3394         hash = fr_hash_update(data, size, hash);
3395
3396         fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3397 }
3398
3399
3400 /*
3401  *      Return a 32-bit random number.
3402  */
3403 uint32_t fr_rand(void)
3404 {
3405         uint32_t num;
3406
3407         /*
3408          *      Ensure that the pool is initialized.
3409          */
3410         if (!fr_rand_initialized) {
3411                 fr_rand_seed(NULL, 0);
3412         }
3413
3414         num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3415         if (fr_rand_pool.randcnt >= 256) {
3416                 fr_rand_pool.randcnt = 0;
3417                 fr_isaac(&fr_rand_pool);
3418         }
3419
3420         return num;
3421 }
3422
3423
3424 /*
3425  *      Allocate a new RADIUS_PACKET
3426  */
3427 RADIUS_PACKET *rad_alloc(int newvector)
3428 {
3429         RADIUS_PACKET   *rp;
3430
3431         if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3432                 fr_strerror_printf("out of memory");
3433                 return NULL;
3434         }
3435         memset(rp, 0, sizeof(*rp));
3436         rp->id = -1;
3437         rp->offset = -1;
3438
3439         if (newvector) {
3440                 int i;
3441                 uint32_t hash, base;
3442
3443                 /*
3444                  *      Don't expose the actual contents of the random
3445                  *      pool.
3446                  */
3447                 base = fr_rand();
3448                 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3449                         hash = fr_rand() ^ base;
3450                         memcpy(rp->vector + i, &hash, sizeof(hash));
3451                 }
3452         }
3453         fr_rand();              /* stir the pool again */
3454
3455         return rp;
3456 }
3457
3458 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3459 {
3460         RADIUS_PACKET *reply;
3461
3462         if (!packet) return NULL;
3463
3464         reply = rad_alloc(0);
3465         if (!reply) return NULL;
3466
3467         /*
3468          *      Initialize the fields from the request.
3469          */
3470         reply->sockfd = packet->sockfd;
3471         reply->dst_ipaddr = packet->src_ipaddr;
3472         reply->src_ipaddr = packet->dst_ipaddr;
3473         reply->dst_port = packet->src_port;
3474         reply->src_port = packet->dst_port;
3475         reply->id = packet->id;
3476         reply->code = 0; /* UNKNOWN code */
3477         memcpy(reply->vector, packet->vector,
3478                sizeof(reply->vector));
3479         reply->vps = NULL;
3480         reply->data = NULL;
3481         reply->data_len = 0;
3482
3483         return reply;
3484 }
3485
3486
3487 /*
3488  *      Free a RADIUS_PACKET
3489  */
3490 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3491 {
3492         RADIUS_PACKET *radius_packet;
3493
3494         if (!radius_packet_ptr || !*radius_packet_ptr) return;
3495         radius_packet = *radius_packet_ptr;
3496
3497         free(radius_packet->data);
3498
3499         pairfree(&radius_packet->vps);
3500
3501         free(radius_packet);
3502
3503         *radius_packet_ptr = NULL;
3504 }