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