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