2 * This library is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU Lesser General Public
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version. either
6 * version 2.1 of the License, or (at your option) any later version.
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * @brief Functions to send/receive radius packets.
24 * @copyright 2000-2003,2006 The FreeRADIUS server project
29 #include <freeradius-devel/libradius.h>
31 #include <freeradius-devel/md5.h>
37 #include <freeradius-devel/udpfromto.h>
41 #define VP_TRACE printf
43 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
47 printf("--- %s ---\n", msg);
48 for (i = 0; i < len; i++) {
49 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
50 printf("%02x ", data[i]);
51 if ((i & 0x0f) == 0x0f) printf("\n");
53 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
58 #define VP_TRACE(_x, ...)
59 #define VP_HEXDUMP(_x, _y, _z)
64 * The RFC says 4096 octets max, and most packets are less than 256.
66 #define MAX_PACKET_LEN 4096
69 * The maximum number of attributes which we allow in an incoming
70 * request. If there are more attributes than this, the request
73 * This helps to minimize the potential for a DoS, when an
74 * attacker spoofs Access-Request packets, which don't have a
75 * Message-Authenticator attribute. This means that the packet
76 * is unsigned, and the attacker can use resources on the server,
77 * even if the end request is rejected.
79 uint32_t fr_max_attributes = 0;
80 FILE *fr_log_fp = NULL;
82 typedef struct radius_packet_t {
86 uint8_t vector[AUTH_VECTOR_LEN];
90 static fr_randctx fr_rand_pool; /* across multiple calls */
91 static int fr_rand_initialized = 0;
92 static unsigned int salt_offset = 0;
93 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
95 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
100 "Accounting-Request",
101 "Accounting-Response",
106 "Accounting-Message", //!< 10
117 "Resource-Free-Request",
118 "Resource-Free-Response",
119 "Resource-Query-Request",
120 "Resource-Query-Response",
121 "Alternate-Resource-Reclaim-Request",
122 "NAS-Reboot-Request",
123 "NAS-Reboot-Response",
136 "Disconnect-Request", //!< 40
146 "IP-Address-Allocate",
147 "IP-Address-Release", //!< 50
151 void fr_printf_log(char const *fmt, ...)
156 if ((fr_debug_lvl == 0) || !fr_log_fp) {
161 vfprintf(fr_log_fp, fmt, ap);
167 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
169 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
173 for (i = 0; i < attrlen; i++) {
174 if ((i > 0) && ((i & 0x0f) == 0x00))
175 fprintf(fr_log_fp, "%.*s", depth, tabs);
176 fprintf(fr_log_fp, "%02x ", ptr[i]);
177 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
179 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
183 void rad_print_hex(RADIUS_PACKET *packet)
187 if (!packet->data || !fr_log_fp) return;
189 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
190 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
191 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
193 fprintf(fr_log_fp, " Vector:\t");
194 for (i = 4; i < 20; i++) {
195 fprintf(fr_log_fp, "%02x", packet->data[i]);
197 fprintf(fr_log_fp, "\n");
199 if (packet->data_len > 20) {
202 fprintf(fr_log_fp, " Data:");
204 total = packet->data_len - 20;
205 ptr = packet->data + 20;
209 unsigned int vendor = 0;
211 fprintf(fr_log_fp, "\t\t");
212 if (total < 2) { /* too short */
213 fprintf(fr_log_fp, "%02x\n", *ptr);
217 if (ptr[1] > total) { /* too long */
218 for (i = 0; i < total; i++) {
219 fprintf(fr_log_fp, "%02x ", ptr[i]);
224 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
225 attrlen = ptr[1] - 2;
227 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
229 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
230 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
231 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
241 print_hex_data(ptr, attrlen, 3);
250 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
253 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
254 #ifdef WITH_UDPFROMTO
255 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
257 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
259 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
262 struct sockaddr_storage dst;
263 socklen_t sizeof_dst;
265 #ifdef WITH_UDPFROMTO
266 struct sockaddr_storage src;
267 socklen_t sizeof_src;
269 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
272 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
276 #ifdef WITH_UDPFROMTO
278 * And if they don't specify a source IP address, don't
281 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
282 (src_ipaddr->af != AF_UNSPEC) &&
283 !fr_inaddr_any(src_ipaddr)) {
284 rcode = sendfromto(sockfd, data, data_len, flags,
285 (struct sockaddr *)&src, sizeof_src,
286 (struct sockaddr *)&dst, sizeof_dst);
292 * No udpfromto, fail gracefully.
294 rcode = sendto(sockfd, data, data_len, flags,
295 (struct sockaddr *) &dst, sizeof_dst);
296 #ifdef WITH_UDPFROMTO
300 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
307 void rad_recv_discard(int sockfd)
310 struct sockaddr_storage src;
311 socklen_t sizeof_src = sizeof(src);
313 (void) recvfrom(sockfd, header, sizeof(header), 0,
314 (struct sockaddr *)&src, &sizeof_src);
318 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
320 ssize_t data_len, packet_len;
322 struct sockaddr_storage src;
323 socklen_t sizeof_src = sizeof(src);
325 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
326 (struct sockaddr *)&src, &sizeof_src);
328 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
333 * Too little data is available, discard the packet.
336 rad_recv_discard(sockfd);
340 } else { /* we got 4 bytes of data. */
342 * See how long the packet says it is.
344 packet_len = (header[2] * 256) + header[3];
347 * The length in the packet says it's less than
348 * a RADIUS header length: discard it.
350 if (packet_len < RADIUS_HDR_LEN) {
351 rad_recv_discard(sockfd);
356 * Enforce RFC requirements, for sanity.
357 * Anything after 4k will be discarded.
359 } else if (packet_len > MAX_PACKET_LEN) {
360 rad_recv_discard(sockfd);
367 * Convert AF. If unknown, discard packet.
369 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
370 rad_recv_discard(sockfd);
378 * The packet says it's this long, but the actual UDP
379 * size could still be smaller.
385 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
388 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
389 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
390 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
392 struct sockaddr_storage src;
393 struct sockaddr_storage dst;
394 socklen_t sizeof_src = sizeof(src);
395 socklen_t sizeof_dst = sizeof(dst);
401 memset(&src, 0, sizeof_src);
402 memset(&dst, 0, sizeof_dst);
405 * Read the length of the packet, from the packet.
406 * This lets us allocate the buffer to use for
407 * reading the rest of the packet.
409 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
410 (struct sockaddr *)&src, &sizeof_src);
412 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
417 * Too little data is available, discard the packet.
420 rad_recv_discard(sockfd);
424 } else { /* we got 4 bytes of data. */
426 * See how long the packet says it is.
428 len = (header[2] * 256) + header[3];
431 * The length in the packet says it's less than
432 * a RADIUS header length: discard it.
434 if (len < RADIUS_HDR_LEN) {
435 recvfrom(sockfd, header, sizeof(header), flags,
436 (struct sockaddr *)&src, &sizeof_src);
440 * Enforce RFC requirements, for sanity.
441 * Anything after 4k will be discarded.
443 } else if (len > MAX_PACKET_LEN) {
444 recvfrom(sockfd, header, sizeof(header), flags,
445 (struct sockaddr *)&src, &sizeof_src);
450 packet->data = talloc_array(packet, uint8_t, len);
451 if (!packet->data) return -1;
454 * Receive the packet. The OS will discard any data in the
455 * packet after "len" bytes.
457 #ifdef WITH_UDPFROMTO
458 data_len = recvfromto(sockfd, packet->data, len, flags,
459 (struct sockaddr *)&src, &sizeof_src,
460 (struct sockaddr *)&dst, &sizeof_dst);
462 data_len = recvfrom(sockfd, packet->data, len, flags,
463 (struct sockaddr *)&src, &sizeof_src);
466 * Get the destination address, too.
468 if (getsockname(sockfd, (struct sockaddr *)&dst,
469 &sizeof_dst) < 0) return -1;
475 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
476 return -1; /* Unknown address family, Die Die Die! */
480 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
484 * Different address families should never happen.
486 if (src.ss_family != dst.ss_family) {
494 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
495 /** Build an encrypted secret value to return in a reply packet
497 * The secret is hidden by xoring with a MD5 digest created from
498 * the shared secret and the authentication vector.
499 * We put them into MD5 in the reverse order from that used when
500 * encrypting passwords to RADIUS.
502 static void make_secret(uint8_t *digest, uint8_t const *vector,
503 char const *secret, uint8_t const *value)
508 fr_md5_init(&context);
509 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
510 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
511 fr_md5_final(digest, &context);
513 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
514 digest[i] ^= value[i];
518 #define MAX_PASS_LEN (128)
519 static void make_passwd(uint8_t *output, ssize_t *outlen,
520 uint8_t const *input, size_t inlen,
521 char const *secret, uint8_t const *vector)
523 FR_MD5_CTX context, old;
524 uint8_t digest[AUTH_VECTOR_LEN];
525 uint8_t passwd[MAX_PASS_LEN];
530 * If the length is zero, round it up.
534 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
536 memcpy(passwd, input, len);
537 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
543 else if ((len & 0x0f) != 0) {
549 fr_md5_init(&context);
550 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
556 fr_md5_update(&context, vector, AUTH_PASS_LEN);
558 for (n = 0; n < len; n += AUTH_PASS_LEN) {
561 fr_md5_update(&context,
562 passwd + n - AUTH_PASS_LEN,
566 fr_md5_final(digest, &context);
567 for (i = 0; i < AUTH_PASS_LEN; i++) {
568 passwd[i + n] ^= digest[i];
572 memcpy(output, passwd, len);
575 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
576 uint8_t const *input, size_t inlen, size_t room,
577 char const *secret, uint8_t const *vector)
579 FR_MD5_CTX context, old;
580 uint8_t digest[AUTH_VECTOR_LEN];
581 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
588 if (room > 253) room = 253;
591 * Account for 2 bytes of the salt, and round the room
592 * available down to the nearest multiple of 16. Then,
593 * subtract one from that to account for the length byte,
594 * and the resulting number is the upper bound on the data
597 * We could short-cut this calculation just be forcing
598 * inlen to be no more than 239. It would work for all
599 * VSA's, as we don't pack multiple VSA's into one
602 * However, this calculation is more general, if a little
603 * complex. And it will work in the future for all possible
604 * kinds of weird attribute packing.
607 room -= (room & 0x0f);
610 if (inlen > room) inlen = room;
613 * Length of the encrypted data is password length plus
614 * one byte for the length of the password.
617 if ((len & 0x0f) != 0) {
621 *outlen = len + 2; /* account for the salt */
624 * Copy the password over.
626 memcpy(passwd + 3, input, inlen);
627 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
630 * Generate salt. The RFC's say:
632 * The high bit of salt[0] must be set, each salt in a
633 * packet should be unique, and they should be random
635 * So, we set the high bit, add in a counter, and then
636 * add in some CSPRNG data. should be OK..
638 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
640 passwd[1] = fr_rand();
641 passwd[2] = inlen; /* length of the password string */
643 fr_md5_init(&context);
644 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
647 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
648 fr_md5_update(&context, &passwd[0], 2);
650 for (n = 0; n < len; n += AUTH_PASS_LEN) {
653 fr_md5_update(&context,
654 passwd + 2 + n - AUTH_PASS_LEN,
658 fr_md5_final(digest, &context);
660 for (i = 0; i < AUTH_PASS_LEN; i++) {
661 passwd[i + 2 + n] ^= digest[i];
664 memcpy(output, passwd, len + 2);
667 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
669 unsigned int tlv1, tlv2;
671 if (nest > fr_attr_max_tlv) return 0;
676 * Keep encoding TLVs which have the same scope.
677 * e.g. two attributes of:
678 * ATTR.TLV1.TLV2.TLV3 = data1
679 * ATTR.TLV1.TLV2.TLV4 = data2
680 * both get put into a container of "ATTR.TLV1.TLV2"
684 * Nothing to follow, we're done.
689 * Not from the same vendor, skip it.
691 if (vp->da->vendor != next->da->vendor) return 0;
694 * In a different TLV space, skip it.
697 tlv2 = next->da->attr;
699 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
700 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
702 if (tlv1 != tlv2) return 0;
708 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
709 RADIUS_PACKET const *original,
710 char const *secret, int nest,
711 VALUE_PAIR const **pvp,
712 uint8_t *start, size_t room);
714 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
715 RADIUS_PACKET const *original,
716 char const *secret, VALUE_PAIR const **pvp,
717 unsigned int attribute, uint8_t *ptr, size_t room);
719 /** Encode the *data* portion of the TLV
721 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
722 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
724 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
725 RADIUS_PACKET const *original,
726 char const *secret, int nest,
727 VALUE_PAIR const **pvp,
728 uint8_t *start, size_t room)
732 uint8_t *ptr = start;
733 VALUE_PAIR const *vp = *pvp;
734 VALUE_PAIR const *svp = vp;
739 if (nest > fr_attr_max_tlv) {
740 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
748 if (room <= 2) return ptr - start;
750 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
754 if (room > 255) my_room = 255;
756 len = vp2data_any(packet, original, secret, nest,
757 &vp, ptr + 2, my_room - 2);
758 if (len < 0) return len;
759 if (len == 0) return ptr - start;
760 /* len can NEVER be more than 253 */
765 if ((fr_debug_lvl > 3) && fr_log_fp) {
766 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
767 print_hex_data(ptr + 2, len, 3);
775 if (!do_next_tlv(svp, vp, nest)) break;
779 if ((fr_debug_lvl > 3) && fr_log_fp) {
782 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
783 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
790 /** Encodes the data portion of an attribute
792 * @return -1 on error, or the length of the data portion.
794 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
795 RADIUS_PACKET const *original,
796 char const *secret, int nest,
797 VALUE_PAIR const **pvp,
798 uint8_t *start, size_t room)
803 uint8_t *ptr = start;
806 VALUE_PAIR const *vp = *pvp;
811 * See if we need to encode a TLV. The low portion of
812 * the attribute has already been placed into the packer.
813 * If there are still attribute bytes left, then go
814 * encode them as TLVs.
816 * If we cared about the stack, we could unroll the loop.
818 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
819 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
820 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
825 * Set up the default sources for the data.
829 switch (vp->da->type) {
835 fr_strerror_printf("ERROR: Cannot encode NULL data");
841 case PW_TYPE_IPV4_ADDR:
842 case PW_TYPE_IPV6_ADDR:
843 case PW_TYPE_IPV6_PREFIX:
844 case PW_TYPE_IPV4_PREFIX:
845 case PW_TYPE_ABINARY:
846 case PW_TYPE_ETHERNET: /* just in case */
847 data = (uint8_t const *) &vp->data;
851 len = 1; /* just in case */
852 array[0] = vp->vp_byte;
857 len = 2; /* just in case */
858 array[0] = (vp->vp_short >> 8) & 0xff;
859 array[1] = vp->vp_short & 0xff;
863 case PW_TYPE_INTEGER:
864 len = 4; /* just in case */
865 lvalue = htonl(vp->vp_integer);
866 memcpy(array, &lvalue, sizeof(lvalue));
870 case PW_TYPE_INTEGER64:
871 len = 8; /* just in case */
872 lvalue64 = htonll(vp->vp_integer64);
873 data = (uint8_t *) &lvalue64;
877 * There are no tagged date attributes.
880 lvalue = htonl(vp->vp_date);
881 data = (uint8_t const *) &lvalue;
882 len = 4; /* just in case */
889 len = 4; /* just in case */
890 slvalue = htonl(vp->vp_signed);
891 memcpy(array, &slvalue, sizeof(slvalue));
896 default: /* unknown type: ignore it */
897 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
910 * Bound the data to the calling size
912 if (len > (ssize_t) room) len = room;
915 * Encrypt the various password styles
917 * Attributes with encrypted values MUST be less than
920 switch (vp->da->flags.encrypt) {
921 case FLAG_ENCRYPT_USER_PASSWORD:
922 make_passwd(ptr, &len, data, len,
923 secret, packet->vector);
926 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
928 if (vp->da->flags.has_tag) lvalue = 1;
931 * Check if there's enough room. If there isn't,
932 * we discard the attribute.
934 * This is ONLY a problem if we have multiple VSA's
935 * in one Vendor-Specific, though.
937 if (room < (18 + lvalue)) return 0;
939 switch (packet->code) {
940 case PW_CODE_ACCESS_ACCEPT:
941 case PW_CODE_ACCESS_REJECT:
942 case PW_CODE_ACCESS_CHALLENGE:
945 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
949 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
950 make_tunnel_passwd(ptr + lvalue, &len, data, len,
952 secret, original->vector);
954 case PW_CODE_ACCOUNTING_REQUEST:
955 case PW_CODE_DISCONNECT_REQUEST:
956 case PW_CODE_COA_REQUEST:
957 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
958 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
959 secret, packet->vector);
965 * The code above ensures that this attribute
968 case FLAG_ENCRYPT_ASCEND_SECRET:
969 if (len != 16) return 0;
970 make_secret(ptr, packet->vector, secret, data);
971 len = AUTH_VECTOR_LEN;
976 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
977 if (vp->da->type == PW_TYPE_STRING) {
978 if (len > ((ssize_t) (room - 1))) len = room - 1;
981 } else if (vp->da->type == PW_TYPE_INTEGER) {
983 } /* else it can't be any other type */
985 memcpy(ptr, data, len);
987 } /* switch over encryption flags */
990 return len + (ptr - start);
993 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
994 uint8_t *ptr, int hdr_len, ssize_t len,
995 int flag_offset, int vsa_offset)
997 int check_len = len - ptr[1];
998 int total = len + hdr_len;
1001 * Pass 1: Check if the addition of the headers
1002 * overflows the available room. If so, return
1003 * what we were capable of encoding.
1006 while (check_len > (255 - hdr_len)) {
1008 check_len -= (255 - hdr_len);
1012 * Note that this results in a number of attributes maybe
1013 * being marked as "encoded", but which aren't in the
1014 * packet. Oh well. The solution is to fix the
1015 * "vp2data_any" function to take into account the header
1018 if ((ptr + ptr[1] + total) > end) {
1019 return (ptr + ptr[1]) - start;
1023 * Pass 2: Now that we know there's enough room,
1024 * re-arrange the data to form a set of valid
1025 * RADIUS attributes.
1028 int sublen = 255 - ptr[1];
1030 if (len <= sublen) {
1035 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1036 memmove(ptr + 255, ptr, hdr_len);
1038 if (vsa_offset) ptr[vsa_offset] += sublen;
1039 ptr[flag_offset] |= 0x80;
1043 if (vsa_offset) ptr[vsa_offset] = 3;
1047 if (vsa_offset) ptr[vsa_offset] += len;
1049 return (ptr + ptr[1]) - start;
1053 /** Encode an "extended" attribute
1055 int rad_vp2extended(RADIUS_PACKET const *packet,
1056 RADIUS_PACKET const *original,
1057 char const *secret, VALUE_PAIR const **pvp,
1058 uint8_t *ptr, size_t room)
1062 uint8_t *start = ptr;
1063 VALUE_PAIR const *vp = *pvp;
1067 if (!vp->da->flags.extended) {
1068 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1073 * The attribute number is encoded into the upper 8 bits
1076 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1078 if (!vp->da->flags.long_extended) {
1079 if (room < 3) return 0;
1082 ptr[2] = vp->da->attr & fr_attr_mask[0];
1085 if (room < 4) return 0;
1088 ptr[2] = vp->da->attr & fr_attr_mask[0];
1093 * Only "flagged" attributes can be longer than one
1096 if (!vp->da->flags.long_extended && (room > 255)) {
1103 if (vp->da->flags.evs) {
1104 uint8_t *evs = ptr + ptr[1];
1106 if (room < (size_t) (ptr[1] + 5)) return 0;
1110 evs[0] = 0; /* always zero */
1111 evs[1] = (vp->da->vendor >> 16) & 0xff;
1112 evs[2] = (vp->da->vendor >> 8) & 0xff;
1113 evs[3] = vp->da->vendor & 0xff;
1114 evs[4] = vp->da->attr & fr_attr_mask[0];
1120 len = vp2data_any(packet, original, secret, 0,
1121 pvp, ptr + ptr[1], room - hdr_len);
1122 if (len <= 0) return len;
1125 * There may be more than 252 octets of data encoded in
1126 * the attribute. If so, move the data up in the packet,
1127 * and copy the existing header over. Set the "M" flag ONLY
1128 * after copying the rest of the data.
1130 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1131 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1137 if ((fr_debug_lvl > 3) && fr_log_fp) {
1140 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1141 if (!vp->da->flags.long_extended) {
1142 fprintf(fr_log_fp, "%02x ", ptr[2]);
1145 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1149 if (vp->da->flags.evs) {
1150 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1151 ptr[jump], ptr[jump + 1],
1152 ptr[jump + 2], ptr[jump + 3],
1153 ((ptr[jump + 1] << 16) |
1154 (ptr[jump + 2] << 8) |
1160 print_hex_data(ptr + jump, len, 3);
1164 return (ptr + ptr[1]) - start;
1168 /** Encode a WiMAX attribute
1171 int rad_vp2wimax(RADIUS_PACKET const *packet,
1172 RADIUS_PACKET const *original,
1173 char const *secret, VALUE_PAIR const **pvp,
1174 uint8_t *ptr, size_t room)
1179 uint8_t *start = ptr;
1180 VALUE_PAIR const *vp = *pvp;
1185 * Double-check for WiMAX format.
1187 if (!vp->da->flags.wimax) {
1188 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1193 * Not enough room for:
1194 * attr, len, vendor-id, vsa, vsalen, continuation
1196 if (room < 9) return 0;
1199 * Build the Vendor-Specific header
1202 ptr[0] = PW_VENDOR_SPECIFIC;
1204 lvalue = htonl(vp->da->vendor);
1205 memcpy(ptr + 2, &lvalue, 4);
1206 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1208 ptr[8] = 0; /* continuation byte */
1212 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1214 if (len <= 0) return len;
1217 * There may be more than 252 octets of data encoded in
1218 * the attribute. If so, move the data up in the packet,
1219 * and copy the existing header over. Set the "C" flag
1220 * ONLY after copying the rest of the data.
1222 if (len > (255 - ptr[1])) {
1223 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1230 if ((fr_debug_lvl > 3) && fr_log_fp) {
1231 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1233 ptr[2], ptr[3], ptr[4], ptr[5],
1234 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1235 ptr[6], ptr[7], ptr[8]);
1236 print_hex_data(ptr + 9, len, 3);
1240 return (ptr + ptr[1]) - start;
1243 /** Encode an RFC format attribute, with the "concat" flag set
1245 * If there isn't enough room in the packet, the data is
1248 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1249 UNUSED RADIUS_PACKET const *original,
1250 UNUSED char const *secret, VALUE_PAIR const **pvp,
1251 unsigned int attribute, uint8_t *start, size_t room)
1253 uint8_t *ptr = start;
1256 VALUE_PAIR const *vp = *pvp;
1261 len = vp->vp_length;
1264 if (room <= 2) break;
1271 /* no more than 253 octets */
1272 if (left > 253) left = 253;
1274 /* no more than "room" octets */
1275 if (room < (left + 2)) left = room - 2;
1277 memcpy(ptr + 2, p, left);
1280 if ((fr_debug_lvl > 3) && fr_log_fp) {
1281 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1282 print_hex_data(ptr + 2, len, 3);
1296 /** Encode an RFC format TLV.
1298 * This could be a standard attribute, or a TLV data type.
1299 * If it's a standard attribute, then vp->da->attr == attribute.
1300 * Otherwise, attribute may be something else.
1302 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1303 RADIUS_PACKET const *original,
1304 char const *secret, VALUE_PAIR const **pvp,
1305 unsigned int attribute, uint8_t *ptr, size_t room)
1309 if (room <= 2) return 0;
1311 ptr[0] = attribute & 0xff;
1314 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1316 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1317 if (len <= 0) return len;
1322 if ((fr_debug_lvl > 3) && fr_log_fp) {
1323 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1324 print_hex_data(ptr + 2, len, 3);
1332 /** Encode a VSA which is a TLV
1334 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1336 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1337 RADIUS_PACKET const *original,
1338 char const *secret, VALUE_PAIR const **pvp,
1339 unsigned int attribute, unsigned int vendor,
1340 uint8_t *ptr, size_t room)
1344 VALUE_PAIR const *vp = *pvp;
1348 * Unknown vendor: RFC format.
1349 * Known vendor and RFC format: go do that.
1351 dv = dict_vendorbyvalue(vendor);
1353 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1354 return vp2attr_rfc(packet, original, secret, pvp,
1355 attribute, ptr, room);
1360 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1361 " type %u", (unsigned) dv->type);
1365 ptr[0] = 0; /* attr must be 24-bit */
1366 ptr[1] = (attribute >> 16) & 0xff;
1367 ptr[2] = (attribute >> 8) & 0xff;
1368 ptr[3] = attribute & 0xff;
1372 ptr[0] = (attribute >> 8) & 0xff;
1373 ptr[1] = attribute & 0xff;
1377 ptr[0] = attribute & 0xff;
1381 switch (dv->length) {
1383 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1384 " length %u", (unsigned) dv->length);
1392 ptr[dv->type + 1] = dv->type + 2;
1396 ptr[dv->type] = dv->type + 1;
1401 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1402 room = 255 - (dv->type + dv->length);
1405 len = vp2data_any(packet, original, secret, 0, pvp,
1406 ptr + dv->type + dv->length, room);
1407 if (len <= 0) return len;
1409 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1412 if ((fr_debug_lvl > 3) && fr_log_fp) {
1418 if ((fr_debug_lvl > 3) && fr_log_fp)
1419 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1420 ptr[0], ptr[1], ptr[2], ptr[3]);
1424 if ((fr_debug_lvl > 3) && fr_log_fp)
1425 fprintf(fr_log_fp, "\t\t%02x%02x ",
1430 if ((fr_debug_lvl > 3) && fr_log_fp)
1431 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1435 switch (dv->length) {
1440 fprintf(fr_log_fp, " ");
1444 fprintf(fr_log_fp, "%02x ",
1449 fprintf(fr_log_fp, "%02x%02x ",
1450 ptr[dv->type], ptr[dv->type] + 1);
1454 print_hex_data(ptr + dv->type + dv->length, len, 3);
1458 return dv->type + dv->length + len;
1462 /** Encode a Vendor-Specific attribute
1465 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1466 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1471 VALUE_PAIR const *vp = *pvp;
1475 if (vp->da->vendor == 0) {
1476 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1481 * Double-check for WiMAX format.
1483 if (vp->da->flags.wimax) {
1484 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1487 if (vp->da->vendor > FR_MAX_VENDOR) {
1488 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1493 * Not enough room for:
1494 * attr, len, vendor-id
1496 if (room < 6) return 0;
1499 * Build the Vendor-Specific header
1501 ptr[0] = PW_VENDOR_SPECIFIC;
1503 lvalue = htonl(vp->da->vendor);
1504 memcpy(ptr + 2, &lvalue, 4);
1506 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1508 len = vp2attr_vsa(packet, original, secret, pvp,
1509 vp->da->attr, vp->da->vendor,
1510 ptr + ptr[1], room);
1511 if (len < 0) return len;
1514 if ((fr_debug_lvl > 3) && fr_log_fp) {
1515 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1517 ptr[2], ptr[3], ptr[4], ptr[5],
1518 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1519 print_hex_data(ptr + 6, len, 3);
1529 /** Encode an RFC standard attribute 1..255
1532 int rad_vp2rfc(RADIUS_PACKET const *packet,
1533 RADIUS_PACKET const *original,
1534 char const *secret, VALUE_PAIR const **pvp,
1535 uint8_t *ptr, size_t room)
1537 VALUE_PAIR const *vp = *pvp;
1541 if (vp->da->vendor != 0) {
1542 fr_strerror_printf("rad_vp2rfc called with VSA");
1546 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1547 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1552 * Only CUI is allowed to have zero length.
1555 if ((vp->vp_length == 0) &&
1556 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1557 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1565 * Message-Authenticator is hard-coded.
1567 if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1568 if (room < 18) return -1;
1570 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1572 memset(ptr + 2, 0, 16);
1574 if ((fr_debug_lvl > 3) && fr_log_fp) {
1575 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1579 *pvp = (*pvp)->next;
1584 * EAP-Message is special.
1586 if (vp->da->flags.concat && (vp->vp_length > 253)) {
1587 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1591 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1595 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1596 RADIUS_PACKET const *original,
1597 char const *secret, VALUE_PAIR const **pvp,
1598 uint8_t *start, size_t room)
1601 VALUE_PAIR const *vp = *pvp;
1605 if (!vp->da->flags.is_tlv) {
1606 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1610 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1611 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1615 if (room < 5) return 0;
1618 * Encode the first level of TLVs
1620 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1622 start[2] = vp->da->attr & fr_attr_mask[0];
1625 len = vp2data_any(packet, original, secret, 0, pvp,
1626 start + 4, room - 4);
1627 if (len <= 0) return len;
1639 /** Parse a data structure into a RADIUS attribute
1642 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1643 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1646 VALUE_PAIR const *vp;
1648 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1655 * RFC format attributes take the fast path.
1657 if (!vp->da->vendor) {
1658 if (vp->da->attr > 255) return 0;
1660 return rad_vp2rfc(packet, original, secret, pvp,
1664 if (vp->da->flags.extended) {
1665 return rad_vp2extended(packet, original, secret, pvp,
1670 * The upper 8 bits of the vendor number are the standard
1671 * space attribute which is a TLV.
1673 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1674 return rad_vp2rfctlv(packet, original, secret, pvp,
1678 if (vp->da->flags.wimax) {
1679 return rad_vp2wimax(packet, original, secret, pvp,
1683 return rad_vp2vsa(packet, original, secret, pvp, start, room);
1690 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1693 radius_packet_t *hdr;
1695 uint16_t total_length;
1697 VALUE_PAIR const *reply;
1700 * A 4K packet, aligned on 64-bits.
1702 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1705 * Double-check some things based on packet code.
1707 switch (packet->code) {
1708 case PW_CODE_ACCESS_ACCEPT:
1709 case PW_CODE_ACCESS_REJECT:
1710 case PW_CODE_ACCESS_CHALLENGE:
1712 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1718 * These packet vectors start off as all zero.
1720 case PW_CODE_ACCOUNTING_REQUEST:
1721 case PW_CODE_DISCONNECT_REQUEST:
1722 case PW_CODE_COA_REQUEST:
1723 memset(packet->vector, 0, sizeof(packet->vector));
1731 * Use memory on the stack, until we know how
1732 * large the packet will be.
1734 hdr = (radius_packet_t *) data;
1737 * Build standard header
1739 hdr->code = packet->code;
1740 hdr->id = packet->id;
1742 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1744 total_length = RADIUS_HDR_LEN;
1747 * Load up the configuration values for the user
1753 * FIXME: Loop twice over the reply list. The first time,
1754 * calculate the total length of data. The second time,
1755 * allocate the memory, and fill in the VP's.
1757 * Hmm... this may be slower than just doing a small
1762 * Loop over the reply attributes for the packet.
1764 reply = packet->vps;
1767 char const *last_name = NULL;
1772 * Ignore non-wire attributes, but allow extended
1775 if ((reply->da->vendor == 0) &&
1776 ((reply->da->attr & 0xFFFF) >= 256) &&
1777 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1780 * Permit the admin to send BADLY formatted
1781 * attributes with a debug build.
1783 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1784 memcpy(ptr, reply->vp_octets, reply->vp_length);
1785 len = reply->vp_length;
1786 reply = reply->next;
1790 reply = reply->next;
1795 * Set the Message-Authenticator to the correct
1796 * length and initial value.
1798 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1800 * Cache the offset to the
1801 * Message-Authenticator
1803 packet->offset = total_length;
1806 last_len = reply->vp_length;
1808 last_name = reply->da->name;
1810 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1811 ((uint8_t *) data) + sizeof(data) - ptr);
1812 if (len < 0) return -1;
1815 * Failed to encode the attribute, likely because
1816 * the packet is full.
1819 if (last_len != 0) {
1820 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1823 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1828 next: /* Used only for Raw-Attribute */
1831 total_length += len;
1832 } /* done looping over all attributes */
1835 * Fill in the rest of the fields, and copy the data over
1836 * from the local stack to the newly allocated memory.
1838 * Yes, all this 'memcpy' is slow, but it means
1839 * that we only allocate the minimum amount of
1840 * memory for a request.
1842 packet->data_len = total_length;
1843 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1844 if (!packet->data) {
1845 fr_strerror_printf("Out of memory");
1849 memcpy(packet->data, hdr, packet->data_len);
1850 hdr = (radius_packet_t *) packet->data;
1852 total_length = htons(total_length);
1853 memcpy(hdr->length, &total_length, sizeof(total_length));
1859 /** Sign a previously encoded packet
1862 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1865 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1868 * It wasn't assigned an Id, this is bad!
1870 if (packet->id < 0) {
1871 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1875 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1876 (packet->offset < 0)) {
1877 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1882 * If there's a Message-Authenticator, update it
1883 * now, BEFORE updating the authentication vector.
1885 if (packet->offset > 0) {
1886 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1888 switch (packet->code) {
1889 case PW_CODE_ACCOUNTING_RESPONSE:
1890 if (original && original->code == PW_CODE_STATUS_SERVER) {
1894 case PW_CODE_ACCOUNTING_REQUEST:
1895 case PW_CODE_DISCONNECT_REQUEST:
1896 case PW_CODE_DISCONNECT_ACK:
1897 case PW_CODE_DISCONNECT_NAK:
1898 case PW_CODE_COA_REQUEST:
1899 case PW_CODE_COA_ACK:
1900 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1904 case PW_CODE_ACCESS_ACCEPT:
1905 case PW_CODE_ACCESS_REJECT:
1906 case PW_CODE_ACCESS_CHALLENGE:
1908 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1911 memcpy(hdr->vector, original->vector,
1915 default: /* others have vector already set to zero */
1921 * Set the authentication vector to zero,
1922 * calculate the HMAC, and put it
1923 * into the Message-Authenticator
1926 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1927 (uint8_t const *) secret, strlen(secret));
1928 memcpy(packet->data + packet->offset + 2,
1929 calc_auth_vector, AUTH_VECTOR_LEN);
1932 * Copy the original request vector back
1933 * to the raw packet.
1935 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1939 * Switch over the packet code, deciding how to
1942 switch (packet->code) {
1944 * Request packets are not signed, bur
1945 * have a random authentication vector.
1947 case PW_CODE_ACCESS_REQUEST:
1948 case PW_CODE_STATUS_SERVER:
1952 * Reply packets are signed with the
1953 * authentication vector of the request.
1960 fr_md5_init(&context);
1961 fr_md5_update(&context, packet->data, packet->data_len);
1962 fr_md5_update(&context, (uint8_t const *) secret,
1964 fr_md5_final(digest, &context);
1966 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1967 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1970 }/* switch over packet codes */
1975 /** Reply to the request
1977 * Also attach reply attribute value pairs and any user message provided.
1979 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1983 * Maybe it's a fake packet. Don't send it.
1985 if (!packet || (packet->sockfd < 0)) {
1990 * First time through, allocate room for the packet
1992 if (!packet->data) {
1994 * Encode the packet.
1996 if (rad_encode(packet, original, secret) < 0) {
2001 * Re-sign it, including updating the
2002 * Message-Authenticator.
2004 if (rad_sign(packet, original, secret) < 0) {
2009 * If packet->data points to data, then we print out
2010 * the VP list again only for debugging.
2015 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2020 * If the socket is TCP, call write(). Calling sendto()
2021 * is allowed on some platforms, but it's not nice. Even
2022 * worse, if UDPFROMTO is defined, we *can't* use it on
2023 * TCP sockets. So... just call write().
2025 if (packet->proto == IPPROTO_TCP) {
2028 rcode = write(packet->sockfd, packet->data, packet->data_len);
2029 if (rcode >= 0) return rcode;
2031 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2037 * And send it on it's way.
2039 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2040 &packet->src_ipaddr, packet->src_port,
2041 &packet->dst_ipaddr, packet->dst_port);
2044 /** Do a comparison of two authentication digests by comparing the FULL digest
2046 * Otherwise, the server can be subject to timing attacks that allow attackers
2047 * find a valid message authenticator.
2049 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2051 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2056 for (i = 0; i < length; i++) {
2057 result |= a[i] ^ b[i];
2060 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2064 /** Validates the requesting client NAS
2066 * Calculates the request Authenticator based on the clients private key.
2068 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2070 uint8_t digest[AUTH_VECTOR_LEN];
2074 * Zero out the auth_vector in the received packet.
2075 * Then append the shared secret to the received packet,
2076 * and calculate the MD5 sum. This must be the same
2077 * as the original MD5 sum (packet->vector).
2079 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2082 * MD5(packet + secret);
2084 fr_md5_init(&context);
2085 fr_md5_update(&context, packet->data, packet->data_len);
2086 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2087 fr_md5_final(digest, &context);
2090 * Return 0 if OK, 2 if not OK.
2092 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2097 /** Validates the requesting client NAS
2099 * Calculates the response Authenticator based on the clients
2102 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2105 uint8_t calc_digest[AUTH_VECTOR_LEN];
2111 if (original == NULL) {
2116 * Copy the original vector in place.
2118 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2121 * MD5(packet + secret);
2123 fr_md5_init(&context);
2124 fr_md5_update(&context, packet->data, packet->data_len);
2125 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2126 fr_md5_final(calc_digest, &context);
2129 * Copy the packet's vector back to the packet.
2131 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2134 * Return 0 if OK, 2 if not OK.
2136 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2140 /** Check if a set of RADIUS formatted TLVs are OK
2143 int rad_tlv_ok(uint8_t const *data, size_t length,
2144 size_t dv_type, size_t dv_length)
2146 uint8_t const *end = data + length;
2148 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2150 VP_HEXDUMP("tlv_ok", data, length);
2152 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2153 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2157 while (data < end) {
2160 if ((data + dv_type + dv_length) > end) {
2161 fr_strerror_printf("Attribute header overflow");
2167 if ((data[0] == 0) && (data[1] == 0) &&
2168 (data[2] == 0) && (data[3] == 0)) {
2170 fr_strerror_printf("Invalid attribute 0");
2175 fr_strerror_printf("Invalid attribute > 2^24");
2181 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2186 * Zero is allowed, because the Colubris
2187 * people are dumb and use it.
2192 fr_strerror_printf("Internal sanity check failed");
2196 switch (dv_length) {
2201 if (data[dv_type] != 0) {
2202 fr_strerror_printf("Attribute is longer than 256 octets");
2207 attrlen = data[dv_type + dv_length - 1];
2212 fr_strerror_printf("Internal sanity check failed");
2216 if (attrlen < (dv_type + dv_length)) {
2217 fr_strerror_printf("Attribute header has invalid length");
2221 if (attrlen > length) {
2222 fr_strerror_printf("Attribute overflows container");
2234 /** See if the data pointed to by PTR is a valid RADIUS packet.
2236 * Packet is not 'const * const' because we may update data_len, if there's more data
2237 * in the UDP packet than in the RADIUS packet.
2239 * @param packet to check
2240 * @param flags to control decoding
2241 * @param reason if not NULL, will have the failure reason written to where it points.
2242 * @return bool, true on success, false on failure.
2244 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2249 radius_packet_t *hdr;
2250 char host_ipaddr[128];
2251 bool require_ma = false;
2252 bool seen_ma = false;
2253 uint32_t num_attributes;
2254 decode_fail_t failure = DECODE_FAIL_NONE;
2257 * Check for packets smaller than the packet header.
2259 * RFC 2865, Section 3., subsection 'length' says:
2261 * "The minimum length is 20 ..."
2263 if (packet->data_len < RADIUS_HDR_LEN) {
2264 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2265 inet_ntop(packet->src_ipaddr.af,
2266 &packet->src_ipaddr.ipaddr,
2267 host_ipaddr, sizeof(host_ipaddr)),
2268 packet->data_len, RADIUS_HDR_LEN);
2269 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2275 * Check for packets with mismatched size.
2276 * i.e. We've received 128 bytes, and the packet header
2277 * says it's 256 bytes long.
2279 totallen = (packet->data[2] << 8) | packet->data[3];
2280 hdr = (radius_packet_t *)packet->data;
2283 * Code of 0 is not understood.
2284 * Code of 16 or greate is not understood.
2286 if ((hdr->code == 0) ||
2287 (hdr->code >= FR_MAX_PACKET_CODE)) {
2288 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2289 inet_ntop(packet->src_ipaddr.af,
2290 &packet->src_ipaddr.ipaddr,
2291 host_ipaddr, sizeof(host_ipaddr)),
2293 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2298 * Message-Authenticator is required in Status-Server
2299 * packets, otherwise they can be trivially forged.
2301 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2304 * It's also required if the caller asks for it.
2306 if (flags) require_ma = true;
2309 * Repeat the length checks. This time, instead of
2310 * looking at the data we received, look at the value
2311 * of the 'length' field inside of the packet.
2313 * Check for packets smaller than the packet header.
2315 * RFC 2865, Section 3., subsection 'length' says:
2317 * "The minimum length is 20 ..."
2319 if (totallen < RADIUS_HDR_LEN) {
2320 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2321 inet_ntop(packet->src_ipaddr.af,
2322 &packet->src_ipaddr.ipaddr,
2323 host_ipaddr, sizeof(host_ipaddr)),
2324 totallen, RADIUS_HDR_LEN);
2325 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2330 * And again, for the value of the 'length' field.
2332 * RFC 2865, Section 3., subsection 'length' says:
2334 * " ... and maximum length is 4096."
2336 * HOWEVER. This requirement is for the network layer.
2337 * If the code gets here, we assume that a well-formed
2338 * packet is an OK packet.
2340 * We allow both the UDP data length, and the RADIUS
2341 * "length" field to contain up to 64K of data.
2345 * RFC 2865, Section 3., subsection 'length' says:
2347 * "If the packet is shorter than the Length field
2348 * indicates, it MUST be silently discarded."
2350 * i.e. No response to the NAS.
2352 if (packet->data_len < totallen) {
2353 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2354 inet_ntop(packet->src_ipaddr.af,
2355 &packet->src_ipaddr.ipaddr,
2356 host_ipaddr, sizeof(host_ipaddr)),
2357 packet->data_len, totallen);
2358 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2363 * RFC 2865, Section 3., subsection 'length' says:
2365 * "Octets outside the range of the Length field MUST be
2366 * treated as padding and ignored on reception."
2368 if (packet->data_len > totallen) {
2370 * We're shortening the packet below, but just
2371 * to be paranoid, zero out the extra data.
2373 memset(packet->data + totallen, 0, packet->data_len - totallen);
2374 packet->data_len = totallen;
2378 * Walk through the packet's attributes, ensuring that
2379 * they add up EXACTLY to the size of the packet.
2381 * If they don't, then the attributes either under-fill
2382 * or over-fill the packet. Any parsing of the packet
2383 * is impossible, and will result in unknown side effects.
2385 * This would ONLY happen with buggy RADIUS implementations,
2386 * or with an intentional attack. Either way, we do NOT want
2387 * to be vulnerable to this problem.
2390 count = totallen - RADIUS_HDR_LEN;
2395 * We need at least 2 bytes to check the
2399 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2400 inet_ntop(packet->src_ipaddr.af,
2401 &packet->src_ipaddr.ipaddr,
2402 host_ipaddr, sizeof(host_ipaddr)));
2403 failure = DECODE_FAIL_HEADER_OVERFLOW;
2408 * Attribute number zero is NOT defined.
2411 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2412 inet_ntop(packet->src_ipaddr.af,
2413 &packet->src_ipaddr.ipaddr,
2414 host_ipaddr, sizeof(host_ipaddr)));
2415 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2420 * Attributes are at LEAST as long as the ID & length
2421 * fields. Anything shorter is an invalid attribute.
2424 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2425 inet_ntop(packet->src_ipaddr.af,
2426 &packet->src_ipaddr.ipaddr,
2427 host_ipaddr, sizeof(host_ipaddr)),
2429 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2434 * If there are fewer bytes in the packet than in the
2435 * attribute, it's a bad packet.
2437 if (count < attr[1]) {
2438 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2439 inet_ntop(packet->src_ipaddr.af,
2440 &packet->src_ipaddr.ipaddr,
2441 host_ipaddr, sizeof(host_ipaddr)),
2443 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2448 * Sanity check the attributes for length.
2451 default: /* don't do anything by default */
2455 * If there's an EAP-Message, we require
2456 * a Message-Authenticator.
2458 case PW_EAP_MESSAGE:
2462 case PW_MESSAGE_AUTHENTICATOR:
2463 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2464 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2465 inet_ntop(packet->src_ipaddr.af,
2466 &packet->src_ipaddr.ipaddr,
2467 host_ipaddr, sizeof(host_ipaddr)),
2469 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2477 * FIXME: Look up the base 255 attributes in the
2478 * dictionary, and switch over their type. For
2479 * integer/date/ip, the attribute length SHOULD
2482 count -= attr[1]; /* grab the attribute length */
2484 num_attributes++; /* seen one more attribute */
2488 * If the attributes add up to a packet, it's allowed.
2490 * If not, we complain, and throw the packet away.
2493 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2494 inet_ntop(packet->src_ipaddr.af,
2495 &packet->src_ipaddr.ipaddr,
2496 host_ipaddr, sizeof(host_ipaddr)));
2497 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2502 * If we're configured to look for a maximum number of
2503 * attributes, and we've seen more than that maximum,
2504 * then throw the packet away, as a possible DoS.
2506 if ((fr_max_attributes > 0) &&
2507 (num_attributes > fr_max_attributes)) {
2508 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2509 inet_ntop(packet->src_ipaddr.af,
2510 &packet->src_ipaddr.ipaddr,
2511 host_ipaddr, sizeof(host_ipaddr)),
2512 num_attributes, fr_max_attributes);
2513 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2518 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2520 * A packet with an EAP-Message attribute MUST also have
2521 * a Message-Authenticator attribute.
2523 * A Message-Authenticator all by itself is OK, though.
2525 * Similarly, Status-Server packets MUST contain
2526 * Message-Authenticator attributes.
2528 if (require_ma && !seen_ma) {
2529 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2530 inet_ntop(packet->src_ipaddr.af,
2531 &packet->src_ipaddr.ipaddr,
2532 host_ipaddr, sizeof(host_ipaddr)));
2533 failure = DECODE_FAIL_MA_MISSING;
2538 * Fill RADIUS header fields
2540 packet->code = hdr->code;
2541 packet->id = hdr->id;
2542 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2550 return (failure == DECODE_FAIL_NONE);
2554 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2557 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2561 RADIUS_PACKET *packet;
2564 * Allocate the new request data structure
2566 packet = rad_alloc(ctx, false);
2568 fr_strerror_printf("out of memory");
2573 sock_flags = MSG_PEEK;
2577 data_len = rad_recvfrom(fd, packet, sock_flags,
2578 &packet->src_ipaddr, &packet->src_port,
2579 &packet->dst_ipaddr, &packet->dst_port);
2582 * Check for socket errors.
2585 fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno));
2586 /* packet->data is NULL */
2590 packet->data_len = data_len; /* unsigned vs signed */
2593 * If the packet is too big, then rad_recvfrom did NOT
2594 * allocate memory. Instead, it just discarded the
2597 if (packet->data_len > MAX_PACKET_LEN) {
2598 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes");
2599 /* packet->data is NULL */
2605 * Read no data. Continue.
2606 * This check is AFTER the MAX_PACKET_LEN check above, because
2607 * if the packet is larger than MAX_PACKET_LEN, we also have
2608 * packet->data == NULL
2610 if ((packet->data_len == 0) || !packet->data) {
2611 fr_strerror_printf("Empty packet: Socket is not ready");
2617 * See if it's a well-formed RADIUS packet.
2619 if (!rad_packet_ok(packet, flags, NULL)) {
2625 * Remember which socket we read the packet from.
2627 packet->sockfd = fd;
2630 * FIXME: Do even more filtering by only permitting
2631 * certain IP's. The problem is that we don't know
2632 * how to do this properly for all possible clients...
2636 * Explicitely set the VP list to empty.
2641 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2648 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2651 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2659 if (!packet || !packet->data) return -1;
2662 * Before we allocate memory for the attributes, do more
2665 ptr = packet->data + RADIUS_HDR_LEN;
2666 length = packet->data_len - RADIUS_HDR_LEN;
2667 while (length > 0) {
2668 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2669 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2674 default: /* don't do anything. */
2678 * Note that more than one Message-Authenticator
2679 * attribute is invalid.
2681 case PW_MESSAGE_AUTHENTICATOR:
2682 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2683 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2685 switch (packet->code) {
2689 case PW_CODE_ACCOUNTING_RESPONSE:
2691 (original->code == PW_CODE_STATUS_SERVER)) {
2695 case PW_CODE_ACCOUNTING_REQUEST:
2696 case PW_CODE_DISCONNECT_REQUEST:
2697 case PW_CODE_COA_REQUEST:
2698 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2702 case PW_CODE_ACCESS_ACCEPT:
2703 case PW_CODE_ACCESS_REJECT:
2704 case PW_CODE_ACCESS_CHALLENGE:
2705 case PW_CODE_DISCONNECT_ACK:
2706 case PW_CODE_DISCONNECT_NAK:
2707 case PW_CODE_COA_ACK:
2708 case PW_CODE_COA_NAK:
2710 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2711 "packet without a request packet");
2714 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2718 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2719 (uint8_t const *) secret, strlen(secret));
2720 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2721 sizeof(calc_auth_vector)) != 0) {
2722 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2723 "(Shared secret is incorrect.)",
2724 inet_ntop(packet->src_ipaddr.af,
2725 &packet->src_ipaddr.ipaddr,
2726 buffer, sizeof(buffer)));
2727 /* Silently drop packet, according to RFC 3579 */
2729 } /* else the message authenticator was good */
2732 * Reinitialize Authenticators.
2734 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2735 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2737 } /* switch over the attributes */
2741 } /* loop over the packet, sanity checking the attributes */
2744 * It looks like a RADIUS packet, but we don't know what it is
2745 * so can't validate the authenticators.
2747 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2748 fr_strerror_printf("Received Unknown packet code %d "
2749 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2751 inet_ntop(packet->src_ipaddr.af,
2752 &packet->src_ipaddr.ipaddr,
2753 buffer, sizeof(buffer)),
2759 * Calculate and/or verify Request or Response Authenticator.
2761 switch (packet->code) {
2762 case PW_CODE_ACCESS_REQUEST:
2763 case PW_CODE_STATUS_SERVER:
2765 * The authentication vector is random
2766 * nonsense, invented by the client.
2770 case PW_CODE_COA_REQUEST:
2771 case PW_CODE_DISCONNECT_REQUEST:
2772 case PW_CODE_ACCOUNTING_REQUEST:
2773 if (calc_acctdigest(packet, secret) > 1) {
2774 fr_strerror_printf("Received %s packet "
2775 "from client %s with invalid Request Authenticator! "
2776 "(Shared secret is incorrect.)",
2777 fr_packet_codes[packet->code],
2778 inet_ntop(packet->src_ipaddr.af,
2779 &packet->src_ipaddr.ipaddr,
2780 buffer, sizeof(buffer)));
2785 /* Verify the reply digest */
2786 case PW_CODE_ACCESS_ACCEPT:
2787 case PW_CODE_ACCESS_REJECT:
2788 case PW_CODE_ACCESS_CHALLENGE:
2789 case PW_CODE_ACCOUNTING_RESPONSE:
2790 case PW_CODE_DISCONNECT_ACK:
2791 case PW_CODE_DISCONNECT_NAK:
2792 case PW_CODE_COA_ACK:
2793 case PW_CODE_COA_NAK:
2794 rcode = calc_replydigest(packet, original, secret);
2796 fr_strerror_printf("Received %s packet "
2797 "from home server %s port %d with invalid Response Authenticator! "
2798 "(Shared secret is incorrect.)",
2799 fr_packet_codes[packet->code],
2800 inet_ntop(packet->src_ipaddr.af,
2801 &packet->src_ipaddr.ipaddr,
2802 buffer, sizeof(buffer)),
2809 fr_strerror_printf("Received Unknown packet code %d "
2810 "from client %s port %d: Cannot validate Request/Response Authenticator",
2812 inet_ntop(packet->src_ipaddr.af,
2813 &packet->src_ipaddr.ipaddr,
2814 buffer, sizeof(buffer)),
2823 /** Convert a "concatenated" attribute to one long VP
2826 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2827 DICT_ATTR const *da, uint8_t const *start,
2828 size_t const packetlen, VALUE_PAIR **pvp)
2832 uint8_t const *ptr = start;
2833 uint8_t const *end = start + packetlen;
2841 * The packet has already been sanity checked, so we
2842 * don't care about walking off of the end of it.
2845 total += ptr[1] - 2;
2850 * Attributes MUST be consecutive.
2852 if (ptr[0] != attr) break;
2855 vp = pairalloc(ctx, da);
2858 vp->vp_length = total;
2859 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2867 while (total < vp->vp_length) {
2868 memcpy(p, ptr + 2, ptr[1] - 2);
2870 total += ptr[1] - 2;
2879 /** Convert TLVs to one or more VPs
2882 static ssize_t data2vp_tlvs(TALLOC_CTX *ctx,
2883 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2884 char const *secret, DICT_ATTR const *da,
2885 uint8_t const *start, size_t length,
2888 uint8_t const *data = start;
2889 DICT_ATTR const *child;
2890 VALUE_PAIR *head, **tail;
2892 if (length < 3) return -1; /* type, length, value */
2894 VP_HEXDUMP("tlvs", data, length);
2896 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2901 while (data < (start + length)) {
2904 child = dict_attrbyparent(da, data[0], da->vendor);
2906 unsigned int my_attr, my_vendor;
2908 VP_TRACE("Failed to find child %u of TLV %s\n",
2912 * Get child attr/vendor so that
2913 * we can call unknown attr.
2916 my_vendor = da->vendor;
2918 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2923 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2930 tlv_len = data2vp(ctx, packet, original, secret, child,
2931 data + 2, data[1] - 2, data[1] - 2, tail);
2936 if (*tail) tail = &((*tail)->next);
2944 /** Convert a top-level VSA to a VP.
2946 * "length" can be LONGER than just this sub-vsa.
2948 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
2949 RADIUS_PACKET const *original,
2950 char const *secret, DICT_VENDOR *dv,
2951 uint8_t const *data, size_t length,
2954 unsigned int attribute;
2955 ssize_t attrlen, my_len;
2956 DICT_ATTR const *da;
2958 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
2961 if (length <= (dv->type + dv->length)) {
2962 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2969 /* data[0] must be zero */
2970 attribute = data[1] << 16;
2971 attribute |= data[2] << 8;
2972 attribute |= data[3];
2976 attribute = data[0] << 8;
2977 attribute |= data[1];
2981 attribute = data[0];
2985 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
2989 switch (dv->length) {
2991 /* data[dv->type] must be zero, from rad_tlv_ok() */
2992 attrlen = data[dv->type + 1];
2996 attrlen = data[dv->type];
3004 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3009 * See if the VSA is known.
3011 da = dict_attrbyvalue(attribute, dv->vendorpec);
3012 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3015 my_len = data2vp(ctx, packet, original, secret, da,
3016 data + dv->type + dv->length,
3017 attrlen - (dv->type + dv->length),
3018 attrlen - (dv->type + dv->length),
3020 if (my_len < 0) return my_len;
3026 /** Convert a fragmented extended attr to a VP
3036 * But for the first fragment, we get passed a pointer to the "extended-attr"
3038 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3039 RADIUS_PACKET const *original,
3040 char const *secret, DICT_ATTR const *da,
3041 uint8_t const *data,
3042 size_t attrlen, size_t packetlen,
3047 uint8_t *head, *tail;
3048 uint8_t const *frag, *end;
3049 uint8_t const *attr;
3053 if (attrlen < 3) return -1;
3056 * Calculate the length of all of the fragments. For
3057 * now, they MUST be contiguous in the packet, and they
3058 * MUST be all of the same TYPE and EXTENDED-TYPE
3061 fraglen = attrlen - 2;
3062 frag = data + attrlen;
3063 end = data + packetlen;
3067 while (frag < end) {
3069 (frag[0] != attr[0]) ||
3070 (frag[1] < 4) || /* too short for long-extended */
3071 (frag[2] != attr[2]) ||
3072 ((frag + frag[1]) > end)) { /* overflow */
3077 last_frag = ((frag[3] & 0x80) == 0);
3079 fraglen += frag[1] - 4;
3084 head = tail = malloc(fraglen);
3085 if (!head) return -1;
3087 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3090 * And again, but faster and looser.
3092 * We copy the first fragment, followed by the rest of
3097 while (fragments > 0) {
3098 memcpy(tail, frag + 4, frag[1] - 4);
3099 tail += frag[1] - 4;
3104 VP_HEXDUMP("long-extended fragments", head, fraglen);
3106 rcode = data2vp(ctx, packet, original, secret, da,
3107 head, fraglen, fraglen, pvp);
3109 if (rcode < 0) return rcode;
3114 /** Convert a Vendor-Specific WIMAX to vps
3116 * @note Called ONLY for Vendor-Specific
3118 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3119 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3120 char const *secret, uint32_t vendor,
3121 uint8_t const *data,
3122 size_t attrlen, size_t packetlen,
3128 uint8_t *head, *tail;
3129 uint8_t const *frag, *end;
3130 DICT_ATTR const *child;
3132 if (attrlen < 8) return -1;
3134 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3136 child = dict_attrbyvalue(data[4], vendor);
3137 if (!child) return -1;
3139 if ((data[6] & 0x80) == 0) {
3140 rcode = data2vp(ctx, packet, original, secret, child,
3141 data + 7, data[5] - 3, data[5] - 3,
3143 if (rcode < 0) return -1;
3148 * Calculate the length of all of the fragments. For
3149 * now, they MUST be contiguous in the packet, and they
3150 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3152 * The first fragment doesn't have a RADIUS attribute
3153 * header, so it needs to be treated a little special.
3155 fraglen = data[5] - 3;
3156 frag = data + attrlen;
3157 end = data + packetlen;
3160 while (frag < end) {
3162 (frag[0] != PW_VENDOR_SPECIFIC) ||
3163 (frag[1] < 9) || /* too short for wimax */
3164 ((frag + frag[1]) > end) || /* overflow */
3165 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3166 (frag[6] != data[4]) || /* not the same wimax attr */
3167 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3172 last_frag = ((frag[8] & 0x80) == 0);
3174 fraglen += frag[7] - 3;
3178 head = tail = malloc(fraglen);
3179 if (!head) return -1;
3182 * And again, but faster and looser.
3184 * We copy the first fragment, followed by the rest of
3189 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3190 tail += frag[4 + 1] - 3;
3191 frag += attrlen; /* should be frag[1] - 7 */
3194 * frag now points to RADIUS attributes
3197 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3198 tail += frag[2 + 4 + 1] - 3;
3200 } while (frag < end);
3202 VP_HEXDUMP("wimax fragments", head, fraglen);
3204 rcode = data2vp(ctx, packet, original, secret, child,
3205 head, fraglen, fraglen, pvp);
3207 if (rcode < 0) return rcode;
3213 /** Convert a top-level VSA to one or more VPs
3216 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3217 RADIUS_PACKET const *original,
3218 char const *secret, uint8_t const *data,
3219 size_t attrlen, size_t packetlen,
3226 VALUE_PAIR *head, **tail;
3229 if (attrlen > packetlen) return -1;
3230 if (attrlen < 5) return -1; /* vid, value */
3231 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3233 VP_TRACE("data2vp_vsas\n");
3235 memcpy(&vendor, data, 4);
3236 vendor = ntohl(vendor);
3237 dv = dict_vendorbyvalue(vendor);
3240 * RFC format is 1 octet type, 1 octet length
3242 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3243 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3248 * It's a known unknown.
3250 memset(&my_dv, 0, sizeof(my_dv));
3254 * Fill in the fields. Note that the name is empty!
3256 dv->vendorpec = vendor;
3266 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3267 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3268 data, attrlen, packetlen, pvp);
3273 * VSAs should normally be in TLV format.
3275 if (rad_tlv_ok(data + 4, attrlen - 4,
3276 dv->type, dv->length) < 0) {
3277 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3282 * There may be more than one VSA in the
3283 * Vendor-Specific. If so, loop over them all.
3293 while (attrlen > 0) {
3296 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3297 data, attrlen, tail);
3300 fr_strerror_printf("Internal sanity check %d", __LINE__);
3305 * Vendors can send zero-length VSAs.
3307 if (*tail) tail = &((*tail)->next);
3311 packetlen -= vsa_len;
3319 /** Create any kind of VP from the attribute contents
3321 * "length" is AT LEAST the length of this attribute, as we
3322 * expect the caller to have verified the data with
3323 * rad_packet_ok(). "length" may be up to the length of the
3326 * @return -1 on error, or "length".
3328 ssize_t data2vp(TALLOC_CTX *ctx,
3329 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3331 DICT_ATTR const *da, uint8_t const *start,
3332 size_t const attrlen, size_t const packetlen,
3335 int8_t tag = TAG_NONE;
3339 DICT_ATTR const *child;
3342 uint8_t const *data = start;
3344 uint8_t buffer[256];
3347 * FIXME: Attrlen can be larger than 253 for extended attrs!
3349 if (!da || (attrlen > packetlen) ||
3350 ((attrlen > 253) && (attrlen != packetlen)) ||
3351 (attrlen > 128*1024)) {
3352 fr_strerror_printf("data2vp: invalid arguments");
3356 VP_HEXDUMP("data2vp", start, attrlen);
3358 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3363 * Hacks for CUI. The WiMAX spec says that it can be
3364 * zero length, even though this is forbidden by the
3365 * RADIUS specs. So... we make a special case for it.
3368 if (!((da->vendor == 0) &&
3369 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3376 * Hacks for Coverity. Editing the dictionary
3377 * will break assumptions about CUI. We know
3378 * this, but Coverity doesn't.
3380 if (da->type != PW_TYPE_OCTETS) return -1;
3385 goto alloc_cui; /* skip everything */
3389 * Hacks for tags. If the attribute is capable of
3390 * encoding a tag, and there's room for the tag, and
3391 * there is a tag, or it's encrypted with Tunnel-Password,
3392 * then decode the tag.
3394 if (da->flags.has_tag && (datalen > 1) &&
3395 ((data[0] < 0x20) ||
3396 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3398 * Only "short" attributes can be encrypted.
3400 if (datalen >= sizeof(buffer)) return -1;
3402 if (da->type == PW_TYPE_STRING) {
3403 memcpy(buffer, data + 1, datalen - 1);
3407 } else if (da->type == PW_TYPE_INTEGER) {
3408 memcpy(buffer, data, attrlen);
3413 return -1; /* only string and integer can have tags */
3420 * Decrypt the attribute.
3422 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3423 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3425 * Encrypted attributes can only exist for the
3426 * old-style format. Extended attributes CANNOT
3429 if (attrlen > 253) {
3433 if (data == start) {
3434 memcpy(buffer, data, attrlen);
3438 switch (da->flags.encrypt) { /* can't be tagged */
3442 case FLAG_ENCRYPT_USER_PASSWORD:
3444 rad_pwdecode((char *) buffer,
3448 rad_pwdecode((char *) buffer,
3453 datalen = strlen((char *) buffer);
3457 * Tunnel-Password's may go ONLY in response
3458 * packets. They can have a tag, so datalen is
3459 * not the same as attrlen.
3461 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3462 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3463 original ? original->vector : nullvector) < 0) {
3469 * Ascend-Send-Secret
3470 * Ascend-Receive-Secret
3472 case FLAG_ENCRYPT_ASCEND_SECRET:
3476 uint8_t my_digest[AUTH_VECTOR_LEN];
3477 make_secret(my_digest,
3480 memcpy(buffer, my_digest,
3482 buffer[AUTH_VECTOR_LEN] = '\0';
3483 datalen = strlen((char *) buffer);
3489 } /* switch over encryption flags */
3493 * Double-check the length after decrypting the
3496 VP_TRACE("data2vp: type %u\n", da->type);
3498 case PW_TYPE_STRING:
3499 case PW_TYPE_OCTETS:
3502 case PW_TYPE_ABINARY:
3503 if (datalen > sizeof(vp->vp_filter)) goto raw;
3506 case PW_TYPE_INTEGER:
3507 case PW_TYPE_IPV4_ADDR:
3509 case PW_TYPE_SIGNED:
3510 if (datalen != 4) goto raw;
3513 case PW_TYPE_INTEGER64:
3515 if (datalen != 8) goto raw;
3518 case PW_TYPE_IPV6_ADDR:
3519 if (datalen != 16) goto raw;
3522 case PW_TYPE_IPV6_PREFIX:
3523 if ((datalen < 2) || (datalen > 18)) goto raw;
3524 if (data[1] > 128) goto raw;
3528 if (datalen != 1) goto raw;
3532 if (datalen != 2) goto raw;
3535 case PW_TYPE_ETHERNET:
3536 if (datalen != 6) goto raw;
3539 case PW_TYPE_COMBO_IP_ADDR:
3541 child = dict_attrbytype(da->attr, da->vendor,
3543 } else if (datalen == 16) {
3544 child = dict_attrbytype(da->attr, da->vendor,
3549 if (!child) goto raw;
3550 da = child; /* re-write it */
3553 case PW_TYPE_IPV4_PREFIX:
3554 if (datalen != 6) goto raw;
3555 if ((data[1] & 0x3f) > 32) goto raw;
3559 * The rest of the data types can cause
3560 * recursion! Ask yourself, "is recursion OK?"
3563 case PW_TYPE_EXTENDED:
3564 if (datalen < 2) goto raw; /* etype, value */
3566 child = dict_attrbyparent(da, data[0], 0);
3567 if (!child) goto raw;
3570 * Recurse to decode the contents, which could be
3571 * a TLV, IPaddr, etc. Note that we decode only
3572 * the current attribute, and we ignore any extra
3575 rcode = data2vp(ctx, packet, original, secret, child,
3576 data + 1, attrlen - 1, attrlen - 1, pvp);
3577 if (rcode < 0) goto raw;
3580 case PW_TYPE_LONG_EXTENDED:
3581 if (datalen < 3) goto raw; /* etype, flags, value */
3583 child = dict_attrbyparent(da, data[0], 0);
3585 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3586 (datalen < (3 + 4 + 1))) {
3587 /* da->attr < 255, da->vendor == 0 */
3588 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3591 * Try to find the VSA.
3593 memcpy(&vendor, data + 3, 4);
3594 vendor = ntohl(vendor);
3596 if (vendor == 0) goto raw;
3598 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3602 fr_strerror_printf("Internal sanity check %d", __LINE__);
3608 * If there no more fragments, then the contents
3609 * have to be a well-known data type.
3612 if ((data[1] & 0x80) == 0) {
3613 rcode = data2vp(ctx, packet, original, secret, child,
3614 data + 2, attrlen - 2, attrlen - 2,
3616 if (rcode < 0) goto raw;
3621 * This requires a whole lot more work.
3623 return data2vp_extended(ctx, packet, original, secret, child,
3624 start, attrlen, packetlen, pvp);
3627 if (datalen < 6) goto raw; /* vid, vtype, value */
3629 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3631 memcpy(&vendor, data, 4);
3632 vendor = ntohl(vendor);
3633 dv = dict_vendorbyvalue(vendor);
3635 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3637 child = dict_attrbyparent(da, data[4], vendor);
3639 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3642 if (!child) goto raw;
3644 rcode = data2vp(ctx, packet, original, secret, child,
3645 data + 5, attrlen - 5, attrlen - 5, pvp);
3646 if (rcode < 0) goto raw;
3651 * We presume that the TLVs all fit into one
3652 * attribute, OR they've already been grouped
3653 * into a contiguous memory buffer.
3655 rcode = data2vp_tlvs(ctx, packet, original, secret, da,
3656 data, attrlen, pvp);
3657 if (rcode < 0) goto raw;
3662 * VSAs can be WiMAX, in which case they don't
3663 * fit into one attribute.
3665 rcode = data2vp_vsas(ctx, packet, original, secret,
3666 data, attrlen, packetlen, pvp);
3667 if (rcode < 0) goto raw;
3673 * Re-write the attribute to be "raw". It is
3674 * therefore of type "octets", and will be
3677 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3679 fr_strerror_printf("Internal sanity check %d", __LINE__);
3687 if (da->type != PW_TYPE_OCTETS) {
3688 dict_attr_free(&da);
3696 * And now that we've verified the basic type
3697 * information, decode the actual data.
3700 vp = pairalloc(ctx, da);
3703 vp->vp_length = datalen;
3707 case PW_TYPE_STRING:
3708 p = talloc_array(vp, char, vp->vp_length + 1);
3709 memcpy(p, data, vp->vp_length);
3710 p[vp->vp_length] = '\0';
3711 vp->vp_strvalue = p;
3714 case PW_TYPE_OCTETS:
3715 pairmemcpy(vp, data, vp->vp_length);
3718 case PW_TYPE_ABINARY:
3719 if (vp->vp_length > sizeof(vp->vp_filter)) {
3720 vp->vp_length = sizeof(vp->vp_filter);
3722 memcpy(vp->vp_filter, data, vp->vp_length);
3726 vp->vp_byte = data[0];
3730 vp->vp_short = (data[0] << 8) | data[1];
3733 case PW_TYPE_INTEGER:
3734 memcpy(&vp->vp_integer, data, 4);
3735 vp->vp_integer = ntohl(vp->vp_integer);
3738 case PW_TYPE_INTEGER64:
3739 memcpy(&vp->vp_integer64, data, 8);
3740 vp->vp_integer64 = ntohll(vp->vp_integer64);
3744 memcpy(&vp->vp_date, data, 4);
3745 vp->vp_date = ntohl(vp->vp_date);
3748 case PW_TYPE_ETHERNET:
3749 memcpy(vp->vp_ether, data, 6);
3752 case PW_TYPE_IPV4_ADDR:
3753 memcpy(&vp->vp_ipaddr, data, 4);
3757 memcpy(vp->vp_ifid, data, 8);
3760 case PW_TYPE_IPV6_ADDR:
3761 memcpy(&vp->vp_ipv6addr, data, 16);
3764 case PW_TYPE_IPV6_PREFIX:
3766 * FIXME: double-check that
3767 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3769 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3770 if (vp->vp_length < 18) {
3771 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3772 18 - vp->vp_length);
3776 case PW_TYPE_IPV4_PREFIX:
3777 /* FIXME: do the same double-check as for IPv6Prefix */
3778 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3781 * /32 means "keep all bits". Otherwise, mask
3784 if ((data[1] & 0x3f) > 32) {
3785 uint32_t addr, mask;
3787 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3789 mask <<= (32 - (data[1] & 0x3f));
3794 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3798 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3799 memcpy(&vp->vp_integer, buffer, 4);
3800 vp->vp_integer = ntohl(vp->vp_integer);
3805 fr_strerror_printf("Internal sanity check %d", __LINE__);
3815 /** Create a "normal" VALUE_PAIR from the given data
3818 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3819 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3821 uint8_t const *data, size_t length,
3826 DICT_ATTR const *da;
3828 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3829 fr_strerror_printf("rad_attr2vp: Insufficient data");
3833 da = dict_attrbyvalue(data[0], 0);
3835 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3836 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3841 * Pass the entire thing to the decoding function
3843 if (da->flags.concat) {
3844 VP_TRACE("attr2vp: concat attribute\n");
3845 return data2vp_concat(ctx, da, data, length, pvp);
3849 * Note that we pass the entire length, not just the
3850 * length of this attribute. The Extended or WiMAX
3851 * attributes may have the "continuation" bit set, and
3852 * will thus be more than one attribute in length.
3854 rcode = data2vp(ctx, packet, original, secret, da,
3855 data + 2, data[1] - 2, length - 2, pvp);
3856 if (rcode < 0) return rcode;
3861 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3863 /** Converts vp_data to network byte order
3865 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3866 * in an architecture independent format.
3868 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3869 * as the source VALUE_PAIR is not freed.
3871 * @param out where to write the pointer to the value.
3872 * @param vp to get the value from.
3873 * @return -1 on error, or the length of the value
3875 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3883 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3887 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3889 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3893 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3895 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3903 switch (vp->da->type) {
3904 case PW_TYPE_STRING:
3905 case PW_TYPE_OCTETS:
3907 memcpy(out, &vp->data.ptr, sizeof(*out));
3911 * All of these values are at the same location.
3914 case PW_TYPE_IPV4_ADDR:
3915 case PW_TYPE_IPV6_ADDR:
3916 case PW_TYPE_IPV6_PREFIX:
3917 case PW_TYPE_IPV4_PREFIX:
3918 case PW_TYPE_ABINARY:
3919 case PW_TYPE_ETHERNET:
3920 case PW_TYPE_COMBO_IP_ADDR:
3921 case PW_TYPE_COMBO_IP_PREFIX:
3923 void const *p = &vp->data;
3924 memcpy(out, &p, sizeof(*out));
3928 case PW_TYPE_BOOLEAN:
3929 buffer[0] = vp->vp_byte & 0x01;
3934 buffer[0] = vp->vp_byte & 0xff;
3939 buffer[0] = (vp->vp_short >> 8) & 0xff;
3940 buffer[1] = vp->vp_short & 0xff;
3944 case PW_TYPE_INTEGER:
3945 lvalue = htonl(vp->vp_integer);
3946 memcpy(buffer, &lvalue, sizeof(lvalue));
3950 case PW_TYPE_INTEGER64:
3951 lvalue64 = htonll(vp->vp_integer64);
3952 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3957 lvalue = htonl(vp->vp_date);
3958 memcpy(buffer, &lvalue, sizeof(lvalue));
3962 case PW_TYPE_SIGNED:
3964 int32_t slvalue = htonl(vp->vp_signed);
3965 memcpy(buffer, &slvalue, sizeof(slvalue));
3970 case PW_TYPE_INVALID:
3971 case PW_TYPE_EXTENDED:
3972 case PW_TYPE_LONG_EXTENDED:
3975 case PW_TYPE_TIMEVAL:
3977 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
3980 /* Don't add default */
3983 return vp->vp_length;
3986 /** Calculate/check digest, and decode radius attributes
3988 * @return -1 on decoding error, 0 on success
3990 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3994 uint32_t num_attributes;
3996 radius_packet_t *hdr;
3997 VALUE_PAIR *head, **tail, *vp;
4000 * Extract attribute-value pairs
4002 hdr = (radius_packet_t *)packet->data;
4004 packet_length = packet->data_len - RADIUS_HDR_LEN;
4011 * Loop over the attributes, decoding them into VPs.
4013 while (packet_length > 0) {
4017 * This may return many VPs
4019 my_len = rad_attr2vp(packet, packet, original, secret,
4020 ptr, packet_length, &vp);
4034 * VSA's may not have been counted properly in
4035 * rad_packet_ok() above, as it is hard to count
4036 * then without using the dictionary. We
4037 * therefore enforce the limits here, too.
4039 if ((fr_max_attributes > 0) &&
4040 (num_attributes > fr_max_attributes)) {
4041 char host_ipaddr[128];
4044 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4045 inet_ntop(packet->src_ipaddr.af,
4046 &packet->src_ipaddr.ipaddr,
4047 host_ipaddr, sizeof(host_ipaddr)),
4048 num_attributes, fr_max_attributes);
4053 packet_length -= my_len;
4057 * Merge information from the outside world into our
4060 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4063 * There may be VP's already in the packet. Don't
4064 * destroy them. Instead, add the decoded attributes to
4065 * the tail of the list.
4067 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4078 * We assume that the passwd buffer passed is big enough.
4079 * RFC2138 says the password is max 128 chars, so the size
4080 * of the passwd buffer must be at least 129 characters.
4081 * Preferably it's just MAX_STRING_LEN.
4083 * int *pwlen is updated to the new length of the encrypted
4084 * password - a multiple of 16 bytes.
4086 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4087 uint8_t const *vector)
4089 FR_MD5_CTX context, old;
4090 uint8_t digest[AUTH_VECTOR_LEN];
4091 int i, n, secretlen;
4095 * RFC maximum is 128 bytes.
4097 * If length is zero, pad it out with zeros.
4099 * If the length isn't aligned to 16 bytes,
4100 * zero out the extra data.
4104 if (len > 128) len = 128;
4107 memset(passwd, 0, AUTH_PASS_LEN);
4108 len = AUTH_PASS_LEN;
4109 } else if ((len % AUTH_PASS_LEN) != 0) {
4110 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4111 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4116 * Use the secret to setup the decryption digest
4118 secretlen = strlen(secret);
4120 fr_md5_init(&context);
4121 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4122 old = context; /* save intermediate work */
4125 * Encrypt it in place. Don't bother checking
4126 * len, as we've ensured above that it's OK.
4128 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4130 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4131 fr_md5_final(digest, &context);
4134 fr_md5_update(&context,
4135 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4137 fr_md5_final(digest, &context);
4140 for (i = 0; i < AUTH_PASS_LEN; i++) {
4141 passwd[i + n] ^= digest[i];
4151 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4152 uint8_t const *vector)
4154 FR_MD5_CTX context, old;
4155 uint8_t digest[AUTH_VECTOR_LEN];
4157 size_t n, secretlen;
4160 * The RFC's say that the maximum is 128.
4161 * The buffer we're putting it into above is 254, so
4162 * we don't need to do any length checking.
4164 if (pwlen > 128) pwlen = 128;
4169 if (pwlen == 0) goto done;
4172 * Use the secret to setup the decryption digest
4174 secretlen = strlen(secret);
4176 fr_md5_init(&context);
4177 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4178 old = context; /* save intermediate work */
4181 * The inverse of the code above.
4183 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4185 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4186 fr_md5_final(digest, &context);
4189 if (pwlen > AUTH_PASS_LEN) {
4190 fr_md5_update(&context, (uint8_t *) passwd,
4194 fr_md5_final(digest, &context);
4197 if (pwlen > (n + AUTH_PASS_LEN)) {
4198 fr_md5_update(&context, (uint8_t *) passwd + n,
4203 for (i = 0; i < AUTH_PASS_LEN; i++) {
4204 passwd[i + n] ^= digest[i];
4209 passwd[pwlen] = '\0';
4210 return strlen(passwd);
4214 /** Encode Tunnel-Password attributes when sending them out on the wire
4216 * int *pwlen is updated to the new length of the encrypted
4217 * password - a multiple of 16 bytes.
4219 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4222 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4223 uint8_t const *vector)
4225 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4226 unsigned char digest[AUTH_VECTOR_LEN];
4228 int i, n, secretlen;
4233 if (len > 127) len = 127;
4236 * Shift the password 3 positions right to place a salt and original
4237 * length, tag will be added automatically on packet send
4239 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4243 * save original password length as first password character;
4250 * Generate salt. The RFC's say:
4252 * The high bit of salt[0] must be set, each salt in a
4253 * packet should be unique, and they should be random
4255 * So, we set the high bit, add in a counter, and then
4256 * add in some CSPRNG data. should be OK..
4258 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4259 (fr_rand() & 0x07));
4260 salt[1] = fr_rand();
4263 * Padd password to multiple of AUTH_PASS_LEN bytes.
4265 n = len % AUTH_PASS_LEN;
4267 n = AUTH_PASS_LEN - n;
4268 for (; n > 0; n--, len++)
4271 /* set new password length */
4275 * Use the secret to setup the decryption digest
4277 secretlen = strlen(secret);
4278 memcpy(buffer, secret, secretlen);
4280 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4282 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4283 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4284 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4286 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4287 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4290 for (i = 0; i < AUTH_PASS_LEN; i++) {
4291 passwd[i + n2] ^= digest[i];
4298 /** Decode Tunnel-Password encrypted attributes
4300 * Defined in RFC-2868, this uses a two char SALT along with the
4301 * initial intermediate value, to differentiate it from the
4304 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4305 uint8_t const *vector)
4307 FR_MD5_CTX context, old;
4308 uint8_t digest[AUTH_VECTOR_LEN];
4310 unsigned i, n, len, reallen;
4315 * We need at least a salt.
4318 fr_strerror_printf("tunnel password is too short");
4323 * There's a salt, but no password. Or, there's a salt
4324 * and a 'data_len' octet. It's wrong, but at least we
4325 * can figure out what it means: the password is empty.
4327 * Note that this means we ignore the 'data_len' field,
4328 * if the attribute length tells us that there's no
4329 * more data. So the 'data_len' field may be wrong,
4338 len -= 2; /* discount the salt */
4341 * Use the secret to setup the decryption digest
4343 secretlen = strlen(secret);
4345 fr_md5_init(&context);
4346 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4347 old = context; /* save intermediate work */
4350 * Set up the initial key:
4352 * b(1) = MD5(secret + vector + salt)
4354 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4355 fr_md5_update(&context, passwd, 2);
4358 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4362 fr_md5_final(digest, &context);
4367 * A quick check: decrypt the first octet
4368 * of the password, which is the
4369 * 'data_len' field. Ensure it's sane.
4371 reallen = passwd[2] ^ digest[0];
4372 if (reallen >= len) {
4373 fr_strerror_printf("tunnel password is too long for the attribute");
4377 fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4381 fr_md5_final(digest, &context);
4384 fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4387 for (i = base; i < AUTH_PASS_LEN; i++) {
4388 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4393 * See make_tunnel_password, above.
4395 if (reallen > 239) reallen = 239;
4398 passwd[reallen] = 0;
4403 /** Encode a CHAP password
4405 * @bug FIXME: might not work with Ascend because
4406 * we use vp->vp_length, and Ascend gear likes
4407 * to send an extra '\0' in the string!
4409 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4410 VALUE_PAIR *password)
4414 uint8_t string[MAX_STRING_LEN * 2 + 1];
4415 VALUE_PAIR *challenge;
4418 * Sanity check the input parameters
4420 if ((packet == NULL) || (password == NULL)) {
4425 * Note that the password VP can be EITHER
4426 * a User-Password attribute (from a check-item list),
4427 * or a CHAP-Password attribute (the client asking
4428 * the library to encode it).
4436 memcpy(ptr, password->vp_strvalue, password->vp_length);
4437 ptr += password->vp_length;
4438 i += password->vp_length;
4441 * Use Chap-Challenge pair if present,
4442 * Request Authenticator otherwise.
4444 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4446 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4447 i += challenge->vp_length;
4449 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4450 i += AUTH_VECTOR_LEN;
4454 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4460 /** Seed the random number generator
4462 * May be called any number of times.
4464 void fr_rand_seed(void const *data, size_t size)
4469 * Ensure that the pool is initialized.
4471 if (!fr_rand_initialized) {
4474 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4476 fd = open("/dev/urandom", O_RDONLY);
4482 while (total < sizeof(fr_rand_pool.randrsl)) {
4483 this = read(fd, fr_rand_pool.randrsl,
4484 sizeof(fr_rand_pool.randrsl) - total);
4485 if ((this < 0) && (errno != EINTR)) break;
4486 if (this > 0) total += this;
4490 fr_rand_pool.randrsl[0] = fd;
4491 fr_rand_pool.randrsl[1] = time(NULL);
4492 fr_rand_pool.randrsl[2] = errno;
4495 fr_randinit(&fr_rand_pool, 1);
4496 fr_rand_pool.randcnt = 0;
4497 fr_rand_initialized = 1;
4503 * Hash the user data
4506 if (!hash) hash = fr_rand();
4507 hash = fr_hash_update(data, size, hash);
4509 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4513 /** Return a 32-bit random number
4516 uint32_t fr_rand(void)
4521 * Ensure that the pool is initialized.
4523 if (!fr_rand_initialized) {
4524 fr_rand_seed(NULL, 0);
4527 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4528 if (fr_rand_pool.randcnt >= 256) {
4529 fr_rand_pool.randcnt = 0;
4530 fr_isaac(&fr_rand_pool);
4537 /** Allocate a new RADIUS_PACKET
4539 * @param ctx the context in which the packet is allocated. May be NULL if
4540 * the packet is not associated with a REQUEST.
4541 * @param new_vector if true a new request authenticator will be generated.
4542 * @return a new RADIUS_PACKET or NULL on error.
4544 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4548 rp = talloc_zero(ctx, RADIUS_PACKET);
4550 fr_strerror_printf("out of memory");
4558 uint32_t hash, base;
4561 * Don't expose the actual contents of the random
4565 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4566 hash = fr_rand() ^ base;
4567 memcpy(rp->vector + i, &hash, sizeof(hash));
4570 fr_rand(); /* stir the pool again */
4575 /** Allocate a new RADIUS_PACKET response
4577 * @param ctx the context in which the packet is allocated. May be NULL if
4578 * the packet is not associated with a REQUEST.
4579 * @param packet The request packet.
4580 * @return a new RADIUS_PACKET or NULL on error.
4582 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4584 RADIUS_PACKET *reply;
4586 if (!packet) return NULL;
4588 reply = rad_alloc(ctx, false);
4589 if (!reply) return NULL;
4592 * Initialize the fields from the request.
4594 reply->sockfd = packet->sockfd;
4595 reply->dst_ipaddr = packet->src_ipaddr;
4596 reply->src_ipaddr = packet->dst_ipaddr;
4597 reply->dst_port = packet->src_port;
4598 reply->src_port = packet->dst_port;
4599 reply->id = packet->id;
4600 reply->code = 0; /* UNKNOWN code */
4601 memcpy(reply->vector, packet->vector,
4602 sizeof(reply->vector));
4605 reply->data_len = 0;
4608 reply->proto = packet->proto;
4614 /** Free a RADIUS_PACKET
4617 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4619 RADIUS_PACKET *radius_packet;
4621 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4622 radius_packet = *radius_packet_ptr;
4624 VERIFY_PACKET(radius_packet);
4626 pairfree(&radius_packet->vps);
4628 talloc_free(radius_packet);
4629 *radius_packet_ptr = NULL;
4632 /** Duplicate a RADIUS_PACKET
4634 * @param ctx the context in which the packet is allocated. May be NULL if
4635 * the packet is not associated with a REQUEST.
4636 * @param in The packet to copy
4637 * @return a new RADIUS_PACKET or NULL on error.
4639 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4643 out = rad_alloc(ctx, false);
4644 if (!out) return NULL;
4647 * Bootstrap by copying everything.
4649 memcpy(out, in, sizeof(*out));
4652 * Then reset necessary fields
4659 out->vps = paircopy(out, in->vps);