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