2 * This library is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU Lesser General Public
4 * License as published by the Free Software Foundation; either
5 * version 2.1 of the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
12 * You should have received a copy of the GNU Lesser General Public
13 * License along with this library; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Functions to send/receive radius packets.
23 * @copyright 2000-2003,2006 The FreeRADIUS server project
28 #include <freeradius-devel/libradius.h>
30 #include <freeradius-devel/md5.h>
36 #include <freeradius-devel/udpfromto.h>
40 #define VP_TRACE if (fr_debug_flag) printf
42 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
46 printf("--- %s ---\n", msg);
47 for (i = 0; i < len; i++) {
48 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
49 printf("%02x ", data[i]);
50 if ((i & 0x0f) == 0x0f) printf("\n");
52 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
56 #define VP_TRACE(_x, ...)
57 #define VP_HEXDUMP(_x, _y, _z)
62 * The RFC says 4096 octets max, and most packets are less than 256.
64 #define MAX_PACKET_LEN 4096
67 * The maximum number of attributes which we allow in an incoming
68 * request. If there are more attributes than this, the request
71 * This helps to minimize the potential for a DoS, when an
72 * attacker spoofs Access-Request packets, which don't have a
73 * Message-Authenticator attribute. This means that the packet
74 * is unsigned, and the attacker can use resources on the server,
75 * even if the end request is rejected.
77 uint32_t fr_max_attributes = 0;
78 FILE *fr_log_fp = NULL;
80 typedef struct radius_packet_t {
84 uint8_t vector[AUTH_VECTOR_LEN];
88 static fr_randctx fr_rand_pool; /* across multiple calls */
89 static int fr_rand_initialized = 0;
90 static unsigned int salt_offset = 0;
91 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
93 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
99 "Accounting-Response",
104 "Accounting-Message", //!< 10
115 "Resource-Free-Request",
116 "Resource-Free-Response",
117 "Resource-Query-Request",
118 "Resource-Query-Response",
119 "Alternate-Resource-Reclaim-Request",
120 "NAS-Reboot-Request",
121 "NAS-Reboot-Response",
134 "Disconnect-Request", //!< 40
144 "IP-Address-Allocate",
145 "IP-Address-Release", //!< 50
149 void fr_printf_log(char const *fmt, ...)
154 if ((fr_debug_flag == 0) || !fr_log_fp) {
159 vfprintf(fr_log_fp, fmt, ap);
165 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
167 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
171 for (i = 0; i < attrlen; i++) {
172 if ((i > 0) && ((i & 0x0f) == 0x00))
173 fprintf(fr_log_fp, "%.*s", depth, tabs);
174 fprintf(fr_log_fp, "%02x ", ptr[i]);
175 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
177 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
181 void rad_print_hex(RADIUS_PACKET *packet)
185 if (!packet->data || !fr_log_fp) return;
187 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
188 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
189 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
191 fprintf(fr_log_fp, " Vector:\t");
192 for (i = 4; i < 20; i++) {
193 fprintf(fr_log_fp, "%02x", packet->data[i]);
195 fprintf(fr_log_fp, "\n");
197 if (packet->data_len > 20) {
200 fprintf(fr_log_fp, " Data:");
202 total = packet->data_len - 20;
203 ptr = packet->data + 20;
207 unsigned int vendor = 0;
209 fprintf(fr_log_fp, "\t\t");
210 if (total < 2) { /* too short */
211 fprintf(fr_log_fp, "%02x\n", *ptr);
215 if (ptr[1] > total) { /* too long */
216 for (i = 0; i < total; i++) {
217 fprintf(fr_log_fp, "%02x ", ptr[i]);
222 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
223 attrlen = ptr[1] - 2;
225 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
227 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
228 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
229 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
239 print_hex_data(ptr, attrlen, 3);
249 * @brief Wrapper for sendto which handles sendfromto, IPv6, and all
250 * possible combinations.
252 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
253 #ifdef WITH_UDPFROMTO
254 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
256 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
258 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
261 struct sockaddr_storage dst;
262 socklen_t sizeof_dst;
264 #ifdef WITH_UDPFROMTO
265 struct sockaddr_storage src;
266 socklen_t sizeof_src;
268 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
271 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
275 #ifdef WITH_UDPFROMTO
277 * And if they don't specify a source IP address, don't
280 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
281 (src_ipaddr->af != AF_UNSPEC) &&
282 !fr_inaddr_any(src_ipaddr)) {
283 rcode = sendfromto(sockfd, data, data_len, flags,
284 (struct sockaddr *)&src, sizeof_src,
285 (struct sockaddr *)&dst, sizeof_dst);
291 * No udpfromto, fail gracefully.
293 rcode = sendto(sockfd, data, data_len, flags,
294 (struct sockaddr *) &dst, sizeof_dst);
295 #ifdef WITH_UDPFROMTO
299 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
306 void rad_recv_discard(int sockfd)
309 struct sockaddr_storage src;
310 socklen_t sizeof_src = sizeof(src);
312 (void) recvfrom(sockfd, header, sizeof(header), 0,
313 (struct sockaddr *)&src, &sizeof_src);
317 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
319 ssize_t data_len, packet_len;
321 struct sockaddr_storage src;
322 socklen_t sizeof_src = sizeof(src);
324 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
325 (struct sockaddr *)&src, &sizeof_src);
327 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
332 * Too little data is available, discard the packet.
335 rad_recv_discard(sockfd);
339 } else { /* we got 4 bytes of data. */
341 * See how long the packet says it is.
343 packet_len = (header[2] * 256) + header[3];
346 * The length in the packet says it's less than
347 * a RADIUS header length: discard it.
349 if (packet_len < AUTH_HDR_LEN) {
350 rad_recv_discard(sockfd);
355 * Enforce RFC requirements, for sanity.
356 * Anything after 4k will be discarded.
358 } else if (packet_len > MAX_PACKET_LEN) {
359 rad_recv_discard(sockfd);
366 * Convert AF. If unknown, discard packet.
368 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
369 rad_recv_discard(sockfd);
377 * The packet says it's this long, but the actual UDP
378 * size could still be smaller.
385 * @brief wrapper for recvfrom, which handles recvfromto, IPv6, and all
386 * possible combinations.
388 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
389 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
390 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
392 struct sockaddr_storage src;
393 struct sockaddr_storage dst;
394 socklen_t sizeof_src = sizeof(src);
395 socklen_t sizeof_dst = sizeof(dst);
401 memset(&src, 0, sizeof_src);
402 memset(&dst, 0, sizeof_dst);
405 * Read the length of the packet, from the packet.
406 * This lets us allocate the buffer to use for
407 * reading the rest of the packet.
409 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
410 (struct sockaddr *)&src, &sizeof_src);
412 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
417 * Too little data is available, discard the packet.
420 rad_recv_discard(sockfd);
424 } else { /* we got 4 bytes of data. */
426 * See how long the packet says it is.
428 len = (header[2] * 256) + header[3];
431 * The length in the packet says it's less than
432 * a RADIUS header length: discard it.
434 if (len < AUTH_HDR_LEN) {
435 recvfrom(sockfd, header, sizeof(header), flags,
436 (struct sockaddr *)&src, &sizeof_src);
440 * Enforce RFC requirements, for sanity.
441 * Anything after 4k will be discarded.
443 } else if (len > MAX_PACKET_LEN) {
444 recvfrom(sockfd, header, sizeof(header), flags,
445 (struct sockaddr *)&src, &sizeof_src);
450 packet->data = talloc_array(packet, uint8_t, len);
451 if (!packet->data) return -1;
454 * Receive the packet. The OS will discard any data in the
455 * packet after "len" bytes.
457 #ifdef WITH_UDPFROMTO
458 data_len = recvfromto(sockfd, packet->data, len, flags,
459 (struct sockaddr *)&src, &sizeof_src,
460 (struct sockaddr *)&dst, &sizeof_dst);
462 data_len = recvfrom(sockfd, packet->data, len, flags,
463 (struct sockaddr *)&src, &sizeof_src);
466 * Get the destination address, too.
468 if (getsockname(sockfd, (struct sockaddr *)&dst,
469 &sizeof_dst) < 0) return -1;
475 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
476 return -1; /* Unknown address family, Die Die Die! */
480 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
484 * Different address families should never happen.
486 if (src.ss_family != dst.ss_family) {
494 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
496 * @brief Build an encrypted secret value to return in a reply packet
498 * The secret is hidden by xoring with a MD5 digest
499 * created from the shared secret and the authentication
500 * vector. We put them into MD5 in the reverse order from
501 * that used when encrypting passwords to RADIUS.
504 static void make_secret(uint8_t *digest, uint8_t const *vector,
505 char const *secret, uint8_t const *value)
510 fr_md5_init(&context);
511 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
512 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
513 fr_md5_final(digest, &context);
515 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
516 digest[i] ^= value[i];
520 #define MAX_PASS_LEN (128)
521 static void make_passwd(uint8_t *output, ssize_t *outlen,
522 uint8_t const *input, size_t inlen,
523 char const *secret, uint8_t const *vector)
525 FR_MD5_CTX context, old;
526 uint8_t digest[AUTH_VECTOR_LEN];
527 uint8_t passwd[MAX_PASS_LEN];
532 * If the length is zero, round it up.
536 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
538 memcpy(passwd, input, len);
539 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
545 else if ((len & 0x0f) != 0) {
551 fr_md5_init(&context);
552 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
558 fr_md5_update(&context, vector, AUTH_PASS_LEN);
560 for (n = 0; n < len; n += AUTH_PASS_LEN) {
563 fr_md5_update(&context,
564 passwd + n - AUTH_PASS_LEN,
568 fr_md5_final(digest, &context);
569 for (i = 0; i < AUTH_PASS_LEN; i++) {
570 passwd[i + n] ^= digest[i];
574 memcpy(output, passwd, len);
577 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
578 uint8_t const *input, size_t inlen, size_t room,
579 char const *secret, uint8_t const *vector)
581 FR_MD5_CTX context, old;
582 uint8_t digest[AUTH_VECTOR_LEN];
583 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
590 if (room > 253) room = 253;
593 * Account for 2 bytes of the salt, and round the room
594 * available down to the nearest multiple of 16. Then,
595 * subtract one from that to account for the length byte,
596 * and the resulting number is the upper bound on the data
599 * We could short-cut this calculation just be forcing
600 * inlen to be no more than 239. It would work for all
601 * VSA's, as we don't pack multiple VSA's into one
604 * However, this calculation is more general, if a little
605 * complex. And it will work in the future for all possible
606 * kinds of weird attribute packing.
609 room -= (room & 0x0f);
612 if (inlen > room) inlen = room;
615 * Length of the encrypted data is password length plus
616 * one byte for the length of the password.
619 if ((len & 0x0f) != 0) {
623 *outlen = len + 2; /* account for the salt */
626 * Copy the password over.
628 memcpy(passwd + 3, input, inlen);
629 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
632 * Generate salt. The RFC's say:
634 * The high bit of salt[0] must be set, each salt in a
635 * packet should be unique, and they should be random
637 * So, we set the high bit, add in a counter, and then
638 * add in some CSPRNG data. should be OK..
640 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
642 passwd[1] = fr_rand();
643 passwd[2] = inlen; /* length of the password string */
645 fr_md5_init(&context);
646 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
649 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
650 fr_md5_update(&context, &passwd[0], 2);
652 for (n = 0; n < len; n += AUTH_PASS_LEN) {
655 fr_md5_update(&context,
656 passwd + 2 + n - AUTH_PASS_LEN,
660 fr_md5_final(digest, &context);
662 for (i = 0; i < AUTH_PASS_LEN; i++) {
663 passwd[i + 2 + n] ^= digest[i];
666 memcpy(output, passwd, len + 2);
669 extern int fr_attr_max_tlv;
670 extern int fr_attr_shift[];
671 extern int fr_attr_mask[];
673 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
675 unsigned int tlv1, tlv2;
677 if (nest > fr_attr_max_tlv) return 0;
682 * Keep encoding TLVs which have the same scope.
683 * e.g. two attributes of:
684 * ATTR.TLV1.TLV2.TLV3 = data1
685 * ATTR.TLV1.TLV2.TLV4 = data2
686 * both get put into a container of "ATTR.TLV1.TLV2"
690 * Nothing to follow, we're done.
695 * Not from the same vendor, skip it.
697 if (vp->da->vendor != next->da->vendor) return 0;
700 * In a different TLV space, skip it.
703 tlv2 = next->da->attr;
705 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
706 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
708 if (tlv1 != tlv2) return 0;
714 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
715 RADIUS_PACKET const *original,
716 char const *secret, int nest,
717 VALUE_PAIR const **pvp,
718 uint8_t *start, size_t room);
720 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
721 RADIUS_PACKET const *original,
722 char const *secret, VALUE_PAIR const **pvp,
723 unsigned int attribute, uint8_t *ptr, size_t room);
726 * @brief This is really a sub-function of vp2data_any(). It encodes
727 * the *data* portion of the TLV, and assumes that the encapsulating
728 * attribute has already been encoded.
730 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
731 RADIUS_PACKET const *original,
732 char const *secret, int nest,
733 VALUE_PAIR const **pvp,
734 uint8_t *start, size_t room)
738 uint8_t *ptr = start;
739 VALUE_PAIR const *vp = *pvp;
740 VALUE_PAIR const *svp = vp;
745 if (nest > fr_attr_max_tlv) {
746 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
754 if (room <= 2) return ptr - start;
756 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
760 if (room > 255) my_room = 255;
762 len = vp2data_any(packet, original, secret, nest,
763 &vp, ptr + 2, my_room - 2);
764 if (len < 0) return len;
765 if (len == 0) return ptr - start;
766 /* len can NEVER be more than 253 */
771 if ((fr_debug_flag > 3) && fr_log_fp) {
772 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
773 print_hex_data(ptr + 2, len, 3);
781 if (!do_next_tlv(svp, vp, nest)) break;
785 if ((fr_debug_flag > 3) && fr_log_fp) {
788 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
789 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
797 * @brief Encodes the data portion of an attribute.
798 * @return -1 on error, or the length of the data portion.
800 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
801 RADIUS_PACKET const *original,
802 char const *secret, int nest,
803 VALUE_PAIR const **pvp,
804 uint8_t *start, size_t room)
809 uint8_t *ptr = start;
812 VALUE_PAIR const *vp = *pvp;
817 * See if we need to encode a TLV. The low portion of
818 * the attribute has already been placed into the packer.
819 * If there are still attribute bytes left, then go
820 * encode them as TLVs.
822 * If we cared about the stack, we could unroll the loop.
824 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
825 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
826 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
833 * Set up the default sources for the data.
837 switch(vp->da->type) {
843 fr_strerror_printf("ERROR: Cannot encode NULL data");
849 case PW_TYPE_IPV4_ADDR:
850 case PW_TYPE_IPV6_ADDR:
851 case PW_TYPE_IPV6_PREFIX:
852 case PW_TYPE_IPV4_PREFIX:
853 case PW_TYPE_ABINARY:
854 case PW_TYPE_ETHERNET: /* just in case */
855 data = (uint8_t const *) &vp->data;
859 len = 1; /* just in case */
860 array[0] = vp->vp_byte;
865 len = 2; /* just in case */
866 array[0] = (vp->vp_short >> 8) & 0xff;
867 array[1] = vp->vp_short & 0xff;
871 case PW_TYPE_INTEGER:
872 len = 4; /* just in case */
873 lvalue = htonl(vp->vp_integer);
874 memcpy(array, &lvalue, sizeof(lvalue));
878 case PW_TYPE_INTEGER64:
879 len = 8; /* just in case */
880 lvalue64 = htonll(vp->vp_integer64);
881 data = (uint8_t *) &lvalue64;
885 * There are no tagged date attributes.
888 lvalue = htonl(vp->vp_date);
889 data = (uint8_t const *) &lvalue;
890 len = 4; /* just in case */
897 len = 4; /* just in case */
898 slvalue = htonl(vp->vp_signed);
899 memcpy(array, &slvalue, sizeof(slvalue));
904 default: /* unknown type: ignore it */
905 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
918 * Bound the data to the calling size
920 if (len > (ssize_t) room) len = room;
923 * Encrypt the various password styles
925 * Attributes with encrypted values MUST be less than
928 switch (vp->da->flags.encrypt) {
929 case FLAG_ENCRYPT_USER_PASSWORD:
930 make_passwd(ptr, &len, data, len,
931 secret, packet->vector);
934 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
936 if (vp->da->flags.has_tag) lvalue = 1;
939 * Check if there's enough room. If there isn't,
940 * we discard the attribute.
942 * This is ONLY a problem if we have multiple VSA's
943 * in one Vendor-Specific, though.
945 if (room < (18 + lvalue)) return 0;
947 switch (packet->code) {
948 case PW_CODE_ACCESS_ACCEPT:
949 case PW_CODE_ACCESS_REJECT:
950 case PW_CODE_ACCESS_CHALLENGE:
953 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
957 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
958 make_tunnel_passwd(ptr + lvalue, &len, data, len,
960 secret, original->vector);
962 case PW_CODE_ACCOUNTING_REQUEST:
963 case PW_CODE_DISCONNECT_REQUEST:
964 case PW_CODE_COA_REQUEST:
965 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
966 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
967 secret, packet->vector);
973 * The code above ensures that this attribute
976 case FLAG_ENCRYPT_ASCEND_SECRET:
977 if (len != 16) return 0;
978 make_secret(ptr, packet->vector, secret, data);
979 len = AUTH_VECTOR_LEN;
984 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
985 if (vp->da->type == PW_TYPE_STRING) {
986 if (len > ((ssize_t) (room - 1))) len = room - 1;
989 } else if (vp->da->type == PW_TYPE_INTEGER) {
991 } /* else it can't be any other type */
993 memcpy(ptr, data, len);
995 } /* switch over encryption flags */
998 return len + (ptr - start);
1001 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1002 uint8_t *ptr, int hdr_len, ssize_t len,
1003 int flag_offset, int vsa_offset)
1005 int check_len = len - ptr[1];
1006 int total = len + hdr_len;
1009 * Pass 1: Check if the addition of the headers
1010 * overflows the available room. If so, return
1011 * what we were capable of encoding.
1014 while (check_len > (255 - hdr_len)) {
1016 check_len -= (255 - hdr_len);
1020 * Note that this results in a number of attributes maybe
1021 * being marked as "encoded", but which aren't in the
1022 * packet. Oh well. The solution is to fix the
1023 * "vp2data_any" function to take into account the header
1026 if ((ptr + ptr[1] + total) > end) {
1027 return (ptr + ptr[1]) - start;
1031 * Pass 2: Now that we know there's enough room,
1032 * re-arrange the data to form a set of valid
1033 * RADIUS attributes.
1036 int sublen = 255 - ptr[1];
1038 if (len <= sublen) {
1043 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1044 memcpy(ptr + 255, ptr, hdr_len);
1046 if (vsa_offset) ptr[vsa_offset] += sublen;
1047 ptr[flag_offset] |= 0x80;
1051 if (vsa_offset) ptr[vsa_offset] = 3;
1055 if (vsa_offset) ptr[vsa_offset] += len;
1057 return (ptr + ptr[1]) - start;
1062 * @brief Encode an "extended" attribute.
1064 int rad_vp2extended(RADIUS_PACKET const *packet,
1065 RADIUS_PACKET const *original,
1066 char const *secret, VALUE_PAIR const **pvp,
1067 uint8_t *ptr, size_t room)
1071 uint8_t *start = ptr;
1072 VALUE_PAIR const *vp = *pvp;
1076 if (!vp->da->flags.extended) {
1077 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1082 * The attribute number is encoded into the upper 8 bits
1085 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1087 if (!vp->da->flags.long_extended) {
1088 if (room < 3) return 0;
1091 ptr[2] = vp->da->attr & fr_attr_mask[0];
1094 if (room < 4) return 0;
1097 ptr[2] = vp->da->attr & fr_attr_mask[0];
1102 * Only "flagged" attributes can be longer than one
1105 if (!vp->da->flags.long_extended && (room > 255)) {
1112 if (vp->da->flags.evs) {
1113 uint8_t *evs = ptr + ptr[1];
1115 if (room < (size_t) (ptr[1] + 5)) return 0;
1119 evs[0] = 0; /* always zero */
1120 evs[1] = (vp->da->vendor >> 16) & 0xff;
1121 evs[2] = (vp->da->vendor >> 8) & 0xff;
1122 evs[3] = vp->da->vendor & 0xff;
1123 evs[4] = vp->da->attr & fr_attr_mask[0];
1129 len = vp2data_any(packet, original, secret, 0,
1130 pvp, ptr + ptr[1], room - hdr_len);
1131 if (len <= 0) return len;
1134 * There may be more than 252 octets of data encoded in
1135 * the attribute. If so, move the data up in the packet,
1136 * and copy the existing header over. Set the "M" flag ONLY
1137 * after copying the rest of the data.
1139 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1140 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1146 if ((fr_debug_flag > 3) && fr_log_fp) {
1149 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1150 if (!vp->da->flags.long_extended) {
1151 fprintf(fr_log_fp, "%02x ", ptr[2]);
1154 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1158 if (vp->da->flags.evs) {
1159 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1160 ptr[jump], ptr[jump + 1],
1161 ptr[jump + 2], ptr[jump + 3],
1162 ((ptr[jump + 1] << 16) |
1163 (ptr[jump + 2] << 8) |
1169 print_hex_data(ptr + jump, len, 3);
1173 return (ptr + ptr[1]) - start;
1178 * @brief Encode a WiMAX attribute.
1180 int rad_vp2wimax(RADIUS_PACKET const *packet,
1181 RADIUS_PACKET const *original,
1182 char const *secret, VALUE_PAIR const **pvp,
1183 uint8_t *ptr, size_t room)
1188 uint8_t *start = ptr;
1189 VALUE_PAIR const *vp = *pvp;
1194 * Double-check for WiMAX format.
1196 if (!vp->da->flags.wimax) {
1197 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1202 * Not enough room for:
1203 * attr, len, vendor-id, vsa, vsalen, continuation
1205 if (room < 9) return 0;
1208 * Build the Vendor-Specific header
1211 ptr[0] = PW_VENDOR_SPECIFIC;
1213 lvalue = htonl(vp->da->vendor);
1214 memcpy(ptr + 2, &lvalue, 4);
1215 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1217 ptr[8] = 0; /* continuation byte */
1221 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1223 if (len <= 0) return len;
1226 * There may be more than 252 octets of data encoded in
1227 * the attribute. If so, move the data up in the packet,
1228 * and copy the existing header over. Set the "C" flag
1229 * ONLY after copying the rest of the data.
1231 if (len > (255 - ptr[1])) {
1232 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1239 if ((fr_debug_flag > 3) && fr_log_fp) {
1240 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1242 ptr[2], ptr[3], ptr[4], ptr[5],
1243 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1244 ptr[6], ptr[7], ptr[8]);
1245 print_hex_data(ptr + 9, len, 3);
1249 return (ptr + ptr[1]) - start;
1253 * @brief Encode an RFC format attribute, with the "concat" flag set.
1255 * If there isn't enough room in the packet, the data is
1258 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1259 UNUSED RADIUS_PACKET const *original,
1260 UNUSED char const *secret, VALUE_PAIR const **pvp,
1261 unsigned int attribute, uint8_t *start, size_t room)
1263 uint8_t *ptr = start;
1266 VALUE_PAIR const *vp = *pvp;
1276 if (room <= 2) break;
1283 /* no more than 253 octets */
1284 if (left > 253) left = 253;
1286 /* no more than "room" octets */
1287 if (room < (left + 2)) left = room - 2;
1289 memcpy(ptr + 2, p, left);
1292 if ((fr_debug_flag > 3) && fr_log_fp) {
1293 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1294 print_hex_data(ptr + 2, len, 3);
1309 * @brief Encode an RFC format TLV.
1311 * This could be a standard attribute,
1312 * or a TLV data type. If it's a standard attribute, then
1313 * vp->da->attr == attribute. Otherwise, attribute may be
1316 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1317 RADIUS_PACKET const *original,
1318 char const *secret, VALUE_PAIR const **pvp,
1319 unsigned int attribute, uint8_t *ptr, size_t room)
1323 if (room <= 2) return 0;
1325 ptr[0] = attribute & 0xff;
1328 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1330 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1331 if (len <= 0) return len;
1336 if ((fr_debug_flag > 3) && fr_log_fp) {
1337 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1338 print_hex_data(ptr + 2, len, 3);
1347 * @brief Encode a VSA which is a TLV. If it's in the RFC format, call
1348 * vp2attr_rfc. Otherwise, encode it here.
1350 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1351 RADIUS_PACKET const *original,
1352 char const *secret, VALUE_PAIR const **pvp,
1353 unsigned int attribute, unsigned int vendor,
1354 uint8_t *ptr, size_t room)
1358 VALUE_PAIR const *vp = *pvp;
1362 * Unknown vendor: RFC format.
1363 * Known vendor and RFC format: go do that.
1365 dv = dict_vendorbyvalue(vendor);
1367 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1368 return vp2attr_rfc(packet, original, secret, pvp,
1369 attribute, ptr, room);
1374 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1375 " type %u", (unsigned) dv->type);
1379 ptr[0] = 0; /* attr must be 24-bit */
1380 ptr[1] = (attribute >> 16) & 0xff;
1381 ptr[2] = (attribute >> 8) & 0xff;
1382 ptr[3] = attribute & 0xff;
1386 ptr[0] = (attribute >> 8) & 0xff;
1387 ptr[1] = attribute & 0xff;
1391 ptr[0] = attribute & 0xff;
1395 switch (dv->length) {
1397 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1398 " length %u", (unsigned) dv->length);
1406 ptr[dv->type + 1] = dv->type + 2;
1410 ptr[dv->type] = dv->type + 1;
1415 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1416 room = 255 - (dv->type + dv->length);
1419 len = vp2data_any(packet, original, secret, 0, pvp,
1420 ptr + dv->type + dv->length, room);
1421 if (len <= 0) return len;
1423 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1426 if ((fr_debug_flag > 3) && fr_log_fp) {
1432 if ((fr_debug_flag > 3) && fr_log_fp)
1433 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1434 ptr[0], ptr[1], ptr[2], ptr[3]);
1438 if ((fr_debug_flag > 3) && fr_log_fp)
1439 fprintf(fr_log_fp, "\t\t%02x%02x ",
1444 if ((fr_debug_flag > 3) && fr_log_fp)
1445 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1449 switch (dv->length) {
1454 fprintf(fr_log_fp, " ");
1458 fprintf(fr_log_fp, "%02x ",
1463 fprintf(fr_log_fp, "%02x%02x ",
1464 ptr[dv->type], ptr[dv->type] + 1);
1468 print_hex_data(ptr + dv->type + dv->length, len, 3);
1472 return dv->type + dv->length + len;
1477 * @brief Encode a Vendor-Specific attribute.
1479 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1480 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1485 VALUE_PAIR const *vp = *pvp;
1489 * Double-check for WiMAX format.
1491 if (vp->da->flags.wimax) {
1492 return rad_vp2wimax(packet, original, secret, pvp,
1496 if (vp->da->vendor > FR_MAX_VENDOR) {
1497 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1502 * Not enough room for:
1503 * attr, len, vendor-id
1505 if (room < 6) return 0;
1508 * Build the Vendor-Specific header
1510 ptr[0] = PW_VENDOR_SPECIFIC;
1512 lvalue = htonl(vp->da->vendor);
1513 memcpy(ptr + 2, &lvalue, 4);
1515 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1517 len = vp2attr_vsa(packet, original, secret, pvp,
1518 vp->da->attr, vp->da->vendor,
1519 ptr + ptr[1], room);
1520 if (len < 0) return len;
1523 if ((fr_debug_flag > 3) && fr_log_fp) {
1524 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1526 ptr[2], ptr[3], ptr[4], ptr[5],
1527 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1528 print_hex_data(ptr + 6, len, 3);
1539 * @brief Encode an RFC standard attribute 1..255
1541 int rad_vp2rfc(RADIUS_PACKET const *packet,
1542 RADIUS_PACKET const *original,
1543 char const *secret, VALUE_PAIR const **pvp,
1544 uint8_t *ptr, size_t room)
1546 VALUE_PAIR const *vp = *pvp;
1550 if (vp->da->vendor != 0) {
1551 fr_strerror_printf("rad_vp2rfc called with VSA");
1555 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1556 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1561 * Only CUI is allowed to have zero length.
1564 if ((vp->length == 0) &&
1565 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1566 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1574 * Message-Authenticator is hard-coded.
1576 if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1577 if (room < 18) return -1;
1580 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1582 memset(ptr + 2, 0, 16);
1584 if ((fr_debug_flag > 3) && fr_log_fp) {
1585 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1589 *pvp = (*pvp)->next;
1594 * EAP-Message is special.
1596 if (vp->da->flags.concat && (vp->length > 253)) {
1597 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1601 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1605 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1606 RADIUS_PACKET const *original,
1607 char const *secret, VALUE_PAIR const **pvp,
1608 uint8_t *start, size_t room)
1611 VALUE_PAIR const *vp = *pvp;
1615 if (!vp->da->flags.is_tlv) {
1616 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1620 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1621 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1625 if (room < 5) return 0;
1628 * Encode the first level of TLVs
1630 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1632 start[2] = vp->da->attr & fr_attr_mask[0];
1635 len = vp2data_any(packet, original, secret, 0, pvp,
1636 start + 4, room - 4);
1637 if (len <= 0) return len;
1650 * @brief Parse a data structure into a RADIUS attribute.
1652 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1653 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1656 VALUE_PAIR const *vp;
1658 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1665 * RFC format attributes take the fast path.
1667 if (!vp->da->vendor) {
1668 if (vp->da->attr > 255) return 0;
1670 return rad_vp2rfc(packet, original, secret, pvp,
1674 if (vp->da->flags.extended) {
1675 return rad_vp2extended(packet, original, secret, pvp,
1680 * The upper 8 bits of the vendor number are the standard
1681 * space attribute which is a TLV.
1683 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1684 return rad_vp2rfctlv(packet, original, secret, pvp,
1688 if (vp->da->flags.wimax) {
1689 return rad_vp2wimax(packet, original, secret, pvp,
1693 return rad_vp2vsa(packet, original, secret, pvp,
1699 * @brief Encode a packet.
1701 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1704 radius_packet_t *hdr;
1706 uint16_t total_length;
1708 VALUE_PAIR const *reply;
1710 char ip_src_buffer[INET6_ADDRSTRLEN];
1711 char ip_dst_buffer[INET6_ADDRSTRLEN];
1714 * A 4K packet, aligned on 64-bits.
1716 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1718 if (is_radius_code(packet->code)) {
1719 what = fr_packet_codes[packet->code];
1724 DEBUG("Sending %s Id %d from %s:%u to %s:%u\n",
1726 inet_ntop(packet->src_ipaddr.af,
1727 &packet->src_ipaddr.ipaddr,
1728 ip_src_buffer, sizeof(ip_src_buffer)),
1730 inet_ntop(packet->dst_ipaddr.af,
1731 &packet->dst_ipaddr.ipaddr,
1732 ip_dst_buffer, sizeof(ip_dst_buffer)),
1736 * Double-check some things based on packet code.
1738 switch (packet->code) {
1739 case PW_CODE_ACCESS_ACCEPT:
1740 case PW_CODE_ACCESS_REJECT:
1741 case PW_CODE_ACCESS_CHALLENGE:
1743 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1749 * These packet vectors start off as all zero.
1751 case PW_CODE_ACCOUNTING_REQUEST:
1752 case PW_CODE_DISCONNECT_REQUEST:
1753 case PW_CODE_COA_REQUEST:
1754 memset(packet->vector, 0, sizeof(packet->vector));
1762 * Use memory on the stack, until we know how
1763 * large the packet will be.
1765 hdr = (radius_packet_t *) data;
1768 * Build standard header
1770 hdr->code = packet->code;
1771 hdr->id = packet->id;
1773 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1775 total_length = AUTH_HDR_LEN;
1778 * Load up the configuration values for the user
1784 * FIXME: Loop twice over the reply list. The first time,
1785 * calculate the total length of data. The second time,
1786 * allocate the memory, and fill in the VP's.
1788 * Hmm... this may be slower than just doing a small
1793 * Loop over the reply attributes for the packet.
1795 reply = packet->vps;
1798 char const *last_name = NULL;
1803 * Ignore non-wire attributes, but allow extended
1806 if ((reply->da->vendor == 0) &&
1807 ((reply->da->attr & 0xFFFF) >= 256) &&
1808 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1811 * Permit the admin to send BADLY formatted
1812 * attributes with a debug build.
1814 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1815 memcpy(ptr, reply->vp_octets, reply->length);
1816 len = reply->length;
1817 reply = reply->next;
1821 reply = reply->next;
1826 * Set the Message-Authenticator to the correct
1827 * length and initial value.
1829 if (reply->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1831 * Cache the offset to the
1832 * Message-Authenticator
1834 packet->offset = total_length;
1837 last_len = reply->length;
1839 last_name = reply->da->name;
1841 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1842 ((uint8_t *) data) + sizeof(data) - ptr);
1843 if (len < 0) return -1;
1846 * Failed to encode the attribute, likely because
1847 * the packet is full.
1850 if (last_len != 0) {
1851 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1854 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1859 next: /* Used only for Raw-Attribute */
1862 total_length += len;
1863 } /* done looping over all attributes */
1866 * Fill in the rest of the fields, and copy the data over
1867 * from the local stack to the newly allocated memory.
1869 * Yes, all this 'memcpy' is slow, but it means
1870 * that we only allocate the minimum amount of
1871 * memory for a request.
1873 packet->data_len = total_length;
1874 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1875 if (!packet->data) {
1876 fr_strerror_printf("Out of memory");
1880 memcpy(packet->data, hdr, packet->data_len);
1881 hdr = (radius_packet_t *) packet->data;
1883 total_length = htons(total_length);
1884 memcpy(hdr->length, &total_length, sizeof(total_length));
1891 * @brief Sign a previously encoded packet.
1893 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1896 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1899 * It wasn't assigned an Id, this is bad!
1901 if (packet->id < 0) {
1902 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1906 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1907 (packet->offset < 0)) {
1908 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1913 * If there's a Message-Authenticator, update it
1914 * now, BEFORE updating the authentication vector.
1916 if (packet->offset > 0) {
1917 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1919 switch (packet->code) {
1920 case PW_CODE_ACCOUNTING_RESPONSE:
1921 if (original && original->code == PW_CODE_STATUS_SERVER) {
1925 case PW_CODE_ACCOUNTING_REQUEST:
1926 case PW_CODE_DISCONNECT_REQUEST:
1927 case PW_CODE_DISCONNECT_ACK:
1928 case PW_CODE_DISCONNECT_NAK:
1929 case PW_CODE_COA_REQUEST:
1930 case PW_CODE_COA_ACK:
1931 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1935 case PW_CODE_ACCESS_ACCEPT:
1936 case PW_CODE_ACCESS_REJECT:
1937 case PW_CODE_ACCESS_CHALLENGE:
1939 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1942 memcpy(hdr->vector, original->vector,
1946 default: /* others have vector already set to zero */
1952 * Set the authentication vector to zero,
1953 * calculate the HMAC, and put it
1954 * into the Message-Authenticator
1957 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1958 (uint8_t const *) secret, strlen(secret));
1959 memcpy(packet->data + packet->offset + 2,
1960 calc_auth_vector, AUTH_VECTOR_LEN);
1963 * Copy the original request vector back
1964 * to the raw packet.
1966 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1970 * Switch over the packet code, deciding how to
1973 switch (packet->code) {
1975 * Request packets are not signed, bur
1976 * have a random authentication vector.
1978 case PW_CODE_ACCESS_REQUEST:
1979 case PW_CODE_STATUS_SERVER:
1983 * Reply packets are signed with the
1984 * authentication vector of the request.
1991 fr_md5_init(&context);
1992 fr_md5_update(&context, packet->data, packet->data_len);
1993 fr_md5_update(&context, (uint8_t const *) secret,
1995 fr_md5_final(digest, &context);
1997 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1998 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2001 }/* switch over packet codes */
2007 * @brief Reply to the request. Also attach
2008 * reply attribute value pairs and any user message provided.
2010 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2015 char ip_src_buffer[128];
2016 char ip_dst_buffer[128];
2019 * Maybe it's a fake packet. Don't send it.
2021 if (!packet || (packet->sockfd < 0)) {
2025 if (is_radius_code(packet->code)) {
2026 what = fr_packet_codes[packet->code];
2032 * First time through, allocate room for the packet
2034 if (!packet->data) {
2036 * Encode the packet.
2038 if (rad_encode(packet, original, secret) < 0) {
2043 * Re-sign it, including updating the
2044 * Message-Authenticator.
2046 if (rad_sign(packet, original, secret) < 0) {
2051 * If packet->data points to data, then we print out
2052 * the VP list again only for debugging.
2054 } else if (fr_debug_flag) {
2055 DEBUG("Sending %s Id %d from %s:%u to %s:%u\n", what,
2057 inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr,
2058 ip_src_buffer, sizeof(ip_src_buffer)),
2060 inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr,
2061 ip_dst_buffer, sizeof(ip_dst_buffer)),
2064 for (reply = packet->vps; reply; reply = reply->next) {
2065 if ((reply->da->vendor == 0) &&
2066 ((reply->da->attr & 0xFFFF) > 0xff)) continue;
2072 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2077 * If the socket is TCP, call write(). Calling sendto()
2078 * is allowed on some platforms, but it's not nice. Even
2079 * worse, if UDPFROMTO is defined, we *can't* use it on
2080 * TCP sockets. So... just call write().
2082 if (packet->proto == IPPROTO_TCP) {
2085 rcode = write(packet->sockfd, packet->data, packet->data_len);
2086 if (rcode >= 0) return rcode;
2088 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2094 * And send it on it's way.
2096 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2097 &packet->src_ipaddr, packet->src_port,
2098 &packet->dst_ipaddr, packet->dst_port);
2102 * @brief Do a comparison of two authentication digests by comparing
2105 * Otherwise, the server can be subject to
2106 * timing attacks that allow attackers find a valid message
2109 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2111 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2116 for (i = 0; i < length; i++) {
2117 result |= a[i] ^ b[i];
2120 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2125 * @brief Validates the requesting client NAS. Calculates the
2126 * Request Authenticator based on the clients private key.
2128 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2130 uint8_t digest[AUTH_VECTOR_LEN];
2134 * Zero out the auth_vector in the received packet.
2135 * Then append the shared secret to the received packet,
2136 * and calculate the MD5 sum. This must be the same
2137 * as the original MD5 sum (packet->vector).
2139 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2142 * MD5(packet + secret);
2144 fr_md5_init(&context);
2145 fr_md5_update(&context, packet->data, packet->data_len);
2146 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2147 fr_md5_final(digest, &context);
2150 * Return 0 if OK, 2 if not OK.
2152 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2158 * @brief Validates the requesting client NAS. Calculates the
2159 * Response Authenticator based on the clients private key.
2161 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2164 uint8_t calc_digest[AUTH_VECTOR_LEN];
2170 if (original == NULL) {
2175 * Copy the original vector in place.
2177 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2180 * MD5(packet + secret);
2182 fr_md5_init(&context);
2183 fr_md5_update(&context, packet->data, packet->data_len);
2184 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2185 fr_md5_final(calc_digest, &context);
2188 * Copy the packet's vector back to the packet.
2190 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2193 * Return 0 if OK, 2 if not OK.
2195 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2201 * @brief Check if a set of RADIUS formatted TLVs are OK.
2203 int rad_tlv_ok(uint8_t const *data, size_t length,
2204 size_t dv_type, size_t dv_length)
2206 uint8_t const *end = data + length;
2208 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2209 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2213 while (data < end) {
2216 if ((data + dv_type + dv_length) > end) {
2217 fr_strerror_printf("Attribute header overflow");
2223 if ((data[0] == 0) && (data[1] == 0) &&
2224 (data[2] == 0) && (data[3] == 0)) {
2226 fr_strerror_printf("Invalid attribute 0");
2231 fr_strerror_printf("Invalid attribute > 2^24");
2237 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2241 if (data[0] == 0) goto zero;
2245 fr_strerror_printf("Internal sanity check failed");
2249 switch (dv_length) {
2254 if (data[dv_type + 1] != 0) {
2255 fr_strerror_printf("Attribute is longer than 256 octets");
2260 attrlen = data[dv_type + dv_length - 1];
2265 fr_strerror_printf("Internal sanity check failed");
2269 if (attrlen < (dv_type + dv_length)) {
2270 fr_strerror_printf("Attribute header has invalid length");
2274 if (attrlen > length) {
2275 fr_strerror_printf("Attribute overflows container");
2287 /** See if the data pointed to by PTR is a valid RADIUS packet.
2289 * Packet is not 'const * const' because we may update data_len, if there's more data
2290 * in the UDP packet than in the RADIUS packet.
2292 * @param packet to check
2293 * @param flags to control decoding
2294 * @param reason if not NULL, will have the failure reason written to where it points.
2295 * @return bool, true on success, false on failure.
2297 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2302 radius_packet_t *hdr;
2303 char host_ipaddr[128];
2304 bool require_ma = false;
2305 bool seen_ma = false;
2306 uint32_t num_attributes;
2307 decode_fail_t failure = DECODE_FAIL_NONE;
2310 * Check for packets smaller than the packet header.
2312 * RFC 2865, Section 3., subsection 'length' says:
2314 * "The minimum length is 20 ..."
2316 if (packet->data_len < AUTH_HDR_LEN) {
2317 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2318 inet_ntop(packet->src_ipaddr.af,
2319 &packet->src_ipaddr.ipaddr,
2320 host_ipaddr, sizeof(host_ipaddr)),
2321 packet->data_len, AUTH_HDR_LEN);
2322 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2328 * Check for packets with mismatched size.
2329 * i.e. We've received 128 bytes, and the packet header
2330 * says it's 256 bytes long.
2332 totallen = (packet->data[2] << 8) | packet->data[3];
2333 hdr = (radius_packet_t *)packet->data;
2336 * Code of 0 is not understood.
2337 * Code of 16 or greate is not understood.
2339 if ((hdr->code == 0) ||
2340 (hdr->code >= FR_MAX_PACKET_CODE)) {
2341 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2342 inet_ntop(packet->src_ipaddr.af,
2343 &packet->src_ipaddr.ipaddr,
2344 host_ipaddr, sizeof(host_ipaddr)),
2346 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2351 * Message-Authenticator is required in Status-Server
2352 * packets, otherwise they can be trivially forged.
2354 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2357 * It's also required if the caller asks for it.
2359 if (flags) require_ma = true;
2362 * Repeat the length checks. This time, instead of
2363 * looking at the data we received, look at the value
2364 * of the 'length' field inside of the packet.
2366 * Check for packets smaller than the packet header.
2368 * RFC 2865, Section 3., subsection 'length' says:
2370 * "The minimum length is 20 ..."
2372 if (totallen < AUTH_HDR_LEN) {
2373 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2374 inet_ntop(packet->src_ipaddr.af,
2375 &packet->src_ipaddr.ipaddr,
2376 host_ipaddr, sizeof(host_ipaddr)),
2377 totallen, AUTH_HDR_LEN);
2378 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2383 * And again, for the value of the 'length' field.
2385 * RFC 2865, Section 3., subsection 'length' says:
2387 * " ... and maximum length is 4096."
2389 * HOWEVER. This requirement is for the network layer.
2390 * If the code gets here, we assume that a well-formed
2391 * packet is an OK packet.
2393 * We allow both the UDP data length, and the RADIUS
2394 * "length" field to contain up to 64K of data.
2398 * RFC 2865, Section 3., subsection 'length' says:
2400 * "If the packet is shorter than the Length field
2401 * indicates, it MUST be silently discarded."
2403 * i.e. No response to the NAS.
2405 if (packet->data_len < totallen) {
2406 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2407 inet_ntop(packet->src_ipaddr.af,
2408 &packet->src_ipaddr.ipaddr,
2409 host_ipaddr, sizeof(host_ipaddr)),
2410 packet->data_len, totallen);
2411 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2416 * RFC 2865, Section 3., subsection 'length' says:
2418 * "Octets outside the range of the Length field MUST be
2419 * treated as padding and ignored on reception."
2421 if (packet->data_len > totallen) {
2423 * We're shortening the packet below, but just
2424 * to be paranoid, zero out the extra data.
2426 memset(packet->data + totallen, 0, packet->data_len - totallen);
2427 packet->data_len = totallen;
2431 * Walk through the packet's attributes, ensuring that
2432 * they add up EXACTLY to the size of the packet.
2434 * If they don't, then the attributes either under-fill
2435 * or over-fill the packet. Any parsing of the packet
2436 * is impossible, and will result in unknown side effects.
2438 * This would ONLY happen with buggy RADIUS implementations,
2439 * or with an intentional attack. Either way, we do NOT want
2440 * to be vulnerable to this problem.
2443 count = totallen - AUTH_HDR_LEN;
2448 * We need at least 2 bytes to check the
2452 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2453 inet_ntop(packet->src_ipaddr.af,
2454 &packet->src_ipaddr.ipaddr,
2455 host_ipaddr, sizeof(host_ipaddr)));
2456 failure = DECODE_FAIL_HEADER_OVERFLOW;
2461 * Attribute number zero is NOT defined.
2464 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2465 inet_ntop(packet->src_ipaddr.af,
2466 &packet->src_ipaddr.ipaddr,
2467 host_ipaddr, sizeof(host_ipaddr)));
2468 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2473 * Attributes are at LEAST as long as the ID & length
2474 * fields. Anything shorter is an invalid attribute.
2477 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2478 inet_ntop(packet->src_ipaddr.af,
2479 &packet->src_ipaddr.ipaddr,
2480 host_ipaddr, sizeof(host_ipaddr)),
2482 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2487 * If there are fewer bytes in the packet than in the
2488 * attribute, it's a bad packet.
2490 if (count < attr[1]) {
2491 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2492 inet_ntop(packet->src_ipaddr.af,
2493 &packet->src_ipaddr.ipaddr,
2494 host_ipaddr, sizeof(host_ipaddr)),
2496 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2501 * Sanity check the attributes for length.
2504 default: /* don't do anything by default */
2508 * If there's an EAP-Message, we require
2509 * a Message-Authenticator.
2511 case PW_EAP_MESSAGE:
2515 case PW_MESSAGE_AUTHENTICATOR:
2516 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2517 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2518 inet_ntop(packet->src_ipaddr.af,
2519 &packet->src_ipaddr.ipaddr,
2520 host_ipaddr, sizeof(host_ipaddr)),
2522 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2530 * FIXME: Look up the base 255 attributes in the
2531 * dictionary, and switch over their type. For
2532 * integer/date/ip, the attribute length SHOULD
2535 count -= attr[1]; /* grab the attribute length */
2537 num_attributes++; /* seen one more attribute */
2541 * If the attributes add up to a packet, it's allowed.
2543 * If not, we complain, and throw the packet away.
2546 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2547 inet_ntop(packet->src_ipaddr.af,
2548 &packet->src_ipaddr.ipaddr,
2549 host_ipaddr, sizeof(host_ipaddr)));
2550 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2555 * If we're configured to look for a maximum number of
2556 * attributes, and we've seen more than that maximum,
2557 * then throw the packet away, as a possible DoS.
2559 if ((fr_max_attributes > 0) &&
2560 (num_attributes > fr_max_attributes)) {
2561 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2562 inet_ntop(packet->src_ipaddr.af,
2563 &packet->src_ipaddr.ipaddr,
2564 host_ipaddr, sizeof(host_ipaddr)),
2565 num_attributes, fr_max_attributes);
2566 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2571 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2573 * A packet with an EAP-Message attribute MUST also have
2574 * a Message-Authenticator attribute.
2576 * A Message-Authenticator all by itself is OK, though.
2578 * Similarly, Status-Server packets MUST contain
2579 * Message-Authenticator attributes.
2581 if (require_ma && !seen_ma) {
2582 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2583 inet_ntop(packet->src_ipaddr.af,
2584 &packet->src_ipaddr.ipaddr,
2585 host_ipaddr, sizeof(host_ipaddr)));
2586 failure = DECODE_FAIL_MA_MISSING;
2591 * Fill RADIUS header fields
2593 packet->code = hdr->code;
2594 packet->id = hdr->id;
2595 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2603 return (failure == DECODE_FAIL_NONE);
2608 * @brief Receive UDP client requests, and fill in
2609 * the basics of a RADIUS_PACKET structure.
2611 RADIUS_PACKET *rad_recv(int fd, int flags)
2615 RADIUS_PACKET *packet;
2618 * Allocate the new request data structure
2620 packet = rad_alloc(NULL, false);
2622 fr_strerror_printf("out of memory");
2627 sock_flags = MSG_PEEK;
2631 data_len = rad_recvfrom(fd, packet, sock_flags,
2632 &packet->src_ipaddr, &packet->src_port,
2633 &packet->dst_ipaddr, &packet->dst_port);
2636 * Check for socket errors.
2639 fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno));
2640 /* packet->data is NULL */
2644 packet->data_len = data_len; /* unsigned vs signed */
2647 * If the packet is too big, then rad_recvfrom did NOT
2648 * allocate memory. Instead, it just discarded the
2651 if (packet->data_len > MAX_PACKET_LEN) {
2652 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes");
2653 /* packet->data is NULL */
2659 * Read no data. Continue.
2660 * This check is AFTER the MAX_PACKET_LEN check above, because
2661 * if the packet is larger than MAX_PACKET_LEN, we also have
2662 * packet->data == NULL
2664 if ((packet->data_len == 0) || !packet->data) {
2665 fr_strerror_printf("Empty packet: Socket is not ready");
2671 * See if it's a well-formed RADIUS packet.
2673 if (!rad_packet_ok(packet, flags, NULL)) {
2679 * Remember which socket we read the packet from.
2681 packet->sockfd = fd;
2684 * FIXME: Do even more filtering by only permitting
2685 * certain IP's. The problem is that we don't know
2686 * how to do this properly for all possible clients...
2690 * Explicitely set the VP list to empty.
2694 if (fr_debug_flag) {
2695 char src_ipaddr[128];
2696 char dst_ipaddr[128];
2698 if (is_radius_code(packet->code)) {
2699 DEBUG("Received %s Id %d from %s:%d to %s:%d length %d\n",
2700 fr_packet_codes[packet->code],
2702 inet_ntop(packet->src_ipaddr.af,
2703 &packet->src_ipaddr.ipaddr,
2704 src_ipaddr, sizeof(src_ipaddr)),
2706 inet_ntop(packet->dst_ipaddr.af,
2707 &packet->dst_ipaddr.ipaddr,
2708 dst_ipaddr, sizeof(dst_ipaddr)),
2710 (int) packet->data_len);
2712 DEBUG("Received code %d Id %d from %s:%d to %s:%d length %d\n",
2715 inet_ntop(packet->src_ipaddr.af,
2716 &packet->src_ipaddr.ipaddr,
2717 src_ipaddr, sizeof(src_ipaddr)),
2719 inet_ntop(packet->dst_ipaddr.af,
2720 &packet->dst_ipaddr.ipaddr,
2721 dst_ipaddr, sizeof(dst_ipaddr)),
2723 (int) packet->data_len);
2728 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2736 * @brief Verify the Request/Response Authenticator
2737 * (and Message-Authenticator if present) of a packet.
2739 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2746 if (!packet || !packet->data) return -1;
2749 * Before we allocate memory for the attributes, do more
2752 ptr = packet->data + AUTH_HDR_LEN;
2753 length = packet->data_len - AUTH_HDR_LEN;
2754 while (length > 0) {
2755 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2756 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2761 default: /* don't do anything. */
2765 * Note that more than one Message-Authenticator
2766 * attribute is invalid.
2768 case PW_MESSAGE_AUTHENTICATOR:
2769 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2770 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2772 switch (packet->code) {
2776 case PW_CODE_ACCOUNTING_RESPONSE:
2778 (original->code == PW_CODE_STATUS_SERVER)) {
2782 case PW_CODE_ACCOUNTING_REQUEST:
2783 case PW_CODE_DISCONNECT_REQUEST:
2784 case PW_CODE_COA_REQUEST:
2785 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2789 case PW_CODE_ACCESS_ACCEPT:
2790 case PW_CODE_ACCESS_REJECT:
2791 case PW_CODE_ACCESS_CHALLENGE:
2792 case PW_CODE_DISCONNECT_ACK:
2793 case PW_CODE_DISCONNECT_NAK:
2794 case PW_CODE_COA_ACK:
2795 case PW_CODE_COA_NAK:
2797 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet");
2800 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2804 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2805 (uint8_t const *) secret, strlen(secret));
2806 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2807 sizeof(calc_auth_vector)) != 0) {
2809 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2810 inet_ntop(packet->src_ipaddr.af,
2811 &packet->src_ipaddr.ipaddr,
2812 buffer, sizeof(buffer)));
2813 /* Silently drop packet, according to RFC 3579 */
2815 } /* else the message authenticator was good */
2818 * Reinitialize Authenticators.
2820 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2821 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2823 } /* switch over the attributes */
2827 } /* loop over the packet, sanity checking the attributes */
2830 * It looks like a RADIUS packet, but we don't know what it is
2831 * so can't validate the authenticators.
2833 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2835 fr_strerror_printf("Received Unknown packet code %d "
2836 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2838 inet_ntop(packet->src_ipaddr.af,
2839 &packet->src_ipaddr.ipaddr,
2840 buffer, sizeof(buffer)),
2846 * Calculate and/or verify Request or Response Authenticator.
2848 switch (packet->code) {
2852 case PW_CODE_ACCESS_REQUEST:
2853 case PW_CODE_STATUS_SERVER:
2855 * The authentication vector is random
2856 * nonsense, invented by the client.
2860 case PW_CODE_COA_REQUEST:
2861 case PW_CODE_DISCONNECT_REQUEST:
2862 case PW_CODE_ACCOUNTING_REQUEST:
2863 if (calc_acctdigest(packet, secret) > 1) {
2864 fr_strerror_printf("Received %s packet "
2865 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2866 fr_packet_codes[packet->code],
2867 inet_ntop(packet->src_ipaddr.af,
2868 &packet->src_ipaddr.ipaddr,
2869 buffer, sizeof(buffer)));
2874 /* Verify the reply digest */
2875 case PW_CODE_ACCESS_ACCEPT:
2876 case PW_CODE_ACCESS_REJECT:
2877 case PW_CODE_ACCESS_CHALLENGE:
2878 case PW_CODE_ACCOUNTING_RESPONSE:
2879 case PW_CODE_DISCONNECT_ACK:
2880 case PW_CODE_DISCONNECT_NAK:
2881 case PW_CODE_COA_ACK:
2882 case PW_CODE_COA_NAK:
2883 rcode = calc_replydigest(packet, original, secret);
2885 fr_strerror_printf("Received %s packet "
2886 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2887 fr_packet_codes[packet->code],
2888 inet_ntop(packet->src_ipaddr.af,
2889 &packet->src_ipaddr.ipaddr,
2890 buffer, sizeof(buffer)),
2897 fr_strerror_printf("Received Unknown packet code %d "
2898 "from client %s port %d: Cannot validate Request/Response Authenticator",
2900 inet_ntop(packet->src_ipaddr.af,
2901 &packet->src_ipaddr.ipaddr,
2902 buffer, sizeof(buffer)),
2912 * @brief convert a "concatenated" attribute to one long VP.
2914 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2915 DICT_ATTR const *da, uint8_t const *start,
2916 size_t const packetlen, VALUE_PAIR **pvp)
2920 uint8_t const *ptr = start;
2921 uint8_t const *end = start + packetlen;
2929 * The packet has already been sanity checked, so we
2930 * don't care about walking off of the end of it.
2933 total += ptr[1] - 2;
2938 * Attributes MUST be consecutive.
2940 if (ptr[0] != attr) break;
2943 vp = pairalloc(ctx, da);
2947 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->length);
2955 while (total < vp->length) {
2956 memcpy(p, ptr + 2, ptr[1] - 2);
2958 total += ptr[1] - 2;
2968 * @brief convert TLVs to one or more VPs
2970 static ssize_t data2vp_tlvs(TALLOC_CTX *ctx,
2971 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2972 char const *secret, DICT_ATTR const *da,
2973 uint8_t const *start, size_t length,
2976 uint8_t const *data = start;
2977 DICT_ATTR const *child;
2978 VALUE_PAIR *head, **tail;
2980 if (length < 3) return -1; /* type, length, value */
2982 VP_HEXDUMP("tlvs", data, length);
2984 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2989 while (data < (start + length)) {
2992 child = dict_attrbyparent(da, data[0], da->vendor);
2994 unsigned int my_attr, my_vendor;
2996 VP_TRACE("Failed to find child %u of TLV %s\n",
3000 * Get child attr/vendor so that
3001 * we can call unknown attr.
3004 my_vendor = da->vendor;
3006 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
3011 child = dict_attrunknown(my_attr, my_vendor, true);
3018 tlv_len = data2vp(ctx, packet, original, secret, child,
3019 data + 2, data[1] - 2, data[1] - 2, tail);
3024 tail = &((*tail)->next);
3033 * @brief Convert a top-level VSA to a VP.
3035 * "length" can be LONGER than just this sub-vsa
3037 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3038 RADIUS_PACKET const *original,
3039 char const *secret, DICT_VENDOR *dv,
3040 uint8_t const *data, size_t length,
3043 unsigned int attribute;
3044 ssize_t attrlen, my_len;
3045 DICT_ATTR const *da;
3048 if (length <= (dv->type + dv->length)) {
3049 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3056 /* data[0] must be zero */
3057 attribute = data[1] << 16;
3058 attribute |= data[2] << 8;
3059 attribute |= data[3];
3063 attribute = data[0] << 8;
3064 attribute |= data[1];
3068 attribute = data[0];
3072 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3076 switch (dv->length) {
3078 /* data[dv->type] must be zero, from rad_tlv_ok() */
3079 attrlen = data[dv->type + 1];
3083 attrlen = data[dv->type];
3091 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3096 if (attrlen <= (ssize_t) (dv->type + dv->length)) {
3097 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3103 * See if the VSA is known.
3105 da = dict_attrbyvalue(attribute, dv->vendorpec);
3106 if (!da) da = dict_attrunknown(attribute, dv->vendorpec, true);
3109 my_len = data2vp(ctx, packet, original, secret, da,
3110 data + dv->type + dv->length,
3111 attrlen - (dv->type + dv->length),
3112 attrlen - (dv->type + dv->length),
3114 if (my_len < 0) return my_len;
3121 * @brief Convert a fragmented extended attr to a VP
3131 * But for the first fragment, we get passed a pointer to the
3134 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3135 RADIUS_PACKET const *original,
3136 char const *secret, DICT_ATTR const *da,
3137 uint8_t const *data,
3138 size_t attrlen, size_t packetlen,
3143 uint8_t *head, *tail;
3144 uint8_t const *frag, *end;
3145 uint8_t const *attr;
3149 if (attrlen < 3) return -1;
3152 * Calculate the length of all of the fragments. For
3153 * now, they MUST be contiguous in the packet, and they
3154 * MUST be all of the same TYPE and EXTENDED-TYPE
3157 fraglen = attrlen - 2;
3158 frag = data + attrlen;
3159 end = data + packetlen;
3163 while (frag < end) {
3165 (frag[0] != attr[0]) ||
3166 (frag[1] < 4) || /* too short for long-extended */
3167 (frag[2] != attr[2]) ||
3168 ((frag + frag[1]) > end)) { /* overflow */
3173 last_frag = ((frag[3] & 0x80) == 0);
3175 fraglen += frag[1] - 4;
3180 head = tail = malloc(fraglen);
3181 if (!head) return -1;
3183 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3186 * And again, but faster and looser.
3188 * We copy the first fragment, followed by the rest of
3193 while (fragments > 0) {
3194 memcpy(tail, frag + 4, frag[1] - 4);
3195 tail += frag[1] - 4;
3200 VP_HEXDUMP("long-extended fragments", head, fraglen);
3202 rcode = data2vp(ctx, packet, original, secret, da,
3203 head, fraglen, fraglen, pvp);
3205 if (rcode < 0) return rcode;
3211 * @brief Convert a Vendor-Specific WIMAX to vps
3213 * Called ONLY for Vendor-Specific
3215 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3216 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3217 char const *secret, uint32_t vendor,
3218 uint8_t const *data,
3219 size_t attrlen, size_t packetlen,
3225 uint8_t *head, *tail;
3226 uint8_t const *frag, *end;
3227 DICT_ATTR const *child;
3229 if (attrlen < 8) return -1;
3231 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3233 child = dict_attrbyvalue(data[4], vendor);
3234 if (!child) return -1;
3236 if ((data[6] & 0x80) == 0) {
3237 rcode = data2vp(ctx, packet, original, secret, child,
3238 data + 7, data[5] - 3, data[5] - 3,
3240 if (rcode < 0) return -1;
3245 * Calculate the length of all of the fragments. For
3246 * now, they MUST be contiguous in the packet, and they
3247 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3249 * The first fragment doesn't have a RADIUS attribute
3250 * header, so it needs to be treated a little special.
3252 fraglen = data[5] - 3;
3253 frag = data + attrlen;
3254 end = data + packetlen;
3257 while (frag < end) {
3259 (frag[0] != PW_VENDOR_SPECIFIC) ||
3260 (frag[1] < 9) || /* too short for wimax */
3261 ((frag + frag[1]) > end) || /* overflow */
3262 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3263 (frag[6] != data[4]) || /* not the same wimax attr */
3264 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3269 last_frag = ((frag[8] & 0x80) == 0);
3271 fraglen += frag[7] - 3;
3275 head = tail = malloc(fraglen);
3276 if (!head) return -1;
3279 * And again, but faster and looser.
3281 * We copy the first fragment, followed by the rest of
3286 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3287 tail += frag[4 + 1] - 3;
3288 frag += attrlen; /* should be frag[1] - 7 */
3291 * frag now points to RADIUS attributes
3294 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3295 tail += frag[2 + 4 + 1] - 3;
3297 } while (frag < end);
3299 VP_HEXDUMP("wimax fragments", head, fraglen);
3301 rcode = data2vp(ctx, packet, original, secret, child,
3302 head, fraglen, fraglen, pvp);
3304 if (rcode < 0) return rcode;
3311 * @brief Convert a top-level VSA to one or more VPs
3313 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3314 RADIUS_PACKET const *original,
3315 char const *secret, uint8_t const *data,
3316 size_t attrlen, size_t packetlen,
3323 VALUE_PAIR *head, **tail;
3325 if (attrlen > packetlen) return -1;
3326 if (attrlen < 5) return -1; /* vid, value */
3327 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3329 memcpy(&vendor, data, 4);
3330 vendor = ntohl(vendor);
3331 dv = dict_vendorbyvalue(vendor);
3337 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3338 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3339 data, attrlen, packetlen, pvp);
3344 * VSAs should normally be in TLV format.
3346 if (rad_tlv_ok(data + 4, attrlen - 4,
3347 dv->type, dv->length) < 0) return -1;
3350 * There may be more than one VSA in the
3351 * Vendor-Specific. If so, loop over them all.
3360 while (attrlen > 0) {
3363 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3364 data, attrlen, tail);
3367 fr_strerror_printf("Internal sanity check %d", __LINE__);
3370 tail = &((*tail)->next);
3373 packetlen -= vsa_len;
3383 * @brief Create any kind of VP from the attribute contents.
3385 * "length" is AT LEAST the length of this attribute, as we
3386 * expect the caller to have verified the data with
3387 * rad_packet_ok(). "length" may be up to the length of the
3390 * @return -1 on error, or "length".
3392 ssize_t data2vp(TALLOC_CTX *ctx,
3393 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3395 DICT_ATTR const *da, uint8_t const *start,
3396 size_t const attrlen, size_t const packetlen,
3399 int8_t tag = TAG_NONE;
3403 DICT_ATTR const *child;
3406 uint8_t const *data = start;
3408 uint8_t buffer[256];
3411 * FIXME: Attrlen can be larger than 253 for extended attrs!
3413 if (!da || (attrlen > packetlen) ||
3414 ((attrlen > 253) && (attrlen != packetlen)) ||
3415 (attrlen > 128*1024)) {
3416 fr_strerror_printf("data2vp: invalid arguments");
3420 VP_HEXDUMP("data2vp", start, attrlen);
3422 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3427 * Hacks for CUI. The WiMAX spec says that it can be
3428 * zero length, even though this is forbidden by the
3429 * RADIUS specs. So... we make a special case for it.
3432 if (!((da->vendor == 0) &&
3433 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3440 * Hacks for Coverity. Editing the dictionary
3441 * will break assumptions about CUI. We know
3442 * this, but Coverity doesn't.
3444 if (da->type != PW_TYPE_OCTETS) return -1;
3449 goto alloc_cui; /* skip everything */
3453 * Hacks for tags. If the attribute is capable of
3454 * encoding a tag, and there's room for the tag, and
3455 * there is a tag, or it's encrypted with Tunnel-Password,
3456 * then decode the tag.
3458 if (da->flags.has_tag && (datalen > 1) &&
3459 ((data[0] < 0x20) ||
3460 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3462 * Only "short" attributes can be encrypted.
3464 if (datalen >= sizeof(buffer)) return -1;
3466 if (da->type == PW_TYPE_STRING) {
3467 memcpy(buffer, data + 1, datalen - 1);
3471 } else if (da->type == PW_TYPE_INTEGER) {
3472 memcpy(buffer, data, attrlen);
3477 return -1; /* only string and integer can have tags */
3484 * Decrypt the attribute.
3486 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3488 * Encrypted attributes can only exist for the
3489 * old-style format. Extended attributes CANNOT
3492 if (attrlen > 253) {
3496 if (data == start) {
3497 memcpy(buffer, data, attrlen);
3501 switch (da->flags.encrypt) { /* can't be tagged */
3505 case FLAG_ENCRYPT_USER_PASSWORD:
3507 rad_pwdecode((char *) buffer,
3511 rad_pwdecode((char *) buffer,
3516 datalen = strlen((char *) buffer);
3520 * Tunnel-Password's may go ONLY in response
3521 * packets. They can have a tag, so datalen is
3522 * not the same as attrlen.
3524 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3525 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3526 original ? original->vector : nullvector) < 0) {
3532 * Ascend-Send-Secret
3533 * Ascend-Receive-Secret
3535 case FLAG_ENCRYPT_ASCEND_SECRET:
3539 uint8_t my_digest[AUTH_VECTOR_LEN];
3540 make_secret(my_digest,
3543 memcpy(buffer, my_digest,
3545 buffer[AUTH_VECTOR_LEN] = '\0';
3546 datalen = strlen((char *) buffer);
3552 } /* switch over encryption flags */
3556 * Double-check the length after decrypting the
3560 case PW_TYPE_STRING:
3561 case PW_TYPE_OCTETS:
3564 case PW_TYPE_ABINARY:
3565 if (datalen > sizeof(vp->vp_filter)) goto raw;
3568 case PW_TYPE_INTEGER:
3569 case PW_TYPE_IPV4_ADDR:
3571 case PW_TYPE_SIGNED:
3572 if (datalen != 4) goto raw;
3575 case PW_TYPE_INTEGER64:
3577 if (datalen != 8) goto raw;
3580 case PW_TYPE_IPV6_ADDR:
3581 if (datalen != 16) goto raw;
3584 case PW_TYPE_IPV6_PREFIX:
3585 if ((datalen < 2) || (datalen > 18)) goto raw;
3586 if (data[1] > 128) goto raw;
3590 if (datalen != 1) goto raw;
3594 if (datalen != 2) goto raw;
3597 case PW_TYPE_ETHERNET:
3598 if (datalen != 6) goto raw;
3601 case PW_TYPE_IP_ADDR:
3603 child = dict_attrbytype(da->attr, da->vendor,
3605 } else if (datalen == 16) {
3606 child = dict_attrbytype(da->attr, da->vendor,
3611 if (!child) goto raw;
3612 da = child; /* re-write it */
3615 case PW_TYPE_IPV4_PREFIX:
3616 if (datalen != 6) goto raw;
3617 if ((data[1] & 0x3f) > 32) goto raw;
3621 * The rest of the data types can cause
3622 * recursion! Ask yourself, "is recursion OK?"
3625 case PW_TYPE_EXTENDED:
3626 if (datalen < 2) goto raw; /* etype, value */
3628 child = dict_attrbyparent(da, data[0], 0);
3629 if (!child) goto raw;
3632 * Recurse to decode the contents, which could be
3633 * a TLV, IPaddr, etc. Note that we decode only
3634 * the current attribute, and we ignore any extra
3637 rcode = data2vp(ctx, packet, original, secret, child,
3638 data + 1, attrlen - 1, attrlen - 1, pvp);
3639 if (rcode < 0) goto raw;
3642 case PW_TYPE_LONG_EXTENDED:
3643 if (datalen < 3) goto raw; /* etype, flags, value */
3645 child = dict_attrbyparent(da, data[0], 0);
3647 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3648 (datalen < (3 + 4 + 1))) {
3649 /* da->attr < 255, da->vendor == 0 */
3650 child = dict_attrunknown(data[0], da->attr * FR_MAX_VENDOR, true);
3653 * Try to find the VSA.
3655 memcpy(&vendor, data + 3, 4);
3656 vendor = ntohl(vendor);
3658 if (vendor == 0) goto raw;
3660 child = dict_attrunknown(data[7], vendor | (da->attr * FR_MAX_VENDOR), true);
3664 fr_strerror_printf("Internal sanity check %d", __LINE__);
3670 * If there no more fragments, then the contents
3671 * have to be a well-known data type.
3674 if ((data[1] & 0x80) == 0) {
3675 rcode = data2vp(ctx, packet, original, secret, child,
3676 data + 2, attrlen - 2, attrlen - 2,
3678 if (rcode < 0) goto raw;
3683 * This requires a whole lot more work.
3685 return data2vp_extended(ctx, packet, original, secret, child,
3686 start, attrlen, packetlen, pvp);
3689 if (datalen < 6) goto raw; /* vid, vtype, value */
3691 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3693 memcpy(&vendor, data, 4);
3694 vendor = ntohl(vendor);
3695 dv = dict_vendorbyvalue(vendor);
3697 child = dict_attrunknown(data[4], da->vendor | vendor, true);
3699 child = dict_attrbyparent(da, data[4], vendor);
3701 child = dict_attrunknown(data[4], da->vendor | vendor, true);
3704 if (!child) goto raw;
3706 rcode = data2vp(ctx, packet, original, secret, child,
3707 data + 5, attrlen - 5, attrlen - 5, pvp);
3708 if (rcode < 0) goto raw;
3713 * We presume that the TLVs all fit into one
3714 * attribute, OR they've already been grouped
3715 * into a contiguous memory buffer.
3717 rcode = data2vp_tlvs(ctx, packet, original, secret, da,
3718 data, attrlen, pvp);
3719 if (rcode < 0) goto raw;
3724 * VSAs can be WiMAX, in which case they don't
3725 * fit into one attribute.
3727 rcode = data2vp_vsas(ctx, packet, original, secret,
3728 data, attrlen, packetlen, pvp);
3729 if (rcode < 0) goto raw;
3735 * Re-write the attribute to be "raw". It is
3736 * therefore of type "octets", and will be
3739 da = dict_attrunknown(da->attr, da->vendor, true);
3741 fr_strerror_printf("Internal sanity check %d", __LINE__);
3749 if (da->type != PW_TYPE_OCTETS) {
3750 dict_attr_free(&da);
3758 * And now that we've verified the basic type
3759 * information, decode the actual data.
3762 vp = pairalloc(ctx, da);
3765 vp->length = datalen;
3769 case PW_TYPE_STRING:
3770 p = talloc_array(vp, char, vp->length + 1);
3771 memcpy(p, data, vp->length);
3772 p[vp->length] = '\0';
3773 vp->vp_strvalue = p;
3776 case PW_TYPE_OCTETS:
3777 pairmemcpy(vp, data, vp->length);
3780 case PW_TYPE_ABINARY:
3781 if (vp->length > sizeof(vp->vp_filter)) {
3782 vp->length = sizeof(vp->vp_filter);
3784 memcpy(vp->vp_filter, data, vp->length);
3788 vp->vp_byte = data[0];
3792 vp->vp_short = (data[0] << 8) | data[1];
3795 case PW_TYPE_INTEGER:
3796 memcpy(&vp->vp_integer, data, 4);
3797 vp->vp_integer = ntohl(vp->vp_integer);
3800 case PW_TYPE_INTEGER64:
3801 memcpy(&vp->vp_integer64, data, 8);
3802 vp->vp_integer64 = ntohll(vp->vp_integer64);
3806 memcpy(&vp->vp_date, data, 4);
3807 vp->vp_date = ntohl(vp->vp_date);
3810 case PW_TYPE_ETHERNET:
3811 memcpy(&vp->vp_ether, data, 6);
3814 case PW_TYPE_IPV4_ADDR:
3815 memcpy(&vp->vp_ipaddr, data, 4);
3819 memcpy(&vp->vp_ifid, data, 8);
3822 case PW_TYPE_IPV6_ADDR:
3823 memcpy(&vp->vp_ipv6addr, data, 16);
3826 case PW_TYPE_IPV6_PREFIX:
3828 * FIXME: double-check that
3829 * (vp->vp_octets[1] >> 3) matches vp->length + 2
3831 memcpy(&vp->vp_ipv6prefix, data, vp->length);
3832 if (vp->length < 18) {
3833 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3838 case PW_TYPE_IPV4_PREFIX:
3839 /* FIXME: do the same double-check as for IPv6Prefix */
3840 memcpy(&vp->vp_ipv4prefix, data, vp->length);
3843 * /32 means "keep all bits". Otherwise, mask
3846 if ((data[1] & 0x3f) > 32) {
3847 uint32_t addr, mask;
3849 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3851 mask <<= (32 - (data[1] & 0x3f));
3856 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3860 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3861 memcpy(&vp->vp_integer, buffer, 4);
3862 vp->vp_integer = ntohl(vp->vp_integer);
3867 fr_strerror_printf("Internal sanity check %d", __LINE__);
3878 * @brief Create a "normal" VALUE_PAIR from the given data.
3880 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3881 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3883 uint8_t const *data, size_t length,
3888 DICT_ATTR const *da;
3890 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3891 fr_strerror_printf("rad_attr2vp: Insufficient data");
3895 da = dict_attrbyvalue(data[0], 0);
3896 if (!da) da = dict_attrunknown(data[0], 0, true);
3900 * Pass the entire thing to the decoding function
3902 if (da->flags.concat) {
3903 return data2vp_concat(ctx, da, data, length, pvp);
3907 * Note that we pass the entire length, not just the
3908 * length of this attribute. The Extended or WiMAX
3909 * attributes may have the "continuation" bit set, and
3910 * will thus be more than one attribute in length.
3912 rcode = data2vp(ctx, packet, original, secret, da,
3913 data + 2, data[1] - 2, length - 2, pvp);
3914 if (rcode < 0) return rcode;
3919 fr_thread_local_setup(uint8_t *, rad_vp2data_buff);
3921 /** Converts vp_data to network byte order
3923 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3924 * in an architecture independent format.
3926 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3927 * as the source VALUE_PAIR is not freed.
3929 * @param out where to write the pointer to the value.
3930 * @param vp to get the value from.
3931 * @return -1 on error, or the length of the value
3933 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3941 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3945 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3947 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3951 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3953 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3961 switch(vp->da->type) {
3962 case PW_TYPE_STRING:
3963 case PW_TYPE_OCTETS:
3965 memcpy(out, &vp->data.ptr, sizeof(*out));
3969 * All of these values are at the same location.
3972 case PW_TYPE_IPV4_ADDR:
3973 case PW_TYPE_IPV6_ADDR:
3974 case PW_TYPE_IPV6_PREFIX:
3975 case PW_TYPE_IPV4_PREFIX:
3976 case PW_TYPE_ABINARY:
3977 case PW_TYPE_ETHERNET:
3978 case PW_TYPE_IP_ADDR:
3979 case PW_TYPE_IP_PREFIX:
3981 void const *p = &vp->data;
3982 memcpy(out, &p, sizeof(*out));
3986 case PW_TYPE_BOOLEAN:
3987 buffer[0] = vp->vp_integer & 0x01;
3992 buffer[0] = vp->vp_integer & 0xff;
3997 buffer[0] = (vp->vp_integer >> 8) & 0xff;
3998 buffer[1] = vp->vp_integer & 0xff;
4002 case PW_TYPE_INTEGER:
4003 lvalue = htonl(vp->vp_integer);
4004 memcpy(buffer, &lvalue, sizeof(lvalue));
4008 case PW_TYPE_INTEGER64:
4009 lvalue64 = htonll(vp->vp_integer64);
4010 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4015 lvalue = htonl(vp->vp_date);
4016 memcpy(buffer, &lvalue, sizeof(lvalue));
4020 case PW_TYPE_SIGNED:
4022 int32_t slvalue = htonl(vp->vp_signed);
4023 memcpy(buffer, &slvalue, sizeof(slvalue));
4028 case PW_TYPE_INVALID:
4029 case PW_TYPE_EXTENDED:
4030 case PW_TYPE_LONG_EXTENDED:
4033 case PW_TYPE_TIMEVAL:
4035 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4038 /* Don't add default */
4045 * @brief Calculate/check digest, and decode radius attributes.
4046 * @return -1 on decoding error, 0 on success
4048 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4052 uint32_t num_attributes;
4054 radius_packet_t *hdr;
4055 VALUE_PAIR *head, **tail, *vp;
4058 * Extract attribute-value pairs
4060 hdr = (radius_packet_t *)packet->data;
4062 packet_length = packet->data_len - AUTH_HDR_LEN;
4069 * Loop over the attributes, decoding them into VPs.
4071 while (packet_length > 0) {
4075 * This may return many VPs
4077 my_len = rad_attr2vp(packet, packet, original, secret,
4078 ptr, packet_length, &vp);
4093 * VSA's may not have been counted properly in
4094 * rad_packet_ok() above, as it is hard to count
4095 * then without using the dictionary. We
4096 * therefore enforce the limits here, too.
4098 if ((fr_max_attributes > 0) &&
4099 (num_attributes > fr_max_attributes)) {
4100 char host_ipaddr[128];
4103 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4104 inet_ntop(packet->src_ipaddr.af,
4105 &packet->src_ipaddr.ipaddr,
4106 host_ipaddr, sizeof(host_ipaddr)),
4107 num_attributes, fr_max_attributes);
4112 packet_length -= my_len;
4116 * Merge information from the outside world into our
4119 fr_rand_seed(packet->data, AUTH_HDR_LEN);
4122 * There may be VP's already in the packet. Don't
4123 * destroy them. Instead, add the decoded attributes to
4124 * the tail of the list.
4126 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4136 * @brief Encode password.
4138 * We assume that the passwd buffer passed is big enough.
4139 * RFC2138 says the password is max 128 chars, so the size
4140 * of the passwd buffer must be at least 129 characters.
4141 * Preferably it's just MAX_STRING_LEN.
4143 * int *pwlen is updated to the new length of the encrypted
4144 * password - a multiple of 16 bytes.
4146 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4147 uint8_t const *vector)
4149 FR_MD5_CTX context, old;
4150 uint8_t digest[AUTH_VECTOR_LEN];
4151 int i, n, secretlen;
4155 * RFC maximum is 128 bytes.
4157 * If length is zero, pad it out with zeros.
4159 * If the length isn't aligned to 16 bytes,
4160 * zero out the extra data.
4164 if (len > 128) len = 128;
4167 memset(passwd, 0, AUTH_PASS_LEN);
4168 len = AUTH_PASS_LEN;
4169 } else if ((len % AUTH_PASS_LEN) != 0) {
4170 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4171 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4176 * Use the secret to setup the decryption digest
4178 secretlen = strlen(secret);
4180 fr_md5_init(&context);
4181 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4182 old = context; /* save intermediate work */
4185 * Encrypt it in place. Don't bother checking
4186 * len, as we've ensured above that it's OK.
4188 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4190 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4191 fr_md5_final(digest, &context);
4194 fr_md5_update(&context,
4195 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4197 fr_md5_final(digest, &context);
4200 for (i = 0; i < AUTH_PASS_LEN; i++) {
4201 passwd[i + n] ^= digest[i];
4209 * @brief Decode password.
4211 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4212 uint8_t const *vector)
4214 FR_MD5_CTX context, old;
4215 uint8_t digest[AUTH_VECTOR_LEN];
4217 size_t n, secretlen;
4220 * The RFC's say that the maximum is 128.
4221 * The buffer we're putting it into above is 254, so
4222 * we don't need to do any length checking.
4224 if (pwlen > 128) pwlen = 128;
4229 if (pwlen == 0) goto done;
4232 * Use the secret to setup the decryption digest
4234 secretlen = strlen(secret);
4236 fr_md5_init(&context);
4237 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4238 old = context; /* save intermediate work */
4241 * The inverse of the code above.
4243 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4245 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4246 fr_md5_final(digest, &context);
4249 if (pwlen > AUTH_PASS_LEN) {
4250 fr_md5_update(&context, (uint8_t *) passwd,
4254 fr_md5_final(digest, &context);
4257 if (pwlen > (n + AUTH_PASS_LEN)) {
4258 fr_md5_update(&context, (uint8_t *) passwd + n,
4263 for (i = 0; i < AUTH_PASS_LEN; i++) {
4264 passwd[i + n] ^= digest[i];
4269 passwd[pwlen] = '\0';
4270 return strlen(passwd);
4275 * @brief Encode Tunnel-Password attributes when sending them out on the wire.
4277 * int *pwlen is updated to the new length of the encrypted
4278 * password - a multiple of 16 bytes.
4280 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4283 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4284 uint8_t const *vector)
4286 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4287 unsigned char digest[AUTH_VECTOR_LEN];
4289 int i, n, secretlen;
4294 if (len > 127) len = 127;
4297 * Shift the password 3 positions right to place a salt and original
4298 * length, tag will be added automatically on packet send
4300 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4304 * save original password length as first password character;
4311 * Generate salt. The RFC's say:
4313 * The high bit of salt[0] must be set, each salt in a
4314 * packet should be unique, and they should be random
4316 * So, we set the high bit, add in a counter, and then
4317 * add in some CSPRNG data. should be OK..
4319 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4320 (fr_rand() & 0x07));
4321 salt[1] = fr_rand();
4324 * Padd password to multiple of AUTH_PASS_LEN bytes.
4326 n = len % AUTH_PASS_LEN;
4328 n = AUTH_PASS_LEN - n;
4329 for (; n > 0; n--, len++)
4332 /* set new password length */
4336 * Use the secret to setup the decryption digest
4338 secretlen = strlen(secret);
4339 memcpy(buffer, secret, secretlen);
4341 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4343 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4344 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4345 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4347 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4348 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4351 for (i = 0; i < AUTH_PASS_LEN; i++) {
4352 passwd[i + n2] ^= digest[i];
4360 * @brief Decode Tunnel-Password encrypted attributes.
4362 * Defined in RFC-2868, this uses a two char SALT along with the
4363 * initial intermediate value, to differentiate it from the
4366 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4367 uint8_t const *vector)
4369 FR_MD5_CTX context, old;
4370 uint8_t digest[AUTH_VECTOR_LEN];
4372 unsigned i, n, len, reallen;
4377 * We need at least a salt.
4380 fr_strerror_printf("tunnel password is too short");
4385 * There's a salt, but no password. Or, there's a salt
4386 * and a 'data_len' octet. It's wrong, but at least we
4387 * can figure out what it means: the password is empty.
4389 * Note that this means we ignore the 'data_len' field,
4390 * if the attribute length tells us that there's no
4391 * more data. So the 'data_len' field may be wrong,
4400 len -= 2; /* discount the salt */
4403 * Use the secret to setup the decryption digest
4405 secretlen = strlen(secret);
4407 fr_md5_init(&context);
4408 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4409 old = context; /* save intermediate work */
4412 * Set up the initial key:
4414 * b(1) = MD5(secret + vector + salt)
4416 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4417 fr_md5_update(&context, passwd, 2);
4420 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4424 fr_md5_final(digest, &context);
4429 * A quick check: decrypt the first octet
4430 * of the password, which is the
4431 * 'data_len' field. Ensure it's sane.
4433 reallen = passwd[2] ^ digest[0];
4434 if (reallen >= len) {
4435 fr_strerror_printf("tunnel password is too long for the attribute");
4439 fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4443 fr_md5_final(digest, &context);
4446 fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4449 for (i = base; i < AUTH_PASS_LEN; i++) {
4450 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4455 * See make_tunnel_password, above.
4457 if (reallen > 239) reallen = 239;
4460 passwd[reallen] = 0;
4466 * @brief Encode a CHAP password
4468 * @bug FIXME: might not work with Ascend because
4469 * we use vp->length, and Ascend gear likes
4470 * to send an extra '\0' in the string!
4472 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4473 VALUE_PAIR *password)
4477 uint8_t string[MAX_STRING_LEN * 2 + 1];
4478 VALUE_PAIR *challenge;
4481 * Sanity check the input parameters
4483 if ((packet == NULL) || (password == NULL)) {
4488 * Note that the password VP can be EITHER
4489 * a User-Password attribute (from a check-item list),
4490 * or a CHAP-Password attribute (the client asking
4491 * the library to encode it).
4499 memcpy(ptr, password->vp_strvalue, password->length);
4500 ptr += password->length;
4501 i += password->length;
4504 * Use Chap-Challenge pair if present,
4505 * Request Authenticator otherwise.
4507 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4509 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4510 i += challenge->length;
4512 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4513 i += AUTH_VECTOR_LEN;
4517 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4524 * @brief Seed the random number generator.
4526 * May be called any number of times.
4528 void fr_rand_seed(void const *data, size_t size)
4533 * Ensure that the pool is initialized.
4535 if (!fr_rand_initialized) {
4538 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4540 fd = open("/dev/urandom", O_RDONLY);
4546 while (total < sizeof(fr_rand_pool.randrsl)) {
4547 this = read(fd, fr_rand_pool.randrsl,
4548 sizeof(fr_rand_pool.randrsl) - total);
4549 if ((this < 0) && (errno != EINTR)) break;
4550 if (this > 0) total += this;
4554 fr_rand_pool.randrsl[0] = fd;
4555 fr_rand_pool.randrsl[1] = time(NULL);
4556 fr_rand_pool.randrsl[2] = errno;
4559 fr_randinit(&fr_rand_pool, 1);
4560 fr_rand_pool.randcnt = 0;
4561 fr_rand_initialized = 1;
4567 * Hash the user data
4570 if (!hash) hash = fr_rand();
4571 hash = fr_hash_update(data, size, hash);
4573 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4578 * @brief Return a 32-bit random number.
4580 uint32_t fr_rand(void)
4585 * Ensure that the pool is initialized.
4587 if (!fr_rand_initialized) {
4588 fr_rand_seed(NULL, 0);
4591 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4592 if (fr_rand_pool.randcnt >= 256) {
4593 fr_rand_pool.randcnt = 0;
4594 fr_isaac(&fr_rand_pool);
4601 /** Allocate a new RADIUS_PACKET
4603 * @param ctx the context in which the packet is allocated. May be NULL if
4604 * the packet is not associated with a REQUEST.
4605 * @param new_vector if true a new request authenticator will be generated.
4606 * @return a new RADIUS_PACKET or NULL on error.
4608 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4612 rp = talloc_zero(ctx, RADIUS_PACKET);
4614 fr_strerror_printf("out of memory");
4622 uint32_t hash, base;
4625 * Don't expose the actual contents of the random
4629 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4630 hash = fr_rand() ^ base;
4631 memcpy(rp->vector + i, &hash, sizeof(hash));
4634 fr_rand(); /* stir the pool again */
4639 /** Allocate a new RADIUS_PACKET response
4641 * @param ctx the context in which the packet is allocated. May be NULL if
4642 * the packet is not associated with a REQUEST.
4643 * @param packet The request packet.
4644 * @return a new RADIUS_PACKET or NULL on error.
4646 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4648 RADIUS_PACKET *reply;
4650 if (!packet) return NULL;
4652 reply = rad_alloc(ctx, false);
4653 if (!reply) return NULL;
4656 * Initialize the fields from the request.
4658 reply->sockfd = packet->sockfd;
4659 reply->dst_ipaddr = packet->src_ipaddr;
4660 reply->src_ipaddr = packet->dst_ipaddr;
4661 reply->dst_port = packet->src_port;
4662 reply->src_port = packet->dst_port;
4663 reply->id = packet->id;
4664 reply->code = 0; /* UNKNOWN code */
4665 memcpy(reply->vector, packet->vector,
4666 sizeof(reply->vector));
4669 reply->data_len = 0;
4672 reply->proto = packet->proto;
4679 * @brief Free a RADIUS_PACKET
4681 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4683 RADIUS_PACKET *radius_packet;
4685 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4686 radius_packet = *radius_packet_ptr;
4688 VERIFY_PACKET(radius_packet);
4690 pairfree(&radius_packet->vps);
4692 talloc_free(radius_packet);
4693 *radius_packet_ptr = NULL;
4696 /** Duplicate a RADIUS_PACKET
4698 * @param ctx the context in which the packet is allocated. May be NULL if
4699 * the packet is not associated with a REQUEST.
4700 * @param in The packet to copy
4701 * @return a new RADIUS_PACKET or NULL on error.
4703 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4707 out = rad_alloc(ctx, false);
4708 if (!out) return NULL;
4711 * Bootstrap by copying everything.
4713 memcpy(out, in, sizeof(*out));
4716 * Then reset necessary fields
4723 out->vps = paircopy(out, in->vps);