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 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");
57 #define VP_TRACE(_x, ...)
58 #define VP_HEXDUMP(_x, _y, _z)
63 * The RFC says 4096 octets max, and most packets are less than 256.
65 #define MAX_PACKET_LEN 4096
68 * The maximum number of attributes which we allow in an incoming
69 * request. If there are more attributes than this, the request
72 * This helps to minimize the potential for a DoS, when an
73 * attacker spoofs Access-Request packets, which don't have a
74 * Message-Authenticator attribute. This means that the packet
75 * is unsigned, and the attacker can use resources on the server,
76 * even if the end request is rejected.
78 uint32_t fr_max_attributes = 0;
79 FILE *fr_log_fp = NULL;
81 typedef struct radius_packet_t {
85 uint8_t vector[AUTH_VECTOR_LEN];
89 static fr_randctx fr_rand_pool; /* across multiple calls */
90 static int fr_rand_initialized = 0;
91 static unsigned int salt_offset = 0;
92 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 */
94 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
100 "Accounting-Response",
105 "Accounting-Message", //!< 10
116 "Resource-Free-Request",
117 "Resource-Free-Response",
118 "Resource-Query-Request",
119 "Resource-Query-Response",
120 "Alternate-Resource-Reclaim-Request",
121 "NAS-Reboot-Request",
122 "NAS-Reboot-Response",
135 "Disconnect-Request", //!< 40
145 "IP-Address-Allocate",
146 "IP-Address-Release", //!< 50
150 void fr_printf_log(char const *fmt, ...)
155 if ((fr_debug_flag == 0) || !fr_log_fp) {
160 vfprintf(fr_log_fp, fmt, ap);
166 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";
168 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
172 for (i = 0; i < attrlen; i++) {
173 if ((i > 0) && ((i & 0x0f) == 0x00))
174 fprintf(fr_log_fp, "%.*s", depth, tabs);
175 fprintf(fr_log_fp, "%02x ", ptr[i]);
176 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
178 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
182 void rad_print_hex(RADIUS_PACKET *packet)
186 if (!packet->data || !fr_log_fp) return;
188 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
189 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
190 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
192 fprintf(fr_log_fp, " Vector:\t");
193 for (i = 4; i < 20; i++) {
194 fprintf(fr_log_fp, "%02x", packet->data[i]);
196 fprintf(fr_log_fp, "\n");
198 if (packet->data_len > 20) {
201 fprintf(fr_log_fp, " Data:");
203 total = packet->data_len - 20;
204 ptr = packet->data + 20;
208 unsigned int vendor = 0;
210 fprintf(fr_log_fp, "\t\t");
211 if (total < 2) { /* too short */
212 fprintf(fr_log_fp, "%02x\n", *ptr);
216 if (ptr[1] > total) { /* too long */
217 for (i = 0; i < total; i++) {
218 fprintf(fr_log_fp, "%02x ", ptr[i]);
223 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
224 attrlen = ptr[1] - 2;
226 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
228 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
229 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
230 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
240 print_hex_data(ptr, attrlen, 3);
249 /** Wrapper for sendto which handles sendfromto, IPv6, and all 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 < RADIUS_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.
384 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
387 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
388 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
389 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
391 struct sockaddr_storage src;
392 struct sockaddr_storage dst;
393 socklen_t sizeof_src = sizeof(src);
394 socklen_t sizeof_dst = sizeof(dst);
400 memset(&src, 0, sizeof_src);
401 memset(&dst, 0, sizeof_dst);
404 * Read the length of the packet, from the packet.
405 * This lets us allocate the buffer to use for
406 * reading the rest of the packet.
408 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
409 (struct sockaddr *)&src, &sizeof_src);
411 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
416 * Too little data is available, discard the packet.
419 rad_recv_discard(sockfd);
423 } else { /* we got 4 bytes of data. */
425 * See how long the packet says it is.
427 len = (header[2] * 256) + header[3];
430 * The length in the packet says it's less than
431 * a RADIUS header length: discard it.
433 if (len < RADIUS_HDR_LEN) {
434 recvfrom(sockfd, header, sizeof(header), flags,
435 (struct sockaddr *)&src, &sizeof_src);
439 * Enforce RFC requirements, for sanity.
440 * Anything after 4k will be discarded.
442 } else if (len > MAX_PACKET_LEN) {
443 recvfrom(sockfd, header, sizeof(header), flags,
444 (struct sockaddr *)&src, &sizeof_src);
449 packet->data = talloc_array(packet, uint8_t, len);
450 if (!packet->data) return -1;
453 * Receive the packet. The OS will discard any data in the
454 * packet after "len" bytes.
456 #ifdef WITH_UDPFROMTO
457 data_len = recvfromto(sockfd, packet->data, len, flags,
458 (struct sockaddr *)&src, &sizeof_src,
459 (struct sockaddr *)&dst, &sizeof_dst);
461 data_len = recvfrom(sockfd, packet->data, len, flags,
462 (struct sockaddr *)&src, &sizeof_src);
465 * Get the destination address, too.
467 if (getsockname(sockfd, (struct sockaddr *)&dst,
468 &sizeof_dst) < 0) return -1;
474 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
475 return -1; /* Unknown address family, Die Die Die! */
479 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
483 * Different address families should never happen.
485 if (src.ss_family != dst.ss_family) {
493 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
494 /** Build an encrypted secret value to return in a reply packet
496 * The secret is hidden by xoring with a MD5 digest created from
497 * the shared secret and the authentication vector.
498 * We put them into MD5 in the reverse order from that used when
499 * encrypting passwords to RADIUS.
501 static void make_secret(uint8_t *digest, uint8_t const *vector,
502 char const *secret, uint8_t const *value)
507 fr_md5_init(&context);
508 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
509 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
510 fr_md5_final(digest, &context);
512 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
513 digest[i] ^= value[i];
517 #define MAX_PASS_LEN (128)
518 static void make_passwd(uint8_t *output, ssize_t *outlen,
519 uint8_t const *input, size_t inlen,
520 char const *secret, uint8_t const *vector)
522 FR_MD5_CTX context, old;
523 uint8_t digest[AUTH_VECTOR_LEN];
524 uint8_t passwd[MAX_PASS_LEN];
529 * If the length is zero, round it up.
533 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
535 memcpy(passwd, input, len);
536 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
542 else if ((len & 0x0f) != 0) {
548 fr_md5_init(&context);
549 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
555 fr_md5_update(&context, vector, AUTH_PASS_LEN);
557 for (n = 0; n < len; n += AUTH_PASS_LEN) {
560 fr_md5_update(&context,
561 passwd + n - AUTH_PASS_LEN,
565 fr_md5_final(digest, &context);
566 for (i = 0; i < AUTH_PASS_LEN; i++) {
567 passwd[i + n] ^= digest[i];
571 memcpy(output, passwd, len);
574 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
575 uint8_t const *input, size_t inlen, size_t room,
576 char const *secret, uint8_t const *vector)
578 FR_MD5_CTX context, old;
579 uint8_t digest[AUTH_VECTOR_LEN];
580 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
587 if (room > 253) room = 253;
590 * Account for 2 bytes of the salt, and round the room
591 * available down to the nearest multiple of 16. Then,
592 * subtract one from that to account for the length byte,
593 * and the resulting number is the upper bound on the data
596 * We could short-cut this calculation just be forcing
597 * inlen to be no more than 239. It would work for all
598 * VSA's, as we don't pack multiple VSA's into one
601 * However, this calculation is more general, if a little
602 * complex. And it will work in the future for all possible
603 * kinds of weird attribute packing.
606 room -= (room & 0x0f);
609 if (inlen > room) inlen = room;
612 * Length of the encrypted data is password length plus
613 * one byte for the length of the password.
616 if ((len & 0x0f) != 0) {
620 *outlen = len + 2; /* account for the salt */
623 * Copy the password over.
625 memcpy(passwd + 3, input, inlen);
626 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
629 * Generate salt. The RFC's say:
631 * The high bit of salt[0] must be set, each salt in a
632 * packet should be unique, and they should be random
634 * So, we set the high bit, add in a counter, and then
635 * add in some CSPRNG data. should be OK..
637 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
639 passwd[1] = fr_rand();
640 passwd[2] = inlen; /* length of the password string */
642 fr_md5_init(&context);
643 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
646 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
647 fr_md5_update(&context, &passwd[0], 2);
649 for (n = 0; n < len; n += AUTH_PASS_LEN) {
652 fr_md5_update(&context,
653 passwd + 2 + n - AUTH_PASS_LEN,
657 fr_md5_final(digest, &context);
659 for (i = 0; i < AUTH_PASS_LEN; i++) {
660 passwd[i + 2 + n] ^= digest[i];
663 memcpy(output, passwd, len + 2);
666 extern int const fr_attr_max_tlv;
667 extern int const fr_attr_shift[];
668 extern int const fr_attr_mask[];
670 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
672 unsigned int tlv1, tlv2;
674 if (nest > fr_attr_max_tlv) return 0;
679 * Keep encoding TLVs which have the same scope.
680 * e.g. two attributes of:
681 * ATTR.TLV1.TLV2.TLV3 = data1
682 * ATTR.TLV1.TLV2.TLV4 = data2
683 * both get put into a container of "ATTR.TLV1.TLV2"
687 * Nothing to follow, we're done.
692 * Not from the same vendor, skip it.
694 if (vp->da->vendor != next->da->vendor) return 0;
697 * In a different TLV space, skip it.
700 tlv2 = next->da->attr;
702 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
703 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
705 if (tlv1 != tlv2) return 0;
711 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
712 RADIUS_PACKET const *original,
713 char const *secret, int nest,
714 VALUE_PAIR const **pvp,
715 uint8_t *start, size_t room);
717 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
718 RADIUS_PACKET const *original,
719 char const *secret, VALUE_PAIR const **pvp,
720 unsigned int attribute, uint8_t *ptr, size_t room);
722 /** Encode the *data* portion of the TLV
724 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
725 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
727 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
728 RADIUS_PACKET const *original,
729 char const *secret, int nest,
730 VALUE_PAIR const **pvp,
731 uint8_t *start, size_t room)
735 uint8_t *ptr = start;
736 VALUE_PAIR const *vp = *pvp;
737 VALUE_PAIR const *svp = vp;
742 if (nest > fr_attr_max_tlv) {
743 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
751 if (room <= 2) return ptr - start;
753 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
757 if (room > 255) my_room = 255;
759 len = vp2data_any(packet, original, secret, nest,
760 &vp, ptr + 2, my_room - 2);
761 if (len < 0) return len;
762 if (len == 0) return ptr - start;
763 /* len can NEVER be more than 253 */
768 if ((fr_debug_flag > 3) && fr_log_fp) {
769 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
770 print_hex_data(ptr + 2, len, 3);
778 if (!do_next_tlv(svp, vp, nest)) break;
782 if ((fr_debug_flag > 3) && fr_log_fp) {
785 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
786 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
793 /** Encodes the data portion of an attribute
795 * @return -1 on error, or the length of the data portion.
797 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
798 RADIUS_PACKET const *original,
799 char const *secret, int nest,
800 VALUE_PAIR const **pvp,
801 uint8_t *start, size_t room)
806 uint8_t *ptr = start;
809 VALUE_PAIR const *vp = *pvp;
814 * See if we need to encode a TLV. The low portion of
815 * the attribute has already been placed into the packer.
816 * If there are still attribute bytes left, then go
817 * encode them as TLVs.
819 * If we cared about the stack, we could unroll the loop.
821 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
822 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
823 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
828 * Set up the default sources for the data.
832 switch (vp->da->type) {
838 fr_strerror_printf("ERROR: Cannot encode NULL data");
844 case PW_TYPE_IPV4_ADDR:
845 case PW_TYPE_IPV6_ADDR:
846 case PW_TYPE_IPV6_PREFIX:
847 case PW_TYPE_IPV4_PREFIX:
848 case PW_TYPE_ABINARY:
849 case PW_TYPE_ETHERNET: /* just in case */
850 data = (uint8_t const *) &vp->data;
854 len = 1; /* just in case */
855 array[0] = vp->vp_byte;
860 len = 2; /* just in case */
861 array[0] = (vp->vp_short >> 8) & 0xff;
862 array[1] = vp->vp_short & 0xff;
866 case PW_TYPE_INTEGER:
867 len = 4; /* just in case */
868 lvalue = htonl(vp->vp_integer);
869 memcpy(array, &lvalue, sizeof(lvalue));
873 case PW_TYPE_INTEGER64:
874 len = 8; /* just in case */
875 lvalue64 = htonll(vp->vp_integer64);
876 data = (uint8_t *) &lvalue64;
880 * There are no tagged date attributes.
883 lvalue = htonl(vp->vp_date);
884 data = (uint8_t const *) &lvalue;
885 len = 4; /* just in case */
892 len = 4; /* just in case */
893 slvalue = htonl(vp->vp_signed);
894 memcpy(array, &slvalue, sizeof(slvalue));
899 default: /* unknown type: ignore it */
900 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
913 * Bound the data to the calling size
915 if (len > (ssize_t) room) len = room;
918 * Encrypt the various password styles
920 * Attributes with encrypted values MUST be less than
923 switch (vp->da->flags.encrypt) {
924 case FLAG_ENCRYPT_USER_PASSWORD:
925 make_passwd(ptr, &len, data, len,
926 secret, packet->vector);
929 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
931 if (vp->da->flags.has_tag) lvalue = 1;
934 * Check if there's enough room. If there isn't,
935 * we discard the attribute.
937 * This is ONLY a problem if we have multiple VSA's
938 * in one Vendor-Specific, though.
940 if (room < (18 + lvalue)) return 0;
942 switch (packet->code) {
943 case PW_CODE_ACCESS_ACCEPT:
944 case PW_CODE_ACCESS_REJECT:
945 case PW_CODE_ACCESS_CHALLENGE:
948 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
952 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
953 make_tunnel_passwd(ptr + lvalue, &len, data, len,
955 secret, original->vector);
957 case PW_CODE_ACCOUNTING_REQUEST:
958 case PW_CODE_DISCONNECT_REQUEST:
959 case PW_CODE_COA_REQUEST:
960 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
961 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
962 secret, packet->vector);
968 * The code above ensures that this attribute
971 case FLAG_ENCRYPT_ASCEND_SECRET:
972 if (len != 16) return 0;
973 make_secret(ptr, packet->vector, secret, data);
974 len = AUTH_VECTOR_LEN;
979 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
980 if (vp->da->type == PW_TYPE_STRING) {
981 if (len > ((ssize_t) (room - 1))) len = room - 1;
984 } else if (vp->da->type == PW_TYPE_INTEGER) {
986 } /* else it can't be any other type */
988 memcpy(ptr, data, len);
990 } /* switch over encryption flags */
993 return len + (ptr - start);
996 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
997 uint8_t *ptr, int hdr_len, ssize_t len,
998 int flag_offset, int vsa_offset)
1000 int check_len = len - ptr[1];
1001 int total = len + hdr_len;
1004 * Pass 1: Check if the addition of the headers
1005 * overflows the available room. If so, return
1006 * what we were capable of encoding.
1009 while (check_len > (255 - hdr_len)) {
1011 check_len -= (255 - hdr_len);
1015 * Note that this results in a number of attributes maybe
1016 * being marked as "encoded", but which aren't in the
1017 * packet. Oh well. The solution is to fix the
1018 * "vp2data_any" function to take into account the header
1021 if ((ptr + ptr[1] + total) > end) {
1022 return (ptr + ptr[1]) - start;
1026 * Pass 2: Now that we know there's enough room,
1027 * re-arrange the data to form a set of valid
1028 * RADIUS attributes.
1031 int sublen = 255 - ptr[1];
1033 if (len <= sublen) {
1038 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1039 memmove(ptr + 255, ptr, hdr_len);
1041 if (vsa_offset) ptr[vsa_offset] += sublen;
1042 ptr[flag_offset] |= 0x80;
1046 if (vsa_offset) ptr[vsa_offset] = 3;
1050 if (vsa_offset) ptr[vsa_offset] += len;
1052 return (ptr + ptr[1]) - start;
1056 /** Encode an "extended" attribute
1058 int rad_vp2extended(RADIUS_PACKET const *packet,
1059 RADIUS_PACKET const *original,
1060 char const *secret, VALUE_PAIR const **pvp,
1061 uint8_t *ptr, size_t room)
1065 uint8_t *start = ptr;
1066 VALUE_PAIR const *vp = *pvp;
1070 if (!vp->da->flags.extended) {
1071 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1076 * The attribute number is encoded into the upper 8 bits
1079 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1081 if (!vp->da->flags.long_extended) {
1082 if (room < 3) return 0;
1085 ptr[2] = vp->da->attr & fr_attr_mask[0];
1088 if (room < 4) return 0;
1091 ptr[2] = vp->da->attr & fr_attr_mask[0];
1096 * Only "flagged" attributes can be longer than one
1099 if (!vp->da->flags.long_extended && (room > 255)) {
1106 if (vp->da->flags.evs) {
1107 uint8_t *evs = ptr + ptr[1];
1109 if (room < (size_t) (ptr[1] + 5)) return 0;
1113 evs[0] = 0; /* always zero */
1114 evs[1] = (vp->da->vendor >> 16) & 0xff;
1115 evs[2] = (vp->da->vendor >> 8) & 0xff;
1116 evs[3] = vp->da->vendor & 0xff;
1117 evs[4] = vp->da->attr & fr_attr_mask[0];
1123 len = vp2data_any(packet, original, secret, 0,
1124 pvp, ptr + ptr[1], room - hdr_len);
1125 if (len <= 0) return len;
1128 * There may be more than 252 octets of data encoded in
1129 * the attribute. If so, move the data up in the packet,
1130 * and copy the existing header over. Set the "M" flag ONLY
1131 * after copying the rest of the data.
1133 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1134 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1140 if ((fr_debug_flag > 3) && fr_log_fp) {
1143 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1144 if (!vp->da->flags.long_extended) {
1145 fprintf(fr_log_fp, "%02x ", ptr[2]);
1148 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1152 if (vp->da->flags.evs) {
1153 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1154 ptr[jump], ptr[jump + 1],
1155 ptr[jump + 2], ptr[jump + 3],
1156 ((ptr[jump + 1] << 16) |
1157 (ptr[jump + 2] << 8) |
1163 print_hex_data(ptr + jump, len, 3);
1167 return (ptr + ptr[1]) - start;
1171 /** Encode a WiMAX attribute
1174 int rad_vp2wimax(RADIUS_PACKET const *packet,
1175 RADIUS_PACKET const *original,
1176 char const *secret, VALUE_PAIR const **pvp,
1177 uint8_t *ptr, size_t room)
1182 uint8_t *start = ptr;
1183 VALUE_PAIR const *vp = *pvp;
1188 * Double-check for WiMAX format.
1190 if (!vp->da->flags.wimax) {
1191 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1196 * Not enough room for:
1197 * attr, len, vendor-id, vsa, vsalen, continuation
1199 if (room < 9) return 0;
1202 * Build the Vendor-Specific header
1205 ptr[0] = PW_VENDOR_SPECIFIC;
1207 lvalue = htonl(vp->da->vendor);
1208 memcpy(ptr + 2, &lvalue, 4);
1209 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1211 ptr[8] = 0; /* continuation byte */
1215 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1217 if (len <= 0) return len;
1220 * There may be more than 252 octets of data encoded in
1221 * the attribute. If so, move the data up in the packet,
1222 * and copy the existing header over. Set the "C" flag
1223 * ONLY after copying the rest of the data.
1225 if (len > (255 - ptr[1])) {
1226 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1233 if ((fr_debug_flag > 3) && fr_log_fp) {
1234 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1236 ptr[2], ptr[3], ptr[4], ptr[5],
1237 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1238 ptr[6], ptr[7], ptr[8]);
1239 print_hex_data(ptr + 9, len, 3);
1243 return (ptr + ptr[1]) - start;
1246 /** Encode an RFC format attribute, with the "concat" flag set
1248 * If there isn't enough room in the packet, the data is
1251 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1252 UNUSED RADIUS_PACKET const *original,
1253 UNUSED char const *secret, VALUE_PAIR const **pvp,
1254 unsigned int attribute, uint8_t *start, size_t room)
1256 uint8_t *ptr = start;
1259 VALUE_PAIR const *vp = *pvp;
1267 if (room <= 2) break;
1274 /* no more than 253 octets */
1275 if (left > 253) left = 253;
1277 /* no more than "room" octets */
1278 if (room < (left + 2)) left = room - 2;
1280 memcpy(ptr + 2, p, left);
1283 if ((fr_debug_flag > 3) && fr_log_fp) {
1284 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1285 print_hex_data(ptr + 2, len, 3);
1299 /** Encode an RFC format TLV.
1301 * This could be a standard attribute, or a TLV data type.
1302 * If it's a standard attribute, then vp->da->attr == attribute.
1303 * Otherwise, attribute may be something else.
1305 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1306 RADIUS_PACKET const *original,
1307 char const *secret, VALUE_PAIR const **pvp,
1308 unsigned int attribute, uint8_t *ptr, size_t room)
1312 if (room <= 2) return 0;
1314 ptr[0] = attribute & 0xff;
1317 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1319 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1320 if (len <= 0) return len;
1325 if ((fr_debug_flag > 3) && fr_log_fp) {
1326 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1327 print_hex_data(ptr + 2, len, 3);
1335 /** Encode a VSA which is a TLV
1337 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1339 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1340 RADIUS_PACKET const *original,
1341 char const *secret, VALUE_PAIR const **pvp,
1342 unsigned int attribute, unsigned int vendor,
1343 uint8_t *ptr, size_t room)
1347 VALUE_PAIR const *vp = *pvp;
1351 * Unknown vendor: RFC format.
1352 * Known vendor and RFC format: go do that.
1354 dv = dict_vendorbyvalue(vendor);
1356 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1357 return vp2attr_rfc(packet, original, secret, pvp,
1358 attribute, ptr, room);
1363 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1364 " type %u", (unsigned) dv->type);
1368 ptr[0] = 0; /* attr must be 24-bit */
1369 ptr[1] = (attribute >> 16) & 0xff;
1370 ptr[2] = (attribute >> 8) & 0xff;
1371 ptr[3] = attribute & 0xff;
1375 ptr[0] = (attribute >> 8) & 0xff;
1376 ptr[1] = attribute & 0xff;
1380 ptr[0] = attribute & 0xff;
1384 switch (dv->length) {
1386 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1387 " length %u", (unsigned) dv->length);
1395 ptr[dv->type + 1] = dv->type + 2;
1399 ptr[dv->type] = dv->type + 1;
1404 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1405 room = 255 - (dv->type + dv->length);
1408 len = vp2data_any(packet, original, secret, 0, pvp,
1409 ptr + dv->type + dv->length, room);
1410 if (len <= 0) return len;
1412 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1415 if ((fr_debug_flag > 3) && fr_log_fp) {
1421 if ((fr_debug_flag > 3) && fr_log_fp)
1422 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1423 ptr[0], ptr[1], ptr[2], ptr[3]);
1427 if ((fr_debug_flag > 3) && fr_log_fp)
1428 fprintf(fr_log_fp, "\t\t%02x%02x ",
1433 if ((fr_debug_flag > 3) && fr_log_fp)
1434 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1438 switch (dv->length) {
1443 fprintf(fr_log_fp, " ");
1447 fprintf(fr_log_fp, "%02x ",
1452 fprintf(fr_log_fp, "%02x%02x ",
1453 ptr[dv->type], ptr[dv->type] + 1);
1457 print_hex_data(ptr + dv->type + dv->length, len, 3);
1461 return dv->type + dv->length + len;
1465 /** Encode a Vendor-Specific attribute
1468 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1469 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1474 VALUE_PAIR const *vp = *pvp;
1478 * Double-check for WiMAX format.
1480 if (vp->da->flags.wimax) {
1481 return rad_vp2wimax(packet, original, secret, pvp,
1485 if (vp->da->vendor > FR_MAX_VENDOR) {
1486 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1491 * Not enough room for:
1492 * attr, len, vendor-id
1494 if (room < 6) return 0;
1497 * Build the Vendor-Specific header
1499 ptr[0] = PW_VENDOR_SPECIFIC;
1501 lvalue = htonl(vp->da->vendor);
1502 memcpy(ptr + 2, &lvalue, 4);
1504 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1506 len = vp2attr_vsa(packet, original, secret, pvp,
1507 vp->da->attr, vp->da->vendor,
1508 ptr + ptr[1], room);
1509 if (len < 0) return len;
1512 if ((fr_debug_flag > 3) && fr_log_fp) {
1513 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1515 ptr[2], ptr[3], ptr[4], ptr[5],
1516 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1517 print_hex_data(ptr + 6, len, 3);
1527 /** Encode an RFC standard attribute 1..255
1530 int rad_vp2rfc(RADIUS_PACKET const *packet,
1531 RADIUS_PACKET const *original,
1532 char const *secret, VALUE_PAIR const **pvp,
1533 uint8_t *ptr, size_t room)
1535 VALUE_PAIR const *vp = *pvp;
1539 if (vp->da->vendor != 0) {
1540 fr_strerror_printf("rad_vp2rfc called with VSA");
1544 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1545 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1550 * Only CUI is allowed to have zero length.
1553 if ((vp->length == 0) &&
1554 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1555 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1563 * Message-Authenticator is hard-coded.
1565 if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1566 if (room < 18) return -1;
1568 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1570 memset(ptr + 2, 0, 16);
1572 if ((fr_debug_flag > 3) && fr_log_fp) {
1573 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1577 *pvp = (*pvp)->next;
1582 * EAP-Message is special.
1584 if (vp->da->flags.concat && (vp->length > 253)) {
1585 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1589 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1593 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1594 RADIUS_PACKET const *original,
1595 char const *secret, VALUE_PAIR const **pvp,
1596 uint8_t *start, size_t room)
1599 VALUE_PAIR const *vp = *pvp;
1603 if (!vp->da->flags.is_tlv) {
1604 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1608 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1609 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1613 if (room < 5) return 0;
1616 * Encode the first level of TLVs
1618 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1620 start[2] = vp->da->attr & fr_attr_mask[0];
1623 len = vp2data_any(packet, original, secret, 0, pvp,
1624 start + 4, room - 4);
1625 if (len <= 0) return len;
1637 /** Parse a data structure into a RADIUS attribute
1640 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1641 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1644 VALUE_PAIR const *vp;
1646 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1653 * RFC format attributes take the fast path.
1655 if (!vp->da->vendor) {
1656 if (vp->da->attr > 255) return 0;
1658 return rad_vp2rfc(packet, original, secret, pvp,
1662 if (vp->da->flags.extended) {
1663 return rad_vp2extended(packet, original, secret, pvp,
1668 * The upper 8 bits of the vendor number are the standard
1669 * space attribute which is a TLV.
1671 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1672 return rad_vp2rfctlv(packet, original, secret, pvp,
1676 if (vp->da->flags.wimax) {
1677 return rad_vp2wimax(packet, original, secret, pvp,
1681 return rad_vp2vsa(packet, original, secret, pvp,
1689 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1692 radius_packet_t *hdr;
1694 uint16_t total_length;
1696 VALUE_PAIR const *reply;
1699 * A 4K packet, aligned on 64-bits.
1701 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1704 * Double-check some things based on packet code.
1706 switch (packet->code) {
1707 case PW_CODE_ACCESS_ACCEPT:
1708 case PW_CODE_ACCESS_REJECT:
1709 case PW_CODE_ACCESS_CHALLENGE:
1711 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1717 * These packet vectors start off as all zero.
1719 case PW_CODE_ACCOUNTING_REQUEST:
1720 case PW_CODE_DISCONNECT_REQUEST:
1721 case PW_CODE_COA_REQUEST:
1722 memset(packet->vector, 0, sizeof(packet->vector));
1730 * Use memory on the stack, until we know how
1731 * large the packet will be.
1733 hdr = (radius_packet_t *) data;
1736 * Build standard header
1738 hdr->code = packet->code;
1739 hdr->id = packet->id;
1741 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1743 total_length = RADIUS_HDR_LEN;
1746 * Load up the configuration values for the user
1752 * FIXME: Loop twice over the reply list. The first time,
1753 * calculate the total length of data. The second time,
1754 * allocate the memory, and fill in the VP's.
1756 * Hmm... this may be slower than just doing a small
1761 * Loop over the reply attributes for the packet.
1763 reply = packet->vps;
1766 char const *last_name = NULL;
1771 * Ignore non-wire attributes, but allow extended
1774 if ((reply->da->vendor == 0) &&
1775 ((reply->da->attr & 0xFFFF) >= 256) &&
1776 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1779 * Permit the admin to send BADLY formatted
1780 * attributes with a debug build.
1782 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1783 memcpy(ptr, reply->vp_octets, reply->length);
1784 len = reply->length;
1785 reply = reply->next;
1789 reply = reply->next;
1794 * Set the Message-Authenticator to the correct
1795 * length and initial value.
1797 if (reply->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1799 * Cache the offset to the
1800 * Message-Authenticator
1802 packet->offset = total_length;
1805 last_len = reply->length;
1807 last_name = reply->da->name;
1809 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1810 ((uint8_t *) data) + sizeof(data) - ptr);
1811 if (len < 0) return -1;
1814 * Failed to encode the attribute, likely because
1815 * the packet is full.
1818 if (last_len != 0) {
1819 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1822 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1827 next: /* Used only for Raw-Attribute */
1830 total_length += len;
1831 } /* done looping over all attributes */
1834 * Fill in the rest of the fields, and copy the data over
1835 * from the local stack to the newly allocated memory.
1837 * Yes, all this 'memcpy' is slow, but it means
1838 * that we only allocate the minimum amount of
1839 * memory for a request.
1841 packet->data_len = total_length;
1842 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1843 if (!packet->data) {
1844 fr_strerror_printf("Out of memory");
1848 memcpy(packet->data, hdr, packet->data_len);
1849 hdr = (radius_packet_t *) packet->data;
1851 total_length = htons(total_length);
1852 memcpy(hdr->length, &total_length, sizeof(total_length));
1858 /** Sign a previously encoded packet
1861 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1864 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1867 * It wasn't assigned an Id, this is bad!
1869 if (packet->id < 0) {
1870 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1874 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1875 (packet->offset < 0)) {
1876 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1881 * If there's a Message-Authenticator, update it
1882 * now, BEFORE updating the authentication vector.
1884 if (packet->offset > 0) {
1885 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1887 switch (packet->code) {
1888 case PW_CODE_ACCOUNTING_RESPONSE:
1889 if (original && original->code == PW_CODE_STATUS_SERVER) {
1893 case PW_CODE_ACCOUNTING_REQUEST:
1894 case PW_CODE_DISCONNECT_REQUEST:
1895 case PW_CODE_DISCONNECT_ACK:
1896 case PW_CODE_DISCONNECT_NAK:
1897 case PW_CODE_COA_REQUEST:
1898 case PW_CODE_COA_ACK:
1899 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1903 case PW_CODE_ACCESS_ACCEPT:
1904 case PW_CODE_ACCESS_REJECT:
1905 case PW_CODE_ACCESS_CHALLENGE:
1907 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1910 memcpy(hdr->vector, original->vector,
1914 default: /* others have vector already set to zero */
1920 * Set the authentication vector to zero,
1921 * calculate the HMAC, and put it
1922 * into the Message-Authenticator
1925 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1926 (uint8_t const *) secret, strlen(secret));
1927 memcpy(packet->data + packet->offset + 2,
1928 calc_auth_vector, AUTH_VECTOR_LEN);
1931 * Copy the original request vector back
1932 * to the raw packet.
1934 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1938 * Switch over the packet code, deciding how to
1941 switch (packet->code) {
1943 * Request packets are not signed, bur
1944 * have a random authentication vector.
1946 case PW_CODE_ACCESS_REQUEST:
1947 case PW_CODE_STATUS_SERVER:
1951 * Reply packets are signed with the
1952 * authentication vector of the request.
1959 fr_md5_init(&context);
1960 fr_md5_update(&context, packet->data, packet->data_len);
1961 fr_md5_update(&context, (uint8_t const *) secret,
1963 fr_md5_final(digest, &context);
1965 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1966 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1969 }/* switch over packet codes */
1974 /** Reply to the request
1976 * Also attach reply attribute value pairs and any user message provided.
1978 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1982 * Maybe it's a fake packet. Don't send it.
1984 if (!packet || (packet->sockfd < 0)) {
1989 * First time through, allocate room for the packet
1991 if (!packet->data) {
1993 * Encode the packet.
1995 if (rad_encode(packet, original, secret) < 0) {
2000 * Re-sign it, including updating the
2001 * Message-Authenticator.
2003 if (rad_sign(packet, original, secret) < 0) {
2008 * If packet->data points to data, then we print out
2009 * the VP list again only for debugging.
2014 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2019 * If the socket is TCP, call write(). Calling sendto()
2020 * is allowed on some platforms, but it's not nice. Even
2021 * worse, if UDPFROMTO is defined, we *can't* use it on
2022 * TCP sockets. So... just call write().
2024 if (packet->proto == IPPROTO_TCP) {
2027 rcode = write(packet->sockfd, packet->data, packet->data_len);
2028 if (rcode >= 0) return rcode;
2030 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2036 * And send it on it's way.
2038 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2039 &packet->src_ipaddr, packet->src_port,
2040 &packet->dst_ipaddr, packet->dst_port);
2043 /** Do a comparison of two authentication digests by comparing the FULL digest
2045 * Otherwise, the server can be subject to timing attacks that allow attackers
2046 * find a valid message authenticator.
2048 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2050 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2055 for (i = 0; i < length; i++) {
2056 result |= a[i] ^ b[i];
2059 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2063 /** Validates the requesting client NAS
2065 * Calculates the request Authenticator based on the clients private key.
2067 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2069 uint8_t digest[AUTH_VECTOR_LEN];
2073 * Zero out the auth_vector in the received packet.
2074 * Then append the shared secret to the received packet,
2075 * and calculate the MD5 sum. This must be the same
2076 * as the original MD5 sum (packet->vector).
2078 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2081 * MD5(packet + secret);
2083 fr_md5_init(&context);
2084 fr_md5_update(&context, packet->data, packet->data_len);
2085 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2086 fr_md5_final(digest, &context);
2089 * Return 0 if OK, 2 if not OK.
2091 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2096 /** Validates the requesting client NAS
2098 * Calculates the response Authenticator based on the clients
2101 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2104 uint8_t calc_digest[AUTH_VECTOR_LEN];
2110 if (original == NULL) {
2115 * Copy the original vector in place.
2117 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2120 * MD5(packet + secret);
2122 fr_md5_init(&context);
2123 fr_md5_update(&context, packet->data, packet->data_len);
2124 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2125 fr_md5_final(calc_digest, &context);
2128 * Copy the packet's vector back to the packet.
2130 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2133 * Return 0 if OK, 2 if not OK.
2135 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2139 /** Check if a set of RADIUS formatted TLVs are OK
2142 int rad_tlv_ok(uint8_t const *data, size_t length,
2143 size_t dv_type, size_t dv_length)
2145 uint8_t const *end = data + length;
2147 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2149 VP_HEXDUMP("tlv_ok", data, length);
2151 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2152 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2156 while (data < end) {
2159 if ((data + dv_type + dv_length) > end) {
2160 fr_strerror_printf("Attribute header overflow");
2166 if ((data[0] == 0) && (data[1] == 0) &&
2167 (data[2] == 0) && (data[3] == 0)) {
2169 fr_strerror_printf("Invalid attribute 0");
2174 fr_strerror_printf("Invalid attribute > 2^24");
2180 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2184 if (data[0] == 0) goto zero;
2188 fr_strerror_printf("Internal sanity check failed");
2192 switch (dv_length) {
2197 if (data[dv_type] != 0) {
2198 fr_strerror_printf("Attribute is longer than 256 octets");
2203 attrlen = data[dv_type + dv_length - 1];
2208 fr_strerror_printf("Internal sanity check failed");
2212 if (attrlen < (dv_type + dv_length)) {
2213 fr_strerror_printf("Attribute header has invalid length");
2217 if (attrlen > length) {
2218 fr_strerror_printf("Attribute overflows container");
2230 /** See if the data pointed to by PTR is a valid RADIUS packet.
2232 * Packet is not 'const * const' because we may update data_len, if there's more data
2233 * in the UDP packet than in the RADIUS packet.
2235 * @param packet to check
2236 * @param flags to control decoding
2237 * @param reason if not NULL, will have the failure reason written to where it points.
2238 * @return bool, true on success, false on failure.
2240 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2245 radius_packet_t *hdr;
2246 char host_ipaddr[128];
2247 bool require_ma = false;
2248 bool seen_ma = false;
2249 uint32_t num_attributes;
2250 decode_fail_t failure = DECODE_FAIL_NONE;
2253 * Check for packets smaller than the packet header.
2255 * RFC 2865, Section 3., subsection 'length' says:
2257 * "The minimum length is 20 ..."
2259 if (packet->data_len < RADIUS_HDR_LEN) {
2260 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2261 inet_ntop(packet->src_ipaddr.af,
2262 &packet->src_ipaddr.ipaddr,
2263 host_ipaddr, sizeof(host_ipaddr)),
2264 packet->data_len, RADIUS_HDR_LEN);
2265 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2271 * Check for packets with mismatched size.
2272 * i.e. We've received 128 bytes, and the packet header
2273 * says it's 256 bytes long.
2275 totallen = (packet->data[2] << 8) | packet->data[3];
2276 hdr = (radius_packet_t *)packet->data;
2279 * Code of 0 is not understood.
2280 * Code of 16 or greate is not understood.
2282 if ((hdr->code == 0) ||
2283 (hdr->code >= FR_MAX_PACKET_CODE)) {
2284 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2285 inet_ntop(packet->src_ipaddr.af,
2286 &packet->src_ipaddr.ipaddr,
2287 host_ipaddr, sizeof(host_ipaddr)),
2289 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2294 * Message-Authenticator is required in Status-Server
2295 * packets, otherwise they can be trivially forged.
2297 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2300 * It's also required if the caller asks for it.
2302 if (flags) require_ma = true;
2305 * Repeat the length checks. This time, instead of
2306 * looking at the data we received, look at the value
2307 * of the 'length' field inside of the packet.
2309 * Check for packets smaller than the packet header.
2311 * RFC 2865, Section 3., subsection 'length' says:
2313 * "The minimum length is 20 ..."
2315 if (totallen < RADIUS_HDR_LEN) {
2316 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2317 inet_ntop(packet->src_ipaddr.af,
2318 &packet->src_ipaddr.ipaddr,
2319 host_ipaddr, sizeof(host_ipaddr)),
2320 totallen, RADIUS_HDR_LEN);
2321 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2326 * And again, for the value of the 'length' field.
2328 * RFC 2865, Section 3., subsection 'length' says:
2330 * " ... and maximum length is 4096."
2332 * HOWEVER. This requirement is for the network layer.
2333 * If the code gets here, we assume that a well-formed
2334 * packet is an OK packet.
2336 * We allow both the UDP data length, and the RADIUS
2337 * "length" field to contain up to 64K of data.
2341 * RFC 2865, Section 3., subsection 'length' says:
2343 * "If the packet is shorter than the Length field
2344 * indicates, it MUST be silently discarded."
2346 * i.e. No response to the NAS.
2348 if (packet->data_len < totallen) {
2349 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2350 inet_ntop(packet->src_ipaddr.af,
2351 &packet->src_ipaddr.ipaddr,
2352 host_ipaddr, sizeof(host_ipaddr)),
2353 packet->data_len, totallen);
2354 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2359 * RFC 2865, Section 3., subsection 'length' says:
2361 * "Octets outside the range of the Length field MUST be
2362 * treated as padding and ignored on reception."
2364 if (packet->data_len > totallen) {
2366 * We're shortening the packet below, but just
2367 * to be paranoid, zero out the extra data.
2369 memset(packet->data + totallen, 0, packet->data_len - totallen);
2370 packet->data_len = totallen;
2374 * Walk through the packet's attributes, ensuring that
2375 * they add up EXACTLY to the size of the packet.
2377 * If they don't, then the attributes either under-fill
2378 * or over-fill the packet. Any parsing of the packet
2379 * is impossible, and will result in unknown side effects.
2381 * This would ONLY happen with buggy RADIUS implementations,
2382 * or with an intentional attack. Either way, we do NOT want
2383 * to be vulnerable to this problem.
2386 count = totallen - RADIUS_HDR_LEN;
2391 * We need at least 2 bytes to check the
2395 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2396 inet_ntop(packet->src_ipaddr.af,
2397 &packet->src_ipaddr.ipaddr,
2398 host_ipaddr, sizeof(host_ipaddr)));
2399 failure = DECODE_FAIL_HEADER_OVERFLOW;
2404 * Attribute number zero is NOT defined.
2407 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2408 inet_ntop(packet->src_ipaddr.af,
2409 &packet->src_ipaddr.ipaddr,
2410 host_ipaddr, sizeof(host_ipaddr)));
2411 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2416 * Attributes are at LEAST as long as the ID & length
2417 * fields. Anything shorter is an invalid attribute.
2420 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2421 inet_ntop(packet->src_ipaddr.af,
2422 &packet->src_ipaddr.ipaddr,
2423 host_ipaddr, sizeof(host_ipaddr)),
2425 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2430 * If there are fewer bytes in the packet than in the
2431 * attribute, it's a bad packet.
2433 if (count < attr[1]) {
2434 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2435 inet_ntop(packet->src_ipaddr.af,
2436 &packet->src_ipaddr.ipaddr,
2437 host_ipaddr, sizeof(host_ipaddr)),
2439 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2444 * Sanity check the attributes for length.
2447 default: /* don't do anything by default */
2451 * If there's an EAP-Message, we require
2452 * a Message-Authenticator.
2454 case PW_EAP_MESSAGE:
2458 case PW_MESSAGE_AUTHENTICATOR:
2459 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2460 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2461 inet_ntop(packet->src_ipaddr.af,
2462 &packet->src_ipaddr.ipaddr,
2463 host_ipaddr, sizeof(host_ipaddr)),
2465 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2473 * FIXME: Look up the base 255 attributes in the
2474 * dictionary, and switch over their type. For
2475 * integer/date/ip, the attribute length SHOULD
2478 count -= attr[1]; /* grab the attribute length */
2480 num_attributes++; /* seen one more attribute */
2484 * If the attributes add up to a packet, it's allowed.
2486 * If not, we complain, and throw the packet away.
2489 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2490 inet_ntop(packet->src_ipaddr.af,
2491 &packet->src_ipaddr.ipaddr,
2492 host_ipaddr, sizeof(host_ipaddr)));
2493 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2498 * If we're configured to look for a maximum number of
2499 * attributes, and we've seen more than that maximum,
2500 * then throw the packet away, as a possible DoS.
2502 if ((fr_max_attributes > 0) &&
2503 (num_attributes > fr_max_attributes)) {
2504 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2505 inet_ntop(packet->src_ipaddr.af,
2506 &packet->src_ipaddr.ipaddr,
2507 host_ipaddr, sizeof(host_ipaddr)),
2508 num_attributes, fr_max_attributes);
2509 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2514 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2516 * A packet with an EAP-Message attribute MUST also have
2517 * a Message-Authenticator attribute.
2519 * A Message-Authenticator all by itself is OK, though.
2521 * Similarly, Status-Server packets MUST contain
2522 * Message-Authenticator attributes.
2524 if (require_ma && !seen_ma) {
2525 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2526 inet_ntop(packet->src_ipaddr.af,
2527 &packet->src_ipaddr.ipaddr,
2528 host_ipaddr, sizeof(host_ipaddr)));
2529 failure = DECODE_FAIL_MA_MISSING;
2534 * Fill RADIUS header fields
2536 packet->code = hdr->code;
2537 packet->id = hdr->id;
2538 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2546 return (failure == DECODE_FAIL_NONE);
2550 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2553 RADIUS_PACKET *rad_recv(int fd, int flags)
2557 RADIUS_PACKET *packet;
2560 * Allocate the new request data structure
2562 packet = rad_alloc(NULL, false);
2564 fr_strerror_printf("out of memory");
2569 sock_flags = MSG_PEEK;
2573 data_len = rad_recvfrom(fd, packet, sock_flags,
2574 &packet->src_ipaddr, &packet->src_port,
2575 &packet->dst_ipaddr, &packet->dst_port);
2578 * Check for socket errors.
2581 fr_strerror_printf("Error receiving packet: %s", fr_syserror(errno));
2582 /* packet->data is NULL */
2586 packet->data_len = data_len; /* unsigned vs signed */
2589 * If the packet is too big, then rad_recvfrom did NOT
2590 * allocate memory. Instead, it just discarded the
2593 if (packet->data_len > MAX_PACKET_LEN) {
2594 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes");
2595 /* packet->data is NULL */
2601 * Read no data. Continue.
2602 * This check is AFTER the MAX_PACKET_LEN check above, because
2603 * if the packet is larger than MAX_PACKET_LEN, we also have
2604 * packet->data == NULL
2606 if ((packet->data_len == 0) || !packet->data) {
2607 fr_strerror_printf("Empty packet: Socket is not ready");
2613 * See if it's a well-formed RADIUS packet.
2615 if (!rad_packet_ok(packet, flags, NULL)) {
2621 * Remember which socket we read the packet from.
2623 packet->sockfd = fd;
2626 * FIXME: Do even more filtering by only permitting
2627 * certain IP's. The problem is that we don't know
2628 * how to do this properly for all possible clients...
2632 * Explicitely set the VP list to empty.
2637 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2644 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2647 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2654 if (!packet || !packet->data) return -1;
2657 * Before we allocate memory for the attributes, do more
2660 ptr = packet->data + RADIUS_HDR_LEN;
2661 length = packet->data_len - RADIUS_HDR_LEN;
2662 while (length > 0) {
2663 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2664 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2669 default: /* don't do anything. */
2673 * Note that more than one Message-Authenticator
2674 * attribute is invalid.
2676 case PW_MESSAGE_AUTHENTICATOR:
2677 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2678 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2680 switch (packet->code) {
2684 case PW_CODE_ACCOUNTING_RESPONSE:
2686 (original->code == PW_CODE_STATUS_SERVER)) {
2690 case PW_CODE_ACCOUNTING_REQUEST:
2691 case PW_CODE_DISCONNECT_REQUEST:
2692 case PW_CODE_COA_REQUEST:
2693 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2697 case PW_CODE_ACCESS_ACCEPT:
2698 case PW_CODE_ACCESS_REJECT:
2699 case PW_CODE_ACCESS_CHALLENGE:
2700 case PW_CODE_DISCONNECT_ACK:
2701 case PW_CODE_DISCONNECT_NAK:
2702 case PW_CODE_COA_ACK:
2703 case PW_CODE_COA_NAK:
2705 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet");
2708 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2712 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2713 (uint8_t const *) secret, strlen(secret));
2714 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2715 sizeof(calc_auth_vector)) != 0) {
2717 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2718 inet_ntop(packet->src_ipaddr.af,
2719 &packet->src_ipaddr.ipaddr,
2720 buffer, sizeof(buffer)));
2721 /* Silently drop packet, according to RFC 3579 */
2723 } /* else the message authenticator was good */
2726 * Reinitialize Authenticators.
2728 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2729 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2731 } /* switch over the attributes */
2735 } /* loop over the packet, sanity checking the attributes */
2738 * It looks like a RADIUS packet, but we don't know what it is
2739 * so can't validate the authenticators.
2741 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2743 fr_strerror_printf("Received Unknown packet code %d "
2744 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2746 inet_ntop(packet->src_ipaddr.af,
2747 &packet->src_ipaddr.ipaddr,
2748 buffer, sizeof(buffer)),
2754 * Calculate and/or verify Request or Response Authenticator.
2756 switch (packet->code) {
2760 case PW_CODE_ACCESS_REQUEST:
2761 case PW_CODE_STATUS_SERVER:
2763 * The authentication vector is random
2764 * nonsense, invented by the client.
2768 case PW_CODE_COA_REQUEST:
2769 case PW_CODE_DISCONNECT_REQUEST:
2770 case PW_CODE_ACCOUNTING_REQUEST:
2771 if (calc_acctdigest(packet, secret) > 1) {
2772 fr_strerror_printf("Received %s packet "
2773 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2774 fr_packet_codes[packet->code],
2775 inet_ntop(packet->src_ipaddr.af,
2776 &packet->src_ipaddr.ipaddr,
2777 buffer, sizeof(buffer)));
2782 /* Verify the reply digest */
2783 case PW_CODE_ACCESS_ACCEPT:
2784 case PW_CODE_ACCESS_REJECT:
2785 case PW_CODE_ACCESS_CHALLENGE:
2786 case PW_CODE_ACCOUNTING_RESPONSE:
2787 case PW_CODE_DISCONNECT_ACK:
2788 case PW_CODE_DISCONNECT_NAK:
2789 case PW_CODE_COA_ACK:
2790 case PW_CODE_COA_NAK:
2791 rcode = calc_replydigest(packet, original, secret);
2793 fr_strerror_printf("Received %s packet "
2794 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2795 fr_packet_codes[packet->code],
2796 inet_ntop(packet->src_ipaddr.af,
2797 &packet->src_ipaddr.ipaddr,
2798 buffer, sizeof(buffer)),
2805 fr_strerror_printf("Received Unknown packet code %d "
2806 "from client %s port %d: Cannot validate Request/Response Authenticator",
2808 inet_ntop(packet->src_ipaddr.af,
2809 &packet->src_ipaddr.ipaddr,
2810 buffer, sizeof(buffer)),
2819 /** Convert a "concatenated" attribute to one long VP
2822 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2823 DICT_ATTR const *da, uint8_t const *start,
2824 size_t const packetlen, VALUE_PAIR **pvp)
2828 uint8_t const *ptr = start;
2829 uint8_t const *end = start + packetlen;
2837 * The packet has already been sanity checked, so we
2838 * don't care about walking off of the end of it.
2841 total += ptr[1] - 2;
2846 * Attributes MUST be consecutive.
2848 if (ptr[0] != attr) break;
2851 vp = pairalloc(ctx, da);
2855 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->length);
2863 while (total < vp->length) {
2864 memcpy(p, ptr + 2, ptr[1] - 2);
2866 total += ptr[1] - 2;
2875 /** Convert TLVs to one or more VPs
2878 static ssize_t data2vp_tlvs(TALLOC_CTX *ctx,
2879 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2880 char const *secret, DICT_ATTR const *da,
2881 uint8_t const *start, size_t length,
2884 uint8_t const *data = start;
2885 DICT_ATTR const *child;
2886 VALUE_PAIR *head, **tail;
2888 if (length < 3) return -1; /* type, length, value */
2890 VP_HEXDUMP("tlvs", data, length);
2892 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2897 while (data < (start + length)) {
2900 child = dict_attrbyparent(da, data[0], da->vendor);
2902 unsigned int my_attr, my_vendor;
2904 VP_TRACE("Failed to find child %u of TLV %s\n",
2908 * Get child attr/vendor so that
2909 * we can call unknown attr.
2912 my_vendor = da->vendor;
2914 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2919 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2926 tlv_len = data2vp(ctx, packet, original, secret, child,
2927 data + 2, data[1] - 2, data[1] - 2, tail);
2932 tail = &((*tail)->next);
2940 /** Convert a top-level VSA to a VP.
2942 * "length" can be LONGER than just this sub-vsa.
2944 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
2945 RADIUS_PACKET const *original,
2946 char const *secret, DICT_VENDOR *dv,
2947 uint8_t const *data, size_t length,
2950 unsigned int attribute;
2951 ssize_t attrlen, my_len;
2952 DICT_ATTR const *da;
2954 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
2957 if (length <= (dv->type + dv->length)) {
2958 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
2965 /* data[0] must be zero */
2966 attribute = data[1] << 16;
2967 attribute |= data[2] << 8;
2968 attribute |= data[3];
2972 attribute = data[0] << 8;
2973 attribute |= data[1];
2977 attribute = data[0];
2981 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
2985 switch (dv->length) {
2987 /* data[dv->type] must be zero, from rad_tlv_ok() */
2988 attrlen = data[dv->type + 1];
2992 attrlen = data[dv->type];
3000 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3005 if (attrlen <= (ssize_t) (dv->type + dv->length)) {
3006 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3012 * See if the VSA is known.
3014 da = dict_attrbyvalue(attribute, dv->vendorpec);
3015 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3018 my_len = data2vp(ctx, packet, original, secret, da,
3019 data + dv->type + dv->length,
3020 attrlen - (dv->type + dv->length),
3021 attrlen - (dv->type + dv->length),
3023 if (my_len < 0) return my_len;
3029 /** Convert a fragmented extended attr to a VP
3039 * But for the first fragment, we get passed a pointer to the "extended-attr"
3041 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3042 RADIUS_PACKET const *original,
3043 char const *secret, DICT_ATTR const *da,
3044 uint8_t const *data,
3045 size_t attrlen, size_t packetlen,
3050 uint8_t *head, *tail;
3051 uint8_t const *frag, *end;
3052 uint8_t const *attr;
3056 if (attrlen < 3) return -1;
3059 * Calculate the length of all of the fragments. For
3060 * now, they MUST be contiguous in the packet, and they
3061 * MUST be all of the same TYPE and EXTENDED-TYPE
3064 fraglen = attrlen - 2;
3065 frag = data + attrlen;
3066 end = data + packetlen;
3070 while (frag < end) {
3072 (frag[0] != attr[0]) ||
3073 (frag[1] < 4) || /* too short for long-extended */
3074 (frag[2] != attr[2]) ||
3075 ((frag + frag[1]) > end)) { /* overflow */
3080 last_frag = ((frag[3] & 0x80) == 0);
3082 fraglen += frag[1] - 4;
3087 head = tail = malloc(fraglen);
3088 if (!head) return -1;
3090 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3093 * And again, but faster and looser.
3095 * We copy the first fragment, followed by the rest of
3100 while (fragments > 0) {
3101 memcpy(tail, frag + 4, frag[1] - 4);
3102 tail += frag[1] - 4;
3107 VP_HEXDUMP("long-extended fragments", head, fraglen);
3109 rcode = data2vp(ctx, packet, original, secret, da,
3110 head, fraglen, fraglen, pvp);
3112 if (rcode < 0) return rcode;
3117 /** Convert a Vendor-Specific WIMAX to vps
3119 * @note Called ONLY for Vendor-Specific
3121 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3122 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3123 char const *secret, uint32_t vendor,
3124 uint8_t const *data,
3125 size_t attrlen, size_t packetlen,
3131 uint8_t *head, *tail;
3132 uint8_t const *frag, *end;
3133 DICT_ATTR const *child;
3135 if (attrlen < 8) return -1;
3137 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3139 child = dict_attrbyvalue(data[4], vendor);
3140 if (!child) return -1;
3142 if ((data[6] & 0x80) == 0) {
3143 rcode = data2vp(ctx, packet, original, secret, child,
3144 data + 7, data[5] - 3, data[5] - 3,
3146 if (rcode < 0) return -1;
3151 * Calculate the length of all of the fragments. For
3152 * now, they MUST be contiguous in the packet, and they
3153 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3155 * The first fragment doesn't have a RADIUS attribute
3156 * header, so it needs to be treated a little special.
3158 fraglen = data[5] - 3;
3159 frag = data + attrlen;
3160 end = data + packetlen;
3163 while (frag < end) {
3165 (frag[0] != PW_VENDOR_SPECIFIC) ||
3166 (frag[1] < 9) || /* too short for wimax */
3167 ((frag + frag[1]) > end) || /* overflow */
3168 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3169 (frag[6] != data[4]) || /* not the same wimax attr */
3170 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3175 last_frag = ((frag[8] & 0x80) == 0);
3177 fraglen += frag[7] - 3;
3181 head = tail = malloc(fraglen);
3182 if (!head) return -1;
3185 * And again, but faster and looser.
3187 * We copy the first fragment, followed by the rest of
3192 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3193 tail += frag[4 + 1] - 3;
3194 frag += attrlen; /* should be frag[1] - 7 */
3197 * frag now points to RADIUS attributes
3200 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3201 tail += frag[2 + 4 + 1] - 3;
3203 } while (frag < end);
3205 VP_HEXDUMP("wimax fragments", head, fraglen);
3207 rcode = data2vp(ctx, packet, original, secret, child,
3208 head, fraglen, fraglen, pvp);
3210 if (rcode < 0) return rcode;
3216 /** Convert a top-level VSA to one or more VPs
3219 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3220 RADIUS_PACKET const *original,
3221 char const *secret, uint8_t const *data,
3222 size_t attrlen, size_t packetlen,
3229 VALUE_PAIR *head, **tail;
3232 if (attrlen > packetlen) return -1;
3233 if (attrlen < 5) return -1; /* vid, value */
3234 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3236 VP_TRACE("data2vp_vsas\n");
3238 memcpy(&vendor, data, 4);
3239 vendor = ntohl(vendor);
3240 dv = dict_vendorbyvalue(vendor);
3243 * RFC format is 1 octet type, 1 octet length
3245 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3246 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3251 * It's a known unknown.
3253 memset(&my_dv, 0, sizeof(my_dv));
3257 * Fill in the fields. Note that the name is empty!
3259 dv->vendorpec = vendor;
3269 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3270 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3271 data, attrlen, packetlen, pvp);
3276 * VSAs should normally be in TLV format.
3278 if (rad_tlv_ok(data + 4, attrlen - 4,
3279 dv->type, dv->length) < 0) {
3280 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3285 * There may be more than one VSA in the
3286 * Vendor-Specific. If so, loop over them all.
3296 while (attrlen > 0) {
3299 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3300 data, attrlen, tail);
3303 fr_strerror_printf("Internal sanity check %d", __LINE__);
3306 tail = &((*tail)->next);
3309 packetlen -= vsa_len;
3317 /** Create any kind of VP from the attribute contents
3319 * "length" is AT LEAST the length of this attribute, as we
3320 * expect the caller to have verified the data with
3321 * rad_packet_ok(). "length" may be up to the length of the
3324 * @return -1 on error, or "length".
3326 ssize_t data2vp(TALLOC_CTX *ctx,
3327 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3329 DICT_ATTR const *da, uint8_t const *start,
3330 size_t const attrlen, size_t const packetlen,
3333 int8_t tag = TAG_NONE;
3337 DICT_ATTR const *child;
3340 uint8_t const *data = start;
3342 uint8_t buffer[256];
3345 * FIXME: Attrlen can be larger than 253 for extended attrs!
3347 if (!da || (attrlen > packetlen) ||
3348 ((attrlen > 253) && (attrlen != packetlen)) ||
3349 (attrlen > 128*1024)) {
3350 fr_strerror_printf("data2vp: invalid arguments");
3354 VP_HEXDUMP("data2vp", start, attrlen);
3356 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3361 * Hacks for CUI. The WiMAX spec says that it can be
3362 * zero length, even though this is forbidden by the
3363 * RADIUS specs. So... we make a special case for it.
3366 if (!((da->vendor == 0) &&
3367 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3374 * Hacks for Coverity. Editing the dictionary
3375 * will break assumptions about CUI. We know
3376 * this, but Coverity doesn't.
3378 if (da->type != PW_TYPE_OCTETS) return -1;
3383 goto alloc_cui; /* skip everything */
3387 * Hacks for tags. If the attribute is capable of
3388 * encoding a tag, and there's room for the tag, and
3389 * there is a tag, or it's encrypted with Tunnel-Password,
3390 * then decode the tag.
3392 if (da->flags.has_tag && (datalen > 1) &&
3393 ((data[0] < 0x20) ||
3394 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3396 * Only "short" attributes can be encrypted.
3398 if (datalen >= sizeof(buffer)) return -1;
3400 if (da->type == PW_TYPE_STRING) {
3401 memcpy(buffer, data + 1, datalen - 1);
3405 } else if (da->type == PW_TYPE_INTEGER) {
3406 memcpy(buffer, data, attrlen);
3411 return -1; /* only string and integer can have tags */
3418 * Decrypt the attribute.
3420 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3421 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3423 * Encrypted attributes can only exist for the
3424 * old-style format. Extended attributes CANNOT
3427 if (attrlen > 253) {
3431 if (data == start) {
3432 memcpy(buffer, data, attrlen);
3436 switch (da->flags.encrypt) { /* can't be tagged */
3440 case FLAG_ENCRYPT_USER_PASSWORD:
3442 rad_pwdecode((char *) buffer,
3446 rad_pwdecode((char *) buffer,
3451 datalen = strlen((char *) buffer);
3455 * Tunnel-Password's may go ONLY in response
3456 * packets. They can have a tag, so datalen is
3457 * not the same as attrlen.
3459 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3460 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3461 original ? original->vector : nullvector) < 0) {
3467 * Ascend-Send-Secret
3468 * Ascend-Receive-Secret
3470 case FLAG_ENCRYPT_ASCEND_SECRET:
3474 uint8_t my_digest[AUTH_VECTOR_LEN];
3475 make_secret(my_digest,
3478 memcpy(buffer, my_digest,
3480 buffer[AUTH_VECTOR_LEN] = '\0';
3481 datalen = strlen((char *) buffer);
3487 } /* switch over encryption flags */
3491 * Double-check the length after decrypting the
3494 VP_TRACE("data2vp: type %u\n", da->type);
3496 case PW_TYPE_STRING:
3497 case PW_TYPE_OCTETS:
3500 case PW_TYPE_ABINARY:
3501 if (datalen > sizeof(vp->vp_filter)) goto raw;
3504 case PW_TYPE_INTEGER:
3505 case PW_TYPE_IPV4_ADDR:
3507 case PW_TYPE_SIGNED:
3508 if (datalen != 4) goto raw;
3511 case PW_TYPE_INTEGER64:
3513 if (datalen != 8) goto raw;
3516 case PW_TYPE_IPV6_ADDR:
3517 if (datalen != 16) goto raw;
3520 case PW_TYPE_IPV6_PREFIX:
3521 if ((datalen < 2) || (datalen > 18)) goto raw;
3522 if (data[1] > 128) goto raw;
3526 if (datalen != 1) goto raw;
3530 if (datalen != 2) goto raw;
3533 case PW_TYPE_ETHERNET:
3534 if (datalen != 6) goto raw;
3537 case PW_TYPE_COMBO_IP_ADDR:
3539 child = dict_attrbytype(da->attr, da->vendor,
3541 } else if (datalen == 16) {
3542 child = dict_attrbytype(da->attr, da->vendor,
3547 if (!child) goto raw;
3548 da = child; /* re-write it */
3551 case PW_TYPE_IPV4_PREFIX:
3552 if (datalen != 6) goto raw;
3553 if ((data[1] & 0x3f) > 32) goto raw;
3557 * The rest of the data types can cause
3558 * recursion! Ask yourself, "is recursion OK?"
3561 case PW_TYPE_EXTENDED:
3562 if (datalen < 2) goto raw; /* etype, value */
3564 child = dict_attrbyparent(da, data[0], 0);
3565 if (!child) goto raw;
3568 * Recurse to decode the contents, which could be
3569 * a TLV, IPaddr, etc. Note that we decode only
3570 * the current attribute, and we ignore any extra
3573 rcode = data2vp(ctx, packet, original, secret, child,
3574 data + 1, attrlen - 1, attrlen - 1, pvp);
3575 if (rcode < 0) goto raw;
3578 case PW_TYPE_LONG_EXTENDED:
3579 if (datalen < 3) goto raw; /* etype, flags, value */
3581 child = dict_attrbyparent(da, data[0], 0);
3583 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3584 (datalen < (3 + 4 + 1))) {
3585 /* da->attr < 255, da->vendor == 0 */
3586 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3589 * Try to find the VSA.
3591 memcpy(&vendor, data + 3, 4);
3592 vendor = ntohl(vendor);
3594 if (vendor == 0) goto raw;
3596 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3600 fr_strerror_printf("Internal sanity check %d", __LINE__);
3606 * If there no more fragments, then the contents
3607 * have to be a well-known data type.
3610 if ((data[1] & 0x80) == 0) {
3611 rcode = data2vp(ctx, packet, original, secret, child,
3612 data + 2, attrlen - 2, attrlen - 2,
3614 if (rcode < 0) goto raw;
3619 * This requires a whole lot more work.
3621 return data2vp_extended(ctx, packet, original, secret, child,
3622 start, attrlen, packetlen, pvp);
3625 if (datalen < 6) goto raw; /* vid, vtype, value */
3627 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3629 memcpy(&vendor, data, 4);
3630 vendor = ntohl(vendor);
3631 dv = dict_vendorbyvalue(vendor);
3633 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3635 child = dict_attrbyparent(da, data[4], vendor);
3637 child = dict_unknown_afrom_fields(ctx, data[4], da->vendor | vendor);
3640 if (!child) goto raw;
3642 rcode = data2vp(ctx, packet, original, secret, child,
3643 data + 5, attrlen - 5, attrlen - 5, pvp);
3644 if (rcode < 0) goto raw;
3649 * We presume that the TLVs all fit into one
3650 * attribute, OR they've already been grouped
3651 * into a contiguous memory buffer.
3653 rcode = data2vp_tlvs(ctx, packet, original, secret, da,
3654 data, attrlen, pvp);
3655 if (rcode < 0) goto raw;
3660 * VSAs can be WiMAX, in which case they don't
3661 * fit into one attribute.
3663 rcode = data2vp_vsas(ctx, packet, original, secret,
3664 data, attrlen, packetlen, pvp);
3665 if (rcode < 0) goto raw;
3671 * Re-write the attribute to be "raw". It is
3672 * therefore of type "octets", and will be
3675 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3677 fr_strerror_printf("Internal sanity check %d", __LINE__);
3685 if (da->type != PW_TYPE_OCTETS) {
3686 dict_attr_free(&da);
3694 * And now that we've verified the basic type
3695 * information, decode the actual data.
3698 vp = pairalloc(ctx, da);
3701 vp->length = datalen;
3705 case PW_TYPE_STRING:
3706 p = talloc_array(vp, char, vp->length + 1);
3707 memcpy(p, data, vp->length);
3708 p[vp->length] = '\0';
3709 vp->vp_strvalue = p;
3712 case PW_TYPE_OCTETS:
3713 pairmemcpy(vp, data, vp->length);
3716 case PW_TYPE_ABINARY:
3717 if (vp->length > sizeof(vp->vp_filter)) {
3718 vp->length = sizeof(vp->vp_filter);
3720 memcpy(vp->vp_filter, data, vp->length);
3724 vp->vp_byte = data[0];
3728 vp->vp_short = (data[0] << 8) | data[1];
3731 case PW_TYPE_INTEGER:
3732 memcpy(&vp->vp_integer, data, 4);
3733 vp->vp_integer = ntohl(vp->vp_integer);
3736 case PW_TYPE_INTEGER64:
3737 memcpy(&vp->vp_integer64, data, 8);
3738 vp->vp_integer64 = ntohll(vp->vp_integer64);
3742 memcpy(&vp->vp_date, data, 4);
3743 vp->vp_date = ntohl(vp->vp_date);
3746 case PW_TYPE_ETHERNET:
3747 memcpy(&vp->vp_ether, data, 6);
3750 case PW_TYPE_IPV4_ADDR:
3751 memcpy(&vp->vp_ipaddr, data, 4);
3755 memcpy(&vp->vp_ifid, data, 8);
3758 case PW_TYPE_IPV6_ADDR:
3759 memcpy(&vp->vp_ipv6addr, data, 16);
3762 case PW_TYPE_IPV6_PREFIX:
3764 * FIXME: double-check that
3765 * (vp->vp_octets[1] >> 3) matches vp->length + 2
3767 memcpy(&vp->vp_ipv6prefix, data, vp->length);
3768 if (vp->length < 18) {
3769 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3774 case PW_TYPE_IPV4_PREFIX:
3775 /* FIXME: do the same double-check as for IPv6Prefix */
3776 memcpy(&vp->vp_ipv4prefix, data, vp->length);
3779 * /32 means "keep all bits". Otherwise, mask
3782 if ((data[1] & 0x3f) > 32) {
3783 uint32_t addr, mask;
3785 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3787 mask <<= (32 - (data[1] & 0x3f));
3792 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3796 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3797 memcpy(&vp->vp_integer, buffer, 4);
3798 vp->vp_integer = ntohl(vp->vp_integer);
3803 fr_strerror_printf("Internal sanity check %d", __LINE__);
3813 /** Create a "normal" VALUE_PAIR from the given data
3816 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3817 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3819 uint8_t const *data, size_t length,
3824 DICT_ATTR const *da;
3826 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3827 fr_strerror_printf("rad_attr2vp: Insufficient data");
3831 da = dict_attrbyvalue(data[0], 0);
3833 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3834 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3839 * Pass the entire thing to the decoding function
3841 if (da->flags.concat) {
3842 VP_TRACE("attr2vp: concat attribute\n");
3843 return data2vp_concat(ctx, da, data, length, pvp);
3847 * Note that we pass the entire length, not just the
3848 * length of this attribute. The Extended or WiMAX
3849 * attributes may have the "continuation" bit set, and
3850 * will thus be more than one attribute in length.
3852 rcode = data2vp(ctx, packet, original, secret, da,
3853 data + 2, data[1] - 2, length - 2, pvp);
3854 if (rcode < 0) return rcode;
3859 fr_thread_local_setup(uint8_t *, rad_vp2data_buff);
3861 /** Converts vp_data to network byte order
3863 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3864 * in an architecture independent format.
3866 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3867 * as the source VALUE_PAIR is not freed.
3869 * @param out where to write the pointer to the value.
3870 * @param vp to get the value from.
3871 * @return -1 on error, or the length of the value
3873 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3881 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3885 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3887 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3891 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3893 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3901 switch (vp->da->type) {
3902 case PW_TYPE_STRING:
3903 case PW_TYPE_OCTETS:
3905 memcpy(out, &vp->data.ptr, sizeof(*out));
3909 * All of these values are at the same location.
3912 case PW_TYPE_IPV4_ADDR:
3913 case PW_TYPE_IPV6_ADDR:
3914 case PW_TYPE_IPV6_PREFIX:
3915 case PW_TYPE_IPV4_PREFIX:
3916 case PW_TYPE_ABINARY:
3917 case PW_TYPE_ETHERNET:
3918 case PW_TYPE_COMBO_IP_ADDR:
3919 case PW_TYPE_COMBO_IP_PREFIX:
3921 void const *p = &vp->data;
3922 memcpy(out, &p, sizeof(*out));
3926 case PW_TYPE_BOOLEAN:
3927 buffer[0] = vp->vp_byte & 0x01;
3932 buffer[0] = vp->vp_byte & 0xff;
3937 buffer[0] = (vp->vp_short >> 8) & 0xff;
3938 buffer[1] = vp->vp_short & 0xff;
3942 case PW_TYPE_INTEGER:
3943 lvalue = htonl(vp->vp_integer);
3944 memcpy(buffer, &lvalue, sizeof(lvalue));
3948 case PW_TYPE_INTEGER64:
3949 lvalue64 = htonll(vp->vp_integer64);
3950 memcpy(buffer, &lvalue64, sizeof(lvalue64));
3955 lvalue = htonl(vp->vp_date);
3956 memcpy(buffer, &lvalue, sizeof(lvalue));
3960 case PW_TYPE_SIGNED:
3962 int32_t slvalue = htonl(vp->vp_signed);
3963 memcpy(buffer, &slvalue, sizeof(slvalue));
3968 case PW_TYPE_INVALID:
3969 case PW_TYPE_EXTENDED:
3970 case PW_TYPE_LONG_EXTENDED:
3973 case PW_TYPE_TIMEVAL:
3975 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
3978 /* Don't add default */
3984 /** Calculate/check digest, and decode radius attributes
3986 * @return -1 on decoding error, 0 on success
3988 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3992 uint32_t num_attributes;
3994 radius_packet_t *hdr;
3995 VALUE_PAIR *head, **tail, *vp;
3998 * Extract attribute-value pairs
4000 hdr = (radius_packet_t *)packet->data;
4002 packet_length = packet->data_len - RADIUS_HDR_LEN;
4009 * Loop over the attributes, decoding them into VPs.
4011 while (packet_length > 0) {
4015 * This may return many VPs
4017 my_len = rad_attr2vp(packet, packet, original, secret,
4018 ptr, packet_length, &vp);
4032 * VSA's may not have been counted properly in
4033 * rad_packet_ok() above, as it is hard to count
4034 * then without using the dictionary. We
4035 * therefore enforce the limits here, too.
4037 if ((fr_max_attributes > 0) &&
4038 (num_attributes > fr_max_attributes)) {
4039 char host_ipaddr[128];
4042 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4043 inet_ntop(packet->src_ipaddr.af,
4044 &packet->src_ipaddr.ipaddr,
4045 host_ipaddr, sizeof(host_ipaddr)),
4046 num_attributes, fr_max_attributes);
4051 packet_length -= my_len;
4055 * Merge information from the outside world into our
4058 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4061 * There may be VP's already in the packet. Don't
4062 * destroy them. Instead, add the decoded attributes to
4063 * the tail of the list.
4065 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4076 * We assume that the passwd buffer passed is big enough.
4077 * RFC2138 says the password is max 128 chars, so the size
4078 * of the passwd buffer must be at least 129 characters.
4079 * Preferably it's just MAX_STRING_LEN.
4081 * int *pwlen is updated to the new length of the encrypted
4082 * password - a multiple of 16 bytes.
4084 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4085 uint8_t const *vector)
4087 FR_MD5_CTX context, old;
4088 uint8_t digest[AUTH_VECTOR_LEN];
4089 int i, n, secretlen;
4093 * RFC maximum is 128 bytes.
4095 * If length is zero, pad it out with zeros.
4097 * If the length isn't aligned to 16 bytes,
4098 * zero out the extra data.
4102 if (len > 128) len = 128;
4105 memset(passwd, 0, AUTH_PASS_LEN);
4106 len = AUTH_PASS_LEN;
4107 } else if ((len % AUTH_PASS_LEN) != 0) {
4108 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4109 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4114 * Use the secret to setup the decryption digest
4116 secretlen = strlen(secret);
4118 fr_md5_init(&context);
4119 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4120 old = context; /* save intermediate work */
4123 * Encrypt it in place. Don't bother checking
4124 * len, as we've ensured above that it's OK.
4126 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4128 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4129 fr_md5_final(digest, &context);
4132 fr_md5_update(&context,
4133 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4135 fr_md5_final(digest, &context);
4138 for (i = 0; i < AUTH_PASS_LEN; i++) {
4139 passwd[i + n] ^= digest[i];
4149 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4150 uint8_t const *vector)
4152 FR_MD5_CTX context, old;
4153 uint8_t digest[AUTH_VECTOR_LEN];
4155 size_t n, secretlen;
4158 * The RFC's say that the maximum is 128.
4159 * The buffer we're putting it into above is 254, so
4160 * we don't need to do any length checking.
4162 if (pwlen > 128) pwlen = 128;
4167 if (pwlen == 0) goto done;
4170 * Use the secret to setup the decryption digest
4172 secretlen = strlen(secret);
4174 fr_md5_init(&context);
4175 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4176 old = context; /* save intermediate work */
4179 * The inverse of the code above.
4181 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4183 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4184 fr_md5_final(digest, &context);
4187 if (pwlen > AUTH_PASS_LEN) {
4188 fr_md5_update(&context, (uint8_t *) passwd,
4192 fr_md5_final(digest, &context);
4195 if (pwlen > (n + AUTH_PASS_LEN)) {
4196 fr_md5_update(&context, (uint8_t *) passwd + n,
4201 for (i = 0; i < AUTH_PASS_LEN; i++) {
4202 passwd[i + n] ^= digest[i];
4207 passwd[pwlen] = '\0';
4208 return strlen(passwd);
4212 /** Encode Tunnel-Password attributes when sending them out on the wire
4214 * int *pwlen is updated to the new length of the encrypted
4215 * password - a multiple of 16 bytes.
4217 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4220 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4221 uint8_t const *vector)
4223 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4224 unsigned char digest[AUTH_VECTOR_LEN];
4226 int i, n, secretlen;
4231 if (len > 127) len = 127;
4234 * Shift the password 3 positions right to place a salt and original
4235 * length, tag will be added automatically on packet send
4237 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4241 * save original password length as first password character;
4248 * Generate salt. The RFC's say:
4250 * The high bit of salt[0] must be set, each salt in a
4251 * packet should be unique, and they should be random
4253 * So, we set the high bit, add in a counter, and then
4254 * add in some CSPRNG data. should be OK..
4256 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4257 (fr_rand() & 0x07));
4258 salt[1] = fr_rand();
4261 * Padd password to multiple of AUTH_PASS_LEN bytes.
4263 n = len % AUTH_PASS_LEN;
4265 n = AUTH_PASS_LEN - n;
4266 for (; n > 0; n--, len++)
4269 /* set new password length */
4273 * Use the secret to setup the decryption digest
4275 secretlen = strlen(secret);
4276 memcpy(buffer, secret, secretlen);
4278 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4280 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4281 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4282 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4284 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4285 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4288 for (i = 0; i < AUTH_PASS_LEN; i++) {
4289 passwd[i + n2] ^= digest[i];
4296 /** Decode Tunnel-Password encrypted attributes
4298 * Defined in RFC-2868, this uses a two char SALT along with the
4299 * initial intermediate value, to differentiate it from the
4302 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4303 uint8_t const *vector)
4305 FR_MD5_CTX context, old;
4306 uint8_t digest[AUTH_VECTOR_LEN];
4308 unsigned i, n, len, reallen;
4313 * We need at least a salt.
4316 fr_strerror_printf("tunnel password is too short");
4321 * There's a salt, but no password. Or, there's a salt
4322 * and a 'data_len' octet. It's wrong, but at least we
4323 * can figure out what it means: the password is empty.
4325 * Note that this means we ignore the 'data_len' field,
4326 * if the attribute length tells us that there's no
4327 * more data. So the 'data_len' field may be wrong,
4336 len -= 2; /* discount the salt */
4339 * Use the secret to setup the decryption digest
4341 secretlen = strlen(secret);
4343 fr_md5_init(&context);
4344 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4345 old = context; /* save intermediate work */
4348 * Set up the initial key:
4350 * b(1) = MD5(secret + vector + salt)
4352 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4353 fr_md5_update(&context, passwd, 2);
4356 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4360 fr_md5_final(digest, &context);
4365 * A quick check: decrypt the first octet
4366 * of the password, which is the
4367 * 'data_len' field. Ensure it's sane.
4369 reallen = passwd[2] ^ digest[0];
4370 if (reallen >= len) {
4371 fr_strerror_printf("tunnel password is too long for the attribute");
4375 fr_md5_update(&context, passwd + 2, AUTH_PASS_LEN);
4379 fr_md5_final(digest, &context);
4382 fr_md5_update(&context, passwd + n + 2, AUTH_PASS_LEN);
4385 for (i = base; i < AUTH_PASS_LEN; i++) {
4386 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4391 * See make_tunnel_password, above.
4393 if (reallen > 239) reallen = 239;
4396 passwd[reallen] = 0;
4401 /** Encode a CHAP password
4403 * @bug FIXME: might not work with Ascend because
4404 * we use vp->length, and Ascend gear likes
4405 * to send an extra '\0' in the string!
4407 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4408 VALUE_PAIR *password)
4412 uint8_t string[MAX_STRING_LEN * 2 + 1];
4413 VALUE_PAIR *challenge;
4416 * Sanity check the input parameters
4418 if ((packet == NULL) || (password == NULL)) {
4423 * Note that the password VP can be EITHER
4424 * a User-Password attribute (from a check-item list),
4425 * or a CHAP-Password attribute (the client asking
4426 * the library to encode it).
4434 memcpy(ptr, password->vp_strvalue, password->length);
4435 ptr += password->length;
4436 i += password->length;
4439 * Use Chap-Challenge pair if present,
4440 * Request Authenticator otherwise.
4442 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4444 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4445 i += challenge->length;
4447 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4448 i += AUTH_VECTOR_LEN;
4452 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4458 /** Seed the random number generator
4460 * May be called any number of times.
4462 void fr_rand_seed(void const *data, size_t size)
4467 * Ensure that the pool is initialized.
4469 if (!fr_rand_initialized) {
4472 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4474 fd = open("/dev/urandom", O_RDONLY);
4480 while (total < sizeof(fr_rand_pool.randrsl)) {
4481 this = read(fd, fr_rand_pool.randrsl,
4482 sizeof(fr_rand_pool.randrsl) - total);
4483 if ((this < 0) && (errno != EINTR)) break;
4484 if (this > 0) total += this;
4488 fr_rand_pool.randrsl[0] = fd;
4489 fr_rand_pool.randrsl[1] = time(NULL);
4490 fr_rand_pool.randrsl[2] = errno;
4493 fr_randinit(&fr_rand_pool, 1);
4494 fr_rand_pool.randcnt = 0;
4495 fr_rand_initialized = 1;
4501 * Hash the user data
4504 if (!hash) hash = fr_rand();
4505 hash = fr_hash_update(data, size, hash);
4507 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4511 /** Return a 32-bit random number
4514 uint32_t fr_rand(void)
4519 * Ensure that the pool is initialized.
4521 if (!fr_rand_initialized) {
4522 fr_rand_seed(NULL, 0);
4525 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4526 if (fr_rand_pool.randcnt >= 256) {
4527 fr_rand_pool.randcnt = 0;
4528 fr_isaac(&fr_rand_pool);
4535 /** Allocate a new RADIUS_PACKET
4537 * @param ctx the context in which the packet is allocated. May be NULL if
4538 * the packet is not associated with a REQUEST.
4539 * @param new_vector if true a new request authenticator will be generated.
4540 * @return a new RADIUS_PACKET or NULL on error.
4542 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4546 rp = talloc_zero(ctx, RADIUS_PACKET);
4548 fr_strerror_printf("out of memory");
4556 uint32_t hash, base;
4559 * Don't expose the actual contents of the random
4563 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4564 hash = fr_rand() ^ base;
4565 memcpy(rp->vector + i, &hash, sizeof(hash));
4568 fr_rand(); /* stir the pool again */
4573 /** Allocate a new RADIUS_PACKET response
4575 * @param ctx the context in which the packet is allocated. May be NULL if
4576 * the packet is not associated with a REQUEST.
4577 * @param packet The request packet.
4578 * @return a new RADIUS_PACKET or NULL on error.
4580 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4582 RADIUS_PACKET *reply;
4584 if (!packet) return NULL;
4586 reply = rad_alloc(ctx, false);
4587 if (!reply) return NULL;
4590 * Initialize the fields from the request.
4592 reply->sockfd = packet->sockfd;
4593 reply->dst_ipaddr = packet->src_ipaddr;
4594 reply->src_ipaddr = packet->dst_ipaddr;
4595 reply->dst_port = packet->src_port;
4596 reply->src_port = packet->dst_port;
4597 reply->id = packet->id;
4598 reply->code = 0; /* UNKNOWN code */
4599 memcpy(reply->vector, packet->vector,
4600 sizeof(reply->vector));
4603 reply->data_len = 0;
4606 reply->proto = packet->proto;
4612 /** Free a RADIUS_PACKET
4615 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4617 RADIUS_PACKET *radius_packet;
4619 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4620 radius_packet = *radius_packet_ptr;
4622 VERIFY_PACKET(radius_packet);
4624 pairfree(&radius_packet->vps);
4626 talloc_free(radius_packet);
4627 *radius_packet_ptr = NULL;
4630 /** Duplicate a RADIUS_PACKET
4632 * @param ctx the context in which the packet is allocated. May be NULL if
4633 * the packet is not associated with a REQUEST.
4634 * @param in The packet to copy
4635 * @return a new RADIUS_PACKET or NULL on error.
4637 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4641 out = rad_alloc(ctx, false);
4642 if (!out) return NULL;
4645 * Bootstrap by copying everything.
4647 memcpy(out, in, sizeof(*out));
4650 * Then reset necessary fields
4657 out->vps = paircopy(out, in->vps);