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 * Some messages get printed out only in debugging mode.
42 #define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf
45 #define VP_TRACE printf
47 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
51 printf("--- %s ---\n", msg);
52 for (i = 0; i < len; i++) {
53 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
54 printf("%02x ", data[i]);
55 if ((i & 0x0f) == 0x0f) printf("\n");
57 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
62 #define VP_TRACE(_x, ...)
63 #define VP_HEXDUMP(_x, _y, _z)
68 * The RFC says 4096 octets max, and most packets are less than 256.
70 #define MAX_PACKET_LEN 4096
73 * The maximum number of attributes which we allow in an incoming
74 * request. If there are more attributes than this, the request
77 * This helps to minimize the potential for a DoS, when an
78 * attacker spoofs Access-Request packets, which don't have a
79 * Message-Authenticator attribute. This means that the packet
80 * is unsigned, and the attacker can use resources on the server,
81 * even if the end request is rejected.
83 uint32_t fr_max_attributes = 0;
84 FILE *fr_log_fp = NULL;
86 typedef struct radius_packet_t {
90 uint8_t vector[AUTH_VECTOR_LEN];
94 static fr_randctx fr_rand_pool; /* across multiple calls */
95 static int fr_rand_initialized = 0;
96 static unsigned int salt_offset = 0;
97 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 */
99 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
104 "Accounting-Request",
105 "Accounting-Response",
110 "Accounting-Message", //!< 10
121 "Resource-Free-Request",
122 "Resource-Free-Response",
123 "Resource-Query-Request",
124 "Resource-Query-Response",
125 "Alternate-Resource-Reclaim-Request",
126 "NAS-Reboot-Request",
127 "NAS-Reboot-Response",
140 "Disconnect-Request", //!< 40
150 "IP-Address-Allocate",
151 "IP-Address-Release", //!< 50
155 void fr_printf_log(char const *fmt, ...)
160 if ((fr_debug_lvl == 0) || !fr_log_fp) {
165 vfprintf(fr_log_fp, fmt, ap);
171 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";
173 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
177 for (i = 0; i < attrlen; i++) {
178 if ((i > 0) && ((i & 0x0f) == 0x00))
179 fprintf(fr_log_fp, "%.*s", depth, tabs);
180 fprintf(fr_log_fp, "%02x ", ptr[i]);
181 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
183 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
187 void rad_print_hex(RADIUS_PACKET *packet)
191 if (!packet->data || !fr_log_fp) return;
193 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
194 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
195 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
197 fprintf(fr_log_fp, " Vector:\t");
198 for (i = 4; i < 20; i++) {
199 fprintf(fr_log_fp, "%02x", packet->data[i]);
201 fprintf(fr_log_fp, "\n");
203 if (packet->data_len > 20) {
206 fprintf(fr_log_fp, " Data:");
208 total = packet->data_len - 20;
209 ptr = packet->data + 20;
213 unsigned int vendor = 0;
215 fprintf(fr_log_fp, "\t\t");
216 if (total < 2) { /* too short */
217 fprintf(fr_log_fp, "%02x\n", *ptr);
221 if (ptr[1] > total) { /* too long */
222 for (i = 0; i < total; i++) {
223 fprintf(fr_log_fp, "%02x ", ptr[i]);
228 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
229 attrlen = ptr[1] - 2;
231 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
233 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
234 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
235 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
245 print_hex_data(ptr, attrlen, 3);
254 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
257 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
258 #ifdef WITH_UDPFROMTO
259 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
261 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
263 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
266 struct sockaddr_storage dst;
267 socklen_t sizeof_dst;
269 #ifdef WITH_UDPFROMTO
270 struct sockaddr_storage src;
271 socklen_t sizeof_src;
273 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
276 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
280 #ifdef WITH_UDPFROMTO
282 * And if they don't specify a source IP address, don't
285 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
286 (src_ipaddr->af != AF_UNSPEC) &&
287 !fr_inaddr_any(src_ipaddr)) {
288 rcode = sendfromto(sockfd, data, data_len, flags,
289 (struct sockaddr *)&src, sizeof_src,
290 (struct sockaddr *)&dst, sizeof_dst);
296 * No udpfromto, fail gracefully.
298 rcode = sendto(sockfd, data, data_len, flags,
299 (struct sockaddr *) &dst, sizeof_dst);
300 #ifdef WITH_UDPFROMTO
304 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
311 void rad_recv_discard(int sockfd)
314 struct sockaddr_storage src;
315 socklen_t sizeof_src = sizeof(src);
317 (void) recvfrom(sockfd, header, sizeof(header), 0,
318 (struct sockaddr *)&src, &sizeof_src);
321 /** Basic validation of RADIUS packet header
323 * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
324 * consumed when discarding malformed packet.
326 * @param[in] sockfd we're reading from.
327 * @param[out] src_ipaddr of the packet.
328 * @param[out] src_port of the packet.
329 * @param[out] code Pointer to where to write the packet code.
332 * - 1 on decode error.
333 * - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
335 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
337 ssize_t data_len, packet_len;
339 struct sockaddr_storage src;
340 socklen_t sizeof_src = sizeof(src);
342 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
343 (struct sockaddr *)&src, &sizeof_src);
345 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
350 * Too little data is available, discard the packet.
353 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
354 rad_recv_discard(sockfd);
358 } else { /* we got 4 bytes of data. */
360 * See how long the packet says it is.
362 packet_len = (header[2] * 256) + header[3];
365 * The length in the packet says it's less than
366 * a RADIUS header length: discard it.
368 if (packet_len < RADIUS_HDR_LEN) {
369 FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN) " bytes of packet "
370 "data, got %zu bytes", packet_len);
371 rad_recv_discard(sockfd);
376 * Enforce RFC requirements, for sanity.
377 * Anything after 4k will be discarded.
379 } else if (packet_len > MAX_PACKET_LEN) {
380 FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
381 STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
382 rad_recv_discard(sockfd);
389 * Convert AF. If unknown, discard packet.
391 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
392 FR_DEBUG_STRERROR_PRINTF("Unkown address family");
393 rad_recv_discard(sockfd);
401 * The packet says it's this long, but the actual UDP
402 * size could still be smaller.
408 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
411 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
412 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
413 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
415 struct sockaddr_storage src;
416 struct sockaddr_storage dst;
417 socklen_t sizeof_src = sizeof(src);
418 socklen_t sizeof_dst = sizeof(dst);
424 memset(&src, 0, sizeof_src);
425 memset(&dst, 0, sizeof_dst);
428 * Read the length of the packet, from the packet.
429 * This lets us allocate the buffer to use for
430 * reading the rest of the packet.
432 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
433 (struct sockaddr *)&src, &sizeof_src);
435 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
440 * Too little data is available, discard the packet.
443 rad_recv_discard(sockfd);
447 } else { /* we got 4 bytes of data. */
449 * See how long the packet says it is.
451 len = (header[2] * 256) + header[3];
454 * The length in the packet says it's less than
455 * a RADIUS header length: discard it.
457 if (len < RADIUS_HDR_LEN) {
458 recvfrom(sockfd, header, sizeof(header), flags,
459 (struct sockaddr *)&src, &sizeof_src);
463 * Enforce RFC requirements, for sanity.
464 * Anything after 4k will be discarded.
466 } else if (len > MAX_PACKET_LEN) {
467 recvfrom(sockfd, header, sizeof(header), flags,
468 (struct sockaddr *)&src, &sizeof_src);
473 packet->data = talloc_array(packet, uint8_t, len);
474 if (!packet->data) return -1;
477 * Receive the packet. The OS will discard any data in the
478 * packet after "len" bytes.
480 #ifdef WITH_UDPFROMTO
481 data_len = recvfromto(sockfd, packet->data, len, flags,
482 (struct sockaddr *)&src, &sizeof_src,
483 (struct sockaddr *)&dst, &sizeof_dst);
485 data_len = recvfrom(sockfd, packet->data, len, flags,
486 (struct sockaddr *)&src, &sizeof_src);
489 * Get the destination address, too.
491 if (getsockname(sockfd, (struct sockaddr *)&dst,
492 &sizeof_dst) < 0) return -1;
498 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
499 return -1; /* Unknown address family, Die Die Die! */
503 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
507 * Different address families should never happen.
509 if (src.ss_family != dst.ss_family) {
517 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
518 /** Build an encrypted secret value to return in a reply packet
520 * The secret is hidden by xoring with a MD5 digest created from
521 * the shared secret and the authentication vector.
522 * We put them into MD5 in the reverse order from that used when
523 * encrypting passwords to RADIUS.
525 static void make_secret(uint8_t *digest, uint8_t const *vector,
526 char const *secret, uint8_t const *value)
531 fr_md5_init(&context);
532 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
533 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
534 fr_md5_final(digest, &context);
536 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
537 digest[i] ^= value[i];
541 #define MAX_PASS_LEN (128)
542 static void make_passwd(uint8_t *output, ssize_t *outlen,
543 uint8_t const *input, size_t inlen,
544 char const *secret, uint8_t const *vector)
546 FR_MD5_CTX context, old;
547 uint8_t digest[AUTH_VECTOR_LEN];
548 uint8_t passwd[MAX_PASS_LEN];
553 * If the length is zero, round it up.
557 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
559 memcpy(passwd, input, len);
560 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
566 else if ((len & 0x0f) != 0) {
572 fr_md5_init(&context);
573 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
579 fr_md5_update(&context, vector, AUTH_PASS_LEN);
581 for (n = 0; n < len; n += AUTH_PASS_LEN) {
584 fr_md5_update(&context,
585 passwd + n - AUTH_PASS_LEN,
589 fr_md5_final(digest, &context);
590 for (i = 0; i < AUTH_PASS_LEN; i++) {
591 passwd[i + n] ^= digest[i];
595 memcpy(output, passwd, len);
598 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
599 uint8_t const *input, size_t inlen, size_t room,
600 char const *secret, uint8_t const *vector)
602 FR_MD5_CTX context, old;
603 uint8_t digest[AUTH_VECTOR_LEN];
604 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
611 if (room > 253) room = 253;
614 * Account for 2 bytes of the salt, and round the room
615 * available down to the nearest multiple of 16. Then,
616 * subtract one from that to account for the length byte,
617 * and the resulting number is the upper bound on the data
620 * We could short-cut this calculation just be forcing
621 * inlen to be no more than 239. It would work for all
622 * VSA's, as we don't pack multiple VSA's into one
625 * However, this calculation is more general, if a little
626 * complex. And it will work in the future for all possible
627 * kinds of weird attribute packing.
630 room -= (room & 0x0f);
633 if (inlen > room) inlen = room;
636 * Length of the encrypted data is password length plus
637 * one byte for the length of the password.
640 if ((len & 0x0f) != 0) {
644 *outlen = len + 2; /* account for the salt */
647 * Copy the password over.
649 memcpy(passwd + 3, input, inlen);
650 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
653 * Generate salt. The RFC's say:
655 * The high bit of salt[0] must be set, each salt in a
656 * packet should be unique, and they should be random
658 * So, we set the high bit, add in a counter, and then
659 * add in some CSPRNG data. should be OK..
661 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
663 passwd[1] = fr_rand();
664 passwd[2] = inlen; /* length of the password string */
666 fr_md5_init(&context);
667 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
670 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
671 fr_md5_update(&context, &passwd[0], 2);
673 for (n = 0; n < len; n += AUTH_PASS_LEN) {
676 fr_md5_update(&context,
677 passwd + 2 + n - AUTH_PASS_LEN,
681 fr_md5_final(digest, &context);
683 for (i = 0; i < AUTH_PASS_LEN; i++) {
684 passwd[i + 2 + n] ^= digest[i];
687 memcpy(output, passwd, len + 2);
690 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
692 unsigned int tlv1, tlv2;
694 if (nest > fr_attr_max_tlv) return 0;
699 * Keep encoding TLVs which have the same scope.
700 * e.g. two attributes of:
701 * ATTR.TLV1.TLV2.TLV3 = data1
702 * ATTR.TLV1.TLV2.TLV4 = data2
703 * both get put into a container of "ATTR.TLV1.TLV2"
707 * Nothing to follow, we're done.
712 * Not from the same vendor, skip it.
714 if (vp->da->vendor != next->da->vendor) return 0;
717 * In a different TLV space, skip it.
720 tlv2 = next->da->attr;
722 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
723 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
725 if (tlv1 != tlv2) return 0;
731 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
732 RADIUS_PACKET const *original,
733 char const *secret, int nest,
734 VALUE_PAIR const **pvp,
735 uint8_t *start, size_t room);
737 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
738 RADIUS_PACKET const *original,
739 char const *secret, VALUE_PAIR const **pvp,
740 unsigned int attribute, uint8_t *ptr, size_t room);
742 /** Encode the *data* portion of the TLV
744 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
745 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
747 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
748 RADIUS_PACKET const *original,
749 char const *secret, int nest,
750 VALUE_PAIR const **pvp,
751 uint8_t *start, size_t room)
755 uint8_t *ptr = start;
756 VALUE_PAIR const *vp = *pvp;
757 VALUE_PAIR const *svp = vp;
762 if (nest > fr_attr_max_tlv) {
763 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
771 if (room <= 2) return ptr - start;
773 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
777 if (room > 255) my_room = 255;
779 len = vp2data_any(packet, original, secret, nest,
780 &vp, ptr + 2, my_room - 2);
781 if (len < 0) return len;
782 if (len == 0) return ptr - start;
783 /* len can NEVER be more than 253 */
788 if ((fr_debug_lvl > 3) && fr_log_fp) {
789 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
790 print_hex_data(ptr + 2, len, 3);
798 if (!do_next_tlv(svp, vp, nest)) break;
802 if ((fr_debug_lvl > 3) && fr_log_fp) {
805 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
806 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
813 /** Encodes the data portion of an attribute
815 * @return -1 on error, or the length of the data portion.
817 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
818 RADIUS_PACKET const *original,
819 char const *secret, int nest,
820 VALUE_PAIR const **pvp,
821 uint8_t *start, size_t room)
826 uint8_t *ptr = start;
829 VALUE_PAIR const *vp = *pvp;
834 * See if we need to encode a TLV. The low portion of
835 * the attribute has already been placed into the packer.
836 * If there are still attribute bytes left, then go
837 * encode them as TLVs.
839 * If we cared about the stack, we could unroll the loop.
841 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
842 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
843 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
848 * Set up the default sources for the data.
852 switch (vp->da->type) {
857 fr_strerror_printf("ERROR: Cannot encode NULL data");
863 case PW_TYPE_IPV4_ADDR:
864 case PW_TYPE_IPV6_ADDR:
865 case PW_TYPE_IPV6_PREFIX:
866 case PW_TYPE_IPV4_PREFIX:
867 case PW_TYPE_ABINARY:
868 case PW_TYPE_ETHERNET: /* just in case */
869 data = (uint8_t const *) &vp->data;
873 len = 1; /* just in case */
874 array[0] = vp->vp_byte;
879 len = 2; /* just in case */
880 array[0] = (vp->vp_short >> 8) & 0xff;
881 array[1] = vp->vp_short & 0xff;
885 case PW_TYPE_INTEGER:
886 len = 4; /* just in case */
887 lvalue = htonl(vp->vp_integer);
888 memcpy(array, &lvalue, sizeof(lvalue));
892 case PW_TYPE_INTEGER64:
893 len = 8; /* just in case */
894 lvalue64 = htonll(vp->vp_integer64);
895 data = (uint8_t *) &lvalue64;
899 * There are no tagged date attributes.
902 lvalue = htonl(vp->vp_date);
903 data = (uint8_t const *) &lvalue;
904 len = 4; /* just in case */
911 len = 4; /* just in case */
912 slvalue = htonl(vp->vp_signed);
913 memcpy(array, &slvalue, sizeof(slvalue));
918 default: /* unknown type: ignore it */
919 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
932 * Bound the data to the calling size
934 if (len > (ssize_t) room) len = room;
937 * Encrypt the various password styles
939 * Attributes with encrypted values MUST be less than
942 switch (vp->da->flags.encrypt) {
943 case FLAG_ENCRYPT_USER_PASSWORD:
944 make_passwd(ptr, &len, data, len,
945 secret, packet->vector);
948 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
950 if (vp->da->flags.has_tag) lvalue = 1;
953 * Check if there's enough room. If there isn't,
954 * we discard the attribute.
956 * This is ONLY a problem if we have multiple VSA's
957 * in one Vendor-Specific, though.
959 if (room < (18 + lvalue)) return 0;
961 switch (packet->code) {
962 case PW_CODE_ACCESS_ACCEPT:
963 case PW_CODE_ACCESS_REJECT:
964 case PW_CODE_ACCESS_CHALLENGE:
967 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
971 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
972 make_tunnel_passwd(ptr + lvalue, &len, data, len,
974 secret, original->vector);
976 case PW_CODE_ACCOUNTING_REQUEST:
977 case PW_CODE_DISCONNECT_REQUEST:
978 case PW_CODE_COA_REQUEST:
979 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
980 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
981 secret, packet->vector);
987 * The code above ensures that this attribute
990 case FLAG_ENCRYPT_ASCEND_SECRET:
991 if (len != 16) return 0;
992 make_secret(ptr, packet->vector, secret, data);
993 len = AUTH_VECTOR_LEN;
998 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
999 if (vp->da->type == PW_TYPE_STRING) {
1000 if (len > ((ssize_t) (room - 1))) len = room - 1;
1003 } else if (vp->da->type == PW_TYPE_INTEGER) {
1005 } /* else it can't be any other type */
1007 memcpy(ptr, data, len);
1009 } /* switch over encryption flags */
1012 return len + (ptr - start);
1015 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1016 uint8_t *ptr, int hdr_len, ssize_t len,
1017 int flag_offset, int vsa_offset)
1019 int check_len = len - ptr[1];
1020 int total = len + hdr_len;
1023 * Pass 1: Check if the addition of the headers
1024 * overflows the available room. If so, return
1025 * what we were capable of encoding.
1028 while (check_len > (255 - hdr_len)) {
1030 check_len -= (255 - hdr_len);
1034 * Note that this results in a number of attributes maybe
1035 * being marked as "encoded", but which aren't in the
1036 * packet. Oh well. The solution is to fix the
1037 * "vp2data_any" function to take into account the header
1040 if ((ptr + ptr[1] + total) > end) {
1041 return (ptr + ptr[1]) - start;
1045 * Pass 2: Now that we know there's enough room,
1046 * re-arrange the data to form a set of valid
1047 * RADIUS attributes.
1050 int sublen = 255 - ptr[1];
1052 if (len <= sublen) {
1057 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1058 memmove(ptr + 255, ptr, hdr_len);
1060 if (vsa_offset) ptr[vsa_offset] += sublen;
1061 ptr[flag_offset] |= 0x80;
1065 if (vsa_offset) ptr[vsa_offset] = 3;
1069 if (vsa_offset) ptr[vsa_offset] += len;
1071 return (ptr + ptr[1]) - start;
1075 /** Encode an "extended" attribute
1077 int rad_vp2extended(RADIUS_PACKET const *packet,
1078 RADIUS_PACKET const *original,
1079 char const *secret, VALUE_PAIR const **pvp,
1080 uint8_t *ptr, size_t room)
1084 uint8_t *start = ptr;
1085 VALUE_PAIR const *vp = *pvp;
1089 if (!vp->da->flags.extended) {
1090 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1095 * The attribute number is encoded into the upper 8 bits
1098 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1100 if (!vp->da->flags.long_extended) {
1101 if (room < 3) return 0;
1104 ptr[2] = vp->da->attr & fr_attr_mask[0];
1107 if (room < 4) return 0;
1110 ptr[2] = vp->da->attr & fr_attr_mask[0];
1115 * Only "flagged" attributes can be longer than one
1118 if (!vp->da->flags.long_extended && (room > 255)) {
1125 if (vp->da->flags.evs) {
1126 uint8_t *evs = ptr + ptr[1];
1128 if (room < (size_t) (ptr[1] + 5)) return 0;
1132 evs[0] = 0; /* always zero */
1133 evs[1] = (vp->da->vendor >> 16) & 0xff;
1134 evs[2] = (vp->da->vendor >> 8) & 0xff;
1135 evs[3] = vp->da->vendor & 0xff;
1136 evs[4] = vp->da->attr & fr_attr_mask[0];
1142 len = vp2data_any(packet, original, secret, 0,
1143 pvp, ptr + ptr[1], room - hdr_len);
1144 if (len <= 0) return len;
1147 * There may be more than 252 octets of data encoded in
1148 * the attribute. If so, move the data up in the packet,
1149 * and copy the existing header over. Set the "M" flag ONLY
1150 * after copying the rest of the data.
1152 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1153 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1159 if ((fr_debug_lvl > 3) && fr_log_fp) {
1162 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1163 if (!vp->da->flags.long_extended) {
1164 fprintf(fr_log_fp, "%02x ", ptr[2]);
1167 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1171 if (vp->da->flags.evs) {
1172 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1173 ptr[jump], ptr[jump + 1],
1174 ptr[jump + 2], ptr[jump + 3],
1175 ((ptr[jump + 1] << 16) |
1176 (ptr[jump + 2] << 8) |
1182 print_hex_data(ptr + jump, len, 3);
1186 return (ptr + ptr[1]) - start;
1190 /** Encode a WiMAX attribute
1193 int rad_vp2wimax(RADIUS_PACKET const *packet,
1194 RADIUS_PACKET const *original,
1195 char const *secret, VALUE_PAIR const **pvp,
1196 uint8_t *ptr, size_t room)
1201 uint8_t *start = ptr;
1202 VALUE_PAIR const *vp = *pvp;
1207 * Double-check for WiMAX format.
1209 if (!vp->da->flags.wimax) {
1210 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1215 * Not enough room for:
1216 * attr, len, vendor-id, vsa, vsalen, continuation
1218 if (room < 9) return 0;
1221 * Build the Vendor-Specific header
1224 ptr[0] = PW_VENDOR_SPECIFIC;
1226 lvalue = htonl(vp->da->vendor);
1227 memcpy(ptr + 2, &lvalue, 4);
1228 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1230 ptr[8] = 0; /* continuation byte */
1234 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1236 if (len <= 0) return len;
1239 * There may be more than 252 octets of data encoded in
1240 * the attribute. If so, move the data up in the packet,
1241 * and copy the existing header over. Set the "C" flag
1242 * ONLY after copying the rest of the data.
1244 if (len > (255 - ptr[1])) {
1245 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1252 if ((fr_debug_lvl > 3) && fr_log_fp) {
1253 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1255 ptr[2], ptr[3], ptr[4], ptr[5],
1256 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1257 ptr[6], ptr[7], ptr[8]);
1258 print_hex_data(ptr + 9, len, 3);
1262 return (ptr + ptr[1]) - start;
1265 /** Encode an RFC format attribute, with the "concat" flag set
1267 * If there isn't enough room in the packet, the data is
1270 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1271 UNUSED RADIUS_PACKET const *original,
1272 UNUSED char const *secret, VALUE_PAIR const **pvp,
1273 unsigned int attribute, uint8_t *start, size_t room)
1275 uint8_t *ptr = start;
1278 VALUE_PAIR const *vp = *pvp;
1283 len = vp->vp_length;
1286 if (room <= 2) break;
1293 /* no more than 253 octets */
1294 if (left > 253) left = 253;
1296 /* no more than "room" octets */
1297 if (room < (left + 2)) left = room - 2;
1299 memcpy(ptr + 2, p, left);
1302 if ((fr_debug_lvl > 3) && fr_log_fp) {
1303 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1304 print_hex_data(ptr + 2, len, 3);
1318 /** Encode an RFC format TLV.
1320 * This could be a standard attribute, or a TLV data type.
1321 * If it's a standard attribute, then vp->da->attr == attribute.
1322 * Otherwise, attribute may be something else.
1324 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1325 RADIUS_PACKET const *original,
1326 char const *secret, VALUE_PAIR const **pvp,
1327 unsigned int attribute, uint8_t *ptr, size_t room)
1331 if (room <= 2) return 0;
1333 ptr[0] = attribute & 0xff;
1336 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1338 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1339 if (len <= 0) return len;
1344 if ((fr_debug_lvl > 3) && fr_log_fp) {
1345 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1346 print_hex_data(ptr + 2, len, 3);
1354 /** Encode a VSA which is a TLV
1356 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1358 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1359 RADIUS_PACKET const *original,
1360 char const *secret, VALUE_PAIR const **pvp,
1361 unsigned int attribute, unsigned int vendor,
1362 uint8_t *ptr, size_t room)
1366 VALUE_PAIR const *vp = *pvp;
1370 * Unknown vendor: RFC format.
1371 * Known vendor and RFC format: go do that.
1373 dv = dict_vendorbyvalue(vendor);
1375 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1376 return vp2attr_rfc(packet, original, secret, pvp,
1377 attribute, ptr, room);
1382 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1383 " type %u", (unsigned) dv->type);
1387 ptr[0] = 0; /* attr must be 24-bit */
1388 ptr[1] = (attribute >> 16) & 0xff;
1389 ptr[2] = (attribute >> 8) & 0xff;
1390 ptr[3] = attribute & 0xff;
1394 ptr[0] = (attribute >> 8) & 0xff;
1395 ptr[1] = attribute & 0xff;
1399 ptr[0] = attribute & 0xff;
1403 switch (dv->length) {
1405 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1406 " length %u", (unsigned) dv->length);
1414 ptr[dv->type + 1] = dv->type + 2;
1418 ptr[dv->type] = dv->type + 1;
1423 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1424 room = 255 - (dv->type + dv->length);
1427 len = vp2data_any(packet, original, secret, 0, pvp,
1428 ptr + dv->type + dv->length, room);
1429 if (len <= 0) return len;
1431 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1434 if ((fr_debug_lvl > 3) && fr_log_fp) {
1440 if ((fr_debug_lvl > 3) && fr_log_fp)
1441 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1442 ptr[0], ptr[1], ptr[2], ptr[3]);
1446 if ((fr_debug_lvl > 3) && fr_log_fp)
1447 fprintf(fr_log_fp, "\t\t%02x%02x ",
1452 if ((fr_debug_lvl > 3) && fr_log_fp)
1453 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1457 switch (dv->length) {
1462 fprintf(fr_log_fp, " ");
1466 fprintf(fr_log_fp, "%02x ",
1471 fprintf(fr_log_fp, "%02x%02x ",
1472 ptr[dv->type], ptr[dv->type] + 1);
1476 print_hex_data(ptr + dv->type + dv->length, len, 3);
1480 return dv->type + dv->length + len;
1484 /** Encode a Vendor-Specific attribute
1487 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1488 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1493 VALUE_PAIR const *vp = *pvp;
1497 if (vp->da->vendor == 0) {
1498 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1503 * Double-check for WiMAX format.
1505 if (vp->da->flags.wimax) {
1506 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1509 if (vp->da->vendor > FR_MAX_VENDOR) {
1510 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1515 * Not enough room for:
1516 * attr, len, vendor-id
1518 if (room < 6) return 0;
1521 * Build the Vendor-Specific header
1523 ptr[0] = PW_VENDOR_SPECIFIC;
1525 lvalue = htonl(vp->da->vendor);
1526 memcpy(ptr + 2, &lvalue, 4);
1528 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1530 len = vp2attr_vsa(packet, original, secret, pvp,
1531 vp->da->attr, vp->da->vendor,
1532 ptr + ptr[1], room);
1533 if (len < 0) return len;
1536 if ((fr_debug_lvl > 3) && fr_log_fp) {
1537 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1539 ptr[2], ptr[3], ptr[4], ptr[5],
1540 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1541 print_hex_data(ptr + 6, len, 3);
1551 /** Encode an RFC standard attribute 1..255
1554 int rad_vp2rfc(RADIUS_PACKET const *packet,
1555 RADIUS_PACKET const *original,
1556 char const *secret, VALUE_PAIR const **pvp,
1557 uint8_t *ptr, size_t room)
1559 VALUE_PAIR const *vp = *pvp;
1563 if (vp->da->vendor != 0) {
1564 fr_strerror_printf("rad_vp2rfc called with VSA");
1568 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1569 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1574 * Only CUI is allowed to have zero length.
1577 if ((vp->vp_length == 0) &&
1578 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1579 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1587 * Message-Authenticator is hard-coded.
1589 if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1590 if (room < 18) return -1;
1592 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1594 memset(ptr + 2, 0, 16);
1596 if ((fr_debug_lvl > 3) && fr_log_fp) {
1597 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1601 *pvp = (*pvp)->next;
1606 * EAP-Message is special.
1608 if (vp->da->flags.concat && (vp->vp_length > 253)) {
1609 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1613 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1617 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1618 RADIUS_PACKET const *original,
1619 char const *secret, VALUE_PAIR const **pvp,
1620 uint8_t *start, size_t room)
1623 VALUE_PAIR const *vp = *pvp;
1627 if (!vp->da->flags.is_tlv) {
1628 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1632 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1633 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1637 if (room < 5) return 0;
1640 * Encode the first level of TLVs
1642 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1644 start[2] = vp->da->attr & fr_attr_mask[0];
1647 len = vp2data_any(packet, original, secret, 0, pvp,
1648 start + 4, room - 4);
1649 if (len <= 0) return len;
1661 /** Parse a data structure into a RADIUS attribute
1664 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1665 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1668 VALUE_PAIR const *vp;
1670 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1677 * RFC format attributes take the fast path.
1679 if (!vp->da->vendor) {
1680 if (vp->da->attr > 255) return 0;
1682 return rad_vp2rfc(packet, original, secret, pvp,
1686 if (vp->da->flags.extended) {
1687 return rad_vp2extended(packet, original, secret, pvp,
1692 * The upper 8 bits of the vendor number are the standard
1693 * space attribute which is a TLV.
1695 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1696 return rad_vp2rfctlv(packet, original, secret, pvp,
1700 if (vp->da->flags.wimax) {
1701 return rad_vp2wimax(packet, original, secret, pvp,
1705 return rad_vp2vsa(packet, original, secret, pvp, start, room);
1712 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1715 radius_packet_t *hdr;
1717 uint16_t total_length;
1719 VALUE_PAIR const *reply;
1722 * A 4K packet, aligned on 64-bits.
1724 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1727 * Double-check some things based on packet code.
1729 switch (packet->code) {
1730 case PW_CODE_ACCESS_ACCEPT:
1731 case PW_CODE_ACCESS_REJECT:
1732 case PW_CODE_ACCESS_CHALLENGE:
1734 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1740 * These packet vectors start off as all zero.
1742 case PW_CODE_ACCOUNTING_REQUEST:
1743 case PW_CODE_DISCONNECT_REQUEST:
1744 case PW_CODE_COA_REQUEST:
1745 memset(packet->vector, 0, sizeof(packet->vector));
1753 * Use memory on the stack, until we know how
1754 * large the packet will be.
1756 hdr = (radius_packet_t *) data;
1759 * Build standard header
1761 hdr->code = packet->code;
1762 hdr->id = packet->id;
1764 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1766 total_length = RADIUS_HDR_LEN;
1769 * Load up the configuration values for the user
1775 * FIXME: Loop twice over the reply list. The first time,
1776 * calculate the total length of data. The second time,
1777 * allocate the memory, and fill in the VP's.
1779 * Hmm... this may be slower than just doing a small
1784 * Loop over the reply attributes for the packet.
1786 reply = packet->vps;
1789 char const *last_name = NULL;
1794 * Ignore non-wire attributes, but allow extended
1797 if ((reply->da->vendor == 0) &&
1798 ((reply->da->attr & 0xFFFF) >= 256) &&
1799 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1802 * Permit the admin to send BADLY formatted
1803 * attributes with a debug build.
1805 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1806 memcpy(ptr, reply->vp_octets, reply->vp_length);
1807 len = reply->vp_length;
1808 reply = reply->next;
1812 reply = reply->next;
1817 * Set the Message-Authenticator to the correct
1818 * length and initial value.
1820 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1822 * Cache the offset to the
1823 * Message-Authenticator
1825 packet->offset = total_length;
1828 last_len = reply->vp_length;
1830 last_name = reply->da->name;
1832 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1833 ((uint8_t *) data) + sizeof(data) - ptr);
1834 if (len < 0) return -1;
1837 * Failed to encode the attribute, likely because
1838 * the packet is full.
1841 if (last_len != 0) {
1842 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1845 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1850 next: /* Used only for Raw-Attribute */
1853 total_length += len;
1854 } /* done looping over all attributes */
1857 * Fill in the rest of the fields, and copy the data over
1858 * from the local stack to the newly allocated memory.
1860 * Yes, all this 'memcpy' is slow, but it means
1861 * that we only allocate the minimum amount of
1862 * memory for a request.
1864 packet->data_len = total_length;
1865 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1866 if (!packet->data) {
1867 fr_strerror_printf("Out of memory");
1871 memcpy(packet->data, hdr, packet->data_len);
1872 hdr = (radius_packet_t *) packet->data;
1874 total_length = htons(total_length);
1875 memcpy(hdr->length, &total_length, sizeof(total_length));
1881 /** Sign a previously encoded packet
1884 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1887 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1890 * It wasn't assigned an Id, this is bad!
1892 if (packet->id < 0) {
1893 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1897 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1898 (packet->offset < 0)) {
1899 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1904 * If there's a Message-Authenticator, update it
1905 * now, BEFORE updating the authentication vector.
1907 if (packet->offset > 0) {
1908 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1910 switch (packet->code) {
1911 case PW_CODE_ACCOUNTING_RESPONSE:
1912 if (original && original->code == PW_CODE_STATUS_SERVER) {
1916 case PW_CODE_ACCOUNTING_REQUEST:
1917 case PW_CODE_DISCONNECT_REQUEST:
1918 case PW_CODE_DISCONNECT_ACK:
1919 case PW_CODE_DISCONNECT_NAK:
1920 case PW_CODE_COA_REQUEST:
1921 case PW_CODE_COA_ACK:
1922 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1926 case PW_CODE_ACCESS_ACCEPT:
1927 case PW_CODE_ACCESS_REJECT:
1928 case PW_CODE_ACCESS_CHALLENGE:
1930 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1933 memcpy(hdr->vector, original->vector,
1937 default: /* others have vector already set to zero */
1943 * Set the authentication vector to zero,
1944 * calculate the HMAC, and put it
1945 * into the Message-Authenticator
1948 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1949 (uint8_t const *) secret, strlen(secret));
1950 memcpy(packet->data + packet->offset + 2,
1951 calc_auth_vector, AUTH_VECTOR_LEN);
1954 * Copy the original request vector back
1955 * to the raw packet.
1957 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1961 * Switch over the packet code, deciding how to
1964 switch (packet->code) {
1966 * Request packets are not signed, bur
1967 * have a random authentication vector.
1969 case PW_CODE_ACCESS_REQUEST:
1970 case PW_CODE_STATUS_SERVER:
1974 * Reply packets are signed with the
1975 * authentication vector of the request.
1982 fr_md5_init(&context);
1983 fr_md5_update(&context, packet->data, packet->data_len);
1984 fr_md5_update(&context, (uint8_t const *) secret,
1986 fr_md5_final(digest, &context);
1988 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1989 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1992 }/* switch over packet codes */
1997 /** Reply to the request
1999 * Also attach reply attribute value pairs and any user message provided.
2001 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2005 * Maybe it's a fake packet. Don't send it.
2007 if (!packet || (packet->sockfd < 0)) {
2012 * First time through, allocate room for the packet
2014 if (!packet->data) {
2016 * Encode the packet.
2018 if (rad_encode(packet, original, secret) < 0) {
2023 * Re-sign it, including updating the
2024 * Message-Authenticator.
2026 if (rad_sign(packet, original, secret) < 0) {
2031 * If packet->data points to data, then we print out
2032 * the VP list again only for debugging.
2037 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2042 * If the socket is TCP, call write(). Calling sendto()
2043 * is allowed on some platforms, but it's not nice. Even
2044 * worse, if UDPFROMTO is defined, we *can't* use it on
2045 * TCP sockets. So... just call write().
2047 if (packet->proto == IPPROTO_TCP) {
2050 rcode = write(packet->sockfd, packet->data, packet->data_len);
2051 if (rcode >= 0) return rcode;
2053 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2059 * And send it on it's way.
2061 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2062 &packet->src_ipaddr, packet->src_port,
2063 &packet->dst_ipaddr, packet->dst_port);
2066 /** Do a comparison of two authentication digests by comparing the FULL digest
2068 * Otherwise, the server can be subject to timing attacks that allow attackers
2069 * find a valid message authenticator.
2071 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2073 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2078 for (i = 0; i < length; i++) {
2079 result |= a[i] ^ b[i];
2082 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2086 /** Validates the requesting client NAS
2088 * Calculates the request Authenticator based on the clients private key.
2090 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2092 uint8_t digest[AUTH_VECTOR_LEN];
2096 * Zero out the auth_vector in the received packet.
2097 * Then append the shared secret to the received packet,
2098 * and calculate the MD5 sum. This must be the same
2099 * as the original MD5 sum (packet->vector).
2101 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2104 * MD5(packet + secret);
2106 fr_md5_init(&context);
2107 fr_md5_update(&context, packet->data, packet->data_len);
2108 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2109 fr_md5_final(digest, &context);
2112 * Return 0 if OK, 2 if not OK.
2114 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2119 /** Validates the requesting client NAS
2121 * Calculates the response Authenticator based on the clients
2124 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2127 uint8_t calc_digest[AUTH_VECTOR_LEN];
2133 if (original == NULL) {
2138 * Copy the original vector in place.
2140 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2143 * MD5(packet + secret);
2145 fr_md5_init(&context);
2146 fr_md5_update(&context, packet->data, packet->data_len);
2147 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2148 fr_md5_final(calc_digest, &context);
2151 * Copy the packet's vector back to the packet.
2153 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2156 * Return 0 if OK, 2 if not OK.
2158 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2162 /** Check if a set of RADIUS formatted TLVs are OK
2165 int rad_tlv_ok(uint8_t const *data, size_t length,
2166 size_t dv_type, size_t dv_length)
2168 uint8_t const *end = data + length;
2170 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2172 VP_HEXDUMP("tlv_ok", data, length);
2174 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2175 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2179 while (data < end) {
2182 if ((data + dv_type + dv_length) > end) {
2183 fr_strerror_printf("Attribute header overflow");
2189 if ((data[0] == 0) && (data[1] == 0) &&
2190 (data[2] == 0) && (data[3] == 0)) {
2192 fr_strerror_printf("Invalid attribute 0");
2197 fr_strerror_printf("Invalid attribute > 2^24");
2203 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2208 * Zero is allowed, because the Colubris
2209 * people are dumb and use it.
2214 fr_strerror_printf("Internal sanity check failed");
2218 switch (dv_length) {
2223 if (data[dv_type] != 0) {
2224 fr_strerror_printf("Attribute is longer than 256 octets");
2229 attrlen = data[dv_type + dv_length - 1];
2234 fr_strerror_printf("Internal sanity check failed");
2238 if (attrlen < (dv_type + dv_length)) {
2239 fr_strerror_printf("Attribute header has invalid length");
2243 if (attrlen > length) {
2244 fr_strerror_printf("Attribute overflows container");
2256 /** See if the data pointed to by PTR is a valid RADIUS packet.
2258 * Packet is not 'const * const' because we may update data_len, if there's more data
2259 * in the UDP packet than in the RADIUS packet.
2261 * @param packet to check
2262 * @param flags to control decoding
2263 * @param reason if not NULL, will have the failure reason written to where it points.
2264 * @return bool, true on success, false on failure.
2266 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2271 radius_packet_t *hdr;
2272 char host_ipaddr[128];
2273 bool require_ma = false;
2274 bool seen_ma = false;
2275 uint32_t num_attributes;
2276 decode_fail_t failure = DECODE_FAIL_NONE;
2279 * Check for packets smaller than the packet header.
2281 * RFC 2865, Section 3., subsection 'length' says:
2283 * "The minimum length is 20 ..."
2285 if (packet->data_len < RADIUS_HDR_LEN) {
2286 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2287 inet_ntop(packet->src_ipaddr.af,
2288 &packet->src_ipaddr.ipaddr,
2289 host_ipaddr, sizeof(host_ipaddr)),
2290 packet->data_len, RADIUS_HDR_LEN);
2291 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2297 * Check for packets with mismatched size.
2298 * i.e. We've received 128 bytes, and the packet header
2299 * says it's 256 bytes long.
2301 totallen = (packet->data[2] << 8) | packet->data[3];
2302 hdr = (radius_packet_t *)packet->data;
2305 * Code of 0 is not understood.
2306 * Code of 16 or greate is not understood.
2308 if ((hdr->code == 0) ||
2309 (hdr->code >= FR_MAX_PACKET_CODE)) {
2310 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2311 inet_ntop(packet->src_ipaddr.af,
2312 &packet->src_ipaddr.ipaddr,
2313 host_ipaddr, sizeof(host_ipaddr)),
2315 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2320 * Message-Authenticator is required in Status-Server
2321 * packets, otherwise they can be trivially forged.
2323 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2326 * It's also required if the caller asks for it.
2328 if (flags) require_ma = true;
2331 * Repeat the length checks. This time, instead of
2332 * looking at the data we received, look at the value
2333 * of the 'length' field inside of the packet.
2335 * Check for packets smaller than the packet header.
2337 * RFC 2865, Section 3., subsection 'length' says:
2339 * "The minimum length is 20 ..."
2341 if (totallen < RADIUS_HDR_LEN) {
2342 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2343 inet_ntop(packet->src_ipaddr.af,
2344 &packet->src_ipaddr.ipaddr,
2345 host_ipaddr, sizeof(host_ipaddr)),
2346 totallen, RADIUS_HDR_LEN);
2347 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2352 * And again, for the value of the 'length' field.
2354 * RFC 2865, Section 3., subsection 'length' says:
2356 * " ... and maximum length is 4096."
2358 * HOWEVER. This requirement is for the network layer.
2359 * If the code gets here, we assume that a well-formed
2360 * packet is an OK packet.
2362 * We allow both the UDP data length, and the RADIUS
2363 * "length" field to contain up to 64K of data.
2367 * RFC 2865, Section 3., subsection 'length' says:
2369 * "If the packet is shorter than the Length field
2370 * indicates, it MUST be silently discarded."
2372 * i.e. No response to the NAS.
2374 if (packet->data_len < totallen) {
2375 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2376 inet_ntop(packet->src_ipaddr.af,
2377 &packet->src_ipaddr.ipaddr,
2378 host_ipaddr, sizeof(host_ipaddr)),
2379 packet->data_len, totallen);
2380 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2385 * RFC 2865, Section 3., subsection 'length' says:
2387 * "Octets outside the range of the Length field MUST be
2388 * treated as padding and ignored on reception."
2390 if (packet->data_len > totallen) {
2392 * We're shortening the packet below, but just
2393 * to be paranoid, zero out the extra data.
2395 memset(packet->data + totallen, 0, packet->data_len - totallen);
2396 packet->data_len = totallen;
2400 * Walk through the packet's attributes, ensuring that
2401 * they add up EXACTLY to the size of the packet.
2403 * If they don't, then the attributes either under-fill
2404 * or over-fill the packet. Any parsing of the packet
2405 * is impossible, and will result in unknown side effects.
2407 * This would ONLY happen with buggy RADIUS implementations,
2408 * or with an intentional attack. Either way, we do NOT want
2409 * to be vulnerable to this problem.
2412 count = totallen - RADIUS_HDR_LEN;
2417 * We need at least 2 bytes to check the
2421 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2422 inet_ntop(packet->src_ipaddr.af,
2423 &packet->src_ipaddr.ipaddr,
2424 host_ipaddr, sizeof(host_ipaddr)));
2425 failure = DECODE_FAIL_HEADER_OVERFLOW;
2430 * Attribute number zero is NOT defined.
2433 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2434 inet_ntop(packet->src_ipaddr.af,
2435 &packet->src_ipaddr.ipaddr,
2436 host_ipaddr, sizeof(host_ipaddr)));
2437 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2442 * Attributes are at LEAST as long as the ID & length
2443 * fields. Anything shorter is an invalid attribute.
2446 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2447 inet_ntop(packet->src_ipaddr.af,
2448 &packet->src_ipaddr.ipaddr,
2449 host_ipaddr, sizeof(host_ipaddr)),
2451 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2456 * If there are fewer bytes in the packet than in the
2457 * attribute, it's a bad packet.
2459 if (count < attr[1]) {
2460 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2461 inet_ntop(packet->src_ipaddr.af,
2462 &packet->src_ipaddr.ipaddr,
2463 host_ipaddr, sizeof(host_ipaddr)),
2465 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2470 * Sanity check the attributes for length.
2473 default: /* don't do anything by default */
2477 * If there's an EAP-Message, we require
2478 * a Message-Authenticator.
2480 case PW_EAP_MESSAGE:
2484 case PW_MESSAGE_AUTHENTICATOR:
2485 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2486 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2487 inet_ntop(packet->src_ipaddr.af,
2488 &packet->src_ipaddr.ipaddr,
2489 host_ipaddr, sizeof(host_ipaddr)),
2491 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2499 * FIXME: Look up the base 255 attributes in the
2500 * dictionary, and switch over their type. For
2501 * integer/date/ip, the attribute length SHOULD
2504 count -= attr[1]; /* grab the attribute length */
2506 num_attributes++; /* seen one more attribute */
2510 * If the attributes add up to a packet, it's allowed.
2512 * If not, we complain, and throw the packet away.
2515 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2516 inet_ntop(packet->src_ipaddr.af,
2517 &packet->src_ipaddr.ipaddr,
2518 host_ipaddr, sizeof(host_ipaddr)));
2519 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2524 * If we're configured to look for a maximum number of
2525 * attributes, and we've seen more than that maximum,
2526 * then throw the packet away, as a possible DoS.
2528 if ((fr_max_attributes > 0) &&
2529 (num_attributes > fr_max_attributes)) {
2530 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2531 inet_ntop(packet->src_ipaddr.af,
2532 &packet->src_ipaddr.ipaddr,
2533 host_ipaddr, sizeof(host_ipaddr)),
2534 num_attributes, fr_max_attributes);
2535 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2540 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2542 * A packet with an EAP-Message attribute MUST also have
2543 * a Message-Authenticator attribute.
2545 * A Message-Authenticator all by itself is OK, though.
2547 * Similarly, Status-Server packets MUST contain
2548 * Message-Authenticator attributes.
2550 if (require_ma && !seen_ma) {
2551 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2552 inet_ntop(packet->src_ipaddr.af,
2553 &packet->src_ipaddr.ipaddr,
2554 host_ipaddr, sizeof(host_ipaddr)));
2555 failure = DECODE_FAIL_MA_MISSING;
2560 * Fill RADIUS header fields
2562 packet->code = hdr->code;
2563 packet->id = hdr->id;
2564 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2572 return (failure == DECODE_FAIL_NONE);
2576 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2579 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2583 RADIUS_PACKET *packet;
2586 * Allocate the new request data structure
2588 packet = rad_alloc(ctx, false);
2590 fr_strerror_printf("out of memory");
2595 sock_flags = MSG_PEEK;
2599 data_len = rad_recvfrom(fd, packet, sock_flags,
2600 &packet->src_ipaddr, &packet->src_port,
2601 &packet->dst_ipaddr, &packet->dst_port);
2604 * Check for socket errors.
2607 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2608 /* packet->data is NULL */
2612 packet->data_len = data_len; /* unsigned vs signed */
2615 * If the packet is too big, then rad_recvfrom did NOT
2616 * allocate memory. Instead, it just discarded the
2619 if (packet->data_len > MAX_PACKET_LEN) {
2620 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2621 /* packet->data is NULL */
2627 * Read no data. Continue.
2628 * This check is AFTER the MAX_PACKET_LEN check above, because
2629 * if the packet is larger than MAX_PACKET_LEN, we also have
2630 * packet->data == NULL
2632 if ((packet->data_len == 0) || !packet->data) {
2633 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2639 * See if it's a well-formed RADIUS packet.
2641 if (!rad_packet_ok(packet, flags, NULL)) {
2647 * Remember which socket we read the packet from.
2649 packet->sockfd = fd;
2652 * FIXME: Do even more filtering by only permitting
2653 * certain IP's. The problem is that we don't know
2654 * how to do this properly for all possible clients...
2658 * Explicitely set the VP list to empty.
2663 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2670 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2673 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2681 if (!packet || !packet->data) return -1;
2684 * Before we allocate memory for the attributes, do more
2687 ptr = packet->data + RADIUS_HDR_LEN;
2688 length = packet->data_len - RADIUS_HDR_LEN;
2689 while (length > 0) {
2690 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2691 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2696 default: /* don't do anything. */
2700 * Note that more than one Message-Authenticator
2701 * attribute is invalid.
2703 case PW_MESSAGE_AUTHENTICATOR:
2704 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2705 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2707 switch (packet->code) {
2711 case PW_CODE_ACCOUNTING_RESPONSE:
2713 (original->code == PW_CODE_STATUS_SERVER)) {
2717 case PW_CODE_ACCOUNTING_REQUEST:
2718 case PW_CODE_DISCONNECT_REQUEST:
2719 case PW_CODE_COA_REQUEST:
2720 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2724 case PW_CODE_ACCESS_ACCEPT:
2725 case PW_CODE_ACCESS_REJECT:
2726 case PW_CODE_ACCESS_CHALLENGE:
2727 case PW_CODE_DISCONNECT_ACK:
2728 case PW_CODE_DISCONNECT_NAK:
2729 case PW_CODE_COA_ACK:
2730 case PW_CODE_COA_NAK:
2732 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2733 "packet without a request packet");
2736 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2740 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2741 (uint8_t const *) secret, strlen(secret));
2742 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2743 sizeof(calc_auth_vector)) != 0) {
2744 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2745 "(Shared secret is incorrect.)",
2746 inet_ntop(packet->src_ipaddr.af,
2747 &packet->src_ipaddr.ipaddr,
2748 buffer, sizeof(buffer)));
2749 /* Silently drop packet, according to RFC 3579 */
2751 } /* else the message authenticator was good */
2754 * Reinitialize Authenticators.
2756 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2757 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2759 } /* switch over the attributes */
2763 } /* loop over the packet, sanity checking the attributes */
2766 * It looks like a RADIUS packet, but we don't know what it is
2767 * so can't validate the authenticators.
2769 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2770 fr_strerror_printf("Received Unknown packet code %d "
2771 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2773 inet_ntop(packet->src_ipaddr.af,
2774 &packet->src_ipaddr.ipaddr,
2775 buffer, sizeof(buffer)),
2781 * Calculate and/or verify Request or Response Authenticator.
2783 switch (packet->code) {
2784 case PW_CODE_ACCESS_REQUEST:
2785 case PW_CODE_STATUS_SERVER:
2787 * The authentication vector is random
2788 * nonsense, invented by the client.
2792 case PW_CODE_COA_REQUEST:
2793 case PW_CODE_DISCONNECT_REQUEST:
2794 case PW_CODE_ACCOUNTING_REQUEST:
2795 if (calc_acctdigest(packet, secret) > 1) {
2796 fr_strerror_printf("Received %s packet "
2797 "from client %s with invalid Request Authenticator! "
2798 "(Shared secret is incorrect.)",
2799 fr_packet_codes[packet->code],
2800 inet_ntop(packet->src_ipaddr.af,
2801 &packet->src_ipaddr.ipaddr,
2802 buffer, sizeof(buffer)));
2807 /* Verify the reply digest */
2808 case PW_CODE_ACCESS_ACCEPT:
2809 case PW_CODE_ACCESS_REJECT:
2810 case PW_CODE_ACCESS_CHALLENGE:
2811 case PW_CODE_ACCOUNTING_RESPONSE:
2812 case PW_CODE_DISCONNECT_ACK:
2813 case PW_CODE_DISCONNECT_NAK:
2814 case PW_CODE_COA_ACK:
2815 case PW_CODE_COA_NAK:
2816 rcode = calc_replydigest(packet, original, secret);
2818 fr_strerror_printf("Received %s packet "
2819 "from home server %s port %d with invalid Response Authenticator! "
2820 "(Shared secret is incorrect.)",
2821 fr_packet_codes[packet->code],
2822 inet_ntop(packet->src_ipaddr.af,
2823 &packet->src_ipaddr.ipaddr,
2824 buffer, sizeof(buffer)),
2831 fr_strerror_printf("Received Unknown packet code %d "
2832 "from client %s port %d: Cannot validate Request/Response Authenticator",
2834 inet_ntop(packet->src_ipaddr.af,
2835 &packet->src_ipaddr.ipaddr,
2836 buffer, sizeof(buffer)),
2845 /** Convert a "concatenated" attribute to one long VP
2848 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2849 DICT_ATTR const *da, uint8_t const *start,
2850 size_t const packetlen, VALUE_PAIR **pvp)
2854 uint8_t const *ptr = start;
2855 uint8_t const *end = start + packetlen;
2863 * The packet has already been sanity checked, so we
2864 * don't care about walking off of the end of it.
2867 total += ptr[1] - 2;
2872 * Attributes MUST be consecutive.
2874 if (ptr[0] != attr) break;
2877 vp = pairalloc(ctx, da);
2880 vp->vp_length = total;
2881 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2889 while (total < vp->vp_length) {
2890 memcpy(p, ptr + 2, ptr[1] - 2);
2892 total += ptr[1] - 2;
2901 /** Convert TLVs to one or more VPs
2904 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2905 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2906 char const *secret, DICT_ATTR const *da,
2907 uint8_t const *start, size_t length,
2910 uint8_t const *data = start;
2911 DICT_ATTR const *child;
2912 VALUE_PAIR *head, **tail;
2914 if (length < 3) return -1; /* type, length, value */
2916 VP_HEXDUMP("tlvs", data, length);
2918 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2923 while (data < (start + length)) {
2926 child = dict_attrbyparent(da, data[0], da->vendor);
2928 unsigned int my_attr, my_vendor;
2930 VP_TRACE("Failed to find child %u of TLV %s\n",
2934 * Get child attr/vendor so that
2935 * we can call unknown attr.
2938 my_vendor = da->vendor;
2940 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2945 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2952 tlv_len = data2vp(ctx, packet, original, secret, child,
2953 data + 2, data[1] - 2, data[1] - 2, tail);
2958 if (*tail) tail = &((*tail)->next);
2966 /** Convert a top-level VSA to a VP.
2968 * "length" can be LONGER than just this sub-vsa.
2970 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
2971 RADIUS_PACKET const *original,
2972 char const *secret, DICT_VENDOR *dv,
2973 uint8_t const *data, size_t length,
2976 unsigned int attribute;
2977 ssize_t attrlen, my_len;
2978 DICT_ATTR const *da;
2980 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
2983 if (length <= (dv->type + dv->length)) {
2984 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2991 /* data[0] must be zero */
2992 attribute = data[1] << 16;
2993 attribute |= data[2] << 8;
2994 attribute |= data[3];
2998 attribute = data[0] << 8;
2999 attribute |= data[1];
3003 attribute = data[0];
3007 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3011 switch (dv->length) {
3013 /* data[dv->type] must be zero, from rad_tlv_ok() */
3014 attrlen = data[dv->type + 1];
3018 attrlen = data[dv->type];
3026 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3031 * See if the VSA is known.
3033 da = dict_attrbyvalue(attribute, dv->vendorpec);
3034 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3037 my_len = data2vp(ctx, packet, original, secret, da,
3038 data + dv->type + dv->length,
3039 attrlen - (dv->type + dv->length),
3040 attrlen - (dv->type + dv->length),
3042 if (my_len < 0) return my_len;
3048 /** Convert a fragmented extended attr to a VP
3058 * But for the first fragment, we get passed a pointer to the "extended-attr"
3060 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3061 RADIUS_PACKET const *original,
3062 char const *secret, DICT_ATTR const *da,
3063 uint8_t const *data,
3064 size_t attrlen, size_t packetlen,
3069 uint8_t *head, *tail;
3070 uint8_t const *frag, *end;
3071 uint8_t const *attr;
3075 if (attrlen < 3) return -1;
3078 * Calculate the length of all of the fragments. For
3079 * now, they MUST be contiguous in the packet, and they
3080 * MUST be all of the same TYPE and EXTENDED-TYPE
3083 fraglen = attrlen - 2;
3084 frag = data + attrlen;
3085 end = data + packetlen;
3089 while (frag < end) {
3091 (frag[0] != attr[0]) ||
3092 (frag[1] < 4) || /* too short for long-extended */
3093 (frag[2] != attr[2]) ||
3094 ((frag + frag[1]) > end)) { /* overflow */
3099 last_frag = ((frag[3] & 0x80) == 0);
3101 fraglen += frag[1] - 4;
3106 head = tail = malloc(fraglen);
3107 if (!head) return -1;
3109 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3112 * And again, but faster and looser.
3114 * We copy the first fragment, followed by the rest of
3119 while (fragments > 0) {
3120 memcpy(tail, frag + 4, frag[1] - 4);
3121 tail += frag[1] - 4;
3126 VP_HEXDUMP("long-extended fragments", head, fraglen);
3128 rcode = data2vp(ctx, packet, original, secret, da,
3129 head, fraglen, fraglen, pvp);
3131 if (rcode < 0) return rcode;
3136 /** Convert a Vendor-Specific WIMAX to vps
3138 * @note Called ONLY for Vendor-Specific
3140 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3141 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3142 char const *secret, uint32_t vendor,
3143 uint8_t const *data,
3144 size_t attrlen, size_t packetlen,
3150 uint8_t *head, *tail;
3151 uint8_t const *frag, *end;
3152 DICT_ATTR const *child;
3154 if (attrlen < 8) return -1;
3156 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3158 child = dict_attrbyvalue(data[4], vendor);
3159 if (!child) return -1;
3161 if ((data[6] & 0x80) == 0) {
3162 rcode = data2vp(ctx, packet, original, secret, child,
3163 data + 7, data[5] - 3, data[5] - 3,
3165 if (rcode < 0) return -1;
3170 * Calculate the length of all of the fragments. For
3171 * now, they MUST be contiguous in the packet, and they
3172 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3174 * The first fragment doesn't have a RADIUS attribute
3175 * header, so it needs to be treated a little special.
3177 fraglen = data[5] - 3;
3178 frag = data + attrlen;
3179 end = data + packetlen;
3182 while (frag < end) {
3184 (frag[0] != PW_VENDOR_SPECIFIC) ||
3185 (frag[1] < 9) || /* too short for wimax */
3186 ((frag + frag[1]) > end) || /* overflow */
3187 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3188 (frag[6] != data[4]) || /* not the same wimax attr */
3189 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3194 last_frag = ((frag[8] & 0x80) == 0);
3196 fraglen += frag[7] - 3;
3200 head = tail = malloc(fraglen);
3201 if (!head) return -1;
3204 * And again, but faster and looser.
3206 * We copy the first fragment, followed by the rest of
3211 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3212 tail += frag[4 + 1] - 3;
3213 frag += attrlen; /* should be frag[1] - 7 */
3216 * frag now points to RADIUS attributes
3219 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3220 tail += frag[2 + 4 + 1] - 3;
3222 } while (frag < end);
3224 VP_HEXDUMP("wimax fragments", head, fraglen);
3226 rcode = data2vp(ctx, packet, original, secret, child,
3227 head, fraglen, fraglen, pvp);
3229 if (rcode < 0) return rcode;
3235 /** Convert a top-level VSA to one or more VPs
3238 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3239 RADIUS_PACKET const *original,
3240 char const *secret, uint8_t const *data,
3241 size_t attrlen, size_t packetlen,
3248 VALUE_PAIR *head, **tail;
3251 if (attrlen > packetlen) return -1;
3252 if (attrlen < 5) return -1; /* vid, value */
3253 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3255 VP_TRACE("data2vp_vsas\n");
3257 memcpy(&vendor, data, 4);
3258 vendor = ntohl(vendor);
3259 dv = dict_vendorbyvalue(vendor);
3262 * RFC format is 1 octet type, 1 octet length
3264 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3265 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3270 * It's a known unknown.
3272 memset(&my_dv, 0, sizeof(my_dv));
3276 * Fill in the fields. Note that the name is empty!
3278 dv->vendorpec = vendor;
3288 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3289 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3290 data, attrlen, packetlen, pvp);
3295 * VSAs should normally be in TLV format.
3297 if (rad_tlv_ok(data + 4, attrlen - 4,
3298 dv->type, dv->length) < 0) {
3299 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3304 * There may be more than one VSA in the
3305 * Vendor-Specific. If so, loop over them all.
3315 while (attrlen > 0) {
3318 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3319 data, attrlen, tail);
3322 fr_strerror_printf("Internal sanity check %d", __LINE__);
3327 * Vendors can send zero-length VSAs.
3329 if (*tail) tail = &((*tail)->next);
3333 packetlen -= vsa_len;
3341 /** Create any kind of VP from the attribute contents
3343 * "length" is AT LEAST the length of this attribute, as we
3344 * expect the caller to have verified the data with
3345 * rad_packet_ok(). "length" may be up to the length of the
3348 * @return -1 on error, or "length".
3350 ssize_t data2vp(TALLOC_CTX *ctx,
3351 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3353 DICT_ATTR const *da, uint8_t const *start,
3354 size_t const attrlen, size_t const packetlen,
3357 int8_t tag = TAG_NONE;
3361 DICT_ATTR const *child;
3363 uint8_t const *data = start;
3365 uint8_t buffer[256];
3368 * FIXME: Attrlen can be larger than 253 for extended attrs!
3370 if (!da || (attrlen > packetlen) ||
3371 ((attrlen > 253) && (attrlen != packetlen)) ||
3372 (attrlen > 128*1024)) {
3373 fr_strerror_printf("data2vp: invalid arguments");
3377 VP_HEXDUMP("data2vp", start, attrlen);
3379 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3384 * Hacks for CUI. The WiMAX spec says that it can be
3385 * zero length, even though this is forbidden by the
3386 * RADIUS specs. So... we make a special case for it.
3389 if (!((da->vendor == 0) &&
3390 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3397 * Hacks for Coverity. Editing the dictionary
3398 * will break assumptions about CUI. We know
3399 * this, but Coverity doesn't.
3401 if (da->type != PW_TYPE_OCTETS) return -1;
3406 goto alloc_cui; /* skip everything */
3410 * Hacks for tags. If the attribute is capable of
3411 * encoding a tag, and there's room for the tag, and
3412 * there is a tag, or it's encrypted with Tunnel-Password,
3413 * then decode the tag.
3415 if (da->flags.has_tag && (datalen > 1) &&
3416 ((data[0] < 0x20) ||
3417 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3419 * Only "short" attributes can be encrypted.
3421 if (datalen >= sizeof(buffer)) return -1;
3423 if (da->type == PW_TYPE_STRING) {
3424 memcpy(buffer, data + 1, datalen - 1);
3428 } else if (da->type == PW_TYPE_INTEGER) {
3429 memcpy(buffer, data, attrlen);
3434 return -1; /* only string and integer can have tags */
3441 * Decrypt the attribute.
3443 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3444 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3446 * Encrypted attributes can only exist for the
3447 * old-style format. Extended attributes CANNOT
3450 if (attrlen > 253) {
3454 if (data == start) {
3455 memcpy(buffer, data, attrlen);
3459 switch (da->flags.encrypt) { /* can't be tagged */
3463 case FLAG_ENCRYPT_USER_PASSWORD:
3465 rad_pwdecode((char *) buffer,
3469 rad_pwdecode((char *) buffer,
3476 * Take off trailing zeros from the END.
3477 * This allows passwords to have zeros in
3478 * the middle of a field.
3480 * However, if the password has a zero at
3481 * the end, it will get mashed by this
3482 * code. There's really no way around
3485 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3489 * Tunnel-Password's may go ONLY in response
3490 * packets. They can have a tag, so datalen is
3491 * not the same as attrlen.
3493 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3494 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3495 original ? original->vector : nullvector) < 0) {
3501 * Ascend-Send-Secret
3502 * Ascend-Receive-Secret
3504 case FLAG_ENCRYPT_ASCEND_SECRET:
3508 uint8_t my_digest[AUTH_VECTOR_LEN];
3509 make_secret(my_digest,
3512 memcpy(buffer, my_digest,
3514 buffer[AUTH_VECTOR_LEN] = '\0';
3515 datalen = strlen((char *) buffer);
3521 } /* switch over encryption flags */
3525 * Double-check the length after decrypting the
3528 VP_TRACE("data2vp: type %u\n", da->type);
3530 case PW_TYPE_STRING:
3531 case PW_TYPE_OCTETS:
3534 case PW_TYPE_ABINARY:
3535 if (datalen > sizeof(vp->vp_filter)) goto raw;
3538 case PW_TYPE_INTEGER:
3539 case PW_TYPE_IPV4_ADDR:
3541 case PW_TYPE_SIGNED:
3542 if (datalen != 4) goto raw;
3545 case PW_TYPE_INTEGER64:
3547 if (datalen != 8) goto raw;
3550 case PW_TYPE_IPV6_ADDR:
3551 if (datalen != 16) goto raw;
3554 case PW_TYPE_IPV6_PREFIX:
3555 if ((datalen < 2) || (datalen > 18)) goto raw;
3556 if (data[1] > 128) goto raw;
3560 if (datalen != 1) goto raw;
3564 if (datalen != 2) goto raw;
3567 case PW_TYPE_ETHERNET:
3568 if (datalen != 6) goto raw;
3571 case PW_TYPE_COMBO_IP_ADDR:
3573 child = dict_attrbytype(da->attr, da->vendor,
3575 } else if (datalen == 16) {
3576 child = dict_attrbytype(da->attr, da->vendor,
3581 if (!child) goto raw;
3582 da = child; /* re-write it */
3585 case PW_TYPE_IPV4_PREFIX:
3586 if (datalen != 6) goto raw;
3587 if ((data[1] & 0x3f) > 32) goto raw;
3591 * The rest of the data types can cause
3592 * recursion! Ask yourself, "is recursion OK?"
3595 case PW_TYPE_EXTENDED:
3596 if (datalen < 2) goto raw; /* etype, value */
3598 child = dict_attrbyparent(da, data[0], 0);
3599 if (!child) goto raw;
3602 * Recurse to decode the contents, which could be
3603 * a TLV, IPaddr, etc. Note that we decode only
3604 * the current attribute, and we ignore any extra
3607 rcode = data2vp(ctx, packet, original, secret, child,
3608 data + 1, attrlen - 1, attrlen - 1, pvp);
3609 if (rcode < 0) goto raw;
3612 case PW_TYPE_LONG_EXTENDED:
3613 if (datalen < 3) goto raw; /* etype, flags, value */
3615 child = dict_attrbyparent(da, data[0], 0);
3617 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3618 (datalen < (3 + 4 + 1))) {
3619 /* da->attr < 255, da->vendor == 0 */
3620 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3623 * Try to find the VSA.
3625 memcpy(&vendor, data + 3, 4);
3626 vendor = ntohl(vendor);
3628 if (vendor == 0) goto raw;
3630 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3634 fr_strerror_printf("Internal sanity check %d", __LINE__);
3640 * If there no more fragments, then the contents
3641 * have to be a well-known data type.
3644 if ((data[1] & 0x80) == 0) {
3645 rcode = data2vp(ctx, packet, original, secret, child,
3646 data + 2, attrlen - 2, attrlen - 2,
3648 if (rcode < 0) goto raw;
3653 * This requires a whole lot more work.
3655 return data2vp_extended(ctx, packet, original, secret, child,
3656 start, attrlen, packetlen, pvp);
3659 if (datalen < 6) goto raw; /* vid, vtype, value */
3661 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3663 memcpy(&vendor, data, 4);
3664 vendor = ntohl(vendor);
3665 vendor |= da->vendor;
3667 child = dict_attrbyvalue(data[4], vendor);
3670 * Create a "raw" attribute from the
3671 * contents of the EVS VSA.
3673 da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3679 rcode = data2vp(ctx, packet, original, secret, child,
3680 data + 5, attrlen - 5, attrlen - 5, pvp);
3681 if (rcode < 0) goto raw;
3686 * We presume that the TLVs all fit into one
3687 * attribute, OR they've already been grouped
3688 * into a contiguous memory buffer.
3690 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3691 data, attrlen, pvp);
3692 if (rcode < 0) goto raw;
3697 * VSAs can be WiMAX, in which case they don't
3698 * fit into one attribute.
3700 rcode = data2vp_vsas(ctx, packet, original, secret,
3701 data, attrlen, packetlen, pvp);
3702 if (rcode < 0) goto raw;
3708 * Re-write the attribute to be "raw". It is
3709 * therefore of type "octets", and will be
3712 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3714 fr_strerror_printf("Internal sanity check %d", __LINE__);
3722 if (da->type != PW_TYPE_OCTETS) {
3723 dict_attr_free(&da);
3731 * And now that we've verified the basic type
3732 * information, decode the actual data.
3735 vp = pairalloc(ctx, da);
3738 vp->vp_length = datalen;
3742 case PW_TYPE_STRING:
3743 p = talloc_array(vp, char, vp->vp_length + 1);
3744 memcpy(p, data, vp->vp_length);
3745 p[vp->vp_length] = '\0';
3746 vp->vp_strvalue = p;
3749 case PW_TYPE_OCTETS:
3750 pairmemcpy(vp, data, vp->vp_length);
3753 case PW_TYPE_ABINARY:
3754 if (vp->vp_length > sizeof(vp->vp_filter)) {
3755 vp->vp_length = sizeof(vp->vp_filter);
3757 memcpy(vp->vp_filter, data, vp->vp_length);
3761 vp->vp_byte = data[0];
3765 vp->vp_short = (data[0] << 8) | data[1];
3768 case PW_TYPE_INTEGER:
3769 memcpy(&vp->vp_integer, data, 4);
3770 vp->vp_integer = ntohl(vp->vp_integer);
3773 case PW_TYPE_INTEGER64:
3774 memcpy(&vp->vp_integer64, data, 8);
3775 vp->vp_integer64 = ntohll(vp->vp_integer64);
3779 memcpy(&vp->vp_date, data, 4);
3780 vp->vp_date = ntohl(vp->vp_date);
3783 case PW_TYPE_ETHERNET:
3784 memcpy(vp->vp_ether, data, 6);
3787 case PW_TYPE_IPV4_ADDR:
3788 memcpy(&vp->vp_ipaddr, data, 4);
3792 memcpy(vp->vp_ifid, data, 8);
3795 case PW_TYPE_IPV6_ADDR:
3796 memcpy(&vp->vp_ipv6addr, data, 16);
3799 case PW_TYPE_IPV6_PREFIX:
3801 * FIXME: double-check that
3802 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3804 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3805 if (vp->vp_length < 18) {
3806 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3807 18 - vp->vp_length);
3811 case PW_TYPE_IPV4_PREFIX:
3812 /* FIXME: do the same double-check as for IPv6Prefix */
3813 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3816 * /32 means "keep all bits". Otherwise, mask
3819 if ((data[1] & 0x3f) > 32) {
3820 uint32_t addr, mask;
3822 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3824 mask <<= (32 - (data[1] & 0x3f));
3829 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3833 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3834 memcpy(&vp->vp_integer, buffer, 4);
3835 vp->vp_integer = ntohl(vp->vp_integer);
3840 fr_strerror_printf("Internal sanity check %d", __LINE__);
3850 /** Create a "normal" VALUE_PAIR from the given data
3853 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3854 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3856 uint8_t const *data, size_t length,
3861 DICT_ATTR const *da;
3863 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3864 fr_strerror_printf("rad_attr2vp: Insufficient data");
3868 da = dict_attrbyvalue(data[0], 0);
3870 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3871 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3876 * Pass the entire thing to the decoding function
3878 if (da->flags.concat) {
3879 VP_TRACE("attr2vp: concat attribute\n");
3880 return data2vp_concat(ctx, da, data, length, pvp);
3884 * Note that we pass the entire length, not just the
3885 * length of this attribute. The Extended or WiMAX
3886 * attributes may have the "continuation" bit set, and
3887 * will thus be more than one attribute in length.
3889 rcode = data2vp(ctx, packet, original, secret, da,
3890 data + 2, data[1] - 2, length - 2, pvp);
3891 if (rcode < 0) return rcode;
3896 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3898 /** Converts vp_data to network byte order
3900 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3901 * in an architecture independent format.
3903 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3904 * as the source VALUE_PAIR is not freed.
3906 * @param out where to write the pointer to the value.
3907 * @param vp to get the value from.
3908 * @return -1 on error, or the length of the value
3910 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3918 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3922 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3924 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3928 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3930 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3938 switch (vp->da->type) {
3939 case PW_TYPE_STRING:
3940 case PW_TYPE_OCTETS:
3941 memcpy(out, &vp->data.ptr, sizeof(*out));
3945 * All of these values are at the same location.
3948 case PW_TYPE_IPV4_ADDR:
3949 case PW_TYPE_IPV6_ADDR:
3950 case PW_TYPE_IPV6_PREFIX:
3951 case PW_TYPE_IPV4_PREFIX:
3952 case PW_TYPE_ABINARY:
3953 case PW_TYPE_ETHERNET:
3954 case PW_TYPE_COMBO_IP_ADDR:
3955 case PW_TYPE_COMBO_IP_PREFIX:
3957 void const *p = &vp->data;
3958 memcpy(out, &p, sizeof(*out));
3962 case PW_TYPE_BOOLEAN:
3963 buffer[0] = vp->vp_byte & 0x01;
3968 buffer[0] = vp->vp_byte & 0xff;
3973 buffer[0] = (vp->vp_short >> 8) & 0xff;
3974 buffer[1] = vp->vp_short & 0xff;
3978 case PW_TYPE_INTEGER:
3979 lvalue = htonl(vp->vp_integer);
3980 memcpy(buffer, &lvalue, sizeof(lvalue));
3984 case PW_TYPE_INTEGER64:
3985 lvalue64 = htonll(vp->vp_integer64);
3986 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3991 lvalue = htonl(vp->vp_date);
3992 memcpy(buffer, &lvalue, sizeof(lvalue));
3996 case PW_TYPE_SIGNED:
3998 int32_t slvalue = htonl(vp->vp_signed);
3999 memcpy(buffer, &slvalue, sizeof(slvalue));
4004 case PW_TYPE_INVALID:
4005 case PW_TYPE_EXTENDED:
4006 case PW_TYPE_LONG_EXTENDED:
4010 case PW_TYPE_TIMEVAL:
4012 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4015 /* Don't add default */
4018 return vp->vp_length;
4021 /** Calculate/check digest, and decode radius attributes
4023 * @return -1 on decoding error, 0 on success
4025 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4029 uint32_t num_attributes;
4031 radius_packet_t *hdr;
4032 VALUE_PAIR *head, **tail, *vp;
4035 * Extract attribute-value pairs
4037 hdr = (radius_packet_t *)packet->data;
4039 packet_length = packet->data_len - RADIUS_HDR_LEN;
4046 * Loop over the attributes, decoding them into VPs.
4048 while (packet_length > 0) {
4052 * This may return many VPs
4054 my_len = rad_attr2vp(packet, packet, original, secret,
4055 ptr, packet_length, &vp);
4069 * VSA's may not have been counted properly in
4070 * rad_packet_ok() above, as it is hard to count
4071 * then without using the dictionary. We
4072 * therefore enforce the limits here, too.
4074 if ((fr_max_attributes > 0) &&
4075 (num_attributes > fr_max_attributes)) {
4076 char host_ipaddr[128];
4079 fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4080 inet_ntop(packet->src_ipaddr.af,
4081 &packet->src_ipaddr.ipaddr,
4082 host_ipaddr, sizeof(host_ipaddr)),
4083 num_attributes, fr_max_attributes);
4088 packet_length -= my_len;
4092 * Merge information from the outside world into our
4095 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4098 * There may be VP's already in the packet. Don't
4099 * destroy them. Instead, add the decoded attributes to
4100 * the tail of the list.
4102 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4113 * We assume that the passwd buffer passed is big enough.
4114 * RFC2138 says the password is max 128 chars, so the size
4115 * of the passwd buffer must be at least 129 characters.
4116 * Preferably it's just MAX_STRING_LEN.
4118 * int *pwlen is updated to the new length of the encrypted
4119 * password - a multiple of 16 bytes.
4121 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4122 uint8_t const *vector)
4124 FR_MD5_CTX context, old;
4125 uint8_t digest[AUTH_VECTOR_LEN];
4126 int i, n, secretlen;
4130 * RFC maximum is 128 bytes.
4132 * If length is zero, pad it out with zeros.
4134 * If the length isn't aligned to 16 bytes,
4135 * zero out the extra data.
4139 if (len > 128) len = 128;
4142 memset(passwd, 0, AUTH_PASS_LEN);
4143 len = AUTH_PASS_LEN;
4144 } else if ((len % AUTH_PASS_LEN) != 0) {
4145 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4146 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4151 * Use the secret to setup the decryption digest
4153 secretlen = strlen(secret);
4155 fr_md5_init(&context);
4156 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4157 old = context; /* save intermediate work */
4160 * Encrypt it in place. Don't bother checking
4161 * len, as we've ensured above that it's OK.
4163 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4165 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4166 fr_md5_final(digest, &context);
4169 fr_md5_update(&context,
4170 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4172 fr_md5_final(digest, &context);
4175 for (i = 0; i < AUTH_PASS_LEN; i++) {
4176 passwd[i + n] ^= digest[i];
4186 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4187 uint8_t const *vector)
4189 FR_MD5_CTX context, old;
4190 uint8_t digest[AUTH_VECTOR_LEN];
4192 size_t n, secretlen;
4195 * The RFC's say that the maximum is 128.
4196 * The buffer we're putting it into above is 254, so
4197 * we don't need to do any length checking.
4199 if (pwlen > 128) pwlen = 128;
4204 if (pwlen == 0) goto done;
4207 * Use the secret to setup the decryption digest
4209 secretlen = strlen(secret);
4211 fr_md5_init(&context);
4212 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4213 old = context; /* save intermediate work */
4216 * The inverse of the code above.
4218 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4220 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4221 fr_md5_final(digest, &context);
4224 if (pwlen > AUTH_PASS_LEN) {
4225 fr_md5_update(&context, (uint8_t *) passwd,
4229 fr_md5_final(digest, &context);
4232 if (pwlen > (n + AUTH_PASS_LEN)) {
4233 fr_md5_update(&context, (uint8_t *) passwd + n,
4238 for (i = 0; i < AUTH_PASS_LEN; i++) {
4239 passwd[i + n] ^= digest[i];
4244 passwd[pwlen] = '\0';
4245 return strlen(passwd);
4249 /** Encode Tunnel-Password attributes when sending them out on the wire
4251 * int *pwlen is updated to the new length of the encrypted
4252 * password - a multiple of 16 bytes.
4254 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4257 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4258 uint8_t const *vector)
4260 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4261 unsigned char digest[AUTH_VECTOR_LEN];
4263 int i, n, secretlen;
4268 if (len > 127) len = 127;
4271 * Shift the password 3 positions right to place a salt and original
4272 * length, tag will be added automatically on packet send
4274 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4278 * save original password length as first password character;
4285 * Generate salt. The RFC's say:
4287 * The high bit of salt[0] must be set, each salt in a
4288 * packet should be unique, and they should be random
4290 * So, we set the high bit, add in a counter, and then
4291 * add in some CSPRNG data. should be OK..
4293 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4294 (fr_rand() & 0x07));
4295 salt[1] = fr_rand();
4298 * Padd password to multiple of AUTH_PASS_LEN bytes.
4300 n = len % AUTH_PASS_LEN;
4302 n = AUTH_PASS_LEN - n;
4303 for (; n > 0; n--, len++)
4306 /* set new password length */
4310 * Use the secret to setup the decryption digest
4312 secretlen = strlen(secret);
4313 memcpy(buffer, secret, secretlen);
4315 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4317 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4318 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4319 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4321 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4322 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4325 for (i = 0; i < AUTH_PASS_LEN; i++) {
4326 passwd[i + n2] ^= digest[i];
4333 /** Decode Tunnel-Password encrypted attributes
4335 * Defined in RFC-2868, this uses a two char SALT along with the
4336 * initial intermediate value, to differentiate it from the
4339 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4340 uint8_t const *vector)
4342 FR_MD5_CTX context, old;
4343 uint8_t digest[AUTH_VECTOR_LEN];
4345 unsigned i, n, len, reallen;
4350 * We need at least a salt.
4353 fr_strerror_printf("tunnel password is too short");
4358 * There's a salt, but no password. Or, there's a salt
4359 * and a 'data_len' octet. It's wrong, but at least we
4360 * can figure out what it means: the password is empty.
4362 * Note that this means we ignore the 'data_len' field,
4363 * if the attribute length tells us that there's no
4364 * more data. So the 'data_len' field may be wrong,
4373 len -= 2; /* discount the salt */
4376 * Use the secret to setup the decryption digest
4378 secretlen = strlen(secret);
4380 fr_md5_init(&context);
4381 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4382 old = context; /* save intermediate work */
4385 * Set up the initial key:
4387 * b(1) = MD5(secret + vector + salt)
4389 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4390 fr_md5_update(&context, passwd, 2);
4393 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4397 fr_md5_final(digest, &context);
4402 * A quick check: decrypt the first octet
4403 * of the password, which is the
4404 * 'data_len' field. Ensure it's sane.
4406 reallen = passwd[2] ^ digest[0];
4407 if (reallen >= len) {
4408 fr_strerror_printf("tunnel password is too long for the attribute");
4412 fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4416 fr_md5_final(digest, &context);
4419 fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4422 for (i = base; i < AUTH_PASS_LEN; i++) {
4423 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4428 * See make_tunnel_password, above.
4430 if (reallen > 239) reallen = 239;
4433 passwd[reallen] = 0;
4438 /** Encode a CHAP password
4440 * @bug FIXME: might not work with Ascend because
4441 * we use vp->vp_length, and Ascend gear likes
4442 * to send an extra '\0' in the string!
4444 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4445 VALUE_PAIR *password)
4449 uint8_t string[MAX_STRING_LEN * 2 + 1];
4450 VALUE_PAIR *challenge;
4453 * Sanity check the input parameters
4455 if ((packet == NULL) || (password == NULL)) {
4460 * Note that the password VP can be EITHER
4461 * a User-Password attribute (from a check-item list),
4462 * or a CHAP-Password attribute (the client asking
4463 * the library to encode it).
4471 memcpy(ptr, password->vp_strvalue, password->vp_length);
4472 ptr += password->vp_length;
4473 i += password->vp_length;
4476 * Use Chap-Challenge pair if present,
4477 * Request Authenticator otherwise.
4479 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4481 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4482 i += challenge->vp_length;
4484 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4485 i += AUTH_VECTOR_LEN;
4489 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4495 /** Seed the random number generator
4497 * May be called any number of times.
4499 void fr_rand_seed(void const *data, size_t size)
4504 * Ensure that the pool is initialized.
4506 if (!fr_rand_initialized) {
4509 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4511 fd = open("/dev/urandom", O_RDONLY);
4517 while (total < sizeof(fr_rand_pool.randrsl)) {
4518 this = read(fd, fr_rand_pool.randrsl,
4519 sizeof(fr_rand_pool.randrsl) - total);
4520 if ((this < 0) && (errno != EINTR)) break;
4521 if (this > 0) total += this;
4525 fr_rand_pool.randrsl[0] = fd;
4526 fr_rand_pool.randrsl[1] = time(NULL);
4527 fr_rand_pool.randrsl[2] = errno;
4530 fr_randinit(&fr_rand_pool, 1);
4531 fr_rand_pool.randcnt = 0;
4532 fr_rand_initialized = 1;
4538 * Hash the user data
4541 if (!hash) hash = fr_rand();
4542 hash = fr_hash_update(data, size, hash);
4544 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4548 /** Return a 32-bit random number
4551 uint32_t fr_rand(void)
4556 * Ensure that the pool is initialized.
4558 if (!fr_rand_initialized) {
4559 fr_rand_seed(NULL, 0);
4562 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4563 if (fr_rand_pool.randcnt >= 256) {
4564 fr_rand_pool.randcnt = 0;
4565 fr_isaac(&fr_rand_pool);
4572 /** Allocate a new RADIUS_PACKET
4574 * @param ctx the context in which the packet is allocated. May be NULL if
4575 * the packet is not associated with a REQUEST.
4576 * @param new_vector if true a new request authenticator will be generated.
4577 * @return a new RADIUS_PACKET or NULL on error.
4579 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4583 rp = talloc_zero(ctx, RADIUS_PACKET);
4585 fr_strerror_printf("out of memory");
4593 uint32_t hash, base;
4596 * Don't expose the actual contents of the random
4600 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4601 hash = fr_rand() ^ base;
4602 memcpy(rp->vector + i, &hash, sizeof(hash));
4605 fr_rand(); /* stir the pool again */
4610 /** Allocate a new RADIUS_PACKET response
4612 * @param ctx the context in which the packet is allocated. May be NULL if
4613 * the packet is not associated with a REQUEST.
4614 * @param packet The request packet.
4615 * @return a new RADIUS_PACKET or NULL on error.
4617 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4619 RADIUS_PACKET *reply;
4621 if (!packet) return NULL;
4623 reply = rad_alloc(ctx, false);
4624 if (!reply) return NULL;
4627 * Initialize the fields from the request.
4629 reply->sockfd = packet->sockfd;
4630 reply->dst_ipaddr = packet->src_ipaddr;
4631 reply->src_ipaddr = packet->dst_ipaddr;
4632 reply->dst_port = packet->src_port;
4633 reply->src_port = packet->dst_port;
4634 reply->id = packet->id;
4635 reply->code = 0; /* UNKNOWN code */
4636 memcpy(reply->vector, packet->vector,
4637 sizeof(reply->vector));
4640 reply->data_len = 0;
4643 reply->proto = packet->proto;
4649 /** Free a RADIUS_PACKET
4652 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4654 RADIUS_PACKET *radius_packet;
4656 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4657 radius_packet = *radius_packet_ptr;
4659 VERIFY_PACKET(radius_packet);
4661 pairfree(&radius_packet->vps);
4663 talloc_free(radius_packet);
4664 *radius_packet_ptr = NULL;
4667 /** Duplicate a RADIUS_PACKET
4669 * @param ctx the context in which the packet is allocated. May be NULL if
4670 * the packet is not associated with a REQUEST.
4671 * @param in The packet to copy
4672 * @return a new RADIUS_PACKET or NULL on error.
4674 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4678 out = rad_alloc(ctx, false);
4679 if (!out) return NULL;
4682 * Bootstrap by copying everything.
4684 memcpy(out, in, sizeof(*out));
4687 * Then reset necessary fields
4694 out->vps = paircopy(out, in->vps);