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 * License as published by the Free Software Foundation; either
5 * version 2.1 of the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
12 * You should have received a copy of the GNU Lesser General Public
13 * License along with this library; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Functions to send/receive radius packets.
23 * @copyright 2000-2003,2006 The FreeRADIUS server project
28 #include <freeradius-devel/libradius.h>
30 #include <freeradius-devel/md5.h>
36 #include <freeradius-devel/udpfromto.h>
40 #define VP_TRACE if (fr_debug_flag) printf
42 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
46 printf("--- %s ---\n", msg);
47 for (i = 0; i < len; i++) {
48 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
49 printf("%02x ", data[i]);
50 if ((i & 0x0f) == 0x0f) printf("\n");
52 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
56 #define VP_TRACE(_x, ...)
57 #define VP_HEXDUMP(_x, _y, _z)
62 * The RFC says 4096 octets max, and most packets are less than 256.
64 #define MAX_PACKET_LEN 4096
67 * The maximum number of attributes which we allow in an incoming
68 * request. If there are more attributes than this, the request
71 * This helps to minimize the potential for a DoS, when an
72 * attacker spoofs Access-Request packets, which don't have a
73 * Message-Authenticator attribute. This means that the packet
74 * is unsigned, and the attacker can use resources on the server,
75 * even if the end request is rejected.
77 uint32_t fr_max_attributes = 0;
78 FILE *fr_log_fp = NULL;
80 typedef struct radius_packet_t {
84 uint8_t vector[AUTH_VECTOR_LEN];
88 static fr_randctx fr_rand_pool; /* across multiple calls */
89 static int fr_rand_initialized = 0;
90 static unsigned int salt_offset = 0;
91 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 */
93 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
99 "Accounting-Response",
104 "Accounting-Message", //!< 10
115 "Resource-Free-Request",
116 "Resource-Free-Response",
117 "Resource-Query-Request",
118 "Resource-Query-Response",
119 "Alternate-Resource-Reclaim-Request",
120 "NAS-Reboot-Request",
121 "NAS-Reboot-Response",
134 "Disconnect-Request", //!< 40
144 "IP-Address-Allocate",
145 "IP-Address-Release", //!< 50
149 void fr_printf_log(char const *fmt, ...)
154 if ((fr_debug_flag == 0) || !fr_log_fp) {
159 vfprintf(fr_log_fp, fmt, ap);
165 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";
167 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
171 for (i = 0; i < attrlen; i++) {
172 if ((i > 0) && ((i & 0x0f) == 0x00))
173 fprintf(fr_log_fp, "%.*s", depth, tabs);
174 fprintf(fr_log_fp, "%02x ", ptr[i]);
175 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
177 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
181 void rad_print_hex(RADIUS_PACKET *packet)
185 if (!packet->data || !fr_log_fp) return;
187 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
188 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
189 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
191 fprintf(fr_log_fp, " Vector:\t");
192 for (i = 4; i < 20; i++) {
193 fprintf(fr_log_fp, "%02x", packet->data[i]);
195 fprintf(fr_log_fp, "\n");
197 if (packet->data_len > 20) {
200 fprintf(fr_log_fp, " Data:");
202 total = packet->data_len - 20;
203 ptr = packet->data + 20;
207 unsigned int vendor = 0;
209 fprintf(fr_log_fp, "\t\t");
210 if (total < 2) { /* too short */
211 fprintf(fr_log_fp, "%02x\n", *ptr);
215 if (ptr[1] > total) { /* too long */
216 for (i = 0; i < total; i++) {
217 fprintf(fr_log_fp, "%02x ", ptr[i]);
222 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
223 attrlen = ptr[1] - 2;
225 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
227 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
228 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
229 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
239 print_hex_data(ptr, attrlen, 3);
248 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
251 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
252 #ifdef WITH_UDPFROMTO
253 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
255 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
257 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
260 struct sockaddr_storage dst;
261 socklen_t sizeof_dst;
263 #ifdef WITH_UDPFROMTO
264 struct sockaddr_storage src;
265 socklen_t sizeof_src;
267 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
270 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
274 #ifdef WITH_UDPFROMTO
276 * And if they don't specify a source IP address, don't
279 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
280 (src_ipaddr->af != AF_UNSPEC) &&
281 !fr_inaddr_any(src_ipaddr)) {
282 rcode = sendfromto(sockfd, data, data_len, flags,
283 (struct sockaddr *)&src, sizeof_src,
284 (struct sockaddr *)&dst, sizeof_dst);
290 * No udpfromto, fail gracefully.
292 rcode = sendto(sockfd, data, data_len, flags,
293 (struct sockaddr *) &dst, sizeof_dst);
294 #ifdef WITH_UDPFROMTO
298 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
305 void rad_recv_discard(int sockfd)
308 struct sockaddr_storage src;
309 socklen_t sizeof_src = sizeof(src);
311 (void) recvfrom(sockfd, header, sizeof(header), 0,
312 (struct sockaddr *)&src, &sizeof_src);
316 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
318 ssize_t data_len, packet_len;
320 struct sockaddr_storage src;
321 socklen_t sizeof_src = sizeof(src);
323 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
324 (struct sockaddr *)&src, &sizeof_src);
326 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
331 * Too little data is available, discard the packet.
334 rad_recv_discard(sockfd);
338 } else { /* we got 4 bytes of data. */
340 * See how long the packet says it is.
342 packet_len = (header[2] * 256) + header[3];
345 * The length in the packet says it's less than
346 * a RADIUS header length: discard it.
348 if (packet_len < RADIUS_HDR_LEN) {
349 rad_recv_discard(sockfd);
354 * Enforce RFC requirements, for sanity.
355 * Anything after 4k will be discarded.
357 } else if (packet_len > MAX_PACKET_LEN) {
358 rad_recv_discard(sockfd);
365 * Convert AF. If unknown, discard packet.
367 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
368 rad_recv_discard(sockfd);
376 * The packet says it's this long, but the actual UDP
377 * size could still be smaller.
383 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
386 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
387 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
388 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
390 struct sockaddr_storage src;
391 struct sockaddr_storage dst;
392 socklen_t sizeof_src = sizeof(src);
393 socklen_t sizeof_dst = sizeof(dst);
399 memset(&src, 0, sizeof_src);
400 memset(&dst, 0, sizeof_dst);
403 * Read the length of the packet, from the packet.
404 * This lets us allocate the buffer to use for
405 * reading the rest of the packet.
407 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
408 (struct sockaddr *)&src, &sizeof_src);
410 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
415 * Too little data is available, discard the packet.
418 rad_recv_discard(sockfd);
422 } else { /* we got 4 bytes of data. */
424 * See how long the packet says it is.
426 len = (header[2] * 256) + header[3];
429 * The length in the packet says it's less than
430 * a RADIUS header length: discard it.
432 if (len < RADIUS_HDR_LEN) {
433 recvfrom(sockfd, header, sizeof(header), flags,
434 (struct sockaddr *)&src, &sizeof_src);
438 * Enforce RFC requirements, for sanity.
439 * Anything after 4k will be discarded.
441 } else if (len > MAX_PACKET_LEN) {
442 recvfrom(sockfd, header, sizeof(header), flags,
443 (struct sockaddr *)&src, &sizeof_src);
448 packet->data = talloc_array(packet, uint8_t, len);
449 if (!packet->data) return -1;
452 * Receive the packet. The OS will discard any data in the
453 * packet after "len" bytes.
455 #ifdef WITH_UDPFROMTO
456 data_len = recvfromto(sockfd, packet->data, len, flags,
457 (struct sockaddr *)&src, &sizeof_src,
458 (struct sockaddr *)&dst, &sizeof_dst);
460 data_len = recvfrom(sockfd, packet->data, len, flags,
461 (struct sockaddr *)&src, &sizeof_src);
464 * Get the destination address, too.
466 if (getsockname(sockfd, (struct sockaddr *)&dst,
467 &sizeof_dst) < 0) return -1;
473 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
474 return -1; /* Unknown address family, Die Die Die! */
478 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
482 * Different address families should never happen.
484 if (src.ss_family != dst.ss_family) {
492 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
493 /** Build an encrypted secret value to return in a reply packet
495 * The secret is hidden by xoring with a MD5 digest created from
496 * the shared secret and the authentication vector.
497 * We put them into MD5 in the reverse order from that used when
498 * encrypting passwords to RADIUS.
500 static void make_secret(uint8_t *digest, uint8_t const *vector,
501 char const *secret, uint8_t const *value)
506 fr_md5_init(&context);
507 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
508 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
509 fr_md5_final(digest, &context);
511 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
512 digest[i] ^= value[i];
516 #define MAX_PASS_LEN (128)
517 static void make_passwd(uint8_t *output, ssize_t *outlen,
518 uint8_t const *input, size_t inlen,
519 char const *secret, uint8_t const *vector)
521 FR_MD5_CTX context, old;
522 uint8_t digest[AUTH_VECTOR_LEN];
523 uint8_t passwd[MAX_PASS_LEN];
528 * If the length is zero, round it up.
532 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
534 memcpy(passwd, input, len);
535 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
541 else if ((len & 0x0f) != 0) {
547 fr_md5_init(&context);
548 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
554 fr_md5_update(&context, vector, AUTH_PASS_LEN);
556 for (n = 0; n < len; n += AUTH_PASS_LEN) {
559 fr_md5_update(&context,
560 passwd + n - AUTH_PASS_LEN,
564 fr_md5_final(digest, &context);
565 for (i = 0; i < AUTH_PASS_LEN; i++) {
566 passwd[i + n] ^= digest[i];
570 memcpy(output, passwd, len);
573 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
574 uint8_t const *input, size_t inlen, size_t room,
575 char const *secret, uint8_t const *vector)
577 FR_MD5_CTX context, old;
578 uint8_t digest[AUTH_VECTOR_LEN];
579 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
586 if (room > 253) room = 253;
589 * Account for 2 bytes of the salt, and round the room
590 * available down to the nearest multiple of 16. Then,
591 * subtract one from that to account for the length byte,
592 * and the resulting number is the upper bound on the data
595 * We could short-cut this calculation just be forcing
596 * inlen to be no more than 239. It would work for all
597 * VSA's, as we don't pack multiple VSA's into one
600 * However, this calculation is more general, if a little
601 * complex. And it will work in the future for all possible
602 * kinds of weird attribute packing.
605 room -= (room & 0x0f);
608 if (inlen > room) inlen = room;
611 * Length of the encrypted data is password length plus
612 * one byte for the length of the password.
615 if ((len & 0x0f) != 0) {
619 *outlen = len + 2; /* account for the salt */
622 * Copy the password over.
624 memcpy(passwd + 3, input, inlen);
625 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
628 * Generate salt. The RFC's say:
630 * The high bit of salt[0] must be set, each salt in a
631 * packet should be unique, and they should be random
633 * So, we set the high bit, add in a counter, and then
634 * add in some CSPRNG data. should be OK..
636 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
638 passwd[1] = fr_rand();
639 passwd[2] = inlen; /* length of the password string */
641 fr_md5_init(&context);
642 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
645 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
646 fr_md5_update(&context, &passwd[0], 2);
648 for (n = 0; n < len; n += AUTH_PASS_LEN) {
651 fr_md5_update(&context,
652 passwd + 2 + n - AUTH_PASS_LEN,
656 fr_md5_final(digest, &context);
658 for (i = 0; i < AUTH_PASS_LEN; i++) {
659 passwd[i + 2 + n] ^= digest[i];
662 memcpy(output, passwd, len + 2);
665 extern int const fr_attr_max_tlv;
666 extern int const fr_attr_shift[];
667 extern int const fr_attr_mask[];
669 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
671 unsigned int tlv1, tlv2;
673 if (nest > fr_attr_max_tlv) return 0;
678 * Keep encoding TLVs which have the same scope.
679 * e.g. two attributes of:
680 * ATTR.TLV1.TLV2.TLV3 = data1
681 * ATTR.TLV1.TLV2.TLV4 = data2
682 * both get put into a container of "ATTR.TLV1.TLV2"
686 * Nothing to follow, we're done.
691 * Not from the same vendor, skip it.
693 if (vp->da->vendor != next->da->vendor) return 0;
696 * In a different TLV space, skip it.
699 tlv2 = next->da->attr;
701 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
702 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
704 if (tlv1 != tlv2) return 0;
710 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
711 RADIUS_PACKET const *original,
712 char const *secret, int nest,
713 VALUE_PAIR const **pvp,
714 uint8_t *start, size_t room);
716 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
717 RADIUS_PACKET const *original,
718 char const *secret, VALUE_PAIR const **pvp,
719 unsigned int attribute, uint8_t *ptr, size_t room);
721 /** Encode the *data* portion of the TLV
723 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
724 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
726 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
727 RADIUS_PACKET const *original,
728 char const *secret, int nest,
729 VALUE_PAIR const **pvp,
730 uint8_t *start, size_t room)
734 uint8_t *ptr = start;
735 VALUE_PAIR const *vp = *pvp;
736 VALUE_PAIR const *svp = vp;
741 if (nest > fr_attr_max_tlv) {
742 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
750 if (room <= 2) return ptr - start;
752 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
756 if (room > 255) my_room = 255;
758 len = vp2data_any(packet, original, secret, nest,
759 &vp, ptr + 2, my_room - 2);
760 if (len < 0) return len;
761 if (len == 0) return ptr - start;
762 /* len can NEVER be more than 253 */
767 if ((fr_debug_flag > 3) && fr_log_fp) {
768 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
769 print_hex_data(ptr + 2, len, 3);
777 if (!do_next_tlv(svp, vp, nest)) break;
781 if ((fr_debug_flag > 3) && fr_log_fp) {
784 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
785 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
792 /** Encodes the data portion of an attribute
794 * @return -1 on error, or the length of the data portion.
796 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
797 RADIUS_PACKET const *original,
798 char const *secret, int nest,
799 VALUE_PAIR const **pvp,
800 uint8_t *start, size_t room)
805 uint8_t *ptr = start;
808 VALUE_PAIR const *vp = *pvp;
813 * See if we need to encode a TLV. The low portion of
814 * the attribute has already been placed into the packer.
815 * If there are still attribute bytes left, then go
816 * encode them as TLVs.
818 * If we cared about the stack, we could unroll the loop.
820 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
821 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
822 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
829 * Set up the default sources for the data.
833 switch(vp->da->type) {
839 fr_strerror_printf("ERROR: Cannot encode NULL data");
845 case PW_TYPE_IPV4_ADDR:
846 case PW_TYPE_IPV6_ADDR:
847 case PW_TYPE_IPV6_PREFIX:
848 case PW_TYPE_IPV4_PREFIX:
849 case PW_TYPE_ABINARY:
850 case PW_TYPE_ETHERNET: /* just in case */
851 data = (uint8_t const *) &vp->data;
855 len = 1; /* just in case */
856 array[0] = vp->vp_byte;
861 len = 2; /* just in case */
862 array[0] = (vp->vp_short >> 8) & 0xff;
863 array[1] = vp->vp_short & 0xff;
867 case PW_TYPE_INTEGER:
868 len = 4; /* just in case */
869 lvalue = htonl(vp->vp_integer);
870 memcpy(array, &lvalue, sizeof(lvalue));
874 case PW_TYPE_INTEGER64:
875 len = 8; /* just in case */
876 lvalue64 = htonll(vp->vp_integer64);
877 data = (uint8_t *) &lvalue64;
881 * There are no tagged date attributes.
884 lvalue = htonl(vp->vp_date);
885 data = (uint8_t const *) &lvalue;
886 len = 4; /* just in case */
893 len = 4; /* just in case */
894 slvalue = htonl(vp->vp_signed);
895 memcpy(array, &slvalue, sizeof(slvalue));
900 default: /* unknown type: ignore it */
901 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
914 * Bound the data to the calling size
916 if (len > (ssize_t) room) len = room;
919 * Encrypt the various password styles
921 * Attributes with encrypted values MUST be less than
924 switch (vp->da->flags.encrypt) {
925 case FLAG_ENCRYPT_USER_PASSWORD:
926 make_passwd(ptr, &len, data, len,
927 secret, packet->vector);
930 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
932 if (vp->da->flags.has_tag) lvalue = 1;
935 * Check if there's enough room. If there isn't,
936 * we discard the attribute.
938 * This is ONLY a problem if we have multiple VSA's
939 * in one Vendor-Specific, though.
941 if (room < (18 + lvalue)) return 0;
943 switch (packet->code) {
944 case PW_CODE_ACCESS_ACCEPT:
945 case PW_CODE_ACCESS_REJECT:
946 case PW_CODE_ACCESS_CHALLENGE:
949 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
953 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
954 make_tunnel_passwd(ptr + lvalue, &len, data, len,
956 secret, original->vector);
958 case PW_CODE_ACCOUNTING_REQUEST:
959 case PW_CODE_DISCONNECT_REQUEST:
960 case PW_CODE_COA_REQUEST:
961 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
962 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
963 secret, packet->vector);
969 * The code above ensures that this attribute
972 case FLAG_ENCRYPT_ASCEND_SECRET:
973 if (len != 16) return 0;
974 make_secret(ptr, packet->vector, secret, data);
975 len = AUTH_VECTOR_LEN;
980 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
981 if (vp->da->type == PW_TYPE_STRING) {
982 if (len > ((ssize_t) (room - 1))) len = room - 1;
985 } else if (vp->da->type == PW_TYPE_INTEGER) {
987 } /* else it can't be any other type */
989 memcpy(ptr, data, len);
991 } /* switch over encryption flags */
994 return len + (ptr - start);
997 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
998 uint8_t *ptr, int hdr_len, ssize_t len,
999 int flag_offset, int vsa_offset)
1001 int check_len = len - ptr[1];
1002 int total = len + hdr_len;
1005 * Pass 1: Check if the addition of the headers
1006 * overflows the available room. If so, return
1007 * what we were capable of encoding.
1010 while (check_len > (255 - hdr_len)) {
1012 check_len -= (255 - hdr_len);
1016 * Note that this results in a number of attributes maybe
1017 * being marked as "encoded", but which aren't in the
1018 * packet. Oh well. The solution is to fix the
1019 * "vp2data_any" function to take into account the header
1022 if ((ptr + ptr[1] + total) > end) {
1023 return (ptr + ptr[1]) - start;
1027 * Pass 2: Now that we know there's enough room,
1028 * re-arrange the data to form a set of valid
1029 * RADIUS attributes.
1032 int sublen = 255 - ptr[1];
1034 if (len <= sublen) {
1039 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1040 memmove(ptr + 255, ptr, hdr_len);
1042 if (vsa_offset) ptr[vsa_offset] += sublen;
1043 ptr[flag_offset] |= 0x80;
1047 if (vsa_offset) ptr[vsa_offset] = 3;
1051 if (vsa_offset) ptr[vsa_offset] += len;
1053 return (ptr + ptr[1]) - start;
1057 /** Encode an "extended" attribute
1059 int rad_vp2extended(RADIUS_PACKET const *packet,
1060 RADIUS_PACKET const *original,
1061 char const *secret, VALUE_PAIR const **pvp,
1062 uint8_t *ptr, size_t room)
1066 uint8_t *start = ptr;
1067 VALUE_PAIR const *vp = *pvp;
1071 if (!vp->da->flags.extended) {
1072 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1077 * The attribute number is encoded into the upper 8 bits
1080 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1082 if (!vp->da->flags.long_extended) {
1083 if (room < 3) return 0;
1086 ptr[2] = vp->da->attr & fr_attr_mask[0];
1089 if (room < 4) return 0;
1092 ptr[2] = vp->da->attr & fr_attr_mask[0];
1097 * Only "flagged" attributes can be longer than one
1100 if (!vp->da->flags.long_extended && (room > 255)) {
1107 if (vp->da->flags.evs) {
1108 uint8_t *evs = ptr + ptr[1];
1110 if (room < (size_t) (ptr[1] + 5)) return 0;
1114 evs[0] = 0; /* always zero */
1115 evs[1] = (vp->da->vendor >> 16) & 0xff;
1116 evs[2] = (vp->da->vendor >> 8) & 0xff;
1117 evs[3] = vp->da->vendor & 0xff;
1118 evs[4] = vp->da->attr & fr_attr_mask[0];
1124 len = vp2data_any(packet, original, secret, 0,
1125 pvp, ptr + ptr[1], room - hdr_len);
1126 if (len <= 0) return len;
1129 * There may be more than 252 octets of data encoded in
1130 * the attribute. If so, move the data up in the packet,
1131 * and copy the existing header over. Set the "M" flag ONLY
1132 * after copying the rest of the data.
1134 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1135 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1141 if ((fr_debug_flag > 3) && fr_log_fp) {
1144 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1145 if (!vp->da->flags.long_extended) {
1146 fprintf(fr_log_fp, "%02x ", ptr[2]);
1149 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1153 if (vp->da->flags.evs) {
1154 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1155 ptr[jump], ptr[jump + 1],
1156 ptr[jump + 2], ptr[jump + 3],
1157 ((ptr[jump + 1] << 16) |
1158 (ptr[jump + 2] << 8) |
1164 print_hex_data(ptr + jump, len, 3);
1168 return (ptr + ptr[1]) - start;
1172 /** Encode a WiMAX attribute
1175 int rad_vp2wimax(RADIUS_PACKET const *packet,
1176 RADIUS_PACKET const *original,
1177 char const *secret, VALUE_PAIR const **pvp,
1178 uint8_t *ptr, size_t room)
1183 uint8_t *start = ptr;
1184 VALUE_PAIR const *vp = *pvp;
1189 * Double-check for WiMAX format.
1191 if (!vp->da->flags.wimax) {
1192 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1197 * Not enough room for:
1198 * attr, len, vendor-id, vsa, vsalen, continuation
1200 if (room < 9) return 0;
1203 * Build the Vendor-Specific header
1206 ptr[0] = PW_VENDOR_SPECIFIC;
1208 lvalue = htonl(vp->da->vendor);
1209 memcpy(ptr + 2, &lvalue, 4);
1210 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1212 ptr[8] = 0; /* continuation byte */
1216 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1218 if (len <= 0) return len;
1221 * There may be more than 252 octets of data encoded in
1222 * the attribute. If so, move the data up in the packet,
1223 * and copy the existing header over. Set the "C" flag
1224 * ONLY after copying the rest of the data.
1226 if (len > (255 - ptr[1])) {
1227 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1234 if ((fr_debug_flag > 3) && fr_log_fp) {
1235 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1237 ptr[2], ptr[3], ptr[4], ptr[5],
1238 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1239 ptr[6], ptr[7], ptr[8]);
1240 print_hex_data(ptr + 9, len, 3);
1244 return (ptr + ptr[1]) - start;
1247 /** Encode an RFC format attribute, with the "concat" flag set
1249 * If there isn't enough room in the packet, the data is
1252 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1253 UNUSED RADIUS_PACKET const *original,
1254 UNUSED char const *secret, VALUE_PAIR const **pvp,
1255 unsigned int attribute, uint8_t *start, size_t room)
1257 uint8_t *ptr = start;
1260 VALUE_PAIR const *vp = *pvp;
1270 if (room <= 2) break;
1277 /* no more than 253 octets */
1278 if (left > 253) left = 253;
1280 /* no more than "room" octets */
1281 if (room < (left + 2)) left = room - 2;
1283 memcpy(ptr + 2, p, left);
1286 if ((fr_debug_flag > 3) && fr_log_fp) {
1287 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1288 print_hex_data(ptr + 2, len, 3);
1302 /** Encode an RFC format TLV.
1304 * This could be a standard attribute, or a TLV data type.
1305 * If it's a standard attribute, then vp->da->attr == attribute.
1306 * Otherwise, attribute may be something else.
1308 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1309 RADIUS_PACKET const *original,
1310 char const *secret, VALUE_PAIR const **pvp,
1311 unsigned int attribute, uint8_t *ptr, size_t room)
1315 if (room <= 2) return 0;
1317 ptr[0] = attribute & 0xff;
1320 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1322 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1323 if (len <= 0) return len;
1328 if ((fr_debug_flag > 3) && fr_log_fp) {
1329 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1330 print_hex_data(ptr + 2, len, 3);
1338 /** Encode a VSA which is a TLV
1340 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1342 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1343 RADIUS_PACKET const *original,
1344 char const *secret, VALUE_PAIR const **pvp,
1345 unsigned int attribute, unsigned int vendor,
1346 uint8_t *ptr, size_t room)
1350 VALUE_PAIR const *vp = *pvp;
1354 * Unknown vendor: RFC format.
1355 * Known vendor and RFC format: go do that.
1357 dv = dict_vendorbyvalue(vendor);
1359 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1360 return vp2attr_rfc(packet, original, secret, pvp,
1361 attribute, ptr, room);
1366 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1367 " type %u", (unsigned) dv->type);
1371 ptr[0] = 0; /* attr must be 24-bit */
1372 ptr[1] = (attribute >> 16) & 0xff;
1373 ptr[2] = (attribute >> 8) & 0xff;
1374 ptr[3] = attribute & 0xff;
1378 ptr[0] = (attribute >> 8) & 0xff;
1379 ptr[1] = attribute & 0xff;
1383 ptr[0] = attribute & 0xff;
1387 switch (dv->length) {
1389 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1390 " length %u", (unsigned) dv->length);
1398 ptr[dv->type + 1] = dv->type + 2;
1402 ptr[dv->type] = dv->type + 1;
1407 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1408 room = 255 - (dv->type + dv->length);
1411 len = vp2data_any(packet, original, secret, 0, pvp,
1412 ptr + dv->type + dv->length, room);
1413 if (len <= 0) return len;
1415 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1418 if ((fr_debug_flag > 3) && fr_log_fp) {
1424 if ((fr_debug_flag > 3) && fr_log_fp)
1425 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1426 ptr[0], ptr[1], ptr[2], ptr[3]);
1430 if ((fr_debug_flag > 3) && fr_log_fp)
1431 fprintf(fr_log_fp, "\t\t%02x%02x ",
1436 if ((fr_debug_flag > 3) && fr_log_fp)
1437 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1441 switch (dv->length) {
1446 fprintf(fr_log_fp, " ");
1450 fprintf(fr_log_fp, "%02x ",
1455 fprintf(fr_log_fp, "%02x%02x ",
1456 ptr[dv->type], ptr[dv->type] + 1);
1460 print_hex_data(ptr + dv->type + dv->length, len, 3);
1464 return dv->type + dv->length + len;
1468 /** Encode a Vendor-Specific attribute
1471 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1472 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1477 VALUE_PAIR const *vp = *pvp;
1481 * Double-check for WiMAX format.
1483 if (vp->da->flags.wimax) {
1484 return rad_vp2wimax(packet, original, secret, pvp,
1488 if (vp->da->vendor > FR_MAX_VENDOR) {
1489 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1494 * Not enough room for:
1495 * attr, len, vendor-id
1497 if (room < 6) return 0;
1500 * Build the Vendor-Specific header
1502 ptr[0] = PW_VENDOR_SPECIFIC;
1504 lvalue = htonl(vp->da->vendor);
1505 memcpy(ptr + 2, &lvalue, 4);
1507 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1509 len = vp2attr_vsa(packet, original, secret, pvp,
1510 vp->da->attr, vp->da->vendor,
1511 ptr + ptr[1], room);
1512 if (len < 0) return len;
1515 if ((fr_debug_flag > 3) && fr_log_fp) {
1516 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1518 ptr[2], ptr[3], ptr[4], ptr[5],
1519 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1520 print_hex_data(ptr + 6, len, 3);
1530 /** Encode an RFC standard attribute 1..255
1533 int rad_vp2rfc(RADIUS_PACKET const *packet,
1534 RADIUS_PACKET const *original,
1535 char const *secret, VALUE_PAIR const **pvp,
1536 uint8_t *ptr, size_t room)
1538 VALUE_PAIR const *vp = *pvp;
1542 if (vp->da->vendor != 0) {
1543 fr_strerror_printf("rad_vp2rfc called with VSA");
1547 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1548 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1553 * Only CUI is allowed to have zero length.
1556 if ((vp->length == 0) &&
1557 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1558 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1566 * Message-Authenticator is hard-coded.
1568 if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1569 if (room < 18) return -1;
1572 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1574 memset(ptr + 2, 0, 16);
1576 if ((fr_debug_flag > 3) && fr_log_fp) {
1577 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1581 *pvp = (*pvp)->next;
1586 * EAP-Message is special.
1588 if (vp->da->flags.concat && (vp->length > 253)) {
1589 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1593 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1597 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1598 RADIUS_PACKET const *original,
1599 char const *secret, VALUE_PAIR const **pvp,
1600 uint8_t *start, size_t room)
1603 VALUE_PAIR const *vp = *pvp;
1607 if (!vp->da->flags.is_tlv) {
1608 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1612 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1613 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1617 if (room < 5) return 0;
1620 * Encode the first level of TLVs
1622 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1624 start[2] = vp->da->attr & fr_attr_mask[0];
1627 len = vp2data_any(packet, original, secret, 0, pvp,
1628 start + 4, room - 4);
1629 if (len <= 0) return len;
1641 /** Parse a data structure into a RADIUS attribute
1644 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1645 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1648 VALUE_PAIR const *vp;
1650 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1657 * RFC format attributes take the fast path.
1659 if (!vp->da->vendor) {
1660 if (vp->da->attr > 255) return 0;
1662 return rad_vp2rfc(packet, original, secret, pvp,
1666 if (vp->da->flags.extended) {
1667 return rad_vp2extended(packet, original, secret, pvp,
1672 * The upper 8 bits of the vendor number are the standard
1673 * space attribute which is a TLV.
1675 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1676 return rad_vp2rfctlv(packet, original, secret, pvp,
1680 if (vp->da->flags.wimax) {
1681 return rad_vp2wimax(packet, original, secret, pvp,
1685 return rad_vp2vsa(packet, original, secret, pvp,
1693 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1696 radius_packet_t *hdr;
1698 uint16_t total_length;
1700 VALUE_PAIR const *reply;
1702 char ip_src_buffer[INET6_ADDRSTRLEN];
1703 char ip_dst_buffer[INET6_ADDRSTRLEN];
1706 * A 4K packet, aligned on 64-bits.
1708 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1710 if (is_radius_code(packet->code)) {
1711 what = fr_packet_codes[packet->code];
1716 DEBUG("Sending %s Id %d from %s:%u to %s:%u\n",
1718 inet_ntop(packet->src_ipaddr.af,
1719 &packet->src_ipaddr.ipaddr,
1720 ip_src_buffer, sizeof(ip_src_buffer)),
1722 inet_ntop(packet->dst_ipaddr.af,
1723 &packet->dst_ipaddr.ipaddr,
1724 ip_dst_buffer, sizeof(ip_dst_buffer)),
1728 * Double-check some things based on packet code.
1730 switch (packet->code) {
1731 case PW_CODE_ACCESS_ACCEPT:
1732 case PW_CODE_ACCESS_REJECT:
1733 case PW_CODE_ACCESS_CHALLENGE:
1735 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1741 * These packet vectors start off as all zero.
1743 case PW_CODE_ACCOUNTING_REQUEST:
1744 case PW_CODE_DISCONNECT_REQUEST:
1745 case PW_CODE_COA_REQUEST:
1746 memset(packet->vector, 0, sizeof(packet->vector));
1754 * Use memory on the stack, until we know how
1755 * large the packet will be.
1757 hdr = (radius_packet_t *) data;
1760 * Build standard header
1762 hdr->code = packet->code;
1763 hdr->id = packet->id;
1765 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1767 total_length = RADIUS_HDR_LEN;
1770 * Load up the configuration values for the user
1776 * FIXME: Loop twice over the reply list. The first time,
1777 * calculate the total length of data. The second time,
1778 * allocate the memory, and fill in the VP's.
1780 * Hmm... this may be slower than just doing a small
1785 * Loop over the reply attributes for the packet.
1787 reply = packet->vps;
1790 char const *last_name = NULL;
1795 * Ignore non-wire attributes, but allow extended
1798 if ((reply->da->vendor == 0) &&
1799 ((reply->da->attr & 0xFFFF) >= 256) &&
1800 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1803 * Permit the admin to send BADLY formatted
1804 * attributes with a debug build.
1806 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1807 memcpy(ptr, reply->vp_octets, reply->length);
1808 len = reply->length;
1809 reply = reply->next;
1813 reply = reply->next;
1818 * Set the Message-Authenticator to the correct
1819 * length and initial value.
1821 if (reply->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1823 * Cache the offset to the
1824 * Message-Authenticator
1826 packet->offset = total_length;
1829 last_len = reply->length;
1831 last_name = reply->da->name;
1833 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1834 ((uint8_t *) data) + sizeof(data) - ptr);
1835 if (len < 0) return -1;
1838 * Failed to encode the attribute, likely because
1839 * the packet is full.
1842 if (last_len != 0) {
1843 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1846 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1851 next: /* Used only for Raw-Attribute */
1854 total_length += len;
1855 } /* done looping over all attributes */
1858 * Fill in the rest of the fields, and copy the data over
1859 * from the local stack to the newly allocated memory.
1861 * Yes, all this 'memcpy' is slow, but it means
1862 * that we only allocate the minimum amount of
1863 * memory for a request.
1865 packet->data_len = total_length;
1866 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1867 if (!packet->data) {
1868 fr_strerror_printf("Out of memory");
1872 memcpy(packet->data, hdr, packet->data_len);
1873 hdr = (radius_packet_t *) packet->data;
1875 total_length = htons(total_length);
1876 memcpy(hdr->length, &total_length, sizeof(total_length));
1882 /** Sign a previously encoded packet
1885 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1888 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1891 * It wasn't assigned an Id, this is bad!
1893 if (packet->id < 0) {
1894 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1898 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1899 (packet->offset < 0)) {
1900 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1905 * If there's a Message-Authenticator, update it
1906 * now, BEFORE updating the authentication vector.
1908 if (packet->offset > 0) {
1909 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1911 switch (packet->code) {
1912 case PW_CODE_ACCOUNTING_RESPONSE:
1913 if (original && original->code == PW_CODE_STATUS_SERVER) {
1917 case PW_CODE_ACCOUNTING_REQUEST:
1918 case PW_CODE_DISCONNECT_REQUEST:
1919 case PW_CODE_DISCONNECT_ACK:
1920 case PW_CODE_DISCONNECT_NAK:
1921 case PW_CODE_COA_REQUEST:
1922 case PW_CODE_COA_ACK:
1923 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1927 case PW_CODE_ACCESS_ACCEPT:
1928 case PW_CODE_ACCESS_REJECT:
1929 case PW_CODE_ACCESS_CHALLENGE:
1931 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1934 memcpy(hdr->vector, original->vector,
1938 default: /* others have vector already set to zero */
1944 * Set the authentication vector to zero,
1945 * calculate the HMAC, and put it
1946 * into the Message-Authenticator
1949 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1950 (uint8_t const *) secret, strlen(secret));
1951 memcpy(packet->data + packet->offset + 2,
1952 calc_auth_vector, AUTH_VECTOR_LEN);
1955 * Copy the original request vector back
1956 * to the raw packet.
1958 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1962 * Switch over the packet code, deciding how to
1965 switch (packet->code) {
1967 * Request packets are not signed, bur
1968 * have a random authentication vector.
1970 case PW_CODE_ACCESS_REQUEST:
1971 case PW_CODE_STATUS_SERVER:
1975 * Reply packets are signed with the
1976 * authentication vector of the request.
1983 fr_md5_init(&context);
1984 fr_md5_update(&context, packet->data, packet->data_len);
1985 fr_md5_update(&context, (uint8_t const *) secret,
1987 fr_md5_final(digest, &context);
1989 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1990 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1993 }/* switch over packet codes */
1998 /** Reply to the request
2000 * Also attach reply attribute value pairs and any user message provided.
2002 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2007 char ip_src_buffer[128];
2008 char ip_dst_buffer[128];
2011 * Maybe it's a fake packet. Don't send it.
2013 if (!packet || (packet->sockfd < 0)) {
2017 if (is_radius_code(packet->code)) {
2018 what = fr_packet_codes[packet->code];
2024 * First time through, allocate room for the packet
2026 if (!packet->data) {
2028 * Encode the packet.
2030 if (rad_encode(packet, original, secret) < 0) {
2035 * Re-sign it, including updating the
2036 * Message-Authenticator.
2038 if (rad_sign(packet, original, secret) < 0) {
2043 * If packet->data points to data, then we print out
2044 * the VP list again only for debugging.
2046 } else if (fr_debug_flag) {
2047 DEBUG("Sending %s Id %d from %s:%u to %s:%u\n", what,
2049 inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr,
2050 ip_src_buffer, sizeof(ip_src_buffer)),
2052 inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr,
2053 ip_dst_buffer, sizeof(ip_dst_buffer)),
2056 for (reply = packet->vps; reply; reply = reply->next) {
2057 if ((reply->da->vendor == 0) &&
2058 ((reply->da->attr & 0xFFFF) > 0xff)) continue;
2064 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2069 * If the socket is TCP, call write(). Calling sendto()
2070 * is allowed on some platforms, but it's not nice. Even
2071 * worse, if UDPFROMTO is defined, we *can't* use it on
2072 * TCP sockets. So... just call write().
2074 if (packet->proto == IPPROTO_TCP) {
2077 rcode = write(packet->sockfd, packet->data, packet->data_len);
2078 if (rcode >= 0) return rcode;
2080 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2086 * And send it on it's way.
2088 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2089 &packet->src_ipaddr, packet->src_port,
2090 &packet->dst_ipaddr, packet->dst_port);
2093 /** Do a comparison of two authentication digests by comparing the FULL digest
2095 * Otherwise, the server can be subject to timing attacks that allow attackers
2096 * find a valid message authenticator.
2098 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2100 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2105 for (i = 0; i < length; i++) {
2106 result |= a[i] ^ b[i];
2109 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2113 /** Validates the requesting client NAS
2115 * Calculates the request Authenticator based on the clients private key.
2117 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2119 uint8_t digest[AUTH_VECTOR_LEN];
2123 * Zero out the auth_vector in the received packet.
2124 * Then append the shared secret to the received packet,
2125 * and calculate the MD5 sum. This must be the same
2126 * as the original MD5 sum (packet->vector).
2128 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2131 * MD5(packet + secret);
2133 fr_md5_init(&context);
2134 fr_md5_update(&context, packet->data, packet->data_len);
2135 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2136 fr_md5_final(digest, &context);
2139 * Return 0 if OK, 2 if not OK.
2141 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2146 /** Validates the requesting client NAS
2148 * Calculates the response Authenticator based on the clients
2151 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2154 uint8_t calc_digest[AUTH_VECTOR_LEN];
2160 if (original == NULL) {
2165 * Copy the original vector in place.
2167 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2170 * MD5(packet + secret);
2172 fr_md5_init(&context);
2173 fr_md5_update(&context, packet->data, packet->data_len);
2174 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2175 fr_md5_final(calc_digest, &context);
2178 * Copy the packet's vector back to the packet.
2180 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2183 * Return 0 if OK, 2 if not OK.
2185 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2189 /** Check if a set of RADIUS formatted TLVs are OK
2192 int rad_tlv_ok(uint8_t const *data, size_t length,
2193 size_t dv_type, size_t dv_length)
2195 uint8_t const *end = data + length;
2197 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2198 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2202 while (data < end) {
2205 if ((data + dv_type + dv_length) > end) {
2206 fr_strerror_printf("Attribute header overflow");
2212 if ((data[0] == 0) && (data[1] == 0) &&
2213 (data[2] == 0) && (data[3] == 0)) {
2215 fr_strerror_printf("Invalid attribute 0");
2220 fr_strerror_printf("Invalid attribute > 2^24");
2226 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2230 if (data[0] == 0) goto zero;
2234 fr_strerror_printf("Internal sanity check failed");
2238 switch (dv_length) {
2243 if (data[dv_type] != 0) {
2244 fr_strerror_printf("Attribute is longer than 256 octets");
2249 attrlen = data[dv_type + dv_length - 1];
2254 fr_strerror_printf("Internal sanity check failed");
2258 if (attrlen < (dv_type + dv_length)) {
2259 fr_strerror_printf("Attribute header has invalid length");
2263 if (attrlen > length) {
2264 fr_strerror_printf("Attribute overflows container");
2276 /** See if the data pointed to by PTR is a valid RADIUS packet.
2278 * Packet is not 'const * const' because we may update data_len, if there's more data
2279 * in the UDP packet than in the RADIUS packet.
2281 * @param packet to check
2282 * @param flags to control decoding
2283 * @param reason if not NULL, will have the failure reason written to where it points.
2284 * @return bool, true on success, false on failure.
2286 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2291 radius_packet_t *hdr;
2292 char host_ipaddr[128];
2293 bool require_ma = false;
2294 bool seen_ma = false;
2295 uint32_t num_attributes;
2296 decode_fail_t failure = DECODE_FAIL_NONE;
2299 * Check for packets smaller than the packet header.
2301 * RFC 2865, Section 3., subsection 'length' says:
2303 * "The minimum length is 20 ..."
2305 if (packet->data_len < RADIUS_HDR_LEN) {
2306 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2307 inet_ntop(packet->src_ipaddr.af,
2308 &packet->src_ipaddr.ipaddr,
2309 host_ipaddr, sizeof(host_ipaddr)),
2310 packet->data_len, RADIUS_HDR_LEN);
2311 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2317 * Check for packets with mismatched size.
2318 * i.e. We've received 128 bytes, and the packet header
2319 * says it's 256 bytes long.
2321 totallen = (packet->data[2] << 8) | packet->data[3];
2322 hdr = (radius_packet_t *)packet->data;
2325 * Code of 0 is not understood.
2326 * Code of 16 or greate is not understood.
2328 if ((hdr->code == 0) ||
2329 (hdr->code >= FR_MAX_PACKET_CODE)) {
2330 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2331 inet_ntop(packet->src_ipaddr.af,
2332 &packet->src_ipaddr.ipaddr,
2333 host_ipaddr, sizeof(host_ipaddr)),
2335 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2340 * Message-Authenticator is required in Status-Server
2341 * packets, otherwise they can be trivially forged.
2343 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2346 * It's also required if the caller asks for it.
2348 if (flags) require_ma = true;
2351 * Repeat the length checks. This time, instead of
2352 * looking at the data we received, look at the value
2353 * of the 'length' field inside of the packet.
2355 * Check for packets smaller than the packet header.
2357 * RFC 2865, Section 3., subsection 'length' says:
2359 * "The minimum length is 20 ..."
2361 if (totallen < RADIUS_HDR_LEN) {
2362 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2363 inet_ntop(packet->src_ipaddr.af,
2364 &packet->src_ipaddr.ipaddr,
2365 host_ipaddr, sizeof(host_ipaddr)),
2366 totallen, RADIUS_HDR_LEN);
2367 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2372 * And again, for the value of the 'length' field.
2374 * RFC 2865, Section 3., subsection 'length' says:
2376 * " ... and maximum length is 4096."
2378 * HOWEVER. This requirement is for the network layer.
2379 * If the code gets here, we assume that a well-formed
2380 * packet is an OK packet.
2382 * We allow both the UDP data length, and the RADIUS
2383 * "length" field to contain up to 64K of data.
2387 * RFC 2865, Section 3., subsection 'length' says:
2389 * "If the packet is shorter than the Length field
2390 * indicates, it MUST be silently discarded."
2392 * i.e. No response to the NAS.
2394 if (packet->data_len < totallen) {
2395 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2396 inet_ntop(packet->src_ipaddr.af,
2397 &packet->src_ipaddr.ipaddr,
2398 host_ipaddr, sizeof(host_ipaddr)),
2399 packet->data_len, totallen);
2400 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2405 * RFC 2865, Section 3., subsection 'length' says:
2407 * "Octets outside the range of the Length field MUST be
2408 * treated as padding and ignored on reception."
2410 if (packet->data_len > totallen) {
2412 * We're shortening the packet below, but just
2413 * to be paranoid, zero out the extra data.
2415 memset(packet->data + totallen, 0, packet->data_len - totallen);
2416 packet->data_len = totallen;
2420 * Walk through the packet's attributes, ensuring that
2421 * they add up EXACTLY to the size of the packet.
2423 * If they don't, then the attributes either under-fill
2424 * or over-fill the packet. Any parsing of the packet
2425 * is impossible, and will result in unknown side effects.
2427 * This would ONLY happen with buggy RADIUS implementations,
2428 * or with an intentional attack. Either way, we do NOT want
2429 * to be vulnerable to this problem.
2432 count = totallen - RADIUS_HDR_LEN;
2437 * We need at least 2 bytes to check the
2441 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2442 inet_ntop(packet->src_ipaddr.af,
2443 &packet->src_ipaddr.ipaddr,
2444 host_ipaddr, sizeof(host_ipaddr)));
2445 failure = DECODE_FAIL_HEADER_OVERFLOW;
2450 * Attribute number zero is NOT defined.
2453 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2454 inet_ntop(packet->src_ipaddr.af,
2455 &packet->src_ipaddr.ipaddr,
2456 host_ipaddr, sizeof(host_ipaddr)));
2457 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2462 * Attributes are at LEAST as long as the ID & length
2463 * fields. Anything shorter is an invalid attribute.
2466 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2467 inet_ntop(packet->src_ipaddr.af,
2468 &packet->src_ipaddr.ipaddr,
2469 host_ipaddr, sizeof(host_ipaddr)),
2471 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2476 * If there are fewer bytes in the packet than in the
2477 * attribute, it's a bad packet.
2479 if (count < attr[1]) {
2480 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2481 inet_ntop(packet->src_ipaddr.af,
2482 &packet->src_ipaddr.ipaddr,
2483 host_ipaddr, sizeof(host_ipaddr)),
2485 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2490 * Sanity check the attributes for length.
2493 default: /* don't do anything by default */
2497 * If there's an EAP-Message, we require
2498 * a Message-Authenticator.
2500 case PW_EAP_MESSAGE:
2504 case PW_MESSAGE_AUTHENTICATOR:
2505 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2506 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2507 inet_ntop(packet->src_ipaddr.af,
2508 &packet->src_ipaddr.ipaddr,
2509 host_ipaddr, sizeof(host_ipaddr)),
2511 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2519 * FIXME: Look up the base 255 attributes in the
2520 * dictionary, and switch over their type. For
2521 * integer/date/ip, the attribute length SHOULD
2524 count -= attr[1]; /* grab the attribute length */
2526 num_attributes++; /* seen one more attribute */
2530 * If the attributes add up to a packet, it's allowed.
2532 * If not, we complain, and throw the packet away.
2535 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2536 inet_ntop(packet->src_ipaddr.af,
2537 &packet->src_ipaddr.ipaddr,
2538 host_ipaddr, sizeof(host_ipaddr)));
2539 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2544 * If we're configured to look for a maximum number of
2545 * attributes, and we've seen more than that maximum,
2546 * then throw the packet away, as a possible DoS.
2548 if ((fr_max_attributes > 0) &&
2549 (num_attributes > fr_max_attributes)) {
2550 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2551 inet_ntop(packet->src_ipaddr.af,
2552 &packet->src_ipaddr.ipaddr,
2553 host_ipaddr, sizeof(host_ipaddr)),
2554 num_attributes, fr_max_attributes);
2555 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2560 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2562 * A packet with an EAP-Message attribute MUST also have
2563 * a Message-Authenticator attribute.
2565 * A Message-Authenticator all by itself is OK, though.
2567 * Similarly, Status-Server packets MUST contain
2568 * Message-Authenticator attributes.
2570 if (require_ma && !seen_ma) {
2571 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2572 inet_ntop(packet->src_ipaddr.af,
2573 &packet->src_ipaddr.ipaddr,
2574 host_ipaddr, sizeof(host_ipaddr)));
2575 failure = DECODE_FAIL_MA_MISSING;
2580 * Fill RADIUS header fields
2582 packet->code = hdr->code;
2583 packet->id = hdr->id;
2584 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2592 return (failure == DECODE_FAIL_NONE);
2596 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2599 RADIUS_PACKET *rad_recv(int fd, int flags)
2603 RADIUS_PACKET *packet;
2606 * Allocate the new request data structure
2608 packet = rad_alloc(NULL, false);
2610 fr_strerror_printf("out of memory");
2615 sock_flags = MSG_PEEK;
2619 data_len = rad_recvfrom(fd, packet, sock_flags,
2620 &packet->src_ipaddr, &packet->src_port,
2621 &packet->dst_ipaddr, &packet->dst_port);
2624 * Check for socket errors.
2627 fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno));
2628 /* packet->data is NULL */
2632 packet->data_len = data_len; /* unsigned vs signed */
2635 * If the packet is too big, then rad_recvfrom did NOT
2636 * allocate memory. Instead, it just discarded the
2639 if (packet->data_len > MAX_PACKET_LEN) {
2640 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes");
2641 /* packet->data is NULL */
2647 * Read no data. Continue.
2648 * This check is AFTER the MAX_PACKET_LEN check above, because
2649 * if the packet is larger than MAX_PACKET_LEN, we also have
2650 * packet->data == NULL
2652 if ((packet->data_len == 0) || !packet->data) {
2653 fr_strerror_printf("Empty packet: Socket is not ready");
2659 * See if it's a well-formed RADIUS packet.
2661 if (!rad_packet_ok(packet, flags, NULL)) {
2667 * Remember which socket we read the packet from.
2669 packet->sockfd = fd;
2672 * FIXME: Do even more filtering by only permitting
2673 * certain IP's. The problem is that we don't know
2674 * how to do this properly for all possible clients...
2678 * Explicitely set the VP list to empty.
2682 if (fr_debug_flag) {
2683 char src_ipaddr[128];
2684 char dst_ipaddr[128];
2686 if (is_radius_code(packet->code)) {
2687 DEBUG("Received %s Id %d from %s:%d to %s:%d length %d\n",
2688 fr_packet_codes[packet->code],
2690 inet_ntop(packet->src_ipaddr.af,
2691 &packet->src_ipaddr.ipaddr,
2692 src_ipaddr, sizeof(src_ipaddr)),
2694 inet_ntop(packet->dst_ipaddr.af,
2695 &packet->dst_ipaddr.ipaddr,
2696 dst_ipaddr, sizeof(dst_ipaddr)),
2698 (int) packet->data_len);
2700 DEBUG("Received code %d Id %d from %s:%d to %s:%d length %d\n",
2703 inet_ntop(packet->src_ipaddr.af,
2704 &packet->src_ipaddr.ipaddr,
2705 src_ipaddr, sizeof(src_ipaddr)),
2707 inet_ntop(packet->dst_ipaddr.af,
2708 &packet->dst_ipaddr.ipaddr,
2709 dst_ipaddr, sizeof(dst_ipaddr)),
2711 (int) packet->data_len);
2716 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2723 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2726 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2733 if (!packet || !packet->data) return -1;
2736 * Before we allocate memory for the attributes, do more
2739 ptr = packet->data + RADIUS_HDR_LEN;
2740 length = packet->data_len - RADIUS_HDR_LEN;
2741 while (length > 0) {
2742 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2743 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2748 default: /* don't do anything. */
2752 * Note that more than one Message-Authenticator
2753 * attribute is invalid.
2755 case PW_MESSAGE_AUTHENTICATOR:
2756 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2757 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2759 switch (packet->code) {
2763 case PW_CODE_ACCOUNTING_RESPONSE:
2765 (original->code == PW_CODE_STATUS_SERVER)) {
2769 case PW_CODE_ACCOUNTING_REQUEST:
2770 case PW_CODE_DISCONNECT_REQUEST:
2771 case PW_CODE_COA_REQUEST:
2772 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2776 case PW_CODE_ACCESS_ACCEPT:
2777 case PW_CODE_ACCESS_REJECT:
2778 case PW_CODE_ACCESS_CHALLENGE:
2779 case PW_CODE_DISCONNECT_ACK:
2780 case PW_CODE_DISCONNECT_NAK:
2781 case PW_CODE_COA_ACK:
2782 case PW_CODE_COA_NAK:
2784 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet");
2787 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2791 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2792 (uint8_t const *) secret, strlen(secret));
2793 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2794 sizeof(calc_auth_vector)) != 0) {
2796 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2797 inet_ntop(packet->src_ipaddr.af,
2798 &packet->src_ipaddr.ipaddr,
2799 buffer, sizeof(buffer)));
2800 /* Silently drop packet, according to RFC 3579 */
2802 } /* else the message authenticator was good */
2805 * Reinitialize Authenticators.
2807 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2808 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2810 } /* switch over the attributes */
2814 } /* loop over the packet, sanity checking the attributes */
2817 * It looks like a RADIUS packet, but we don't know what it is
2818 * so can't validate the authenticators.
2820 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2822 fr_strerror_printf("Received Unknown packet code %d "
2823 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2825 inet_ntop(packet->src_ipaddr.af,
2826 &packet->src_ipaddr.ipaddr,
2827 buffer, sizeof(buffer)),
2833 * Calculate and/or verify Request or Response Authenticator.
2835 switch (packet->code) {
2839 case PW_CODE_ACCESS_REQUEST:
2840 case PW_CODE_STATUS_SERVER:
2842 * The authentication vector is random
2843 * nonsense, invented by the client.
2847 case PW_CODE_COA_REQUEST:
2848 case PW_CODE_DISCONNECT_REQUEST:
2849 case PW_CODE_ACCOUNTING_REQUEST:
2850 if (calc_acctdigest(packet, secret) > 1) {
2851 fr_strerror_printf("Received %s packet "
2852 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2853 fr_packet_codes[packet->code],
2854 inet_ntop(packet->src_ipaddr.af,
2855 &packet->src_ipaddr.ipaddr,
2856 buffer, sizeof(buffer)));
2861 /* Verify the reply digest */
2862 case PW_CODE_ACCESS_ACCEPT:
2863 case PW_CODE_ACCESS_REJECT:
2864 case PW_CODE_ACCESS_CHALLENGE:
2865 case PW_CODE_ACCOUNTING_RESPONSE:
2866 case PW_CODE_DISCONNECT_ACK:
2867 case PW_CODE_DISCONNECT_NAK:
2868 case PW_CODE_COA_ACK:
2869 case PW_CODE_COA_NAK:
2870 rcode = calc_replydigest(packet, original, secret);
2872 fr_strerror_printf("Received %s packet "
2873 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2874 fr_packet_codes[packet->code],
2875 inet_ntop(packet->src_ipaddr.af,
2876 &packet->src_ipaddr.ipaddr,
2877 buffer, sizeof(buffer)),
2884 fr_strerror_printf("Received Unknown packet code %d "
2885 "from client %s port %d: Cannot validate Request/Response Authenticator",
2887 inet_ntop(packet->src_ipaddr.af,
2888 &packet->src_ipaddr.ipaddr,
2889 buffer, sizeof(buffer)),
2898 /** Convert a "concatenated" attribute to one long VP
2901 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2902 DICT_ATTR const *da, uint8_t const *start,
2903 size_t const packetlen, VALUE_PAIR **pvp)
2907 uint8_t const *ptr = start;
2908 uint8_t const *end = start + packetlen;
2916 * The packet has already been sanity checked, so we
2917 * don't care about walking off of the end of it.
2920 total += ptr[1] - 2;
2925 * Attributes MUST be consecutive.
2927 if (ptr[0] != attr) break;
2930 vp = pairalloc(ctx, da);
2934 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->length);
2942 while (total < vp->length) {
2943 memcpy(p, ptr + 2, ptr[1] - 2);
2945 total += ptr[1] - 2;
2954 /** Convert TLVs to one or more VPs
2957 static ssize_t data2vp_tlvs(TALLOC_CTX *ctx,
2958 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2959 char const *secret, DICT_ATTR const *da,
2960 uint8_t const *start, size_t length,
2963 uint8_t const *data = start;
2964 DICT_ATTR const *child;
2965 VALUE_PAIR *head, **tail;
2967 if (length < 3) return -1; /* type, length, value */
2969 VP_HEXDUMP("tlvs", data, length);
2971 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2976 while (data < (start + length)) {
2979 child = dict_attrbyparent(da, data[0], da->vendor);
2981 unsigned int my_attr, my_vendor;
2983 VP_TRACE("Failed to find child %u of TLV %s\n",
2987 * Get child attr/vendor so that
2988 * we can call unknown attr.
2991 my_vendor = da->vendor;
2993 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2998 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
3005 tlv_len = data2vp(ctx, packet, original, secret, child,
3006 data + 2, data[1] - 2, data[1] - 2, tail);
3011 tail = &((*tail)->next);
3019 /** Convert a top-level VSA to a VP.
3021 * "length" can be LONGER than just this sub-vsa.
3023 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3024 RADIUS_PACKET const *original,
3025 char const *secret, DICT_VENDOR *dv,
3026 uint8_t const *data, size_t length,
3029 unsigned int attribute;
3030 ssize_t attrlen, my_len;
3031 DICT_ATTR const *da;
3034 if (length <= (dv->type + dv->length)) {
3035 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3042 /* data[0] must be zero */
3043 attribute = data[1] << 16;
3044 attribute |= data[2] << 8;
3045 attribute |= data[3];
3049 attribute = data[0] << 8;
3050 attribute |= data[1];
3054 attribute = data[0];
3058 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3062 switch (dv->length) {
3064 /* data[dv->type] must be zero, from rad_tlv_ok() */
3065 attrlen = data[dv->type + 1];
3069 attrlen = data[dv->type];
3077 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3082 if (attrlen <= (ssize_t) (dv->type + dv->length)) {
3083 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3089 * See if the VSA is known.
3091 da = dict_attrbyvalue(attribute, dv->vendorpec);
3092 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3095 my_len = data2vp(ctx, packet, original, secret, da,
3096 data + dv->type + dv->length,
3097 attrlen - (dv->type + dv->length),
3098 attrlen - (dv->type + dv->length),
3100 if (my_len < 0) return my_len;
3106 /** Convert a fragmented extended attr to a VP
3116 * But for the first fragment, we get passed a pointer to the "extended-attr"
3118 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3119 RADIUS_PACKET const *original,
3120 char const *secret, DICT_ATTR const *da,
3121 uint8_t const *data,
3122 size_t attrlen, size_t packetlen,
3127 uint8_t *head, *tail;
3128 uint8_t const *frag, *end;
3129 uint8_t const *attr;
3133 if (attrlen < 3) return -1;
3136 * Calculate the length of all of the fragments. For
3137 * now, they MUST be contiguous in the packet, and they
3138 * MUST be all of the same TYPE and EXTENDED-TYPE
3141 fraglen = attrlen - 2;
3142 frag = data + attrlen;
3143 end = data + packetlen;
3147 while (frag < end) {
3149 (frag[0] != attr[0]) ||
3150 (frag[1] < 4) || /* too short for long-extended */
3151 (frag[2] != attr[2]) ||
3152 ((frag + frag[1]) > end)) { /* overflow */
3157 last_frag = ((frag[3] & 0x80) == 0);
3159 fraglen += frag[1] - 4;
3164 head = tail = malloc(fraglen);
3165 if (!head) return -1;
3167 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3170 * And again, but faster and looser.
3172 * We copy the first fragment, followed by the rest of
3177 while (fragments > 0) {
3178 memcpy(tail, frag + 4, frag[1] - 4);
3179 tail += frag[1] - 4;
3184 VP_HEXDUMP("long-extended fragments", head, fraglen);
3186 rcode = data2vp(ctx, packet, original, secret, da,
3187 head, fraglen, fraglen, pvp);
3189 if (rcode < 0) return rcode;
3194 /** Convert a Vendor-Specific WIMAX to vps
3196 * @note Called ONLY for Vendor-Specific
3198 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3199 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3200 char const *secret, uint32_t vendor,
3201 uint8_t const *data,
3202 size_t attrlen, size_t packetlen,
3208 uint8_t *head, *tail;
3209 uint8_t const *frag, *end;
3210 DICT_ATTR const *child;
3212 if (attrlen < 8) return -1;
3214 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3216 child = dict_attrbyvalue(data[4], vendor);
3217 if (!child) return -1;
3219 if ((data[6] & 0x80) == 0) {
3220 rcode = data2vp(ctx, packet, original, secret, child,
3221 data + 7, data[5] - 3, data[5] - 3,
3223 if (rcode < 0) return -1;
3228 * Calculate the length of all of the fragments. For
3229 * now, they MUST be contiguous in the packet, and they
3230 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3232 * The first fragment doesn't have a RADIUS attribute
3233 * header, so it needs to be treated a little special.
3235 fraglen = data[5] - 3;
3236 frag = data + attrlen;
3237 end = data + packetlen;
3240 while (frag < end) {
3242 (frag[0] != PW_VENDOR_SPECIFIC) ||
3243 (frag[1] < 9) || /* too short for wimax */
3244 ((frag + frag[1]) > end) || /* overflow */
3245 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3246 (frag[6] != data[4]) || /* not the same wimax attr */
3247 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3252 last_frag = ((frag[8] & 0x80) == 0);
3254 fraglen += frag[7] - 3;
3258 head = tail = malloc(fraglen);
3259 if (!head) return -1;
3262 * And again, but faster and looser.
3264 * We copy the first fragment, followed by the rest of
3269 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3270 tail += frag[4 + 1] - 3;
3271 frag += attrlen; /* should be frag[1] - 7 */
3274 * frag now points to RADIUS attributes
3277 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3278 tail += frag[2 + 4 + 1] - 3;
3280 } while (frag < end);
3282 VP_HEXDUMP("wimax fragments", head, fraglen);
3284 rcode = data2vp(ctx, packet, original, secret, child,
3285 head, fraglen, fraglen, pvp);
3287 if (rcode < 0) return rcode;
3293 /** Convert a top-level VSA to one or more VPs
3296 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3297 RADIUS_PACKET const *original,
3298 char const *secret, uint8_t const *data,
3299 size_t attrlen, size_t packetlen,
3306 VALUE_PAIR *head, **tail;
3308 if (attrlen > packetlen) return -1;
3309 if (attrlen < 5) return -1; /* vid, value */
3310 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3312 memcpy(&vendor, data, 4);
3313 vendor = ntohl(vendor);
3314 dv = dict_vendorbyvalue(vendor);
3320 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3321 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3322 data, attrlen, packetlen, pvp);
3327 * VSAs should normally be in TLV format.
3329 if (rad_tlv_ok(data + 4, attrlen - 4,
3330 dv->type, dv->length) < 0) return -1;
3333 * There may be more than one VSA in the
3334 * Vendor-Specific. If so, loop over them all.
3343 while (attrlen > 0) {
3346 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3347 data, attrlen, tail);
3350 fr_strerror_printf("Internal sanity check %d", __LINE__);
3353 tail = &((*tail)->next);
3356 packetlen -= vsa_len;
3364 /** Create any kind of VP from the attribute contents
3366 * "length" is AT LEAST the length of this attribute, as we
3367 * expect the caller to have verified the data with
3368 * rad_packet_ok(). "length" may be up to the length of the
3371 * @return -1 on error, or "length".
3373 ssize_t data2vp(TALLOC_CTX *ctx,
3374 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3376 DICT_ATTR const *da, uint8_t const *start,
3377 size_t const attrlen, size_t const packetlen,
3380 int8_t tag = TAG_NONE;
3384 DICT_ATTR const *child;
3387 uint8_t const *data = start;
3389 uint8_t buffer[256];
3392 * FIXME: Attrlen can be larger than 253 for extended attrs!
3394 if (!da || (attrlen > packetlen) ||
3395 ((attrlen > 253) && (attrlen != packetlen)) ||
3396 (attrlen > 128*1024)) {
3397 fr_strerror_printf("data2vp: invalid arguments");
3401 VP_HEXDUMP("data2vp", start, attrlen);
3403 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3408 * Hacks for CUI. The WiMAX spec says that it can be
3409 * zero length, even though this is forbidden by the
3410 * RADIUS specs. So... we make a special case for it.
3413 if (!((da->vendor == 0) &&
3414 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3421 * Hacks for Coverity. Editing the dictionary
3422 * will break assumptions about CUI. We know
3423 * this, but Coverity doesn't.
3425 if (da->type != PW_TYPE_OCTETS) return -1;
3430 goto alloc_cui; /* skip everything */
3434 * Hacks for tags. If the attribute is capable of
3435 * encoding a tag, and there's room for the tag, and
3436 * there is a tag, or it's encrypted with Tunnel-Password,
3437 * then decode the tag.
3439 if (da->flags.has_tag && (datalen > 1) &&
3440 ((data[0] < 0x20) ||
3441 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3443 * Only "short" attributes can be encrypted.
3445 if (datalen >= sizeof(buffer)) return -1;
3447 if (da->type == PW_TYPE_STRING) {
3448 memcpy(buffer, data + 1, datalen - 1);
3452 } else if (da->type == PW_TYPE_INTEGER) {
3453 memcpy(buffer, data, attrlen);
3458 return -1; /* only string and integer can have tags */
3465 * Decrypt the attribute.
3467 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3469 * Encrypted attributes can only exist for the
3470 * old-style format. Extended attributes CANNOT
3473 if (attrlen > 253) {
3477 if (data == start) {
3478 memcpy(buffer, data, attrlen);
3482 switch (da->flags.encrypt) { /* can't be tagged */
3486 case FLAG_ENCRYPT_USER_PASSWORD:
3488 rad_pwdecode((char *) buffer,
3492 rad_pwdecode((char *) buffer,
3497 datalen = strlen((char *) buffer);
3501 * Tunnel-Password's may go ONLY in response
3502 * packets. They can have a tag, so datalen is
3503 * not the same as attrlen.
3505 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3506 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3507 original ? original->vector : nullvector) < 0) {
3513 * Ascend-Send-Secret
3514 * Ascend-Receive-Secret
3516 case FLAG_ENCRYPT_ASCEND_SECRET:
3520 uint8_t my_digest[AUTH_VECTOR_LEN];
3521 make_secret(my_digest,
3524 memcpy(buffer, my_digest,
3526 buffer[AUTH_VECTOR_LEN] = '\0';
3527 datalen = strlen((char *) buffer);
3533 } /* switch over encryption flags */
3537 * Double-check the length after decrypting the
3541 case PW_TYPE_STRING:
3542 case PW_TYPE_OCTETS:
3545 case PW_TYPE_ABINARY:
3546 if (datalen > sizeof(vp->vp_filter)) goto raw;
3549 case PW_TYPE_INTEGER:
3550 case PW_TYPE_IPV4_ADDR:
3552 case PW_TYPE_SIGNED:
3553 if (datalen != 4) goto raw;
3556 case PW_TYPE_INTEGER64:
3558 if (datalen != 8) goto raw;
3561 case PW_TYPE_IPV6_ADDR:
3562 if (datalen != 16) goto raw;
3565 case PW_TYPE_IPV6_PREFIX:
3566 if ((datalen < 2) || (datalen > 18)) goto raw;
3567 if (data[1] > 128) goto raw;
3571 if (datalen != 1) goto raw;
3575 if (datalen != 2) goto raw;
3578 case PW_TYPE_ETHERNET:
3579 if (datalen != 6) goto raw;
3582 case PW_TYPE_IP_ADDR:
3584 child = dict_attrbytype(da->attr, da->vendor,
3586 } else if (datalen == 16) {
3587 child = dict_attrbytype(da->attr, da->vendor,
3592 if (!child) goto raw;
3593 da = child; /* re-write it */
3596 case PW_TYPE_IPV4_PREFIX:
3597 if (datalen != 6) goto raw;
3598 if ((data[1] & 0x3f) > 32) goto raw;
3602 * The rest of the data types can cause
3603 * recursion! Ask yourself, "is recursion OK?"
3606 case PW_TYPE_EXTENDED:
3607 if (datalen < 2) goto raw; /* etype, value */
3609 child = dict_attrbyparent(da, data[0], 0);
3610 if (!child) goto raw;
3613 * Recurse to decode the contents, which could be
3614 * a TLV, IPaddr, etc. Note that we decode only
3615 * the current attribute, and we ignore any extra
3618 rcode = data2vp(ctx, packet, original, secret, child,
3619 data + 1, attrlen - 1, attrlen - 1, pvp);
3620 if (rcode < 0) goto raw;
3623 case PW_TYPE_LONG_EXTENDED:
3624 if (datalen < 3) goto raw; /* etype, flags, value */
3626 child = dict_attrbyparent(da, data[0], 0);
3628 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3629 (datalen < (3 + 4 + 1))) {
3630 /* da->attr < 255, da->vendor == 0 */
3631 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3634 * Try to find the VSA.
3636 memcpy(&vendor, data + 3, 4);
3637 vendor = ntohl(vendor);
3639 if (vendor == 0) goto raw;
3641 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3645 fr_strerror_printf("Internal sanity check %d", __LINE__);
3651 * If there no more fragments, then the contents
3652 * have to be a well-known data type.
3655 if ((data[1] & 0x80) == 0) {
3656 rcode = data2vp(ctx, packet, original, secret, child,
3657 data + 2, attrlen - 2, attrlen - 2,
3659 if (rcode < 0) goto raw;
3664 * This requires a whole lot more work.
3666 return data2vp_extended(ctx, packet, original, secret, child,
3667 start, attrlen, packetlen, pvp);
3670 if (datalen < 6) goto raw; /* vid, vtype, value */
3672 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3674 memcpy(&vendor, data, 4);
3675 vendor = ntohl(vendor);
3676 dv = dict_vendorbyvalue(vendor);
3678 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3680 child = dict_attrbyparent(da, data[4], vendor);
3682 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3685 if (!child) goto raw;
3687 rcode = data2vp(ctx, packet, original, secret, child,
3688 data + 5, attrlen - 5, attrlen - 5, pvp);
3689 if (rcode < 0) goto raw;
3694 * We presume that the TLVs all fit into one
3695 * attribute, OR they've already been grouped
3696 * into a contiguous memory buffer.
3698 rcode = data2vp_tlvs(ctx, packet, original, secret, da,
3699 data, attrlen, pvp);
3700 if (rcode < 0) goto raw;
3705 * VSAs can be WiMAX, in which case they don't
3706 * fit into one attribute.
3708 rcode = data2vp_vsas(ctx, packet, original, secret,
3709 data, attrlen, packetlen, pvp);
3710 if (rcode < 0) goto raw;
3716 * Re-write the attribute to be "raw". It is
3717 * therefore of type "octets", and will be
3720 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3722 fr_strerror_printf("Internal sanity check %d", __LINE__);
3730 if (da->type != PW_TYPE_OCTETS) {
3731 dict_attr_free(&da);
3739 * And now that we've verified the basic type
3740 * information, decode the actual data.
3743 vp = pairalloc(ctx, da);
3746 vp->length = datalen;
3750 case PW_TYPE_STRING:
3751 p = talloc_array(vp, char, vp->length + 1);
3752 memcpy(p, data, vp->length);
3753 p[vp->length] = '\0';
3754 vp->vp_strvalue = p;
3757 case PW_TYPE_OCTETS:
3758 pairmemcpy(vp, data, vp->length);
3761 case PW_TYPE_ABINARY:
3762 if (vp->length > sizeof(vp->vp_filter)) {
3763 vp->length = sizeof(vp->vp_filter);
3765 memcpy(vp->vp_filter, data, vp->length);
3769 vp->vp_byte = data[0];
3773 vp->vp_short = (data[0] << 8) | data[1];
3776 case PW_TYPE_INTEGER:
3777 memcpy(&vp->vp_integer, data, 4);
3778 vp->vp_integer = ntohl(vp->vp_integer);
3781 case PW_TYPE_INTEGER64:
3782 memcpy(&vp->vp_integer64, data, 8);
3783 vp->vp_integer64 = ntohll(vp->vp_integer64);
3787 memcpy(&vp->vp_date, data, 4);
3788 vp->vp_date = ntohl(vp->vp_date);
3791 case PW_TYPE_ETHERNET:
3792 memcpy(&vp->vp_ether, data, 6);
3795 case PW_TYPE_IPV4_ADDR:
3796 memcpy(&vp->vp_ipaddr, data, 4);
3800 memcpy(&vp->vp_ifid, data, 8);
3803 case PW_TYPE_IPV6_ADDR:
3804 memcpy(&vp->vp_ipv6addr, data, 16);
3807 case PW_TYPE_IPV6_PREFIX:
3809 * FIXME: double-check that
3810 * (vp->vp_octets[1] >> 3) matches vp->length + 2
3812 memcpy(&vp->vp_ipv6prefix, data, vp->length);
3813 if (vp->length < 18) {
3814 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3819 case PW_TYPE_IPV4_PREFIX:
3820 /* FIXME: do the same double-check as for IPv6Prefix */
3821 memcpy(&vp->vp_ipv4prefix, data, vp->length);
3824 * /32 means "keep all bits". Otherwise, mask
3827 if ((data[1] & 0x3f) > 32) {
3828 uint32_t addr, mask;
3830 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3832 mask <<= (32 - (data[1] & 0x3f));
3837 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3841 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3842 memcpy(&vp->vp_integer, buffer, 4);
3843 vp->vp_integer = ntohl(vp->vp_integer);
3848 fr_strerror_printf("Internal sanity check %d", __LINE__);
3858 /** Create a "normal" VALUE_PAIR from the given data
3861 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3862 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3864 uint8_t const *data, size_t length,
3869 DICT_ATTR const *da;
3871 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3872 fr_strerror_printf("rad_attr2vp: Insufficient data");
3876 da = dict_attrbyvalue(data[0], 0);
3877 if (!da) da = dict_unknown_afrom_fields(ctx, data[0], 0);
3881 * Pass the entire thing to the decoding function
3883 if (da->flags.concat) {
3884 return data2vp_concat(ctx, da, data, length, pvp);
3888 * Note that we pass the entire length, not just the
3889 * length of this attribute. The Extended or WiMAX
3890 * attributes may have the "continuation" bit set, and
3891 * will thus be more than one attribute in length.
3893 rcode = data2vp(ctx, packet, original, secret, da,
3894 data + 2, data[1] - 2, length - 2, pvp);
3895 if (rcode < 0) return rcode;
3900 fr_thread_local_setup(uint8_t *, rad_vp2data_buff);
3902 /** Converts vp_data to network byte order
3904 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3905 * in an architecture independent format.
3907 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3908 * as the source VALUE_PAIR is not freed.
3910 * @param out where to write the pointer to the value.
3911 * @param vp to get the value from.
3912 * @return -1 on error, or the length of the value
3914 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3922 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3926 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3928 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3932 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3934 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3942 switch(vp->da->type) {
3943 case PW_TYPE_STRING:
3944 case PW_TYPE_OCTETS:
3946 memcpy(out, &vp->data.ptr, sizeof(*out));
3950 * All of these values are at the same location.
3953 case PW_TYPE_IPV4_ADDR:
3954 case PW_TYPE_IPV6_ADDR:
3955 case PW_TYPE_IPV6_PREFIX:
3956 case PW_TYPE_IPV4_PREFIX:
3957 case PW_TYPE_ABINARY:
3958 case PW_TYPE_ETHERNET:
3959 case PW_TYPE_IP_ADDR:
3960 case PW_TYPE_IP_PREFIX:
3962 void const *p = &vp->data;
3963 memcpy(out, &p, sizeof(*out));
3967 case PW_TYPE_BOOLEAN:
3968 buffer[0] = vp->vp_byte & 0x01;
3973 buffer[0] = vp->vp_byte & 0xff;
3978 buffer[0] = (vp->vp_short >> 8) & 0xff;
3979 buffer[1] = vp->vp_short & 0xff;
3983 case PW_TYPE_INTEGER:
3984 lvalue = htonl(vp->vp_integer);
3985 memcpy(buffer, &lvalue, sizeof(lvalue));
3989 case PW_TYPE_INTEGER64:
3990 lvalue64 = htonll(vp->vp_integer64);
3991 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3996 lvalue = htonl(vp->vp_date);
3997 memcpy(buffer, &lvalue, sizeof(lvalue));
4001 case PW_TYPE_SIGNED:
4003 int32_t slvalue = htonl(vp->vp_signed);
4004 memcpy(buffer, &slvalue, sizeof(slvalue));
4009 case PW_TYPE_INVALID:
4010 case PW_TYPE_EXTENDED:
4011 case PW_TYPE_LONG_EXTENDED:
4014 case PW_TYPE_TIMEVAL:
4016 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4019 /* Don't add default */
4025 /** Calculate/check digest, and decode radius attributes
4027 * @return -1 on decoding error, 0 on success
4029 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4033 uint32_t num_attributes;
4035 radius_packet_t *hdr;
4036 VALUE_PAIR *head, **tail, *vp;
4039 * Extract attribute-value pairs
4041 hdr = (radius_packet_t *)packet->data;
4043 packet_length = packet->data_len - RADIUS_HDR_LEN;
4050 * Loop over the attributes, decoding them into VPs.
4052 while (packet_length > 0) {
4056 * This may return many VPs
4058 my_len = rad_attr2vp(packet, packet, original, secret,
4059 ptr, packet_length, &vp);
4074 * VSA's may not have been counted properly in
4075 * rad_packet_ok() above, as it is hard to count
4076 * then without using the dictionary. We
4077 * therefore enforce the limits here, too.
4079 if ((fr_max_attributes > 0) &&
4080 (num_attributes > fr_max_attributes)) {
4081 char host_ipaddr[128];
4084 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4085 inet_ntop(packet->src_ipaddr.af,
4086 &packet->src_ipaddr.ipaddr,
4087 host_ipaddr, sizeof(host_ipaddr)),
4088 num_attributes, fr_max_attributes);
4093 packet_length -= my_len;
4097 * Merge information from the outside world into our
4100 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4103 * There may be VP's already in the packet. Don't
4104 * destroy them. Instead, add the decoded attributes to
4105 * the tail of the list.
4107 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4118 * We assume that the passwd buffer passed is big enough.
4119 * RFC2138 says the password is max 128 chars, so the size
4120 * of the passwd buffer must be at least 129 characters.
4121 * Preferably it's just MAX_STRING_LEN.
4123 * int *pwlen is updated to the new length of the encrypted
4124 * password - a multiple of 16 bytes.
4126 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4127 uint8_t const *vector)
4129 FR_MD5_CTX context, old;
4130 uint8_t digest[AUTH_VECTOR_LEN];
4131 int i, n, secretlen;
4135 * RFC maximum is 128 bytes.
4137 * If length is zero, pad it out with zeros.
4139 * If the length isn't aligned to 16 bytes,
4140 * zero out the extra data.
4144 if (len > 128) len = 128;
4147 memset(passwd, 0, AUTH_PASS_LEN);
4148 len = AUTH_PASS_LEN;
4149 } else if ((len % AUTH_PASS_LEN) != 0) {
4150 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4151 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4156 * Use the secret to setup the decryption digest
4158 secretlen = strlen(secret);
4160 fr_md5_init(&context);
4161 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4162 old = context; /* save intermediate work */
4165 * Encrypt it in place. Don't bother checking
4166 * len, as we've ensured above that it's OK.
4168 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4170 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4171 fr_md5_final(digest, &context);
4174 fr_md5_update(&context,
4175 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4177 fr_md5_final(digest, &context);
4180 for (i = 0; i < AUTH_PASS_LEN; i++) {
4181 passwd[i + n] ^= digest[i];
4191 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4192 uint8_t const *vector)
4194 FR_MD5_CTX context, old;
4195 uint8_t digest[AUTH_VECTOR_LEN];
4197 size_t n, secretlen;
4200 * The RFC's say that the maximum is 128.
4201 * The buffer we're putting it into above is 254, so
4202 * we don't need to do any length checking.
4204 if (pwlen > 128) pwlen = 128;
4209 if (pwlen == 0) goto done;
4212 * Use the secret to setup the decryption digest
4214 secretlen = strlen(secret);
4216 fr_md5_init(&context);
4217 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4218 old = context; /* save intermediate work */
4221 * The inverse of the code above.
4223 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4225 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4226 fr_md5_final(digest, &context);
4229 if (pwlen > AUTH_PASS_LEN) {
4230 fr_md5_update(&context, (uint8_t *) passwd,
4234 fr_md5_final(digest, &context);
4237 if (pwlen > (n + AUTH_PASS_LEN)) {
4238 fr_md5_update(&context, (uint8_t *) passwd + n,
4243 for (i = 0; i < AUTH_PASS_LEN; i++) {
4244 passwd[i + n] ^= digest[i];
4249 passwd[pwlen] = '\0';
4250 return strlen(passwd);
4254 /** Encode Tunnel-Password attributes when sending them out on the wire
4256 * int *pwlen is updated to the new length of the encrypted
4257 * password - a multiple of 16 bytes.
4259 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4262 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4263 uint8_t const *vector)
4265 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4266 unsigned char digest[AUTH_VECTOR_LEN];
4268 int i, n, secretlen;
4273 if (len > 127) len = 127;
4276 * Shift the password 3 positions right to place a salt and original
4277 * length, tag will be added automatically on packet send
4279 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4283 * save original password length as first password character;
4290 * Generate salt. The RFC's say:
4292 * The high bit of salt[0] must be set, each salt in a
4293 * packet should be unique, and they should be random
4295 * So, we set the high bit, add in a counter, and then
4296 * add in some CSPRNG data. should be OK..
4298 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4299 (fr_rand() & 0x07));
4300 salt[1] = fr_rand();
4303 * Padd password to multiple of AUTH_PASS_LEN bytes.
4305 n = len % AUTH_PASS_LEN;
4307 n = AUTH_PASS_LEN - n;
4308 for (; n > 0; n--, len++)
4311 /* set new password length */
4315 * Use the secret to setup the decryption digest
4317 secretlen = strlen(secret);
4318 memcpy(buffer, secret, secretlen);
4320 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4322 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4323 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4324 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4326 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4327 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4330 for (i = 0; i < AUTH_PASS_LEN; i++) {
4331 passwd[i + n2] ^= digest[i];
4338 /** Decode Tunnel-Password encrypted attributes
4340 * Defined in RFC-2868, this uses a two char SALT along with the
4341 * initial intermediate value, to differentiate it from the
4344 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4345 uint8_t const *vector)
4347 FR_MD5_CTX context, old;
4348 uint8_t digest[AUTH_VECTOR_LEN];
4350 unsigned i, n, len, reallen;
4355 * We need at least a salt.
4358 fr_strerror_printf("tunnel password is too short");
4363 * There's a salt, but no password. Or, there's a salt
4364 * and a 'data_len' octet. It's wrong, but at least we
4365 * can figure out what it means: the password is empty.
4367 * Note that this means we ignore the 'data_len' field,
4368 * if the attribute length tells us that there's no
4369 * more data. So the 'data_len' field may be wrong,
4378 len -= 2; /* discount the salt */
4381 * Use the secret to setup the decryption digest
4383 secretlen = strlen(secret);
4385 fr_md5_init(&context);
4386 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4387 old = context; /* save intermediate work */
4390 * Set up the initial key:
4392 * b(1) = MD5(secret + vector + salt)
4394 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4395 fr_md5_update(&context, passwd, 2);
4398 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4402 fr_md5_final(digest, &context);
4407 * A quick check: decrypt the first octet
4408 * of the password, which is the
4409 * 'data_len' field. Ensure it's sane.
4411 reallen = passwd[2] ^ digest[0];
4412 if (reallen >= len) {
4413 fr_strerror_printf("tunnel password is too long for the attribute");
4417 fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4421 fr_md5_final(digest, &context);
4424 fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4427 for (i = base; i < AUTH_PASS_LEN; i++) {
4428 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4433 * See make_tunnel_password, above.
4435 if (reallen > 239) reallen = 239;
4438 passwd[reallen] = 0;
4443 /** Encode a CHAP password
4445 * @bug FIXME: might not work with Ascend because
4446 * we use vp->length, and Ascend gear likes
4447 * to send an extra '\0' in the string!
4449 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4450 VALUE_PAIR *password)
4454 uint8_t string[MAX_STRING_LEN * 2 + 1];
4455 VALUE_PAIR *challenge;
4458 * Sanity check the input parameters
4460 if ((packet == NULL) || (password == NULL)) {
4465 * Note that the password VP can be EITHER
4466 * a User-Password attribute (from a check-item list),
4467 * or a CHAP-Password attribute (the client asking
4468 * the library to encode it).
4476 memcpy(ptr, password->vp_strvalue, password->length);
4477 ptr += password->length;
4478 i += password->length;
4481 * Use Chap-Challenge pair if present,
4482 * Request Authenticator otherwise.
4484 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4486 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4487 i += challenge->length;
4489 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4490 i += AUTH_VECTOR_LEN;
4494 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4500 /** Seed the random number generator
4502 * May be called any number of times.
4504 void fr_rand_seed(void const *data, size_t size)
4509 * Ensure that the pool is initialized.
4511 if (!fr_rand_initialized) {
4514 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4516 fd = open("/dev/urandom", O_RDONLY);
4522 while (total < sizeof(fr_rand_pool.randrsl)) {
4523 this = read(fd, fr_rand_pool.randrsl,
4524 sizeof(fr_rand_pool.randrsl) - total);
4525 if ((this < 0) && (errno != EINTR)) break;
4526 if (this > 0) total += this;
4530 fr_rand_pool.randrsl[0] = fd;
4531 fr_rand_pool.randrsl[1] = time(NULL);
4532 fr_rand_pool.randrsl[2] = errno;
4535 fr_randinit(&fr_rand_pool, 1);
4536 fr_rand_pool.randcnt = 0;
4537 fr_rand_initialized = 1;
4543 * Hash the user data
4546 if (!hash) hash = fr_rand();
4547 hash = fr_hash_update(data, size, hash);
4549 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4553 /** Return a 32-bit random number
4556 uint32_t fr_rand(void)
4561 * Ensure that the pool is initialized.
4563 if (!fr_rand_initialized) {
4564 fr_rand_seed(NULL, 0);
4567 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4568 if (fr_rand_pool.randcnt >= 256) {
4569 fr_rand_pool.randcnt = 0;
4570 fr_isaac(&fr_rand_pool);
4577 /** Allocate a new RADIUS_PACKET
4579 * @param ctx the context in which the packet is allocated. May be NULL if
4580 * the packet is not associated with a REQUEST.
4581 * @param new_vector if true a new request authenticator will be generated.
4582 * @return a new RADIUS_PACKET or NULL on error.
4584 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4588 rp = talloc_zero(ctx, RADIUS_PACKET);
4590 fr_strerror_printf("out of memory");
4598 uint32_t hash, base;
4601 * Don't expose the actual contents of the random
4605 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4606 hash = fr_rand() ^ base;
4607 memcpy(rp->vector + i, &hash, sizeof(hash));
4610 fr_rand(); /* stir the pool again */
4615 /** Allocate a new RADIUS_PACKET response
4617 * @param ctx the context in which the packet is allocated. May be NULL if
4618 * the packet is not associated with a REQUEST.
4619 * @param packet The request packet.
4620 * @return a new RADIUS_PACKET or NULL on error.
4622 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4624 RADIUS_PACKET *reply;
4626 if (!packet) return NULL;
4628 reply = rad_alloc(ctx, false);
4629 if (!reply) return NULL;
4632 * Initialize the fields from the request.
4634 reply->sockfd = packet->sockfd;
4635 reply->dst_ipaddr = packet->src_ipaddr;
4636 reply->src_ipaddr = packet->dst_ipaddr;
4637 reply->dst_port = packet->src_port;
4638 reply->src_port = packet->dst_port;
4639 reply->id = packet->id;
4640 reply->code = 0; /* UNKNOWN code */
4641 memcpy(reply->vector, packet->vector,
4642 sizeof(reply->vector));
4645 reply->data_len = 0;
4648 reply->proto = packet->proto;
4654 /** Free a RADIUS_PACKET
4657 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4659 RADIUS_PACKET *radius_packet;
4661 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4662 radius_packet = *radius_packet_ptr;
4664 VERIFY_PACKET(radius_packet);
4666 pairfree(&radius_packet->vps);
4668 talloc_free(radius_packet);
4669 *radius_packet_ptr = NULL;
4672 /** Duplicate a RADIUS_PACKET
4674 * @param ctx the context in which the packet is allocated. May be NULL if
4675 * the packet is not associated with a REQUEST.
4676 * @param in The packet to copy
4677 * @return a new RADIUS_PACKET or NULL on error.
4679 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4683 out = rad_alloc(ctx, false);
4684 if (!out) return NULL;
4687 * Bootstrap by copying everything.
4689 memcpy(out, in, sizeof(*out));
4692 * Then reset necessary fields
4699 out->vps = paircopy(out, in->vps);