2 * radius.c Functions to send/receive radius packets.
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.
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.
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
20 * Copyright 2000-2003,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/libradius.h>
27 #include <freeradius-devel/md5.h>
33 #include <freeradius-devel/udpfromto.h>
41 * The RFC says 4096 octets max, and most packets are less than 256.
43 #define MAX_PACKET_LEN 4096
46 * The maximum number of attributes which we allow in an incoming
47 * request. If there are more attributes than this, the request
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.
56 int fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
59 typedef struct radius_packet_t {
63 uint8_t vector[AUTH_VECTOR_LEN];
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
77 "Accounting-Response",
93 "Resource-Free-Request",
94 "Resource-Free-Response",
95 "Resource-Query-Request",
96 "Resource-Query-Response",
97 "Alternate-Resource-Reclaim-Request",
99 "NAS-Reboot-Response",
112 "Disconnect-Request",
122 "IP-Address-Allocate",
127 void fr_printf_log(const char *fmt, ...)
132 if ((fr_debug_flag == 0) || !fr_log_fp) {
137 vfprintf(fr_log_fp, fmt, ap);
144 static void print_hex(RADIUS_PACKET *packet)
148 if (!packet->data) return;
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) |
154 printf(" Vector:\t");
155 for (i = 4; i < 20; i++) {
156 printf("%02x", packet->data[i]);
160 if (packet->data_len > 20) {
165 total = packet->data_len - 20;
166 ptr = packet->data + 20;
172 if (total < 2) { /* too short */
173 printf("%02x\n", *ptr);
177 if (ptr[1] > total) { /* too long */
178 for (i = 0; i < total; i++) {
179 printf("%02x ", ptr[i]);
184 printf("%02x %02x ", ptr[0], ptr[1]);
185 attrlen = ptr[1] - 2;
189 for (i = 0; i < attrlen; i++) {
190 if ((i > 0) && ((i & 0x0f) == 0x00))
192 printf("%02x ", ptr[i]);
193 if ((i & 0x0f) == 0x0f) printf("\n");
196 if ((attrlen & 0x0f) != 0x00) printf("\n");
207 * Wrapper for sendto which handles sendfromto, IPv6, and all
208 * possible combinations.
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)
214 struct sockaddr_storage dst;
215 socklen_t sizeof_dst;
217 #ifdef WITH_UDPFROMTO
218 struct sockaddr_storage src;
219 socklen_t sizeof_src;
221 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
223 src_port = src_port; /* -Wunused */
226 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
230 #ifdef WITH_UDPFROMTO
232 * Only IPv4 is supported for udpfromto.
234 * And if they don't specify a source IP address, don't
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);
244 src_ipaddr = src_ipaddr; /* -Wunused */
248 * No udpfromto, OR an IPv6 socket, fail gracefully.
250 return sendto(sockfd, data, data_len, flags,
251 (struct sockaddr *) &dst, sizeof_dst);
255 void rad_recv_discard(int sockfd)
258 struct sockaddr_storage src;
259 socklen_t sizeof_src = sizeof(src);
261 recvfrom(sockfd, header, sizeof(header), 0,
262 (struct sockaddr *)&src, &sizeof_src);
266 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
269 ssize_t data_len, packet_len;
271 struct sockaddr_storage src;
272 socklen_t sizeof_src = sizeof(src);
274 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
275 (struct sockaddr *)&src, &sizeof_src);
277 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
282 * Too little data is available, discard the packet.
285 recvfrom(sockfd, header, sizeof(header), 0,
286 (struct sockaddr *)&src, &sizeof_src);
289 } else { /* we got 4 bytes of data. */
291 * See how long the packet says it is.
293 packet_len = (header[2] * 256) + header[3];
296 * The length in the packet says it's less than
297 * a RADIUS header length: discard it.
299 if (packet_len < AUTH_HDR_LEN) {
300 recvfrom(sockfd, header, sizeof(header), 0,
301 (struct sockaddr *)&src, &sizeof_src);
305 * Enforce RFC requirements, for sanity.
306 * Anything after 4k will be discarded.
308 } else if (packet_len > MAX_PACKET_LEN) {
309 recvfrom(sockfd, header, sizeof(header), 0,
310 (struct sockaddr *)&src, &sizeof_src);
316 * Convert AF. If unknown, discard packet.
318 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
319 recvfrom(sockfd, header, sizeof(header), 0,
320 (struct sockaddr *)&src, &sizeof_src);
327 * The packet says it's this long, but the actual UDP
328 * size could still be smaller.
335 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
336 * possible combinations.
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)
342 struct sockaddr_storage src;
343 struct sockaddr_storage dst;
344 socklen_t sizeof_src = sizeof(src);
345 socklen_t sizeof_dst = sizeof(dst);
352 memset(&src, 0, sizeof_src);
353 memset(&dst, 0, sizeof_dst);
356 * Get address family, etc. first, so we know if we
357 * need to do udpfromto.
359 * FIXME: udpfromto also does this, but it's not
360 * a critical problem.
362 if (getsockname(sockfd, (struct sockaddr *)&dst,
363 &sizeof_dst) < 0) return -1;
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.
370 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
371 (struct sockaddr *)&src, &sizeof_src);
373 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
378 * Too little data is available, discard the packet.
381 recvfrom(sockfd, header, sizeof(header), flags,
382 (struct sockaddr *)&src, &sizeof_src);
385 } else { /* we got 4 bytes of data. */
387 * See how long the packet says it is.
389 len = (header[2] * 256) + header[3];
392 * The length in the packet says it's less than
393 * a RADIUS header length: discard it.
395 if (len < AUTH_HDR_LEN) {
396 recvfrom(sockfd, header, sizeof(header), flags,
397 (struct sockaddr *)&src, &sizeof_src);
401 * Enforce RFC requirements, for sanity.
402 * Anything after 4k will be discarded.
404 } else if (len > MAX_PACKET_LEN) {
405 recvfrom(sockfd, header, sizeof(header), flags,
406 (struct sockaddr *)&src, &sizeof_src);
415 * Receive the packet. The OS will discard any data in the
416 * packet after "len" bytes.
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);
426 * No udpfromto, OR an IPv6 socket. Fail gracefully.
428 data_len = recvfrom(sockfd, buf, len, flags,
429 (struct sockaddr *)&src, &sizeof_src);
435 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
437 return -1; /* Unknown address family, Die Die Die! */
441 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
445 * Different address families should never happen.
447 if (src.ss_family != dst.ss_family) {
453 * Tell the caller about the data
461 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
462 /*************************************************************************
464 * Function: make_secret
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.
472 *************************************************************************/
473 static void make_secret(uint8_t *digest, const uint8_t *vector,
474 const char *secret, const uint8_t *value)
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);
484 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
485 digest[i] ^= value[i];
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)
494 FR_MD5_CTX context, old;
495 uint8_t digest[AUTH_VECTOR_LEN];
496 uint8_t passwd[MAX_PASS_LEN];
501 * If the length is zero, round it up.
505 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
507 memcpy(passwd, input, len);
508 memset(passwd + len, 0, sizeof(passwd) - len);
514 else if ((len & 0x0f) != 0) {
520 fr_MD5Init(&context);
521 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
527 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
529 for (n = 0; n < len; n += AUTH_PASS_LEN) {
532 fr_MD5Update(&context,
533 passwd + n - AUTH_PASS_LEN,
537 fr_MD5Final(digest, &context);
538 for (i = 0; i < AUTH_PASS_LEN; i++) {
539 passwd[i + n] ^= digest[i];
543 memcpy(output, passwd, len);
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)
550 FR_MD5_CTX context, old;
551 uint8_t digest[AUTH_VECTOR_LEN];
552 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
559 if (room > 253) room = 253;
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
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
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.
578 room -= (room & 0x0f);
581 if (inlen > room) inlen = room;
584 * Length of the encrypted data is password length plus
585 * one byte for the length of the password.
588 if ((len & 0x0f) != 0) {
592 *outlen = len + 2; /* account for the salt */
595 * Copy the password over.
597 memcpy(passwd + 3, input, inlen);
598 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
601 * Generate salt. The RFC's say:
603 * The high bit of salt[0] must be set, each salt in a
604 * packet should be unique, and they should be random
606 * So, we set the high bit, add in a counter, and then
607 * add in some CSPRNG data. should be OK..
609 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
611 passwd[1] = fr_rand();
612 passwd[2] = inlen; /* length of the password string */
614 fr_MD5Init(&context);
615 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
618 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
619 fr_MD5Update(&context, &passwd[0], 2);
621 for (n = 0; n < len; n += AUTH_PASS_LEN) {
624 fr_MD5Update(&context,
625 passwd + 2 + n - AUTH_PASS_LEN,
629 fr_MD5Final(digest, &context);
631 for (i = 0; i < AUTH_PASS_LEN; i++) {
632 passwd[i + 2 + n] ^= digest[i];
635 memcpy(output, passwd, len + 2);
638 extern int fr_attr_max_tlv;
639 extern int fr_attr_shift[];
640 extern int fr_attr_mask[];
642 static int do_next_tlv(const VALUE_PAIR *vp, int nest)
644 unsigned int tlv1, tlv2;
646 if (nest >= fr_attr_max_tlv) return 0;
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"
657 * Nothing to follow, we're done.
659 if (!vp->next) return 0;
662 * Not from the same vendor, skip it.
664 if (vp->vendor != vp->next->vendor) return 0;
667 * The next one has already been done. Maybe by
668 * another level of recursion. Skip it.
670 if (vp->next->flags.encoded) return 0;
673 * In a different TLV space, skip it.
675 tlv1 = vp->attribute;
676 tlv2 = vp->next->attribute;
678 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
679 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
681 if (tlv1 != tlv2) return 0;
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);
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)
698 uint8_t *ptr = start;
699 uint8_t *end = start + room;
700 VALUE_PAIR *vp = vps;
703 if (nest > fr_attr_max_tlv) {
704 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
710 ptr[0] = (vp->attribute >> fr_attr_shift[nest]) & fr_attr_mask[nest];
713 len = vp2data_any(packet, original, secret, nest + 1, vp,
714 ptr + ptr[1], end - ptr);
716 if (vp != vps) break;
722 vp->flags.encoded = 1;
724 if (!do_next_tlv(vp, nest)) break;
732 * Encodes the data portion of an attribute.
733 * Returns -1 on error, or the length of the data portion.
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)
743 uint8_t *ptr = start;
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.
752 * If we cared about the stack, we could unroll the loop.
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,
761 * Set up the default sources for the data.
763 data = vp->vp_octets;
770 case PW_TYPE_IPV6ADDR:
771 case PW_TYPE_IPV6PREFIX:
772 case PW_TYPE_ABINARY:
773 /* nothing more to do */
777 len = 1; /* just in case */
778 array[0] = vp->vp_integer & 0xff;
783 len = 2; /* just in case */
784 array[0] = (vp->vp_integer >> 8) & 0xff;
785 array[1] = vp->vp_integer & 0xff;
789 case PW_TYPE_INTEGER:
790 len = 4; /* just in case */
791 lvalue = htonl(vp->vp_integer);
792 memcpy(array, &lvalue, sizeof(lvalue));
797 data = (const uint8_t *) &vp->vp_ipaddr;
798 len = 4; /* just in case */
802 * There are no tagged date attributes.
805 lvalue = htonl(vp->vp_date);
806 data = (const uint8_t *) &lvalue;
807 len = 4; /* just in case */
814 len = 4; /* just in case */
815 slvalue = htonl(vp->vp_signed);
816 memcpy(array, &slvalue, sizeof(slvalue));
823 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
826 if (vp->length > room) return 0; /* can't chop TLVs to fit */
829 default: /* unknown type: ignore it */
830 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
835 * Bound the data to the calling size
837 if (len > (ssize_t) room) len = room;
840 * Encrypt the various password styles
842 * Attributes with encrypted values MUST be less than
845 switch (vp->flags.encrypt) {
846 case FLAG_ENCRYPT_USER_PASSWORD:
847 make_passwd(ptr, &len, data, len,
848 secret, packet->vector);
851 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
853 if (vp->flags.has_tag) lvalue = 1;
856 * Check if there's enough room. If there isn't,
857 * we discard the attribute.
859 * This is ONLY a problem if we have multiple VSA's
860 * in one Vendor-Specific, though.
862 if (room < (18 + lvalue)) return 0;
864 switch (packet->code) {
865 case PW_AUTHENTICATION_ACK:
866 case PW_AUTHENTICATION_REJECT:
867 case PW_ACCESS_CHALLENGE:
870 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
874 if (lvalue) ptr[0] = vp->flags.tag;
875 make_tunnel_passwd(ptr + lvalue, &len, data, len,
877 secret, original->vector);
879 case PW_ACCOUNTING_REQUEST:
880 case PW_DISCONNECT_REQUEST:
882 ptr[0] = vp->flags.tag;
883 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
884 secret, packet->vector);
890 * The code above ensures that this attribute
893 case FLAG_ENCRYPT_ASCEND_SECRET:
894 make_secret(ptr, packet->vector, secret, data);
895 len = AUTH_VECTOR_LEN;
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;
905 } else if (vp->type == PW_TYPE_INTEGER) {
906 array[0] = vp->flags.tag;
907 } /* else it can't be any other type */
909 memcpy(ptr, data, len);
911 } /* switch over encryption flags */
913 vp->flags.encoded = 1;
914 return len + (ptr - start);;
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)
921 int check_len = len - ptr[1];
922 int total = len + hdr_len;
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.
930 while (check_len > (255 - hdr_len)) {
932 check_len -= (255 - hdr_len);
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
942 if ((ptr + ptr[1] + total) > end) {
943 return (ptr + ptr[1]) - start;
947 * Pass 2: Now that we know there's enough room,
948 * re-arrange the data to form a set of valid
952 int sublen = 255 - ptr[1];
959 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
960 memcpy(ptr + 255, ptr, hdr_len);
962 if (vsa_offset) ptr[vsa_offset] += sublen;
963 ptr[flag_offset] |= 0x80;
967 if (vsa_offset) ptr[vsa_offset] = 3;
971 if (vsa_offset) ptr[vsa_offset] += len;
973 return (ptr + ptr[1]) - start;
978 * Encode an "extended" attribute.
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)
988 uint8_t *start = ptr;
990 if (vp->vendor < VENDORPEC_EXTENDED) {
991 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
995 if (room < 3) return 0;
997 ptr[0] = vp->attribute & 0xff;
1000 if (vp->flags.extended) {
1001 ptr[2] = (vp->attribute & 0xff00) >> 8;
1003 } else if (vp->flags.extended_flags) {
1004 if (room < 4) return 0;
1007 ptr[2] = (vp->attribute & 0xff00) >> 8;
1012 * Only "flagged" attributes can be longer than one
1015 if (!vp->flags.extended_flags && (room > 255)) {
1022 if (vp->flags.evs) {
1023 uint8_t *evs = ptr + ptr[1];
1025 if (room < (size_t) (ptr[1] + 5)) return 0;
1028 * RADIUS Attribute Type is packed into the high byte
1029 * of the Vendor Id. So over-write it in the packet.
1031 * And hard-code Extended-Type to Vendor-Specific.
1033 ptr[0] = (vp->vendor >> 24) & 0xff;
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;
1047 len = vp2data_any(packet, original, secret, nest,
1048 vp, ptr + ptr[1], room - hdr_len);
1049 if (len < 0) return len;
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.
1057 if (vp->flags.extended_flags && (len > (255 - ptr[1]))) {
1058 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1063 return (ptr + ptr[1]) - start;
1068 * Encode a WiMAX attribute.
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)
1078 uint8_t *start = ptr;
1081 * Double-check for WiMAX
1083 if (vp->vendor != VENDORPEC_WIMAX) {
1084 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1089 * Not enough room for:
1090 * attr, len, vendor-id, vsa, vsalen, continuation
1092 if (room < 9) return 0;
1095 * Build the Vendor-Specific header
1098 ptr[0] = PW_VENDOR_SPECIFIC;
1100 lvalue = htonl(vp->vendor);
1101 memcpy(ptr + 2, &lvalue, 4);
1102 ptr[6] = (vp->attribute & fr_attr_mask[1]);
1104 ptr[8] = 0; /* continuation byte */
1108 len = vp2data_any(packet, original, secret, 1, vp, ptr + ptr[1],
1110 if (len <= 0) return len;
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.
1118 if (len > (255 - ptr[1])) {
1119 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1125 return (ptr + ptr[1]) - start;
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
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)
1141 if (room < 2) return 0;
1143 ptr[0] = attribute & 0xff;
1146 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1148 len = vp2data_any(packet, original, secret, 0, vp, ptr + ptr[1], room);
1149 if (len < 0) return len;
1158 * Encode a VSA which is a TLV. If it's in the RFC format, call
1159 * vp2attr_rfc. Otherwise, encode it here.
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)
1171 * Unknown vendor: RFC format.
1172 * Known vendor and RFC format: go do that.
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);
1182 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1183 " type %u", (unsigned) dv->type);
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;
1194 ptr[0] = (attribute >> 8) & 0xff;
1195 ptr[1] = attribute & 0xff;
1199 ptr[0] = attribute & 0xff;
1203 switch (dv->length) {
1205 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1206 " length %u", (unsigned) dv->length);
1217 ptr[dv->type + dv->length - 1] = dv->type + dv->length;
1222 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1223 room = 255 - (dv->type + dv->length);
1226 len = vp2data_any(packet, original, secret, 0, vp,
1227 ptr + dv->type + dv->length, room);
1228 if (len < 0) return len;
1230 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1232 return dv->type + dv->length + len;
1237 * Encode a Vendor-Specific attribute.
1239 int rad_vp2vsa(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1240 const char *secret, VALUE_PAIR *vp, uint8_t *ptr,
1247 * Double-check for WiMAX
1249 if (vp->vendor == VENDORPEC_WIMAX) {
1250 return rad_vp2wimax(packet, original, secret, vp,
1254 if (vp->vendor > FR_MAX_VENDOR) {
1255 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1260 * Not enough room for:
1261 * attr, len, vendor-id
1263 if (room < 6) return 0;
1266 * Build the Vendor-Specific header
1268 ptr[0] = PW_VENDOR_SPECIFIC;
1270 lvalue = htonl(vp->vendor);
1271 memcpy(ptr + 2, &lvalue, 4);
1273 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1275 len = vp2attr_vsa(packet, original, secret, vp,
1276 vp->attribute, vp->vendor,
1277 ptr + ptr[1], room);
1278 if (len < 0) return len;
1287 * Encode an RFC standard attribute 1..255
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)
1294 if (vp->vendor != 0) {
1295 fr_strerror_printf("rad_vp2rfc called with VSA");
1299 if ((vp->attribute == 0) || (vp->attribute > 255)) {
1300 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->attribute);
1304 return vp2attr_rfc(packet, original, secret, vp, vp->attribute,
1310 * Parse a data structure into a RADIUS attribute.
1312 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1313 const char *secret, VALUE_PAIR *vp, uint8_t *start,
1317 * RFC format attributes take the fast path.
1319 if (vp->vendor == 0) {
1320 return rad_vp2rfc(packet, original, secret, vp,
1324 if (vp->vendor > FR_MAX_VENDOR) {
1325 return rad_vp2extended(packet, original, secret, vp,
1329 if (vp->vendor == VENDORPEC_WIMAX) {
1330 return rad_vp2wimax(packet, original, secret, vp,
1334 return rad_vp2vsa(packet, original, secret, vp,
1342 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1345 radius_packet_t *hdr;
1347 uint16_t total_length;
1351 char ip_buffer[128];
1354 * A 4K packet, aligned on 64-bits.
1356 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1358 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1359 what = fr_packet_codes[packet->code];
1364 DEBUG("Sending %s of id %d to %s port %d\n",
1366 inet_ntop(packet->dst_ipaddr.af,
1367 &packet->dst_ipaddr.ipaddr,
1368 ip_buffer, sizeof(ip_buffer)),
1372 * Double-check some things based on packet code.
1374 switch (packet->code) {
1375 case PW_AUTHENTICATION_ACK:
1376 case PW_AUTHENTICATION_REJECT:
1377 case PW_ACCESS_CHALLENGE:
1379 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1385 * These packet vectors start off as all zero.
1387 case PW_ACCOUNTING_REQUEST:
1388 case PW_DISCONNECT_REQUEST:
1389 case PW_COA_REQUEST:
1390 memset(packet->vector, 0, sizeof(packet->vector));
1398 * Use memory on the stack, until we know how
1399 * large the packet will be.
1401 hdr = (radius_packet_t *) data;
1404 * Build standard header
1406 hdr->code = packet->code;
1407 hdr->id = packet->id;
1409 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1411 total_length = AUTH_HDR_LEN;
1414 * Load up the configuration values for the user
1420 * FIXME: Loop twice over the reply list. The first time,
1421 * calculate the total length of data. The second time,
1422 * allocate the memory, and fill in the VP's.
1424 * Hmm... this may be slower than just doing a small
1429 * Loop over the reply attributes for the packet.
1431 for (reply = packet->vps; reply; reply = reply->next) {
1433 * Ignore non-wire attributes, but allow extended
1436 if ((reply->vendor == 0) &&
1437 ((reply->attribute & 0xFFFF) >= 256) &&
1438 !reply->flags.extended && !reply->flags.extended_flags) {
1441 * Permit the admin to send BADLY formatted
1442 * attributes with a debug build.
1444 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1445 memcpy(ptr, reply->vp_octets, reply->length);
1446 len = reply->length;
1454 * Set the Message-Authenticator to the correct
1455 * length and initial value.
1457 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1458 reply->length = AUTH_VECTOR_LEN;
1459 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1462 * Cache the offset to the
1463 * Message-Authenticator
1465 packet->offset = total_length;
1469 * Print out ONLY the attributes which
1470 * we're sending over the wire, and print
1471 * them out BEFORE they're encrypted.
1476 * Skip attributes that have already been
1477 * encoded. This can be done when the "vp2attr"
1478 * function sees multiple contiguous TLVs.
1480 if (reply->flags.encoded) continue;
1482 len = rad_vp2attr(packet, original, secret, reply, ptr,
1483 ((uint8_t *) data) + sizeof(data) - ptr);
1484 if (len < 0) return -1;
1487 * Failed to encode the attribute, likely because
1488 * the packet is full.
1491 (total_length > (sizeof(data) - 2 - reply->length))) {
1492 DEBUG("WARNING: Attributes are too long for packet. Discarding data past %d bytes", total_length);
1498 total_length += len;
1499 } /* done looping over all attributes */
1502 * Fill in the rest of the fields, and copy the data over
1503 * from the local stack to the newly allocated memory.
1505 * Yes, all this 'memcpy' is slow, but it means
1506 * that we only allocate the minimum amount of
1507 * memory for a request.
1509 packet->data_len = total_length;
1510 packet->data = (uint8_t *) malloc(packet->data_len);
1511 if (!packet->data) {
1512 fr_strerror_printf("Out of memory");
1516 memcpy(packet->data, hdr, packet->data_len);
1517 hdr = (radius_packet_t *) packet->data;
1519 total_length = htons(total_length);
1520 memcpy(hdr->length, &total_length, sizeof(total_length));
1527 * Sign a previously encoded packet.
1529 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1532 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1535 * It wasn't assigned an Id, this is bad!
1537 if (packet->id < 0) {
1538 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1542 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1543 (packet->offset < 0)) {
1544 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1549 * If there's a Message-Authenticator, update it
1550 * now, BEFORE updating the authentication vector.
1552 if (packet->offset > 0) {
1553 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1555 switch (packet->code) {
1556 case PW_ACCOUNTING_REQUEST:
1557 case PW_ACCOUNTING_RESPONSE:
1558 case PW_DISCONNECT_REQUEST:
1559 case PW_DISCONNECT_ACK:
1560 case PW_DISCONNECT_NAK:
1561 case PW_COA_REQUEST:
1564 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1567 case PW_AUTHENTICATION_ACK:
1568 case PW_AUTHENTICATION_REJECT:
1569 case PW_ACCESS_CHALLENGE:
1571 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1574 memcpy(hdr->vector, original->vector,
1578 default: /* others have vector already set to zero */
1584 * Set the authentication vector to zero,
1585 * calculate the signature, and put it
1586 * into the Message-Authenticator
1589 fr_hmac_md5(packet->data, packet->data_len,
1590 (const uint8_t *) secret, strlen(secret),
1592 memcpy(packet->data + packet->offset + 2,
1593 calc_auth_vector, AUTH_VECTOR_LEN);
1596 * Copy the original request vector back
1597 * to the raw packet.
1599 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1603 * Switch over the packet code, deciding how to
1606 switch (packet->code) {
1608 * Request packets are not signed, bur
1609 * have a random authentication vector.
1611 case PW_AUTHENTICATION_REQUEST:
1612 case PW_STATUS_SERVER:
1616 * Reply packets are signed with the
1617 * authentication vector of the request.
1624 fr_MD5Init(&context);
1625 fr_MD5Update(&context, packet->data, packet->data_len);
1626 fr_MD5Update(&context, (const uint8_t *) secret,
1628 fr_MD5Final(digest, &context);
1630 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1631 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1634 }/* switch over packet codes */
1640 * Reply to the request. Also attach
1641 * reply attribute value pairs and any user message provided.
1643 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1648 char ip_buffer[128];
1651 * Maybe it's a fake packet. Don't send it.
1653 if (!packet || (packet->sockfd < 0)) {
1657 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1658 what = fr_packet_codes[packet->code];
1664 * First time through, allocate room for the packet
1666 if (!packet->data) {
1668 * Encode the packet.
1670 if (rad_encode(packet, original, secret) < 0) {
1675 * Re-sign it, including updating the
1676 * Message-Authenticator.
1678 if (rad_sign(packet, original, secret) < 0) {
1683 * If packet->data points to data, then we print out
1684 * the VP list again only for debugging.
1686 } else if (fr_debug_flag) {
1687 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1688 inet_ntop(packet->dst_ipaddr.af,
1689 &packet->dst_ipaddr.ipaddr,
1690 ip_buffer, sizeof(ip_buffer)),
1693 for (reply = packet->vps; reply; reply = reply->next) {
1694 if ((reply->vendor == 0) &&
1695 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1701 * And send it on it's way.
1703 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1704 &packet->src_ipaddr, packet->src_port,
1705 &packet->dst_ipaddr, packet->dst_port);
1709 * Do a comparison of two authentication digests by comparing
1710 * the FULL digest. Otehrwise, the server can be subject to
1711 * timing attacks that allow attackers find a valid message
1714 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1716 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1721 for (i = 0; i < length; i++) {
1722 result |= a[i] ^ b[i];
1725 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1730 * Validates the requesting client NAS. Calculates the
1731 * signature based on the clients private key.
1733 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1735 uint8_t digest[AUTH_VECTOR_LEN];
1739 * Zero out the auth_vector in the received packet.
1740 * Then append the shared secret to the received packet,
1741 * and calculate the MD5 sum. This must be the same
1742 * as the original MD5 sum (packet->vector).
1744 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1747 * MD5(packet + secret);
1749 fr_MD5Init(&context);
1750 fr_MD5Update(&context, packet->data, packet->data_len);
1751 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1752 fr_MD5Final(digest, &context);
1755 * Return 0 if OK, 2 if not OK.
1757 if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1763 * Validates the requesting client NAS. Calculates the
1764 * signature based on the clients private key.
1766 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1769 uint8_t calc_digest[AUTH_VECTOR_LEN];
1775 if (original == NULL) {
1780 * Copy the original vector in place.
1782 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1785 * MD5(packet + secret);
1787 fr_MD5Init(&context);
1788 fr_MD5Update(&context, packet->data, packet->data_len);
1789 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1790 fr_MD5Final(calc_digest, &context);
1793 * Copy the packet's vector back to the packet.
1795 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1798 * Return 0 if OK, 2 if not OK.
1800 if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1806 * Check if a set of RADIUS formatted TLVs are OK.
1808 int rad_tlv_ok(const uint8_t *data, size_t length,
1809 size_t dv_type, size_t dv_length)
1811 const uint8_t *end = data + length;
1813 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
1814 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
1818 while (data < end) {
1821 if ((data + dv_type + dv_length) > end) {
1822 fr_strerror_printf("Attribute header overflow");
1828 if ((data[0] == 0) && (data[1] == 0) &&
1829 (data[2] == 0) && (data[3] == 0)) {
1831 fr_strerror_printf("Invalid attribute 0");
1836 fr_strerror_printf("Invalid attribute > 2^24");
1842 if ((data[1] == 0) && (data[1] == 0)) goto zero;
1846 if (data[0] == 0) goto zero;
1850 fr_strerror_printf("Internal sanity check failed");
1854 switch (dv_length) {
1859 if (data[dv_type + 1] != 0) {
1860 fr_strerror_printf("Attribute is longer than 256 octets");
1865 attrlen = data[dv_type + dv_length - 1];
1870 fr_strerror_printf("Internal sanity check failed");
1874 if (attrlen < (dv_type + dv_length)) {
1875 fr_strerror_printf("Attribute header has invalid length");
1879 if (attrlen > length) {
1880 fr_strerror_printf("Attribute overflows container");
1893 * See if the data pointed to by PTR is a valid RADIUS packet.
1895 * packet is not 'const * const' because we may update data_len,
1896 * if there's more data in the UDP packet than in the RADIUS packet.
1898 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1903 radius_packet_t *hdr;
1904 char host_ipaddr[128];
1910 * Check for packets smaller than the packet header.
1912 * RFC 2865, Section 3., subsection 'length' says:
1914 * "The minimum length is 20 ..."
1916 if (packet->data_len < AUTH_HDR_LEN) {
1917 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1918 inet_ntop(packet->src_ipaddr.af,
1919 &packet->src_ipaddr.ipaddr,
1920 host_ipaddr, sizeof(host_ipaddr)),
1921 (int) packet->data_len, AUTH_HDR_LEN);
1926 * RFC 2865, Section 3., subsection 'length' says:
1928 * " ... and maximum length is 4096."
1930 if (packet->data_len > MAX_PACKET_LEN) {
1931 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1932 inet_ntop(packet->src_ipaddr.af,
1933 &packet->src_ipaddr.ipaddr,
1934 host_ipaddr, sizeof(host_ipaddr)),
1935 (int) packet->data_len, MAX_PACKET_LEN);
1940 * Check for packets with mismatched size.
1941 * i.e. We've received 128 bytes, and the packet header
1942 * says it's 256 bytes long.
1944 totallen = (packet->data[2] << 8) | packet->data[3];
1945 hdr = (radius_packet_t *)packet->data;
1948 * Code of 0 is not understood.
1949 * Code of 16 or greate is not understood.
1951 if ((hdr->code == 0) ||
1952 (hdr->code >= FR_MAX_PACKET_CODE)) {
1953 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1954 inet_ntop(packet->src_ipaddr.af,
1955 &packet->src_ipaddr.ipaddr,
1956 host_ipaddr, sizeof(host_ipaddr)),
1962 * Message-Authenticator is required in Status-Server
1963 * packets, otherwise they can be trivially forged.
1965 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1968 * It's also required if the caller asks for it.
1970 if (flags) require_ma = 1;
1973 * Repeat the length checks. This time, instead of
1974 * looking at the data we received, look at the value
1975 * of the 'length' field inside of the packet.
1977 * Check for packets smaller than the packet header.
1979 * RFC 2865, Section 3., subsection 'length' says:
1981 * "The minimum length is 20 ..."
1983 if (totallen < AUTH_HDR_LEN) {
1984 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1985 inet_ntop(packet->src_ipaddr.af,
1986 &packet->src_ipaddr.ipaddr,
1987 host_ipaddr, sizeof(host_ipaddr)),
1988 totallen, AUTH_HDR_LEN);
1993 * And again, for the value of the 'length' field.
1995 * RFC 2865, Section 3., subsection 'length' says:
1997 * " ... and maximum length is 4096."
1999 if (totallen > MAX_PACKET_LEN) {
2000 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
2001 inet_ntop(packet->src_ipaddr.af,
2002 &packet->src_ipaddr.ipaddr,
2003 host_ipaddr, sizeof(host_ipaddr)),
2004 totallen, MAX_PACKET_LEN);
2009 * RFC 2865, Section 3., subsection 'length' says:
2011 * "If the packet is shorter than the Length field
2012 * indicates, it MUST be silently discarded."
2014 * i.e. No response to the NAS.
2016 if (packet->data_len < totallen) {
2017 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
2018 inet_ntop(packet->src_ipaddr.af,
2019 &packet->src_ipaddr.ipaddr,
2020 host_ipaddr, sizeof(host_ipaddr)),
2021 (int) packet->data_len, totallen);
2026 * RFC 2865, Section 3., subsection 'length' says:
2028 * "Octets outside the range of the Length field MUST be
2029 * treated as padding and ignored on reception."
2031 if (packet->data_len > totallen) {
2033 * We're shortening the packet below, but just
2034 * to be paranoid, zero out the extra data.
2036 memset(packet->data + totallen, 0, packet->data_len - totallen);
2037 packet->data_len = totallen;
2041 * Walk through the packet's attributes, ensuring that
2042 * they add up EXACTLY to the size of the packet.
2044 * If they don't, then the attributes either under-fill
2045 * or over-fill the packet. Any parsing of the packet
2046 * is impossible, and will result in unknown side effects.
2048 * This would ONLY happen with buggy RADIUS implementations,
2049 * or with an intentional attack. Either way, we do NOT want
2050 * to be vulnerable to this problem.
2053 count = totallen - AUTH_HDR_LEN;
2058 * We need at least 2 bytes to check the
2062 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2063 inet_ntop(packet->src_ipaddr.af,
2064 &packet->src_ipaddr.ipaddr,
2065 host_ipaddr, sizeof(host_ipaddr)));
2070 * Attribute number zero is NOT defined.
2073 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2074 inet_ntop(packet->src_ipaddr.af,
2075 &packet->src_ipaddr.ipaddr,
2076 host_ipaddr, sizeof(host_ipaddr)));
2081 * Attributes are at LEAST as long as the ID & length
2082 * fields. Anything shorter is an invalid attribute.
2085 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2086 inet_ntop(packet->src_ipaddr.af,
2087 &packet->src_ipaddr.ipaddr,
2088 host_ipaddr, sizeof(host_ipaddr)),
2094 * If there are fewer bytes in the packet than in the
2095 * attribute, it's a bad packet.
2097 if (count < attr[1]) {
2098 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2099 inet_ntop(packet->src_ipaddr.af,
2100 &packet->src_ipaddr.ipaddr,
2101 host_ipaddr, sizeof(host_ipaddr)),
2107 * Sanity check the attributes for length.
2110 default: /* don't do anything by default */
2114 * If there's an EAP-Message, we require
2115 * a Message-Authenticator.
2117 case PW_EAP_MESSAGE:
2121 case PW_MESSAGE_AUTHENTICATOR:
2122 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2123 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2124 inet_ntop(packet->src_ipaddr.af,
2125 &packet->src_ipaddr.ipaddr,
2126 host_ipaddr, sizeof(host_ipaddr)),
2135 * FIXME: Look up the base 255 attributes in the
2136 * dictionary, and switch over their type. For
2137 * integer/date/ip, the attribute length SHOULD
2140 count -= attr[1]; /* grab the attribute length */
2142 num_attributes++; /* seen one more attribute */
2146 * If the attributes add up to a packet, it's allowed.
2148 * If not, we complain, and throw the packet away.
2151 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2152 inet_ntop(packet->src_ipaddr.af,
2153 &packet->src_ipaddr.ipaddr,
2154 host_ipaddr, sizeof(host_ipaddr)));
2159 * If we're configured to look for a maximum number of
2160 * attributes, and we've seen more than that maximum,
2161 * then throw the packet away, as a possible DoS.
2163 if ((fr_max_attributes > 0) &&
2164 (num_attributes > fr_max_attributes)) {
2165 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2166 inet_ntop(packet->src_ipaddr.af,
2167 &packet->src_ipaddr.ipaddr,
2168 host_ipaddr, sizeof(host_ipaddr)),
2169 num_attributes, fr_max_attributes);
2174 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2176 * A packet with an EAP-Message attribute MUST also have
2177 * a Message-Authenticator attribute.
2179 * A Message-Authenticator all by itself is OK, though.
2181 * Similarly, Status-Server packets MUST contain
2182 * Message-Authenticator attributes.
2184 if (require_ma && ! seen_ma) {
2185 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2186 inet_ntop(packet->src_ipaddr.af,
2187 &packet->src_ipaddr.ipaddr,
2188 host_ipaddr, sizeof(host_ipaddr)));
2193 * Fill RADIUS header fields
2195 packet->code = hdr->code;
2196 packet->id = hdr->id;
2197 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2204 * Receive UDP client requests, and fill in
2205 * the basics of a RADIUS_PACKET structure.
2207 RADIUS_PACKET *rad_recv(int fd, int flags)
2210 RADIUS_PACKET *packet;
2213 * Allocate the new request data structure
2215 if ((packet = malloc(sizeof(*packet))) == NULL) {
2216 fr_strerror_printf("out of memory");
2219 memset(packet, 0, sizeof(*packet));
2222 sock_flags = MSG_PEEK;
2226 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
2227 &packet->src_ipaddr, &packet->src_port,
2228 &packet->dst_ipaddr, &packet->dst_port);
2231 * Check for socket errors.
2233 if (packet->data_len < 0) {
2234 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
2235 /* packet->data is NULL */
2241 * If the packet is too big, then rad_recvfrom did NOT
2242 * allocate memory. Instead, it just discarded the
2245 if (packet->data_len > MAX_PACKET_LEN) {
2246 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
2247 /* packet->data is NULL */
2253 * Read no data. Continue.
2254 * This check is AFTER the MAX_PACKET_LEN check above, because
2255 * if the packet is larger than MAX_PACKET_LEN, we also have
2256 * packet->data == NULL
2258 if ((packet->data_len == 0) || !packet->data) {
2259 fr_strerror_printf("Empty packet: Socket is not ready.");
2265 * See if it's a well-formed RADIUS packet.
2267 if (!rad_packet_ok(packet, flags)) {
2273 * Remember which socket we read the packet from.
2275 packet->sockfd = fd;
2278 * FIXME: Do even more filtering by only permitting
2279 * certain IP's. The problem is that we don't know
2280 * how to do this properly for all possible clients...
2284 * Explicitely set the VP list to empty.
2288 if (fr_debug_flag) {
2289 char host_ipaddr[128];
2291 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2292 DEBUG("rad_recv: %s packet from host %s port %d",
2293 fr_packet_codes[packet->code],
2294 inet_ntop(packet->src_ipaddr.af,
2295 &packet->src_ipaddr.ipaddr,
2296 host_ipaddr, sizeof(host_ipaddr)),
2299 DEBUG("rad_recv: Packet from host %s port %d code=%d",
2300 inet_ntop(packet->src_ipaddr.af,
2301 &packet->src_ipaddr.ipaddr,
2302 host_ipaddr, sizeof(host_ipaddr)),
2306 DEBUG(", id=%d, length=%d\n",
2307 packet->id, (int) packet->data_len);
2315 * Verify the signature of a packet.
2317 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2324 if (!packet || !packet->data) return -1;
2327 * Before we allocate memory for the attributes, do more
2330 ptr = packet->data + AUTH_HDR_LEN;
2331 length = packet->data_len - AUTH_HDR_LEN;
2332 while (length > 0) {
2333 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2334 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2339 default: /* don't do anything. */
2343 * Note that more than one Message-Authenticator
2344 * attribute is invalid.
2346 case PW_MESSAGE_AUTHENTICATOR:
2347 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2348 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2350 switch (packet->code) {
2354 case PW_ACCOUNTING_REQUEST:
2355 case PW_ACCOUNTING_RESPONSE:
2356 case PW_DISCONNECT_REQUEST:
2357 case PW_DISCONNECT_ACK:
2358 case PW_DISCONNECT_NAK:
2359 case PW_COA_REQUEST:
2362 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2365 case PW_AUTHENTICATION_ACK:
2366 case PW_AUTHENTICATION_REJECT:
2367 case PW_ACCESS_CHALLENGE:
2369 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2372 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2376 fr_hmac_md5(packet->data, packet->data_len,
2377 (const uint8_t *) secret, strlen(secret),
2379 if (digest_cmp(calc_auth_vector, msg_auth_vector,
2380 sizeof(calc_auth_vector)) != 0) {
2382 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2383 inet_ntop(packet->src_ipaddr.af,
2384 &packet->src_ipaddr.ipaddr,
2385 buffer, sizeof(buffer)));
2386 /* Silently drop packet, according to RFC 3579 */
2388 } /* else the message authenticator was good */
2391 * Reinitialize Authenticators.
2393 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2394 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2396 } /* switch over the attributes */
2400 } /* loop over the packet, sanity checking the attributes */
2403 * It looks like a RADIUS packet, but we can't validate
2406 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2408 fr_strerror_printf("Received Unknown packet code %d "
2409 "from client %s port %d: Cannot validate signature.",
2411 inet_ntop(packet->src_ipaddr.af,
2412 &packet->src_ipaddr.ipaddr,
2413 buffer, sizeof(buffer)),
2419 * Calculate and/or verify digest.
2421 switch(packet->code) {
2425 case PW_AUTHENTICATION_REQUEST:
2426 case PW_STATUS_SERVER:
2428 * The authentication vector is random
2429 * nonsense, invented by the client.
2433 case PW_COA_REQUEST:
2434 case PW_DISCONNECT_REQUEST:
2435 case PW_ACCOUNTING_REQUEST:
2436 if (calc_acctdigest(packet, secret) > 1) {
2437 fr_strerror_printf("Received %s packet "
2438 "from client %s with invalid signature! (Shared secret is incorrect.)",
2439 fr_packet_codes[packet->code],
2440 inet_ntop(packet->src_ipaddr.af,
2441 &packet->src_ipaddr.ipaddr,
2442 buffer, sizeof(buffer)));
2447 /* Verify the reply digest */
2448 case PW_AUTHENTICATION_ACK:
2449 case PW_AUTHENTICATION_REJECT:
2450 case PW_ACCESS_CHALLENGE:
2451 case PW_ACCOUNTING_RESPONSE:
2452 case PW_DISCONNECT_ACK:
2453 case PW_DISCONNECT_NAK:
2456 rcode = calc_replydigest(packet, original, secret);
2458 fr_strerror_printf("Received %s packet "
2459 "from home server %s port %d with invalid signature! (Shared secret is incorrect.)",
2460 fr_packet_codes[packet->code],
2461 inet_ntop(packet->src_ipaddr.af,
2462 &packet->src_ipaddr.ipaddr,
2463 buffer, sizeof(buffer)),
2470 fr_strerror_printf("Received Unknown packet code %d "
2471 "from client %s port %d: Cannot validate signature",
2473 inet_ntop(packet->src_ipaddr.af,
2474 &packet->src_ipaddr.ipaddr,
2475 buffer, sizeof(buffer)),
2485 * Create a "raw" attribute from the attribute contents.
2487 static ssize_t data2vp_raw(UNUSED const RADIUS_PACKET *packet,
2488 UNUSED const RADIUS_PACKET *original,
2489 UNUSED const char *secret,
2490 unsigned int attribute, unsigned int vendor,
2491 const uint8_t *data, size_t length,
2497 if (length > sizeof(vp->vp_octets)) {
2498 fr_strerror_printf("data2vp_raw: Too much data");
2504 * Keep the next function happy.
2506 vp = pairalloc(NULL);
2507 vp = paircreate_raw(attribute, vendor, PW_TYPE_OCTETS, vp);
2509 fr_strerror_printf("data2vp_raw: Failed creating attribute");
2513 vp->length = length;
2514 memcpy(vp->vp_octets, data, length);
2522 static ssize_t data2vp_tlvs(const RADIUS_PACKET *packet,
2523 const RADIUS_PACKET *original,
2525 unsigned int attribute, unsigned int vendor,
2527 const uint8_t *start, size_t length,
2531 * Create any kind of VP from the attribute contents.
2533 * Will return -1 on error, or "length".
2535 static ssize_t data2vp_any(const RADIUS_PACKET *packet,
2536 const RADIUS_PACKET *original,
2537 const char *secret, int nest,
2538 unsigned int attribute, unsigned int vendor,
2539 const uint8_t *data, size_t length,
2542 int data_offset = 0;
2544 VALUE_PAIR *vp = NULL;
2546 da = dict_attrbyvalue(attribute, vendor);
2549 * Unknown attribute. Create it as a "raw" attribute.
2553 if (vp) pairfree(&vp);
2554 return data2vp_raw(packet, original, secret,
2555 attribute, vendor, data, length, pvp);
2559 * TLVs are handled first. They can't be tagged, and
2560 * they can't be encrypted.
2562 if (da->type == PW_TYPE_TLV) {
2563 return data2vp_tlvs(packet, original, secret,
2564 attribute, vendor, nest,
2569 * The attribute is known, and well formed. We can now
2570 * create it. The main failure from here on in is being
2579 if (vp->flags.has_tag) {
2580 if (TAG_VALID(data[0]) ||
2581 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2583 * Tunnel passwords REQUIRE a tag, even
2584 * if don't have a valid tag.
2586 vp->flags.tag = data[0];
2588 if ((vp->type == PW_TYPE_STRING) ||
2589 (vp->type == PW_TYPE_OCTETS)) {
2590 if (length == 0) goto raw;
2597 * Copy the data to be decrypted
2599 vp->length = length - data_offset;
2600 memcpy(&vp->vp_octets[0], data + data_offset, vp->length);
2603 * Decrypt the attribute.
2605 switch (vp->flags.encrypt) {
2609 case FLAG_ENCRYPT_USER_PASSWORD:
2611 rad_pwdecode(vp->vp_strvalue,
2615 rad_pwdecode(vp->vp_strvalue,
2619 if (vp->attribute == PW_USER_PASSWORD) {
2620 vp->length = strlen(vp->vp_strvalue);
2625 * Tunnel-Password's may go ONLY
2626 * in response packets.
2628 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2629 if (!original) goto raw;
2631 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2632 secret, original->vector) < 0) {
2638 * Ascend-Send-Secret
2639 * Ascend-Receive-Secret
2641 case FLAG_ENCRYPT_ASCEND_SECRET:
2645 uint8_t my_digest[AUTH_VECTOR_LEN];
2646 make_secret(my_digest,
2649 memcpy(vp->vp_strvalue, my_digest,
2651 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2652 vp->length = strlen(vp->vp_strvalue);
2658 } /* switch over encryption flags */
2662 case PW_TYPE_STRING:
2663 case PW_TYPE_OCTETS:
2664 case PW_TYPE_ABINARY:
2665 /* nothing more to do */
2669 if (vp->length != 1) goto raw;
2671 vp->vp_integer = vp->vp_octets[0];
2676 if (vp->length != 2) goto raw;
2678 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2681 case PW_TYPE_INTEGER:
2682 if (vp->length != 4) goto raw;
2684 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2685 vp->vp_integer = ntohl(vp->vp_integer);
2687 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2690 * Try to get named VALUEs
2694 dval = dict_valbyattr(vp->attribute, vp->vendor,
2697 strlcpy(vp->vp_strvalue,
2699 sizeof(vp->vp_strvalue));
2705 if (vp->length != 4) goto raw;
2707 memcpy(&vp->vp_date, vp->vp_octets, 4);
2708 vp->vp_date = ntohl(vp->vp_date);
2712 case PW_TYPE_IPADDR:
2713 if (vp->length != 4) goto raw;
2715 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2719 * IPv6 interface ID is 8 octets long.
2722 if (vp->length != 8) goto raw;
2723 /* vp->vp_ifid == vp->vp_octets */
2727 * IPv6 addresses are 16 octets long
2729 case PW_TYPE_IPV6ADDR:
2730 if (vp->length != 16) goto raw;
2731 /* vp->vp_ipv6addr == vp->vp_octets */
2735 * IPv6 prefixes are 2 to 18 octets long.
2737 * RFC 3162: The first octet is unused.
2738 * The second is the length of the prefix
2739 * the rest are the prefix data.
2741 * The prefix length can have value 0 to 128.
2743 case PW_TYPE_IPV6PREFIX:
2744 if (vp->length < 2 || vp->length > 18) goto raw;
2745 if (vp->vp_octets[1] > 128) goto raw;
2748 * FIXME: double-check that
2749 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2751 if (vp->length < 18) {
2752 memset(vp->vp_octets + vp->length, 0,
2757 case PW_TYPE_SIGNED:
2758 if (vp->length != 4) goto raw;
2761 * Overload vp_integer for ntohl, which takes
2762 * uint32_t, not int32_t
2764 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2765 vp->vp_integer = ntohl(vp->vp_integer);
2766 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2771 fr_strerror_printf("data2vp_any: Internal sanity check failed");
2774 case PW_TYPE_COMBO_IP:
2775 if (vp->length == 4) {
2776 vp->type = PW_TYPE_IPADDR;
2777 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2780 } else if (vp->length == 16) {
2781 vp->type = PW_TYPE_IPV6ADDR;
2782 /* vp->vp_ipv6addr == vp->vp_octets */
2799 * Convert a top-level VSA to a VP.
2801 static ssize_t attr2vp_vsa(const RADIUS_PACKET *packet,
2802 const RADIUS_PACKET *original,
2803 const char *secret, DICT_VENDOR *dv,
2804 const uint8_t *data, size_t length,
2807 unsigned int attribute;
2808 ssize_t attrlen, my_len;
2811 if (length <= (dv->type + dv->length)) {
2812 fr_strerror_printf("attr2vp_vsa: Failure to call rad_tlv_ok");
2819 /* data[0] must be zero */
2820 attribute = data[1] << 16;
2821 attribute |= data[2] << 8;
2822 attribute |= data[3];
2826 attribute = data[0];
2827 attribute |= data[1];
2831 attribute = data[0];
2835 fr_strerror_printf("attr2vp_vsa: Internal sanity check failed");
2839 switch (dv->length) {
2841 /* data[dv->type] must be zero */
2842 attrlen = data[dv->type + 1];
2846 attrlen = data[dv->type];
2854 fr_strerror_printf("attr2vp_vsa: Internal sanity check failed");
2859 if (attrlen <= (ssize_t) (dv->type + dv->length)) {
2860 fr_strerror_printf("attr2vp_vsa: Failure to call rad_tlv_ok");
2865 attrlen -= (dv->type + dv->length);
2867 my_len = data2vp_any(packet, original, secret, 0,
2868 attribute, dv->vendorpec,
2869 data + dv->type + dv->length, attrlen, pvp);
2870 if (my_len < 0) return my_len;
2873 if (my_len != attrlen) {
2875 fr_strerror_printf("attr2vp_vsa: Incomplete decode %d != %d",
2876 (int) my_len, (int) attrlen);
2881 return dv->type + dv->length + attrlen;
2885 * Convert one or more TLVs to VALUE_PAIRs. This function can
2886 * be called recursively...
2888 static ssize_t data2vp_tlvs(const RADIUS_PACKET *packet,
2889 const RADIUS_PACKET *original,
2891 unsigned int attribute, unsigned int vendor,
2893 const uint8_t *start, size_t length,
2896 size_t dv_type, dv_length;
2897 const uint8_t *data, *end;
2898 VALUE_PAIR *head, **last, *vp;
2903 * The default format for a VSA is the RFC recommended
2910 * Top-level TLVs can be of a weird format. TLVs
2911 * encapsulated in a TLV can only be in the RFC format.
2915 dv = dict_vendorbyvalue(vendor);
2918 dv_length = dv->length;
2919 /* dict.c enforces sane values on the above fields */
2923 if (nest >= fr_attr_max_tlv) {
2924 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in recursion");
2929 * The VSAs do not exactly fill the data, it's malformed.
2931 if (rad_tlv_ok(data, length, dv_type, dv_length) < 0) {
2932 return data2vp_raw(packet, original, secret,
2933 attribute, vendor, data, length, pvp);
2936 end = data + length;
2940 while (data < end) {
2941 unsigned int my_attr;
2942 unsigned int my_len;
2945 if ((data + dv_type + dv_length) > end) {
2946 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: Insufficient data");
2954 my_attr = attribute;
2955 my_attr |= ((data[0] & fr_attr_mask[nest + 1])
2956 << fr_attr_shift[nest + 1]);
2959 my_attr = (data[0] << 8) | data[1];
2963 my_attr = (data[1] << 16) | (data[1] << 8) | data[3];
2967 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed");
2971 switch (dv_length) {
2978 my_len = data[dv_type + dv_length - 1];
2982 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed");
2987 if (my_len < (dv_type + dv_length)) {
2988 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: underflow");
2993 if ((data + my_len) > end) {
2994 fr_strerror_printf("data2vp_tlvs: Internal sanity check failed in tlvs: overflow");
3000 my_len -= dv_type + dv_length;
3003 * If this returns > 0, it returns "my_len"
3005 if (data2vp_any(packet, original, secret, nest + 1,
3007 data + dv_type + dv_length, my_len, &vp) < 0) {
3012 data += my_len + dv_type + dv_length;
3022 return data - start;
3027 * Group "continued" attributes together, and create VPs from them.
3028 * The caller ensures that the RADIUS packet is OK, and that the
3029 * continuations have all been checked.
3031 static ssize_t data2vp_continued(const RADIUS_PACKET *packet,
3032 const RADIUS_PACKET *original,
3034 const uint8_t *start, size_t length,
3035 VALUE_PAIR **pvp, int nest,
3036 unsigned int attribute, unsigned int vendor,
3037 int first_offset, int later_offset,
3041 uint8_t *attr, *ptr;
3042 const uint8_t *data;
3044 attr = malloc(attrlen);
3046 fr_strerror_printf("Out of memory");
3057 memcpy(ptr, data + first_offset, data[1] - first_offset);
3058 ptr += data[1] - first_offset;
3059 left -= data[1] - first_offset;
3064 if (data >= (start + length)) {
3065 fr_strerror_printf("data2vp_continued: Internal sanity check failed");
3069 memcpy(ptr, data + later_offset, data[1] - later_offset);
3070 ptr += data[1] - later_offset;
3071 left -= data[1] - later_offset;
3075 left = data2vp_any(packet, original, secret, nest,
3077 attr, attrlen, pvp);
3079 if (left < 0) return left;
3081 return data - start;
3086 * Create a "raw" VALUE_PAIR from a RADIUS attribute.
3088 ssize_t rad_attr2vp_raw(const RADIUS_PACKET *packet,
3089 const RADIUS_PACKET *original,
3091 const uint8_t *data, size_t length,
3096 if ((data[1] < 2) || (data[1] > length)) {
3097 fr_strerror_printf("rad_attr2vp_raw: Invalid length");
3101 my_len = data2vp_raw(packet, original, secret, data[0], 0,
3102 data + 2, data[1] - 2, pvp);
3103 if (my_len < 0) return my_len;
3110 * Get the length of the data portion of all of the contiguous
3111 * continued attributes.
3113 * 0 for "no continuation"
3114 * -1 on malformed packets (continuation followed by non-wimax, etc.)
3116 static ssize_t wimax_attrlen(const uint8_t *start, const uint8_t *end)
3118 uint32_t lvalue = htonl(VENDORPEC_WIMAX);
3120 const uint8_t *data = start;
3122 if ((data[8] & 0x80) == 0) return 0;
3123 total = data[7] - 3;
3128 if ((data + 9) > end) return -1;
3130 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3132 (memcmp(data + 2, &lvalue, 4) != 0) ||
3133 (data[6] != start[6]) ||
3134 ((data[7] + 6) != data[1])) return -1;
3136 total += data[7] - 3;
3137 if ((data[8] & 0x80) == 0) break;
3138 } while (data < end);
3145 * Get the length of the data portion of all of the contiguous
3146 * continued attributes.
3148 * 0 for "no continuation"
3149 * -1 on malformed packets (continuation followed by non-wimax, etc.)
3151 static ssize_t extended_attrlen(const uint8_t *start, const uint8_t *end)
3154 const uint8_t *data = start;
3156 if ((data[3] & 0x80) == 0) return 0;
3157 total = data[1] - 4;
3162 if ((data + 4) > end) return -1;
3164 if ((data[0] != start[0]) ||
3166 (data[2] != start[2])) return -1;
3168 total += data[1] - 4;
3169 if ((data[3] & 0x80) == 0) break;
3170 } while (data < end);
3177 * Create WiMAX VALUE_PAIRs from a RADIUS attribute.
3179 ssize_t rad_attr2vp_wimax(const RADIUS_PACKET *packet,
3180 const RADIUS_PACKET *original,
3182 const uint8_t *data, size_t length,
3186 unsigned int attribute;
3189 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3190 fr_strerror_printf("rad_attr2vp_wimax: Invalid length");
3194 if (data[0] != PW_VENDOR_SPECIFIC) {
3195 fr_strerror_printf("rad_attr2vp_wimax: Invalid attribute");
3200 * Not enough room for a Vendor-Id. + WiMAX header
3203 return rad_attr2vp_raw(packet, original, secret,
3207 memcpy(&lvalue, data + 2, 4);
3208 lvalue = ntohl(lvalue);
3213 if (lvalue != VENDORPEC_WIMAX) {
3214 fr_strerror_printf("rad_attr2vp_wimax: Not a WiMAX attribute");
3219 * The WiMAX attribute is encapsulated in a VSA. If the
3220 * WiMAX length disagrees with the VSA length, it's malformed.
3222 if ((data[7] + 6) != data[1]) {
3223 return rad_attr2vp_raw(packet, original, secret,
3227 attribute = data[6];
3230 * Attribute is continued. Do some more work.
3233 my_len = wimax_attrlen(data, data + length);
3235 return rad_attr2vp_raw(packet, original, secret,
3239 return data2vp_continued(packet, original, secret,
3240 data, length, pvp, 0,
3241 data[6], VENDORPEC_WIMAX,
3245 my_len = data2vp_any(packet, original, secret, 0, attribute, lvalue,
3246 data + 9, data[1] - 9, pvp);
3247 if (my_len < 0) return my_len;
3253 * Create Vendor-Specifc VALUE_PAIRs from a RADIUS attribute.
3255 ssize_t rad_attr2vp_vsa(const RADIUS_PACKET *packet,
3256 const RADIUS_PACKET *original,
3258 const uint8_t *data, size_t length,
3261 size_t dv_type, dv_length;
3266 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3267 fr_strerror_printf("rad_attr2vp_vsa: Invalid length");
3271 if (data[0] != PW_VENDOR_SPECIFIC) {
3272 fr_strerror_printf("rad_attr2vp_vsa: Invalid attribute");
3277 * Not enough room for a Vendor-Id.
3278 * Or the high octet of the Vendor-Id is set.
3280 if ((data[1] < 6) || (data[2] != 0)) {
3281 return rad_attr2vp_raw(packet, original, secret,
3285 memcpy(&lvalue, data + 2, 4);
3286 lvalue = ntohl(lvalue);
3289 * WiMAX gets its own set of magic.
3291 if (lvalue == VENDORPEC_WIMAX) {
3292 return rad_attr2vp_wimax(packet, original, secret,
3296 dv_type = dv_length = 1;
3297 dv = dict_vendorbyvalue(lvalue);
3300 dv_length = dv->length;
3304 * Attribute is not in the correct form.
3306 if (rad_tlv_ok(data + 6, data[1] - 6, dv_type, dv_length) < 0) {
3307 return rad_attr2vp_raw(packet, original, secret,
3311 my_len = attr2vp_vsa(packet, original, secret, dv,
3312 data + 6, data[1] - 6, pvp);
3313 if (my_len < 0) return my_len;
3316 if (my_len != (data[1] - 6)) {
3318 fr_strerror_printf("rad_attr2vp_vsa: Incomplete decode");
3327 * Create an "extended" VALUE_PAIR from a RADIUS attribute.
3329 ssize_t rad_attr2vp_extended(const RADIUS_PACKET *packet,
3330 const RADIUS_PACKET *original,
3332 const uint8_t *start, size_t length,
3335 unsigned int attribute;
3338 unsigned int vendor = VENDORPEC_EXTENDED;
3339 size_t data_len = length;
3340 const uint8_t *data;
3345 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3346 fr_strerror_printf("rad_attr2vp_extended: Invalid length");
3350 da = dict_attrbyvalue(data[0], vendor);
3352 fr_strerror_printf("rad_attr2vp_extended: Attribute is not extended format");
3359 * No Extended-Type. It's a raw attribute.
3360 * Also, if there's no data following the Extended-Type,
3361 * it's a raw attribute.
3365 return rad_attr2vp_raw(packet, original, secret, start,
3370 * The attribute is "241.1", for example. Go look that
3371 * up to see what type it is.
3373 attribute = data[0];
3374 attribute |= (data[2] << fr_attr_shift[1]);
3376 da = dict_attrbyvalue(attribute, vendor);
3379 vendor = VENDORPEC_EXTENDED;
3382 if (data[1] < length) data_len = data[1];
3388 * If there's supposed to be a flag octet. If not, it's
3389 * a raw attribute. If the flag is set, it's supposed to
3392 if (da->flags.extended_flags) {
3393 if (data_len == 0) goto raw;
3395 continued = ((data[0] & 0x80) != 0);
3401 * Extended VSAs have 4 octets of
3402 * Vendor-Id followed by one octet of
3405 if (da->flags.evs) {
3406 if (data_len < 5) goto raw;
3409 * Vendor Ids can only be 24-bit.
3411 if (data[0] != 0) goto raw;
3413 vendor = ((data[1] << 16) |
3418 * Pack the *encapsulating* attribute number into
3421 vendor |= start[0] * FR_MAX_VENDOR;
3425 * Over-write the attribute with the
3428 attribute = data[4];
3434 int first_offset = 4;
3437 if (vendor != VENDORPEC_EXTENDED) first_offset += 5;
3439 my_len = extended_attrlen(start, start + length);
3440 if (my_len < 0) goto raw;
3442 if (vendor != VENDORPEC_EXTENDED) my_len -= 5;
3444 return data2vp_continued(packet, original, secret,
3445 start, length, pvp, shift,
3447 first_offset, 4, my_len);
3450 if (data2vp_any(packet, original, secret, shift,
3451 attribute, vendor, data, data_len, pvp) < 0) {
3455 return (data + data_len) - start;
3460 * Create a "standard" RFC VALUE_PAIR from the given data.
3462 ssize_t rad_attr2vp_rfc(const RADIUS_PACKET *packet,
3463 const RADIUS_PACKET *original,
3465 const uint8_t *data, size_t length,
3468 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3469 fr_strerror_printf("rad_attr2vp_rfc: Insufficient data");
3473 if (data2vp_any(packet, original, secret, 0,
3474 data[0], 0, data + 2, data[1] - 2, pvp) < 0) {
3482 * Create a "normal" VALUE_PAIR from the given data.
3484 ssize_t rad_attr2vp(const RADIUS_PACKET *packet,
3485 const RADIUS_PACKET *original,
3487 const uint8_t *data, size_t length,
3490 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3491 fr_strerror_printf("rad_attr2vp: Insufficient data");
3496 * VSAs get their own handler.
3498 if (data[0] == PW_VENDOR_SPECIFIC) {
3499 return rad_attr2vp_vsa(packet, original, secret,
3504 * Extended attribute format gets their own handler.
3506 if (dict_attrbyvalue(data[0], VENDORPEC_EXTENDED) != NULL) {
3507 return rad_attr2vp_extended(packet, original, secret,
3511 return rad_attr2vp_rfc(packet, original, secret, data, length, pvp);
3516 * Calculate/check digest, and decode radius attributes.
3518 * -1 on decoding error
3521 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3527 radius_packet_t *hdr;
3528 VALUE_PAIR *head, **tail, *vp;
3531 * Extract attribute-value pairs
3533 hdr = (radius_packet_t *)packet->data;
3535 packet_length = packet->data_len - AUTH_HDR_LEN;
3542 * Loop over the attributes, decoding them into VPs.
3544 while (packet_length > 0) {
3548 * This may return many VPs
3550 my_len = rad_attr2vp(packet, original, secret,
3551 ptr, packet_length, &vp);
3566 * VSA's may not have been counted properly in
3567 * rad_packet_ok() above, as it is hard to count
3568 * then without using the dictionary. We
3569 * therefore enforce the limits here, too.
3571 if ((fr_max_attributes > 0) &&
3572 (num_attributes > fr_max_attributes)) {
3573 char host_ipaddr[128];
3576 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3577 inet_ntop(packet->src_ipaddr.af,
3578 &packet->src_ipaddr.ipaddr,
3579 host_ipaddr, sizeof(host_ipaddr)),
3580 num_attributes, fr_max_attributes);
3585 packet_length -= my_len;
3589 * Merge information from the outside world into our
3592 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3595 * There may be VP's already in the packet. Don't
3596 * destroy them. Instead, add the decoded attributes to
3597 * the tail of the list.
3599 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
3611 * We assume that the passwd buffer passed is big enough.
3612 * RFC2138 says the password is max 128 chars, so the size
3613 * of the passwd buffer must be at least 129 characters.
3614 * Preferably it's just MAX_STRING_LEN.
3616 * int *pwlen is updated to the new length of the encrypted
3617 * password - a multiple of 16 bytes.
3619 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3620 const uint8_t *vector)
3622 FR_MD5_CTX context, old;
3623 uint8_t digest[AUTH_VECTOR_LEN];
3624 int i, n, secretlen;
3628 * RFC maximum is 128 bytes.
3630 * If length is zero, pad it out with zeros.
3632 * If the length isn't aligned to 16 bytes,
3633 * zero out the extra data.
3637 if (len > 128) len = 128;
3640 memset(passwd, 0, AUTH_PASS_LEN);
3641 len = AUTH_PASS_LEN;
3642 } else if ((len % AUTH_PASS_LEN) != 0) {
3643 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3644 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3649 * Use the secret to setup the decryption digest
3651 secretlen = strlen(secret);
3653 fr_MD5Init(&context);
3654 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3655 old = context; /* save intermediate work */
3658 * Encrypt it in place. Don't bother checking
3659 * len, as we've ensured above that it's OK.
3661 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3663 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3664 fr_MD5Final(digest, &context);
3667 fr_MD5Update(&context,
3668 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3670 fr_MD5Final(digest, &context);
3673 for (i = 0; i < AUTH_PASS_LEN; i++) {
3674 passwd[i + n] ^= digest[i];
3684 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3685 const uint8_t *vector)
3687 FR_MD5_CTX context, old;
3688 uint8_t digest[AUTH_VECTOR_LEN];
3690 size_t n, secretlen;
3693 * The RFC's say that the maximum is 128.
3694 * The buffer we're putting it into above is 254, so
3695 * we don't need to do any length checking.
3697 if (pwlen > 128) pwlen = 128;
3702 if (pwlen == 0) goto done;
3705 * Use the secret to setup the decryption digest
3707 secretlen = strlen(secret);
3709 fr_MD5Init(&context);
3710 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3711 old = context; /* save intermediate work */
3714 * The inverse of the code above.
3716 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3718 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3719 fr_MD5Final(digest, &context);
3722 if (pwlen > AUTH_PASS_LEN) {
3723 fr_MD5Update(&context, (uint8_t *) passwd,
3727 fr_MD5Final(digest, &context);
3730 if (pwlen > (n + AUTH_PASS_LEN)) {
3731 fr_MD5Update(&context, (uint8_t *) passwd + n,
3736 for (i = 0; i < AUTH_PASS_LEN; i++) {
3737 passwd[i + n] ^= digest[i];
3742 passwd[pwlen] = '\0';
3743 return strlen(passwd);
3748 * Encode Tunnel-Password attributes when sending them out on the wire.
3750 * int *pwlen is updated to the new length of the encrypted
3751 * password - a multiple of 16 bytes.
3753 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3756 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3757 const uint8_t *vector)
3759 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3760 unsigned char digest[AUTH_VECTOR_LEN];
3762 int i, n, secretlen;
3767 if (len > 127) len = 127;
3770 * Shift the password 3 positions right to place a salt and original
3771 * length, tag will be added automatically on packet send
3773 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3777 * save original password length as first password character;
3784 * Generate salt. The RFC's say:
3786 * The high bit of salt[0] must be set, each salt in a
3787 * packet should be unique, and they should be random
3789 * So, we set the high bit, add in a counter, and then
3790 * add in some CSPRNG data. should be OK..
3792 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3793 (fr_rand() & 0x07));
3794 salt[1] = fr_rand();
3797 * Padd password to multiple of AUTH_PASS_LEN bytes.
3799 n = len % AUTH_PASS_LEN;
3801 n = AUTH_PASS_LEN - n;
3802 for (; n > 0; n--, len++)
3805 /* set new password length */
3809 * Use the secret to setup the decryption digest
3811 secretlen = strlen(secret);
3812 memcpy(buffer, secret, secretlen);
3814 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3816 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3817 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3818 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3820 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3821 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3824 for (i = 0; i < AUTH_PASS_LEN; i++) {
3825 passwd[i + n2] ^= digest[i];
3833 * Decode Tunnel-Password encrypted attributes.
3835 * Defined in RFC-2868, this uses a two char SALT along with the
3836 * initial intermediate value, to differentiate it from the
3839 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3840 const uint8_t *vector)
3842 FR_MD5_CTX context, old;
3843 uint8_t digest[AUTH_VECTOR_LEN];
3845 unsigned i, n, len, reallen;
3850 * We need at least a salt.
3853 fr_strerror_printf("tunnel password is too short");
3858 * There's a salt, but no password. Or, there's a salt
3859 * and a 'data_len' octet. It's wrong, but at least we
3860 * can figure out what it means: the password is empty.
3862 * Note that this means we ignore the 'data_len' field,
3863 * if the attribute length tells us that there's no
3864 * more data. So the 'data_len' field may be wrong,
3873 len -= 2; /* discount the salt */
3876 * Use the secret to setup the decryption digest
3878 secretlen = strlen(secret);
3880 fr_MD5Init(&context);
3881 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3882 old = context; /* save intermediate work */
3885 * Set up the initial key:
3887 * b(1) = MD5(secret + vector + salt)
3889 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3890 fr_MD5Update(&context, passwd, 2);
3893 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3897 fr_MD5Final(digest, &context);
3902 * A quick check: decrypt the first octet
3903 * of the password, which is the
3904 * 'data_len' field. Ensure it's sane.
3906 reallen = passwd[2] ^ digest[0];
3907 if (reallen >= len) {
3908 fr_strerror_printf("tunnel password is too long for the attribute");
3912 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3916 fr_MD5Final(digest, &context);
3919 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3922 for (i = base; i < AUTH_PASS_LEN; i++) {
3923 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3928 * See make_tunnel_password, above.
3930 if (reallen > 239) reallen = 239;
3933 passwd[reallen] = 0;
3939 * Encode a CHAP password
3941 * FIXME: might not work with Ascend because
3942 * we use vp->length, and Ascend gear likes
3943 * to send an extra '\0' in the string!
3945 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3946 VALUE_PAIR *password)
3950 uint8_t string[MAX_STRING_LEN * 2 + 1];
3951 VALUE_PAIR *challenge;
3954 * Sanity check the input parameters
3956 if ((packet == NULL) || (password == NULL)) {
3961 * Note that the password VP can be EITHER
3962 * a User-Password attribute (from a check-item list),
3963 * or a CHAP-Password attribute (the client asking
3964 * the library to encode it).
3972 memcpy(ptr, password->vp_strvalue, password->length);
3973 ptr += password->length;
3974 i += password->length;
3977 * Use Chap-Challenge pair if present,
3978 * Request-Authenticator otherwise.
3980 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
3982 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3983 i += challenge->length;
3985 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3986 i += AUTH_VECTOR_LEN;
3990 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3997 * Seed the random number generator.
3999 * May be called any number of times.
4001 void fr_rand_seed(const void *data, size_t size)
4006 * Ensure that the pool is initialized.
4008 if (!fr_rand_initialized) {
4011 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4013 fd = open("/dev/urandom", O_RDONLY);
4019 while (total < sizeof(fr_rand_pool.randrsl)) {
4020 this = read(fd, fr_rand_pool.randrsl,
4021 sizeof(fr_rand_pool.randrsl) - total);
4022 if ((this < 0) && (errno != EINTR)) break;
4023 if (this > 0) total += this;
4027 fr_rand_pool.randrsl[0] = fd;
4028 fr_rand_pool.randrsl[1] = time(NULL);
4029 fr_rand_pool.randrsl[2] = errno;
4032 fr_randinit(&fr_rand_pool, 1);
4033 fr_rand_pool.randcnt = 0;
4034 fr_rand_initialized = 1;
4040 * Hash the user data
4043 if (!hash) hash = fr_rand();
4044 hash = fr_hash_update(data, size, hash);
4046 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4051 * Return a 32-bit random number.
4053 uint32_t fr_rand(void)
4058 * Ensure that the pool is initialized.
4060 if (!fr_rand_initialized) {
4061 fr_rand_seed(NULL, 0);
4064 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4065 if (fr_rand_pool.randcnt >= 256) {
4066 fr_rand_pool.randcnt = 0;
4067 fr_isaac(&fr_rand_pool);
4075 * Allocate a new RADIUS_PACKET
4077 RADIUS_PACKET *rad_alloc(int newvector)
4081 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
4082 fr_strerror_printf("out of memory");
4085 memset(rp, 0, sizeof(*rp));
4091 uint32_t hash, base;
4094 * Don't expose the actual contents of the random
4098 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4099 hash = fr_rand() ^ base;
4100 memcpy(rp->vector + i, &hash, sizeof(hash));
4103 fr_rand(); /* stir the pool again */
4108 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
4110 RADIUS_PACKET *reply;
4112 if (!packet) return NULL;
4114 reply = rad_alloc(0);
4115 if (!reply) return NULL;
4118 * Initialize the fields from the request.
4120 reply->sockfd = packet->sockfd;
4121 reply->dst_ipaddr = packet->src_ipaddr;
4122 reply->src_ipaddr = packet->dst_ipaddr;
4123 reply->dst_port = packet->src_port;
4124 reply->src_port = packet->dst_port;
4125 reply->id = packet->id;
4126 reply->code = 0; /* UNKNOWN code */
4127 memcpy(reply->vector, packet->vector,
4128 sizeof(reply->vector));
4131 reply->data_len = 0;
4138 * Free a RADIUS_PACKET
4140 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4142 RADIUS_PACKET *radius_packet;
4144 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4145 radius_packet = *radius_packet_ptr;
4147 free(radius_packet->data);
4149 pairfree(&radius_packet->vps);
4151 free(radius_packet);
4153 *radius_packet_ptr = NULL;