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 int 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",
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",
144 "IP-Address-Allocate",
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, int src_port,
256 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED int src_port,
258 fr_ipaddr_t *dst_ipaddr, int 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 DEBUG("rad_send() failed: %s\n", strerror(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, int *src_port,
320 ssize_t data_len, packet_len;
322 struct sockaddr_storage src;
323 socklen_t sizeof_src = sizeof(src);
325 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
326 (struct sockaddr *)&src, &sizeof_src);
328 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
333 * Too little data is available, discard the packet.
336 rad_recv_discard(sockfd);
340 } else { /* we got 4 bytes of data. */
342 * See how long the packet says it is.
344 packet_len = (header[2] * 256) + header[3];
347 * The length in the packet says it's less than
348 * a RADIUS header length: discard it.
350 if (packet_len < AUTH_HDR_LEN) {
351 rad_recv_discard(sockfd);
356 * Enforce RFC requirements, for sanity.
357 * Anything after 4k will be discarded.
359 } else if (packet_len > MAX_PACKET_LEN) {
360 rad_recv_discard(sockfd);
367 * Convert AF. If unknown, discard packet.
369 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
370 rad_recv_discard(sockfd);
378 * The packet says it's this long, but the actual UDP
379 * size could still be smaller.
386 * @brief wrapper for recvfrom, which handles recvfromto, IPv6, and all
387 * possible combinations.
389 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
390 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
391 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
393 struct sockaddr_storage src;
394 struct sockaddr_storage dst;
395 socklen_t sizeof_src = sizeof(src);
396 socklen_t sizeof_dst = sizeof(dst);
402 memset(&src, 0, sizeof_src);
403 memset(&dst, 0, sizeof_dst);
406 * Read the length of the packet, from the packet.
407 * This lets us allocate the buffer to use for
408 * reading the rest of the packet.
410 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
411 (struct sockaddr *)&src, &sizeof_src);
413 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
418 * Too little data is available, discard the packet.
421 rad_recv_discard(sockfd);
425 } else { /* we got 4 bytes of data. */
427 * See how long the packet says it is.
429 len = (header[2] * 256) + header[3];
432 * The length in the packet says it's less than
433 * a RADIUS header length: discard it.
435 if (len < AUTH_HDR_LEN) {
436 recvfrom(sockfd, header, sizeof(header), flags,
437 (struct sockaddr *)&src, &sizeof_src);
441 * Enforce RFC requirements, for sanity.
442 * Anything after 4k will be discarded.
444 } else if (len > MAX_PACKET_LEN) {
445 recvfrom(sockfd, header, sizeof(header), flags,
446 (struct sockaddr *)&src, &sizeof_src);
451 packet->data = talloc_array(packet, uint8_t, len);
452 if (!packet->data) return -1;
455 * Receive the packet. The OS will discard any data in the
456 * packet after "len" bytes.
458 #ifdef WITH_UDPFROMTO
459 data_len = recvfromto(sockfd, packet->data, len, flags,
460 (struct sockaddr *)&src, &sizeof_src,
461 (struct sockaddr *)&dst, &sizeof_dst);
463 data_len = recvfrom(sockfd, packet->data, len, flags,
464 (struct sockaddr *)&src, &sizeof_src);
467 * Get the destination address, too.
469 if (getsockname(sockfd, (struct sockaddr *)&dst,
470 &sizeof_dst) < 0) return -1;
476 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
477 return -1; /* Unknown address family, Die Die Die! */
481 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
485 * Different address families should never happen.
487 if (src.ss_family != dst.ss_family) {
495 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
497 * @brief Build an encrypted secret value to return in a reply packet
499 * The secret is hidden by xoring with a MD5 digest
500 * created from the shared secret and the authentication
501 * vector. We put them into MD5 in the reverse order from
502 * that used when encrypting passwords to RADIUS.
505 static void make_secret(uint8_t *digest, uint8_t const *vector,
506 char const *secret, uint8_t const *value)
511 fr_MD5Init(&context);
512 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
513 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
514 fr_MD5Final(digest, &context);
516 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
517 digest[i] ^= value[i];
521 #define MAX_PASS_LEN (128)
522 static void make_passwd(uint8_t *output, ssize_t *outlen,
523 uint8_t const *input, size_t inlen,
524 char const *secret, uint8_t const *vector)
526 FR_MD5_CTX context, old;
527 uint8_t digest[AUTH_VECTOR_LEN];
528 uint8_t passwd[MAX_PASS_LEN];
533 * If the length is zero, round it up.
537 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
539 memcpy(passwd, input, len);
540 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
546 else if ((len & 0x0f) != 0) {
552 fr_MD5Init(&context);
553 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
559 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
561 for (n = 0; n < len; n += AUTH_PASS_LEN) {
564 fr_MD5Update(&context,
565 passwd + n - AUTH_PASS_LEN,
569 fr_MD5Final(digest, &context);
570 for (i = 0; i < AUTH_PASS_LEN; i++) {
571 passwd[i + n] ^= digest[i];
575 memcpy(output, passwd, len);
578 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
579 uint8_t const *input, size_t inlen, size_t room,
580 char const *secret, uint8_t const *vector)
582 FR_MD5_CTX context, old;
583 uint8_t digest[AUTH_VECTOR_LEN];
584 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
591 if (room > 253) room = 253;
594 * Account for 2 bytes of the salt, and round the room
595 * available down to the nearest multiple of 16. Then,
596 * subtract one from that to account for the length byte,
597 * and the resulting number is the upper bound on the data
600 * We could short-cut this calculation just be forcing
601 * inlen to be no more than 239. It would work for all
602 * VSA's, as we don't pack multiple VSA's into one
605 * However, this calculation is more general, if a little
606 * complex. And it will work in the future for all possible
607 * kinds of weird attribute packing.
610 room -= (room & 0x0f);
613 if (inlen > room) inlen = room;
616 * Length of the encrypted data is password length plus
617 * one byte for the length of the password.
620 if ((len & 0x0f) != 0) {
624 *outlen = len + 2; /* account for the salt */
627 * Copy the password over.
629 memcpy(passwd + 3, input, inlen);
630 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
633 * Generate salt. The RFC's say:
635 * The high bit of salt[0] must be set, each salt in a
636 * packet should be unique, and they should be random
638 * So, we set the high bit, add in a counter, and then
639 * add in some CSPRNG data. should be OK..
641 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
643 passwd[1] = fr_rand();
644 passwd[2] = inlen; /* length of the password string */
646 fr_MD5Init(&context);
647 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
650 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
651 fr_MD5Update(&context, &passwd[0], 2);
653 for (n = 0; n < len; n += AUTH_PASS_LEN) {
656 fr_MD5Update(&context,
657 passwd + 2 + n - AUTH_PASS_LEN,
661 fr_MD5Final(digest, &context);
663 for (i = 0; i < AUTH_PASS_LEN; i++) {
664 passwd[i + 2 + n] ^= digest[i];
667 memcpy(output, passwd, len + 2);
670 extern int fr_attr_max_tlv;
671 extern int fr_attr_shift[];
672 extern int fr_attr_mask[];
674 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
676 unsigned int tlv1, tlv2;
678 if (nest > fr_attr_max_tlv) return 0;
683 * Keep encoding TLVs which have the same scope.
684 * e.g. two attributes of:
685 * ATTR.TLV1.TLV2.TLV3 = data1
686 * ATTR.TLV1.TLV2.TLV4 = data2
687 * both get put into a container of "ATTR.TLV1.TLV2"
691 * Nothing to follow, we're done.
696 * Not from the same vendor, skip it.
698 if (vp->da->vendor != next->da->vendor) return 0;
701 * In a different TLV space, skip it.
704 tlv2 = next->da->attr;
706 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
707 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
709 if (tlv1 != tlv2) return 0;
715 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
716 RADIUS_PACKET const *original,
717 char const *secret, int nest,
718 VALUE_PAIR const **pvp,
719 uint8_t *start, size_t room);
721 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
722 RADIUS_PACKET const *original,
723 char const *secret, VALUE_PAIR const **pvp,
724 unsigned int attribute, uint8_t *ptr, size_t room);
727 * @brief This is really a sub-function of vp2data_any(). It encodes
728 * the *data* portion of the TLV, and assumes that the encapsulating
729 * attribute has already been encoded.
731 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
732 RADIUS_PACKET const *original,
733 char const *secret, int nest,
734 VALUE_PAIR const **pvp,
735 uint8_t *start, size_t room)
739 uint8_t *ptr = start;
740 VALUE_PAIR const *vp = *pvp;
741 VALUE_PAIR const *svp = vp;
746 if (nest > fr_attr_max_tlv) {
747 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
755 if (room <= 2) return ptr - start;
757 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
761 if (room > 255) my_room = 255;
763 len = vp2data_any(packet, original, secret, nest,
764 &vp, ptr + 2, my_room - 2);
765 if (len < 0) return len;
766 if (len == 0) return ptr - start;
767 /* len can NEVER be more than 253 */
772 if ((fr_debug_flag > 3) && fr_log_fp) {
773 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
774 print_hex_data(ptr + 2, len, 3);
782 if (!do_next_tlv(svp, vp, nest)) break;
786 if ((fr_debug_flag > 3) && fr_log_fp) {
789 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
790 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
798 * @brief Encodes the data portion of an attribute.
799 * @return -1 on error, or the length of the data portion.
801 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
802 RADIUS_PACKET const *original,
803 char const *secret, int nest,
804 VALUE_PAIR const **pvp,
805 uint8_t *start, size_t room)
810 uint8_t *ptr = start;
813 VALUE_PAIR const *vp = *pvp;
818 * See if we need to encode a TLV. The low portion of
819 * the attribute has already been placed into the packer.
820 * If there are still attribute bytes left, then go
821 * encode them as TLVs.
823 * If we cared about the stack, we could unroll the loop.
825 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
826 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
827 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
834 * Set up the default sources for the data.
838 switch(vp->da->type) {
844 fr_strerror_printf("ERROR: Cannot encode NULL data");
851 case PW_TYPE_IPV6ADDR:
852 case PW_TYPE_IPV6PREFIX:
853 case PW_TYPE_IPV4PREFIX:
854 case PW_TYPE_ABINARY:
855 data = (uint8_t const *) &vp->data;
859 len = 1; /* just in case */
860 array[0] = vp->vp_integer & 0xff;
865 len = 2; /* just in case */
866 array[0] = (vp->vp_integer >> 8) & 0xff;
867 array[1] = vp->vp_integer & 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",
919 * Bound the data to the calling size
921 if (len > (ssize_t) room) len = room;
924 * Encrypt the various password styles
926 * Attributes with encrypted values MUST be less than
929 switch (vp->da->flags.encrypt) {
930 case FLAG_ENCRYPT_USER_PASSWORD:
931 make_passwd(ptr, &len, data, len,
932 secret, packet->vector);
935 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
937 if (vp->da->flags.has_tag) lvalue = 1;
940 * Check if there's enough room. If there isn't,
941 * we discard the attribute.
943 * This is ONLY a problem if we have multiple VSA's
944 * in one Vendor-Specific, though.
946 if (room < (18 + lvalue)) return 0;
948 switch (packet->code) {
949 case PW_AUTHENTICATION_ACK:
950 case PW_AUTHENTICATION_REJECT:
951 case PW_ACCESS_CHALLENGE:
954 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
958 if (lvalue) ptr[0] = vp->tag;
959 make_tunnel_passwd(ptr + lvalue, &len, data, len,
961 secret, original->vector);
963 case PW_ACCOUNTING_REQUEST:
964 case PW_DISCONNECT_REQUEST:
967 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
968 secret, packet->vector);
974 * The code above ensures that this attribute
977 case FLAG_ENCRYPT_ASCEND_SECRET:
978 if (len != 16) return 0;
979 make_secret(ptr, packet->vector, secret, data);
980 len = AUTH_VECTOR_LEN;
985 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
986 if (vp->da->type == PW_TYPE_STRING) {
987 if (len > ((ssize_t) (room - 1))) len = room - 1;
990 } else if (vp->da->type == PW_TYPE_INTEGER) {
992 } /* else it can't be any other type */
994 memcpy(ptr, data, len);
996 } /* switch over encryption flags */
999 return len + (ptr - start);
1002 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1003 uint8_t *ptr, int hdr_len, ssize_t len,
1004 int flag_offset, int vsa_offset)
1006 int check_len = len - ptr[1];
1007 int total = len + hdr_len;
1010 * Pass 1: Check if the addition of the headers
1011 * overflows the available room. If so, return
1012 * what we were capable of encoding.
1015 while (check_len > (255 - hdr_len)) {
1017 check_len -= (255 - hdr_len);
1021 * Note that this results in a number of attributes maybe
1022 * being marked as "encoded", but which aren't in the
1023 * packet. Oh well. The solution is to fix the
1024 * "vp2data_any" function to take into account the header
1027 if ((ptr + ptr[1] + total) > end) {
1028 return (ptr + ptr[1]) - start;
1032 * Pass 2: Now that we know there's enough room,
1033 * re-arrange the data to form a set of valid
1034 * RADIUS attributes.
1037 int sublen = 255 - ptr[1];
1039 if (len <= sublen) {
1044 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1045 memcpy(ptr + 255, ptr, hdr_len);
1047 if (vsa_offset) ptr[vsa_offset] += sublen;
1048 ptr[flag_offset] |= 0x80;
1052 if (vsa_offset) ptr[vsa_offset] = 3;
1056 if (vsa_offset) ptr[vsa_offset] += len;
1058 return (ptr + ptr[1]) - start;
1063 * @brief Encode an "extended" attribute.
1065 int rad_vp2extended(RADIUS_PACKET const *packet,
1066 RADIUS_PACKET const *original,
1067 char const *secret, VALUE_PAIR const **pvp,
1068 uint8_t *ptr, size_t room)
1072 uint8_t *start = ptr;
1073 VALUE_PAIR const *vp = *pvp;
1077 if (!vp->da->flags.extended) {
1078 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1083 * The attribute number is encoded into the upper 8 bits
1086 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1088 if (!vp->da->flags.long_extended) {
1089 if (room < 3) return 0;
1092 ptr[2] = vp->da->attr & fr_attr_mask[0];
1095 if (room < 4) return 0;
1098 ptr[2] = vp->da->attr & fr_attr_mask[0];
1103 * Only "flagged" attributes can be longer than one
1106 if (!vp->da->flags.long_extended && (room > 255)) {
1113 if (vp->da->flags.evs) {
1114 uint8_t *evs = ptr + ptr[1];
1116 if (room < (size_t) (ptr[1] + 5)) return 0;
1120 evs[0] = 0; /* always zero */
1121 evs[1] = (vp->da->vendor >> 16) & 0xff;
1122 evs[2] = (vp->da->vendor >> 8) & 0xff;
1123 evs[3] = vp->da->vendor & 0xff;
1124 evs[4] = vp->da->attr & fr_attr_mask[0];
1130 len = vp2data_any(packet, original, secret, 0,
1131 pvp, ptr + ptr[1], room - hdr_len);
1132 if (len <= 0) return len;
1135 * There may be more than 252 octets of data encoded in
1136 * the attribute. If so, move the data up in the packet,
1137 * and copy the existing header over. Set the "M" flag ONLY
1138 * after copying the rest of the data.
1140 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1141 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1147 if ((fr_debug_flag > 3) && fr_log_fp) {
1150 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1151 if (!vp->da->flags.long_extended) {
1152 fprintf(fr_log_fp, "%02x ", ptr[2]);
1155 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1159 if (vp->da->flags.evs) {
1160 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1161 ptr[jump], ptr[jump + 1],
1162 ptr[jump + 2], ptr[jump + 3],
1163 ((ptr[jump + 1] << 16) |
1164 (ptr[jump + 2] << 8) |
1170 print_hex_data(ptr + jump, len, 3);
1174 return (ptr + ptr[1]) - start;
1179 * @brief Encode a WiMAX attribute.
1181 int rad_vp2wimax(RADIUS_PACKET const *packet,
1182 RADIUS_PACKET const *original,
1183 char const *secret, VALUE_PAIR const **pvp,
1184 uint8_t *ptr, size_t room)
1189 uint8_t *start = ptr;
1190 VALUE_PAIR const *vp = *pvp;
1195 * Double-check for WiMAX format.
1197 if (!vp->da->flags.wimax) {
1198 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1203 * Not enough room for:
1204 * attr, len, vendor-id, vsa, vsalen, continuation
1206 if (room < 9) return 0;
1209 * Build the Vendor-Specific header
1212 ptr[0] = PW_VENDOR_SPECIFIC;
1214 lvalue = htonl(vp->da->vendor);
1215 memcpy(ptr + 2, &lvalue, 4);
1216 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1218 ptr[8] = 0; /* continuation byte */
1222 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1224 if (len <= 0) return len;
1227 * There may be more than 252 octets of data encoded in
1228 * the attribute. If so, move the data up in the packet,
1229 * and copy the existing header over. Set the "C" flag
1230 * ONLY after copying the rest of the data.
1232 if (len > (255 - ptr[1])) {
1233 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1240 if ((fr_debug_flag > 3) && fr_log_fp) {
1241 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1243 ptr[2], ptr[3], ptr[4], ptr[5],
1244 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1245 ptr[6], ptr[7], ptr[8]);
1246 print_hex_data(ptr + 9, len, 3);
1250 return (ptr + ptr[1]) - start;
1254 * @brief Encode an RFC format attribute, with the "concat" flag set.
1256 * If there isn't enough room in the packet, the data is
1259 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1260 UNUSED RADIUS_PACKET const *original,
1261 UNUSED char const *secret, VALUE_PAIR const **pvp,
1262 unsigned int attribute, uint8_t *start, size_t room)
1264 uint8_t *ptr = start;
1267 VALUE_PAIR const *vp = *pvp;
1277 if (room <= 2) break;
1284 /* no more than 253 octets */
1285 if (left > 253) left = 253;
1287 /* no more than "room" octets */
1288 if (room < (left + 2)) left = room - 2;
1290 memcpy(ptr + 2, p, left);
1293 if ((fr_debug_flag > 3) && fr_log_fp) {
1294 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1295 print_hex_data(ptr + 2, len, 3);
1310 * @brief Encode an RFC format TLV.
1312 * This could be a standard attribute,
1313 * or a TLV data type. If it's a standard attribute, then
1314 * vp->da->attr == attribute. Otherwise, attribute may be
1317 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1318 RADIUS_PACKET const *original,
1319 char const *secret, VALUE_PAIR const **pvp,
1320 unsigned int attribute, uint8_t *ptr, size_t room)
1324 if (room <= 2) return 0;
1326 ptr[0] = attribute & 0xff;
1329 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1331 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1332 if (len <= 0) return len;
1337 if ((fr_debug_flag > 3) && fr_log_fp) {
1338 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1339 print_hex_data(ptr + 2, len, 3);
1348 * @brief Encode a VSA which is a TLV. If it's in the RFC format, call
1349 * vp2attr_rfc. Otherwise, encode it here.
1351 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1352 RADIUS_PACKET const *original,
1353 char const *secret, VALUE_PAIR const **pvp,
1354 unsigned int attribute, unsigned int vendor,
1355 uint8_t *ptr, size_t room)
1359 VALUE_PAIR const *vp = *pvp;
1363 * Unknown vendor: RFC format.
1364 * Known vendor and RFC format: go do that.
1366 dv = dict_vendorbyvalue(vendor);
1368 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1369 return vp2attr_rfc(packet, original, secret, pvp,
1370 attribute, ptr, room);
1375 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1376 " type %u", (unsigned) dv->type);
1380 ptr[0] = 0; /* attr must be 24-bit */
1381 ptr[1] = (attribute >> 16) & 0xff;
1382 ptr[2] = (attribute >> 8) & 0xff;
1383 ptr[3] = attribute & 0xff;
1387 ptr[0] = (attribute >> 8) & 0xff;
1388 ptr[1] = attribute & 0xff;
1392 ptr[0] = attribute & 0xff;
1396 switch (dv->length) {
1398 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1399 " length %u", (unsigned) dv->length);
1407 ptr[dv->type + 1] = dv->type + 2;
1411 ptr[dv->type] = dv->type + 1;
1416 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1417 room = 255 - (dv->type + dv->length);
1420 len = vp2data_any(packet, original, secret, 0, pvp,
1421 ptr + dv->type + dv->length, room);
1422 if (len <= 0) return len;
1424 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1427 if ((fr_debug_flag > 3) && fr_log_fp) {
1433 if ((fr_debug_flag > 3) && fr_log_fp)
1434 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1435 ptr[0], ptr[1], ptr[2], ptr[3]);
1439 if ((fr_debug_flag > 3) && fr_log_fp)
1440 fprintf(fr_log_fp, "\t\t%02x%02x ",
1445 if ((fr_debug_flag > 3) && fr_log_fp)
1446 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1450 switch (dv->length) {
1455 fprintf(fr_log_fp, " ");
1459 fprintf(fr_log_fp, "%02x ",
1464 fprintf(fr_log_fp, "%02x%02x ",
1465 ptr[dv->type], ptr[dv->type] + 1);
1469 print_hex_data(ptr + dv->type + dv->length, len, 3);
1473 return dv->type + dv->length + len;
1478 * @brief Encode a Vendor-Specific attribute.
1480 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1481 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1486 VALUE_PAIR const *vp = *pvp;
1490 * Double-check for WiMAX format.
1492 if (vp->da->flags.wimax) {
1493 return rad_vp2wimax(packet, original, secret, pvp,
1497 if (vp->da->vendor > FR_MAX_VENDOR) {
1498 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1503 * Not enough room for:
1504 * attr, len, vendor-id
1506 if (room < 6) return 0;
1509 * Build the Vendor-Specific header
1511 ptr[0] = PW_VENDOR_SPECIFIC;
1513 lvalue = htonl(vp->da->vendor);
1514 memcpy(ptr + 2, &lvalue, 4);
1516 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1518 len = vp2attr_vsa(packet, original, secret, pvp,
1519 vp->da->attr, vp->da->vendor,
1520 ptr + ptr[1], room);
1521 if (len < 0) return len;
1524 if ((fr_debug_flag > 3) && fr_log_fp) {
1525 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1527 ptr[2], ptr[3], ptr[4], ptr[5],
1528 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1529 print_hex_data(ptr + 6, len, 3);
1540 * @brief Encode an RFC standard attribute 1..255
1542 int rad_vp2rfc(RADIUS_PACKET const *packet,
1543 RADIUS_PACKET const *original,
1544 char const *secret, VALUE_PAIR const **pvp,
1545 uint8_t *ptr, size_t room)
1547 VALUE_PAIR const *vp = *pvp;
1551 if (vp->da->vendor != 0) {
1552 fr_strerror_printf("rad_vp2rfc called with VSA");
1556 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1557 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1562 * Only CUI is allowed to have zero length.
1565 if ((vp->length == 0) &&
1566 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1567 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1575 * Message-Authenticator is hard-coded.
1577 if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1578 if (room < 18) return -1;
1581 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1583 memset(ptr + 2, 0, 16);
1585 if ((fr_debug_flag > 3) && fr_log_fp) {
1586 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1590 *pvp = (*pvp)->next;
1595 * EAP-Message is special.
1597 if (vp->da->flags.concat && (vp->length > 253)) {
1598 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1602 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1606 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1607 RADIUS_PACKET const *original,
1608 char const *secret, VALUE_PAIR const **pvp,
1609 uint8_t *start, size_t room)
1612 VALUE_PAIR const *vp = *pvp;
1616 if (!vp->da->flags.is_tlv) {
1617 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1621 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1622 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1626 if (room < 5) return 0;
1629 * Encode the first level of TLVs
1631 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1633 start[2] = vp->da->attr & fr_attr_mask[0];
1636 len = vp2data_any(packet, original, secret, 0, pvp,
1637 start + 4, room - 4);
1638 if (len <= 0) return len;
1651 * @brief Parse a data structure into a RADIUS attribute.
1653 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1654 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1657 VALUE_PAIR const *vp;
1659 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1666 * RFC format attributes take the fast path.
1668 if (!vp->da->vendor) {
1669 if (vp->da->attr > 255) return 0;
1671 return rad_vp2rfc(packet, original, secret, pvp,
1675 if (vp->da->flags.extended) {
1676 return rad_vp2extended(packet, original, secret, pvp,
1681 * The upper 8 bits of the vendor number are the standard
1682 * space attribute which is a TLV.
1684 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1685 return rad_vp2rfctlv(packet, original, secret, pvp,
1689 if (vp->da->flags.wimax) {
1690 return rad_vp2wimax(packet, original, secret, pvp,
1694 return rad_vp2vsa(packet, original, secret, pvp,
1700 * @brief Encode a packet.
1702 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1705 radius_packet_t *hdr;
1707 uint16_t total_length;
1709 VALUE_PAIR const *reply;
1711 char ip_src_buffer[INET6_ADDRSTRLEN];
1712 char ip_dst_buffer[INET6_ADDRSTRLEN];
1715 * A 4K packet, aligned on 64-bits.
1717 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1719 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1720 what = fr_packet_codes[packet->code];
1725 DEBUG("Sending %s of id %d from %s port %u to %s port %u\n",
1727 inet_ntop(packet->src_ipaddr.af,
1728 &packet->src_ipaddr.ipaddr,
1729 ip_src_buffer, sizeof(ip_src_buffer)),
1731 inet_ntop(packet->dst_ipaddr.af,
1732 &packet->dst_ipaddr.ipaddr,
1733 ip_dst_buffer, sizeof(ip_dst_buffer)),
1737 * Double-check some things based on packet code.
1739 switch (packet->code) {
1740 case PW_AUTHENTICATION_ACK:
1741 case PW_AUTHENTICATION_REJECT:
1742 case PW_ACCESS_CHALLENGE:
1744 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1750 * These packet vectors start off as all zero.
1752 case PW_ACCOUNTING_REQUEST:
1753 case PW_DISCONNECT_REQUEST:
1754 case PW_COA_REQUEST:
1755 memset(packet->vector, 0, sizeof(packet->vector));
1763 * Use memory on the stack, until we know how
1764 * large the packet will be.
1766 hdr = (radius_packet_t *) data;
1769 * Build standard header
1771 hdr->code = packet->code;
1772 hdr->id = packet->id;
1774 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1776 total_length = AUTH_HDR_LEN;
1779 * Load up the configuration values for the user
1785 * FIXME: Loop twice over the reply list. The first time,
1786 * calculate the total length of data. The second time,
1787 * allocate the memory, and fill in the VP's.
1789 * Hmm... this may be slower than just doing a small
1794 * Loop over the reply attributes for the packet.
1796 reply = packet->vps;
1799 char const *last_name = NULL;
1804 * Ignore non-wire attributes, but allow extended
1807 if ((reply->da->vendor == 0) &&
1808 ((reply->da->attr & 0xFFFF) >= 256) &&
1809 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1812 * Permit the admin to send BADLY formatted
1813 * attributes with a debug build.
1815 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1816 memcpy(ptr, reply->vp_octets, reply->length);
1817 len = reply->length;
1818 reply = reply->next;
1822 reply = reply->next;
1827 * Set the Message-Authenticator to the correct
1828 * length and initial value.
1830 if (reply->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1832 * Cache the offset to the
1833 * Message-Authenticator
1835 packet->offset = total_length;
1838 last_len = reply->length;
1840 last_name = reply->da->name;
1842 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1843 ((uint8_t *) data) + sizeof(data) - ptr);
1844 if (len < 0) return -1;
1847 * Failed to encode the attribute, likely because
1848 * the packet is full.
1851 if (last_len != 0) {
1852 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_ACCOUNTING_RESPONSE:
1921 if (original && original->code == PW_STATUS_SERVER) {
1925 case PW_ACCOUNTING_REQUEST:
1926 case PW_DISCONNECT_REQUEST:
1927 case PW_DISCONNECT_ACK:
1928 case PW_DISCONNECT_NAK:
1929 case PW_COA_REQUEST:
1932 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1936 case PW_AUTHENTICATION_ACK:
1937 case PW_AUTHENTICATION_REJECT:
1938 case PW_ACCESS_CHALLENGE:
1940 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1943 memcpy(hdr->vector, original->vector,
1947 default: /* others have vector already set to zero */
1953 * Set the authentication vector to zero,
1954 * calculate the HMAC, and put it
1955 * into the Message-Authenticator
1958 fr_hmac_md5(packet->data, packet->data_len,
1959 (uint8_t const *) secret, strlen(secret),
1961 memcpy(packet->data + packet->offset + 2,
1962 calc_auth_vector, AUTH_VECTOR_LEN);
1965 * Copy the original request vector back
1966 * to the raw packet.
1968 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1972 * Switch over the packet code, deciding how to
1975 switch (packet->code) {
1977 * Request packets are not signed, bur
1978 * have a random authentication vector.
1980 case PW_AUTHENTICATION_REQUEST:
1981 case PW_STATUS_SERVER:
1985 * Reply packets are signed with the
1986 * authentication vector of the request.
1993 fr_MD5Init(&context);
1994 fr_MD5Update(&context, packet->data, packet->data_len);
1995 fr_MD5Update(&context, (uint8_t const *) secret,
1997 fr_MD5Final(digest, &context);
1999 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2000 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2003 }/* switch over packet codes */
2009 * @brief Reply to the request. Also attach
2010 * reply attribute value pairs and any user message provided.
2012 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2017 char ip_src_buffer[128];
2018 char ip_dst_buffer[128];
2021 * Maybe it's a fake packet. Don't send it.
2023 if (!packet || (packet->sockfd < 0)) {
2027 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2028 what = fr_packet_codes[packet->code];
2034 * First time through, allocate room for the packet
2036 if (!packet->data) {
2038 * Encode the packet.
2040 if (rad_encode(packet, original, secret) < 0) {
2045 * Re-sign it, including updating the
2046 * Message-Authenticator.
2048 if (rad_sign(packet, original, secret) < 0) {
2053 * If packet->data points to data, then we print out
2054 * the VP list again only for debugging.
2056 } else if (fr_debug_flag) {
2057 DEBUG("Sending %s of id %d from %s port %u to %s port %u\n", what,
2059 inet_ntop(packet->src_ipaddr.af, &packet->src_ipaddr.ipaddr,
2060 ip_src_buffer, sizeof(ip_src_buffer)),
2062 inet_ntop(packet->dst_ipaddr.af, &packet->dst_ipaddr.ipaddr,
2063 ip_dst_buffer, sizeof(ip_dst_buffer)),
2066 for (reply = packet->vps; reply; reply = reply->next) {
2067 if ((reply->da->vendor == 0) &&
2068 ((reply->da->attr & 0xFFFF) > 0xff)) continue;
2074 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2078 * And send it on it's way.
2080 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2081 &packet->src_ipaddr, packet->src_port,
2082 &packet->dst_ipaddr, packet->dst_port);
2086 * @brief Do a comparison of two authentication digests by comparing
2089 * Otherwise, the server can be subject to
2090 * timing attacks that allow attackers find a valid message
2093 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2095 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2100 for (i = 0; i < length; i++) {
2101 result |= a[i] ^ b[i];
2104 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2109 * @brief Validates the requesting client NAS. Calculates the
2110 * Request Authenticator based on the clients private key.
2112 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2114 uint8_t digest[AUTH_VECTOR_LEN];
2118 * Zero out the auth_vector in the received packet.
2119 * Then append the shared secret to the received packet,
2120 * and calculate the MD5 sum. This must be the same
2121 * as the original MD5 sum (packet->vector).
2123 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2126 * MD5(packet + secret);
2128 fr_MD5Init(&context);
2129 fr_MD5Update(&context, packet->data, packet->data_len);
2130 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
2131 fr_MD5Final(digest, &context);
2134 * Return 0 if OK, 2 if not OK.
2136 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2142 * @brief Validates the requesting client NAS. Calculates the
2143 * Response Authenticator based on the clients private key.
2145 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2148 uint8_t calc_digest[AUTH_VECTOR_LEN];
2154 if (original == NULL) {
2159 * Copy the original vector in place.
2161 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2164 * MD5(packet + secret);
2166 fr_MD5Init(&context);
2167 fr_MD5Update(&context, packet->data, packet->data_len);
2168 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
2169 fr_MD5Final(calc_digest, &context);
2172 * Copy the packet's vector back to the packet.
2174 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2177 * Return 0 if OK, 2 if not OK.
2179 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2185 * @brief Check if a set of RADIUS formatted TLVs are OK.
2187 int rad_tlv_ok(uint8_t const *data, size_t length,
2188 size_t dv_type, size_t dv_length)
2190 uint8_t const *end = data + length;
2192 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2193 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2197 while (data < end) {
2200 if ((data + dv_type + dv_length) > end) {
2201 fr_strerror_printf("Attribute header overflow");
2207 if ((data[0] == 0) && (data[1] == 0) &&
2208 (data[2] == 0) && (data[3] == 0)) {
2210 fr_strerror_printf("Invalid attribute 0");
2215 fr_strerror_printf("Invalid attribute > 2^24");
2221 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2225 if (data[0] == 0) goto zero;
2229 fr_strerror_printf("Internal sanity check failed");
2233 switch (dv_length) {
2238 if (data[dv_type + 1] != 0) {
2239 fr_strerror_printf("Attribute is longer than 256 octets");
2244 attrlen = data[dv_type + dv_length - 1];
2249 fr_strerror_printf("Internal sanity check failed");
2253 if (attrlen < (dv_type + dv_length)) {
2254 fr_strerror_printf("Attribute header has invalid length");
2258 if (attrlen > length) {
2259 fr_strerror_printf("Attribute overflows container");
2272 * @brief See if the data pointed to by PTR is a valid RADIUS packet.
2274 * packet is not 'const * const' because we may update data_len,
2275 * if there's more data in the UDP packet than in the RADIUS packet.
2277 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
2282 radius_packet_t *hdr;
2283 char host_ipaddr[128];
2289 * Check for packets smaller than the packet header.
2291 * RFC 2865, Section 3., subsection 'length' says:
2293 * "The minimum length is 20 ..."
2295 if (packet->data_len < AUTH_HDR_LEN) {
2296 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2297 inet_ntop(packet->src_ipaddr.af,
2298 &packet->src_ipaddr.ipaddr,
2299 host_ipaddr, sizeof(host_ipaddr)),
2300 packet->data_len, AUTH_HDR_LEN);
2306 * Check for packets with mismatched size.
2307 * i.e. We've received 128 bytes, and the packet header
2308 * says it's 256 bytes long.
2310 totallen = (packet->data[2] << 8) | packet->data[3];
2311 hdr = (radius_packet_t *)packet->data;
2314 * Code of 0 is not understood.
2315 * Code of 16 or greate is not understood.
2317 if ((hdr->code == 0) ||
2318 (hdr->code >= FR_MAX_PACKET_CODE)) {
2319 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
2320 inet_ntop(packet->src_ipaddr.af,
2321 &packet->src_ipaddr.ipaddr,
2322 host_ipaddr, sizeof(host_ipaddr)),
2328 * Message-Authenticator is required in Status-Server
2329 * packets, otherwise they can be trivially forged.
2331 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
2334 * It's also required if the caller asks for it.
2336 if (flags) require_ma = 1;
2339 * Repeat the length checks. This time, instead of
2340 * looking at the data we received, look at the value
2341 * of the 'length' field inside of the packet.
2343 * Check for packets smaller than the packet header.
2345 * RFC 2865, Section 3., subsection 'length' says:
2347 * "The minimum length is 20 ..."
2349 if (totallen < AUTH_HDR_LEN) {
2350 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2351 inet_ntop(packet->src_ipaddr.af,
2352 &packet->src_ipaddr.ipaddr,
2353 host_ipaddr, sizeof(host_ipaddr)),
2354 totallen, AUTH_HDR_LEN);
2359 * And again, for the value of the 'length' field.
2361 * RFC 2865, Section 3., subsection 'length' says:
2363 * " ... and maximum length is 4096."
2365 * HOWEVER. This requirement is for the network layer.
2366 * If the code gets here, we assume that a well-formed
2367 * packet is an OK packet.
2369 * We allow both the UDP data length, and the RADIUS
2370 * "length" field to contain up to 64K of data.
2374 * RFC 2865, Section 3., subsection 'length' says:
2376 * "If the packet is shorter than the Length field
2377 * indicates, it MUST be silently discarded."
2379 * i.e. No response to the NAS.
2381 if (packet->data_len < totallen) {
2382 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2383 inet_ntop(packet->src_ipaddr.af,
2384 &packet->src_ipaddr.ipaddr,
2385 host_ipaddr, sizeof(host_ipaddr)),
2386 packet->data_len, totallen);
2391 * RFC 2865, Section 3., subsection 'length' says:
2393 * "Octets outside the range of the Length field MUST be
2394 * treated as padding and ignored on reception."
2396 if (packet->data_len > totallen) {
2398 * We're shortening the packet below, but just
2399 * to be paranoid, zero out the extra data.
2401 memset(packet->data + totallen, 0, packet->data_len - totallen);
2402 packet->data_len = totallen;
2406 * Walk through the packet's attributes, ensuring that
2407 * they add up EXACTLY to the size of the packet.
2409 * If they don't, then the attributes either under-fill
2410 * or over-fill the packet. Any parsing of the packet
2411 * is impossible, and will result in unknown side effects.
2413 * This would ONLY happen with buggy RADIUS implementations,
2414 * or with an intentional attack. Either way, we do NOT want
2415 * to be vulnerable to this problem.
2418 count = totallen - AUTH_HDR_LEN;
2423 * We need at least 2 bytes to check the
2427 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
2428 inet_ntop(packet->src_ipaddr.af,
2429 &packet->src_ipaddr.ipaddr,
2430 host_ipaddr, sizeof(host_ipaddr)));
2435 * Attribute number zero is NOT defined.
2438 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
2439 inet_ntop(packet->src_ipaddr.af,
2440 &packet->src_ipaddr.ipaddr,
2441 host_ipaddr, sizeof(host_ipaddr)));
2446 * Attributes are at LEAST as long as the ID & length
2447 * fields. Anything shorter is an invalid attribute.
2450 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
2451 inet_ntop(packet->src_ipaddr.af,
2452 &packet->src_ipaddr.ipaddr,
2453 host_ipaddr, sizeof(host_ipaddr)),
2459 * If there are fewer bytes in the packet than in the
2460 * attribute, it's a bad packet.
2462 if (count < attr[1]) {
2463 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2464 inet_ntop(packet->src_ipaddr.af,
2465 &packet->src_ipaddr.ipaddr,
2466 host_ipaddr, sizeof(host_ipaddr)),
2472 * Sanity check the attributes for length.
2475 default: /* don't do anything by default */
2479 * If there's an EAP-Message, we require
2480 * a Message-Authenticator.
2482 case PW_EAP_MESSAGE:
2486 case PW_MESSAGE_AUTHENTICATOR:
2487 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2488 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2489 inet_ntop(packet->src_ipaddr.af,
2490 &packet->src_ipaddr.ipaddr,
2491 host_ipaddr, sizeof(host_ipaddr)),
2500 * FIXME: Look up the base 255 attributes in the
2501 * dictionary, and switch over their type. For
2502 * integer/date/ip, the attribute length SHOULD
2505 count -= attr[1]; /* grab the attribute length */
2507 num_attributes++; /* seen one more attribute */
2511 * If the attributes add up to a packet, it's allowed.
2513 * If not, we complain, and throw the packet away.
2516 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2517 inet_ntop(packet->src_ipaddr.af,
2518 &packet->src_ipaddr.ipaddr,
2519 host_ipaddr, sizeof(host_ipaddr)));
2524 * If we're configured to look for a maximum number of
2525 * attributes, and we've seen more than that maximum,
2526 * then throw the packet away, as a possible DoS.
2528 if ((fr_max_attributes > 0) &&
2529 (num_attributes > fr_max_attributes)) {
2530 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2531 inet_ntop(packet->src_ipaddr.af,
2532 &packet->src_ipaddr.ipaddr,
2533 host_ipaddr, sizeof(host_ipaddr)),
2534 num_attributes, fr_max_attributes);
2539 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2541 * A packet with an EAP-Message attribute MUST also have
2542 * a Message-Authenticator attribute.
2544 * A Message-Authenticator all by itself is OK, though.
2546 * Similarly, Status-Server packets MUST contain
2547 * Message-Authenticator attributes.
2549 if (require_ma && ! seen_ma) {
2550 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2551 inet_ntop(packet->src_ipaddr.af,
2552 &packet->src_ipaddr.ipaddr,
2553 host_ipaddr, sizeof(host_ipaddr)));
2558 * Fill RADIUS header fields
2560 packet->code = hdr->code;
2561 packet->id = hdr->id;
2562 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2569 * @brief Receive UDP client requests, and fill in
2570 * the basics of a RADIUS_PACKET structure.
2572 RADIUS_PACKET *rad_recv(int fd, int flags)
2576 RADIUS_PACKET *packet;
2579 * Allocate the new request data structure
2581 packet = rad_alloc(NULL, 0);
2583 fr_strerror_printf("out of memory");
2588 sock_flags = MSG_PEEK;
2592 data_len = rad_recvfrom(fd, packet, sock_flags,
2593 &packet->src_ipaddr, &packet->src_port,
2594 &packet->dst_ipaddr, &packet->dst_port);
2597 * Check for socket errors.
2600 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
2601 /* packet->data is NULL */
2605 packet->data_len = data_len; /* unsigned vs signed */
2608 * If the packet is too big, then rad_recvfrom did NOT
2609 * allocate memory. Instead, it just discarded the
2612 if (packet->data_len > MAX_PACKET_LEN) {
2613 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
2614 /* packet->data is NULL */
2620 * Read no data. Continue.
2621 * This check is AFTER the MAX_PACKET_LEN check above, because
2622 * if the packet is larger than MAX_PACKET_LEN, we also have
2623 * packet->data == NULL
2625 if ((packet->data_len == 0) || !packet->data) {
2626 fr_strerror_printf("Empty packet: Socket is not ready.");
2632 * See if it's a well-formed RADIUS packet.
2634 if (!rad_packet_ok(packet, flags)) {
2640 * Remember which socket we read the packet from.
2642 packet->sockfd = fd;
2645 * FIXME: Do even more filtering by only permitting
2646 * certain IP's. The problem is that we don't know
2647 * how to do this properly for all possible clients...
2651 * Explicitely set the VP list to empty.
2655 if (fr_debug_flag) {
2656 char host_ipaddr[128];
2658 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2659 DEBUG("rad_recv: %s packet from host %s port %d",
2660 fr_packet_codes[packet->code],
2661 inet_ntop(packet->src_ipaddr.af,
2662 &packet->src_ipaddr.ipaddr,
2663 host_ipaddr, sizeof(host_ipaddr)),
2666 DEBUG("rad_recv: Packet from host %s port %d code=%d",
2667 inet_ntop(packet->src_ipaddr.af,
2668 &packet->src_ipaddr.ipaddr,
2669 host_ipaddr, sizeof(host_ipaddr)),
2673 DEBUG(", id=%d, length=%d\n",
2674 packet->id, (int) packet->data_len);
2678 if ((fr_debug_flag > 3) && fr_log_fp) rad_print_hex(packet);
2686 * @brief Verify the Request/Response Authenticator
2687 * (and Message-Authenticator if present) of a packet.
2689 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2696 if (!packet || !packet->data) return -1;
2699 * Before we allocate memory for the attributes, do more
2702 ptr = packet->data + AUTH_HDR_LEN;
2703 length = packet->data_len - AUTH_HDR_LEN;
2704 while (length > 0) {
2705 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2706 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2711 default: /* don't do anything. */
2715 * Note that more than one Message-Authenticator
2716 * attribute is invalid.
2718 case PW_MESSAGE_AUTHENTICATOR:
2719 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2720 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2722 switch (packet->code) {
2726 case PW_ACCOUNTING_RESPONSE:
2728 (original->code == PW_STATUS_SERVER)) {
2732 case PW_ACCOUNTING_REQUEST:
2733 case PW_DISCONNECT_REQUEST:
2734 case PW_DISCONNECT_ACK:
2735 case PW_DISCONNECT_NAK:
2736 case PW_COA_REQUEST:
2739 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2743 case PW_AUTHENTICATION_ACK:
2744 case PW_AUTHENTICATION_REJECT:
2745 case PW_ACCESS_CHALLENGE:
2747 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2750 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2754 fr_hmac_md5(packet->data, packet->data_len,
2755 (uint8_t const *) secret, strlen(secret),
2757 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2758 sizeof(calc_auth_vector)) != 0) {
2760 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2761 inet_ntop(packet->src_ipaddr.af,
2762 &packet->src_ipaddr.ipaddr,
2763 buffer, sizeof(buffer)));
2764 /* Silently drop packet, according to RFC 3579 */
2766 } /* else the message authenticator was good */
2769 * Reinitialize Authenticators.
2771 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2772 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2774 } /* switch over the attributes */
2778 } /* loop over the packet, sanity checking the attributes */
2781 * It looks like a RADIUS packet, but we don't know what it is
2782 * so can't validate the authenticators.
2784 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2786 fr_strerror_printf("Received Unknown packet code %d "
2787 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2789 inet_ntop(packet->src_ipaddr.af,
2790 &packet->src_ipaddr.ipaddr,
2791 buffer, sizeof(buffer)),
2797 * Calculate and/or verify Request or Response Authenticator.
2799 switch(packet->code) {
2803 case PW_AUTHENTICATION_REQUEST:
2804 case PW_STATUS_SERVER:
2806 * The authentication vector is random
2807 * nonsense, invented by the client.
2811 case PW_COA_REQUEST:
2812 case PW_DISCONNECT_REQUEST:
2813 case PW_ACCOUNTING_REQUEST:
2814 if (calc_acctdigest(packet, secret) > 1) {
2815 fr_strerror_printf("Received %s packet "
2816 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2817 fr_packet_codes[packet->code],
2818 inet_ntop(packet->src_ipaddr.af,
2819 &packet->src_ipaddr.ipaddr,
2820 buffer, sizeof(buffer)));
2825 /* Verify the reply digest */
2826 case PW_AUTHENTICATION_ACK:
2827 case PW_AUTHENTICATION_REJECT:
2828 case PW_ACCESS_CHALLENGE:
2829 case PW_ACCOUNTING_RESPONSE:
2830 case PW_DISCONNECT_ACK:
2831 case PW_DISCONNECT_NAK:
2834 rcode = calc_replydigest(packet, original, secret);
2836 fr_strerror_printf("Received %s packet "
2837 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2838 fr_packet_codes[packet->code],
2839 inet_ntop(packet->src_ipaddr.af,
2840 &packet->src_ipaddr.ipaddr,
2841 buffer, sizeof(buffer)),
2848 fr_strerror_printf("Received Unknown packet code %d "
2849 "from client %s port %d: Cannot validate Request/Response Authenticator",
2851 inet_ntop(packet->src_ipaddr.af,
2852 &packet->src_ipaddr.ipaddr,
2853 buffer, sizeof(buffer)),
2862 static ssize_t data2vp(RADIUS_PACKET *packet,
2863 RADIUS_PACKET const *original,
2865 DICT_ATTR const *da, uint8_t const *start,
2866 size_t const attrlen, size_t const packetlen,
2870 * @brief convert a "concatenated" attribute to one long VP.
2872 static ssize_t data2vp_concat(RADIUS_PACKET *packet,
2873 DICT_ATTR const *da, uint8_t const *start,
2874 size_t const packetlen, VALUE_PAIR **pvp)
2878 uint8_t const *ptr = start;
2879 uint8_t const *end = start + packetlen;
2887 * The packet has already been sanity checked, so we
2888 * don't care about walking off of the end of it.
2891 total += ptr[1] - 2;
2896 * Attributes MUST be consecutive.
2898 if (ptr[0] != attr) break;
2901 vp = pairalloc(packet, da);
2905 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->length);
2913 while (total < vp->length) {
2914 memcpy(p, ptr + 2, ptr[1] - 2);
2916 total += ptr[1] - 2;
2926 * @brief convert TLVs to one or more VPs
2928 static ssize_t data2vp_tlvs(RADIUS_PACKET *packet,
2929 RADIUS_PACKET const *original,
2930 char const *secret, DICT_ATTR const *da,
2931 uint8_t const *start, size_t length,
2934 uint8_t const *data = start;
2935 DICT_ATTR const *child;
2936 VALUE_PAIR *head, **tail;
2938 if (length < 3) return -1; /* type, length, value */
2940 VP_HEXDUMP("tlvs", data, length);
2942 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2947 while (data < (start + length)) {
2950 child = dict_attrbyparent(da, data[0], da->vendor);
2952 unsigned int my_attr, my_vendor;
2954 VP_TRACE("Failed to find child %u of TLV %s\n",
2958 * Get child attr/vendor so that
2959 * we can call unknown attr.
2962 my_vendor = da->vendor;
2964 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2969 child = dict_attrunknown(my_attr, my_vendor, true);
2976 tlv_len = data2vp(packet, original, secret, child,
2977 data + 2, data[1] - 2, data[1] - 2, tail);
2982 tail = &((*tail)->next);
2991 * @brief Convert a top-level VSA to a VP.
2993 * "length" can be LONGER than just this sub-vsa
2995 static ssize_t data2vp_vsa(RADIUS_PACKET *packet,
2996 RADIUS_PACKET const *original,
2997 char const *secret, DICT_VENDOR *dv,
2998 uint8_t const *data, size_t length,
3001 unsigned int attribute;
3002 ssize_t attrlen, my_len;
3003 DICT_ATTR const *da;
3006 if (length <= (dv->type + dv->length)) {
3007 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3014 /* data[0] must be zero */
3015 attribute = data[1] << 16;
3016 attribute |= data[2] << 8;
3017 attribute |= data[3];
3021 attribute = data[0] << 8;
3022 attribute |= data[1];
3026 attribute = data[0];
3030 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3034 switch (dv->length) {
3036 /* data[dv->type] must be zero, from rad_tlv_ok() */
3037 attrlen = data[dv->type + 1];
3041 attrlen = data[dv->type];
3049 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3054 if (attrlen <= (ssize_t) (dv->type + dv->length)) {
3055 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3061 * See if the VSA is known.
3063 da = dict_attrbyvalue(attribute, dv->vendorpec);
3064 if (!da) da = dict_attrunknown(attribute, dv->vendorpec, true);
3067 my_len = data2vp(packet, original, secret, da,
3068 data + dv->type + dv->length,
3069 attrlen - (dv->type + dv->length),
3070 attrlen - (dv->type + dv->length),
3072 if (my_len < 0) return my_len;
3079 * @brief Convert a fragmented extended attr to a VP
3089 * But for the first fragment, we get passed a pointer to the
3092 static ssize_t data2vp_extended(RADIUS_PACKET *packet,
3093 RADIUS_PACKET const *original,
3094 char const *secret, DICT_ATTR const *da,
3095 uint8_t const *data,
3096 size_t attrlen, size_t packetlen,
3101 uint8_t *head, *tail;
3102 uint8_t const *frag, *end;
3103 uint8_t const *attr;
3107 if (attrlen < 3) return -1;
3110 * Calculate the length of all of the fragments. For
3111 * now, they MUST be contiguous in the packet, and they
3112 * MUST be all of the same TYPE and EXTENDED-TYPE
3115 fraglen = attrlen - 2;
3116 frag = data + attrlen;
3117 end = data + packetlen;
3121 while (frag < end) {
3123 (frag[0] != attr[0]) ||
3124 (frag[1] < 4) || /* too short for long-extended */
3125 (frag[2] != attr[2]) ||
3126 ((frag + frag[1]) > end)) { /* overflow */
3131 last_frag = ((frag[3] & 0x80) == 0);
3133 fraglen += frag[1] - 4;
3138 head = tail = malloc(fraglen);
3139 if (!head) return -1;
3141 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3144 * And again, but faster and looser.
3146 * We copy the first fragment, followed by the rest of
3151 while (fragments > 0) {
3152 memcpy(tail, frag + 4, frag[1] - 4);
3153 tail += frag[1] - 4;
3158 VP_HEXDUMP("long-extended fragments", head, fraglen);
3160 rcode = data2vp(packet, original, secret, da,
3161 head, fraglen, fraglen, pvp);
3163 if (rcode < 0) return rcode;
3169 * @brief Convert a Vendor-Specific WIMAX to vps
3171 * Called ONLY for Vendor-Specific
3173 static ssize_t data2vp_wimax(RADIUS_PACKET *packet,
3174 RADIUS_PACKET const *original,
3175 char const *secret, uint32_t vendor,
3176 uint8_t const *data,
3177 size_t attrlen, size_t packetlen,
3183 uint8_t *head, *tail;
3184 uint8_t const *frag, *end;
3185 DICT_ATTR const *child;
3187 if (attrlen < 8) return -1;
3189 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3191 child = dict_attrbyvalue(data[4], vendor);
3192 if (!child) return -1;
3194 if ((data[6] & 0x80) == 0) {
3195 rcode = data2vp(packet, original, secret, child,
3196 data + 7, data[5] - 3, data[5] - 3,
3198 if (rcode < 0) return -1;
3203 * Calculate the length of all of the fragments. For
3204 * now, they MUST be contiguous in the packet, and they
3205 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3207 * The first fragment doesn't have a RADIUS attribute
3208 * header, so it needs to be treated a little special.
3210 fraglen = data[5] - 3;
3211 frag = data + attrlen;
3212 end = data + packetlen;
3215 while (frag < end) {
3217 (frag[0] != PW_VENDOR_SPECIFIC) ||
3218 (frag[1] < 9) || /* too short for wimax */
3219 ((frag + frag[1]) > end) || /* overflow */
3220 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3221 (frag[6] != data[4]) || /* not the same wimax attr */
3222 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3227 last_frag = ((frag[8] & 0x80) == 0);
3229 fraglen += frag[7] - 3;
3233 head = tail = malloc(fraglen);
3234 if (!head) return -1;
3237 * And again, but faster and looser.
3239 * We copy the first fragment, followed by the rest of
3244 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3245 tail += frag[4 + 1] - 3;
3246 frag += attrlen; /* should be frag[1] - 7 */
3249 * frag now points to RADIUS attributes
3252 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3253 tail += frag[2 + 4 + 1] - 3;
3255 } while (frag < end);
3257 VP_HEXDUMP("wimax fragments", head, fraglen);
3259 rcode = data2vp(packet, original, secret, child,
3260 head, fraglen, fraglen, pvp);
3262 if (rcode < 0) return rcode;
3269 * @brief Convert a top-level VSA to one or more VPs
3271 static ssize_t data2vp_vsas(RADIUS_PACKET *packet,
3272 RADIUS_PACKET const *original,
3273 char const *secret, uint8_t const *data,
3274 size_t attrlen, size_t packetlen,
3281 VALUE_PAIR *head, **tail;
3283 if (attrlen > packetlen) return -1;
3284 if (attrlen < 5) return -1; /* vid, value */
3285 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3287 memcpy(&vendor, data, 4);
3288 vendor = ntohl(vendor);
3289 dv = dict_vendorbyvalue(vendor);
3295 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3296 rcode = data2vp_wimax(packet, original, secret, vendor,
3297 data, attrlen, packetlen, pvp);
3302 * VSAs should normally be in TLV format.
3304 if (rad_tlv_ok(data + 4, attrlen - 4,
3305 dv->type, dv->length) < 0) return -1;
3308 * There may be more than one VSA in the
3309 * Vendor-Specific. If so, loop over them all.
3318 while (attrlen > 0) {
3321 vsa_len = data2vp_vsa(packet, original, secret, dv,
3322 data, attrlen, tail);
3325 fr_strerror_printf("Internal sanity check %d", __LINE__);
3328 tail = &((*tail)->next);
3331 packetlen -= vsa_len;
3341 * @brief Create any kind of VP from the attribute contents.
3343 * "length" is AT LEAST the length of this attribute, as we
3344 * expect the caller to have verified the data with
3345 * rad_packet_ok(). "length" may be up to the length of the
3348 * @return -1 on error, or "length".
3350 static ssize_t data2vp(RADIUS_PACKET *packet,
3351 RADIUS_PACKET const *original,
3353 DICT_ATTR const *da, uint8_t const *start,
3354 size_t const attrlen, size_t const packetlen,
3361 DICT_ATTR const *child;
3364 uint8_t const *data = start;
3366 uint8_t buffer[256];
3369 * FIXME: Attrlen can be larger than 253 for extended attrs!
3371 if (!da || (attrlen > packetlen) ||
3372 ((attrlen > 253) && (attrlen != packetlen)) ||
3373 (attrlen > 128*1024)) {
3374 fr_strerror_printf("data2vp: invalid arguments");
3378 VP_HEXDUMP("data2vp", start, attrlen);
3380 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3385 * Hacks for CUI. The WiMAX spec says that it can be
3386 * zero length, even though this is forbidden by the
3387 * RADIUS specs. So... we make a special case for it.
3390 if (!((da->vendor == 0) &&
3391 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3398 * Hacks for Coverity. Editing the dictionary
3399 * will break assumptions about CUI. We know
3400 * this, but Coverity doesn't.
3402 if (da->type != PW_TYPE_STRING) return -1;
3405 data = (uint8_t const *) "";
3407 goto alloc_cui; /* skip everything */
3411 * Hacks for tags. If the attribute is capable of
3412 * encoding a tag, and there's room for the tag, and
3413 * there is a tag, or it's encrypted with Tunnel-Password,
3414 * then decode the tag.
3416 if (da->flags.has_tag && (datalen > 1) &&
3417 ((data[0] < 0x20) ||
3418 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3420 * Only "short" attributes can be encrypted.
3422 if (datalen >= sizeof(buffer)) return -1;
3424 if (da->type == PW_TYPE_STRING) {
3425 memcpy(buffer, data + 1, datalen - 1);
3429 } else if (da->type == PW_TYPE_INTEGER) {
3430 memcpy(buffer, data, attrlen);
3435 return -1; /* only string and integer can have tags */
3442 * Decrypt the attribute.
3444 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3445 if (data == start) memcpy(buffer, data, attrlen);
3448 switch (da->flags.encrypt) { /* can't be tagged */
3452 case FLAG_ENCRYPT_USER_PASSWORD:
3454 rad_pwdecode((char *) buffer,
3458 rad_pwdecode((char *) buffer,
3463 datalen = strlen((char *) buffer);
3467 * Tunnel-Password's may go ONLY in response
3468 * packets. They can have a tag, so datalen is
3469 * not the same as attrlen.
3471 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3472 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3473 original ? original->vector : nullvector) < 0) {
3479 * Ascend-Send-Secret
3480 * Ascend-Receive-Secret
3482 case FLAG_ENCRYPT_ASCEND_SECRET:
3486 uint8_t my_digest[AUTH_VECTOR_LEN];
3487 make_secret(my_digest,
3490 memcpy(buffer, my_digest,
3492 buffer[AUTH_VECTOR_LEN] = '\0';
3493 datalen = strlen((char *) buffer);
3499 } /* switch over encryption flags */
3503 * Double-check the length after decrypting the
3507 case PW_TYPE_STRING:
3508 case PW_TYPE_OCTETS:
3511 case PW_TYPE_ABINARY:
3512 if (datalen > sizeof(vp->vp_filter)) goto raw;
3515 case PW_TYPE_INTEGER:
3516 case PW_TYPE_IPADDR:
3518 case PW_TYPE_SIGNED:
3519 if (datalen != 4) goto raw;
3522 case PW_TYPE_INTEGER64:
3524 if (datalen != 8) goto raw;
3527 case PW_TYPE_IPV6ADDR:
3528 if (datalen != 16) goto raw;
3531 case PW_TYPE_IPV6PREFIX:
3532 if ((datalen < 2) || (datalen > 18)) goto raw;
3533 if (data[1] > 128) goto raw;
3537 if (datalen != 1) goto raw;
3541 if (datalen != 2) goto raw;
3544 case PW_TYPE_ETHERNET:
3545 if (datalen != 6) goto raw;
3548 case PW_TYPE_COMBO_IP:
3550 child = dict_attrbytype(da->attr, da->vendor,
3552 } else if (datalen == 16) {
3553 child = dict_attrbytype(da->attr, da->vendor,
3558 if (!child) goto raw;
3559 da = child; /* re-write it */
3562 case PW_TYPE_IPV4PREFIX:
3563 if (datalen != 6) goto raw;
3564 if ((data[1] & 0x3f) > 32) goto raw;
3568 * The rest of the data types can cause
3569 * recursion! Ask yourself, "is recursion OK?"
3572 case PW_TYPE_EXTENDED:
3573 if (datalen < 2) goto raw; /* etype, value */
3575 child = dict_attrbyparent(da, data[0], 0);
3576 if (!child) goto raw;
3579 * Recurse to decode the contents, which could be
3580 * a TLV, IPaddr, etc. Note that we decode only
3581 * the current attribute, and we ignore any extra
3584 rcode = data2vp(packet, original, secret, child,
3585 data + 1, attrlen - 1, attrlen - 1, pvp);
3586 if (rcode < 0) goto raw;
3589 case PW_TYPE_LONG_EXTENDED:
3590 if (datalen < 3) goto raw; /* etype, flags, value */
3592 child = dict_attrbyparent(da, data[0], 0);
3594 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3595 (datalen < (3 + 4 + 1))) {
3596 /* da->attr < 255, da->vendor == 0 */
3597 child = dict_attrunknown(data[0], da->attr * FR_MAX_VENDOR, true);
3600 * Try to find the VSA.
3602 memcpy(&vendor, data + 3, 4);
3603 vendor = ntohl(vendor);
3605 if (vendor == 0) goto raw;
3607 child = dict_attrunknown(data[7], vendor | (da->attr * FR_MAX_VENDOR), true);
3611 fr_strerror_printf("Internal sanity check %d", __LINE__);
3617 * If there no more fragments, then the contents
3618 * have to be a well-known data type.
3621 if ((data[1] & 0x80) == 0) {
3622 rcode = data2vp(packet, original, secret, child,
3623 data + 2, attrlen - 2, attrlen - 2,
3625 if (rcode < 0) goto raw;
3630 * This requires a whole lot more work.
3632 return data2vp_extended(packet, original, secret, child,
3633 start, attrlen, packetlen, pvp);
3636 if (datalen < 6) goto raw; /* vid, vtype, value */
3638 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3640 memcpy(&vendor, data, 4);
3641 vendor = ntohl(vendor);
3642 dv = dict_vendorbyvalue(vendor);
3644 child = dict_attrunknown(data[4], da->vendor | vendor, true);
3646 child = dict_attrbyparent(da, data[4], vendor);
3648 child = dict_attrunknown(data[4], da->vendor | vendor, true);
3651 if (!child) goto raw;
3653 rcode = data2vp(packet, original, secret, child,
3654 data + 5, attrlen - 5, attrlen - 5, pvp);
3655 if (rcode < 0) goto raw;
3660 * We presume that the TLVs all fit into one
3661 * attribute, OR they've already been grouped
3662 * into a contiguous memory buffer.
3664 rcode = data2vp_tlvs(packet, original, secret, da,
3665 data, attrlen, pvp);
3666 if (rcode < 0) goto raw;
3671 * VSAs can be WiMAX, in which case they don't
3672 * fit into one attribute.
3674 rcode = data2vp_vsas(packet, original, secret,
3675 data, attrlen, packetlen, pvp);
3676 if (rcode < 0) goto raw;
3682 * Re-write the attribute to be "raw". It is
3683 * therefore of type "octets", and will be
3686 da = dict_attrunknown(da->attr, da->vendor, true);
3688 fr_strerror_printf("Internal sanity check %d", __LINE__);
3696 if (da->type != PW_TYPE_OCTETS) {
3697 dict_attr_free(&da);
3705 * And now that we've verified the basic type
3706 * information, decode the actual data.
3709 vp = pairalloc(packet, da);
3712 vp->length = datalen;
3716 case PW_TYPE_STRING:
3717 p = talloc_array(vp, char, vp->length + 1);
3718 memcpy(p, data, vp->length);
3719 p[vp->length] = '\0';
3720 vp->vp_strvalue = p;
3723 case PW_TYPE_OCTETS:
3724 vp->vp_octets = talloc_memdup(vp, data, vp->length);
3727 case PW_TYPE_ABINARY:
3728 if (vp->length > sizeof(vp->vp_filter)) {
3729 vp->length = sizeof(vp->vp_filter);
3731 memcpy(vp->vp_filter, data, vp->length);
3735 vp->vp_integer = data[0];
3739 vp->vp_integer = (data[0] << 8) | data[1];
3742 case PW_TYPE_INTEGER:
3743 memcpy(&vp->vp_integer, data, 4);
3744 vp->vp_integer = ntohl(vp->vp_integer);
3747 case PW_TYPE_INTEGER64:
3748 memcpy(&vp->vp_integer64, data, 8);
3749 vp->vp_integer64 = ntohll(vp->vp_integer64);
3753 memcpy(&vp->vp_date, data, 4);
3754 vp->vp_date = ntohl(vp->vp_date);
3757 case PW_TYPE_ETHERNET:
3758 memcpy(&vp->vp_ether, data, 6);
3761 case PW_TYPE_IPADDR:
3762 memcpy(&vp->vp_ipaddr, data, 4);
3766 memcpy(&vp->vp_ifid, data, 8);
3769 case PW_TYPE_IPV6ADDR:
3770 memcpy(&vp->vp_ipv6addr, data, 16);
3773 case PW_TYPE_IPV6PREFIX:
3775 * FIXME: double-check that
3776 * (vp->vp_octets[1] >> 3) matches vp->length + 2
3778 memcpy(&vp->vp_ipv6prefix, data, vp->length);
3779 if (vp->length < 18) {
3780 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->length, 0,
3785 case PW_TYPE_IPV4PREFIX:
3786 /* FIXME: do the same double-check as for IPv6Prefix */
3787 memcpy(&vp->vp_ipv4prefix, buffer, sizeof(vp->vp_ipv4prefix));
3790 * /32 means "keep all bits". Otherwise, mask
3793 if ((data[1] & 0x3f) > 32) {
3794 uint32_t addr, mask;
3796 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3798 mask <<= (32 - (buffer[1] & 0x3f));
3803 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3807 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3808 memcpy(&vp->vp_integer, buffer, 4);
3809 vp->vp_integer = ntohl(vp->vp_integer);
3814 fr_strerror_printf("Internal sanity check %d", __LINE__);
3825 * @brief Create a "normal" VALUE_PAIR from the given data.
3827 ssize_t rad_attr2vp(RADIUS_PACKET *packet,
3828 RADIUS_PACKET const *original,
3830 uint8_t const *data, size_t length,
3835 DICT_ATTR const *da;
3837 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3838 fr_strerror_printf("rad_attr2vp: Insufficient data");
3842 da = dict_attrbyvalue(data[0], 0);
3843 if (!da) da = dict_attrunknown(data[0], 0, true);
3847 * Pass the entire thing to the decoding function
3849 if (da->flags.concat) {
3850 return data2vp_concat(packet, da, data, length, pvp);
3854 * Note that we pass the entire length, not just the
3855 * length of this attribute. The Extended or WiMAX
3856 * attributes may have the "continuation" bit set, and
3857 * will thus be more than one attribute in length.
3859 rcode = data2vp(packet, original, secret, da,
3860 data + 2, data[1] - 2, length - 2, pvp);
3861 if (rcode < 0) return rcode;
3868 * @brief Converts data in network byte order to a VP
3869 * @return -1 on error, or the length of the data read
3871 ssize_t rad_data2vp(unsigned int attribute, unsigned int vendor,
3872 uint8_t const *data, size_t length,
3875 DICT_ATTR const *da;
3877 if (!data || (length == 0) || !pvp) return -1;
3879 da = dict_attrbyvalue(attribute, vendor);
3880 if (!da) da = dict_attrunknown(attribute, vendor, true);
3883 return data2vp(NULL, NULL, NULL, da,
3884 data, length, length, pvp);
3888 * @brief Converts vp_data to network byte order
3889 * @return -1 on error, or the length of the value
3891 ssize_t rad_vp2data(VALUE_PAIR const *vp, uint8_t *out, size_t outlen)
3901 fr_strerror_printf("ERROR: rad_vp2data buffer passed too small");
3905 switch(vp->da->type) {
3906 case PW_TYPE_STRING:
3907 case PW_TYPE_OCTETS:
3909 memcpy(out, vp->data.ptr, len);
3913 * All of this data is at the same
3917 case PW_TYPE_IPADDR:
3918 case PW_TYPE_IPV6ADDR:
3919 case PW_TYPE_IPV6PREFIX:
3920 case PW_TYPE_IPV4PREFIX:
3921 case PW_TYPE_ABINARY:
3922 memcpy(out, &vp->data, len);
3926 out[0] = vp->vp_integer & 0xff;
3930 out[0] = (vp->vp_integer >> 8) & 0xff;
3931 out[1] = vp->vp_integer & 0xff;
3934 case PW_TYPE_INTEGER:
3935 lvalue = htonl(vp->vp_integer);
3936 memcpy(out, &lvalue, sizeof(lvalue));
3939 case PW_TYPE_INTEGER64:
3940 lvalue64 = htonll(vp->vp_integer64);
3941 memcpy(out, &lvalue64, sizeof(lvalue64));
3945 lvalue = htonl(vp->vp_date);
3946 memcpy(out, &lvalue, sizeof(lvalue));
3949 case PW_TYPE_SIGNED:
3953 slvalue = htonl(vp->vp_signed);
3954 memcpy(out, &slvalue, sizeof(slvalue));
3957 /* unknown type: ignore it */
3959 fr_strerror_printf("ERROR: Unknown attribute type %d",
3968 * @brief Calculate/check digest, and decode radius attributes.
3969 * @return -1 on decoding error, 0 on success
3971 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
3977 radius_packet_t *hdr;
3978 VALUE_PAIR *head, **tail, *vp;
3981 * Extract attribute-value pairs
3983 hdr = (radius_packet_t *)packet->data;
3985 packet_length = packet->data_len - AUTH_HDR_LEN;
3992 * Loop over the attributes, decoding them into VPs.
3994 while (packet_length > 0) {
3998 * This may return many VPs
4000 my_len = rad_attr2vp(packet, original, secret,
4001 ptr, packet_length, &vp);
4016 * VSA's may not have been counted properly in
4017 * rad_packet_ok() above, as it is hard to count
4018 * then without using the dictionary. We
4019 * therefore enforce the limits here, too.
4021 if ((fr_max_attributes > 0) &&
4022 (num_attributes > fr_max_attributes)) {
4023 char host_ipaddr[128];
4026 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4027 inet_ntop(packet->src_ipaddr.af,
4028 &packet->src_ipaddr.ipaddr,
4029 host_ipaddr, sizeof(host_ipaddr)),
4030 num_attributes, fr_max_attributes);
4035 packet_length -= my_len;
4039 * Merge information from the outside world into our
4042 fr_rand_seed(packet->data, AUTH_HDR_LEN);
4045 * There may be VP's already in the packet. Don't
4046 * destroy them. Instead, add the decoded attributes to
4047 * the tail of the list.
4049 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4059 * @brief Encode password.
4061 * We assume that the passwd buffer passed is big enough.
4062 * RFC2138 says the password is max 128 chars, so the size
4063 * of the passwd buffer must be at least 129 characters.
4064 * Preferably it's just MAX_STRING_LEN.
4066 * int *pwlen is updated to the new length of the encrypted
4067 * password - a multiple of 16 bytes.
4069 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4070 uint8_t const *vector)
4072 FR_MD5_CTX context, old;
4073 uint8_t digest[AUTH_VECTOR_LEN];
4074 int i, n, secretlen;
4078 * RFC maximum is 128 bytes.
4080 * If length is zero, pad it out with zeros.
4082 * If the length isn't aligned to 16 bytes,
4083 * zero out the extra data.
4087 if (len > 128) len = 128;
4090 memset(passwd, 0, AUTH_PASS_LEN);
4091 len = AUTH_PASS_LEN;
4092 } else if ((len % AUTH_PASS_LEN) != 0) {
4093 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4094 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4099 * Use the secret to setup the decryption digest
4101 secretlen = strlen(secret);
4103 fr_MD5Init(&context);
4104 fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
4105 old = context; /* save intermediate work */
4108 * Encrypt it in place. Don't bother checking
4109 * len, as we've ensured above that it's OK.
4111 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4113 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
4114 fr_MD5Final(digest, &context);
4117 fr_MD5Update(&context,
4118 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4120 fr_MD5Final(digest, &context);
4123 for (i = 0; i < AUTH_PASS_LEN; i++) {
4124 passwd[i + n] ^= digest[i];
4132 * @brief Decode password.
4134 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4135 uint8_t const *vector)
4137 FR_MD5_CTX context, old;
4138 uint8_t digest[AUTH_VECTOR_LEN];
4140 size_t n, secretlen;
4143 * The RFC's say that the maximum is 128.
4144 * The buffer we're putting it into above is 254, so
4145 * we don't need to do any length checking.
4147 if (pwlen > 128) pwlen = 128;
4152 if (pwlen == 0) goto done;
4155 * Use the secret to setup the decryption digest
4157 secretlen = strlen(secret);
4159 fr_MD5Init(&context);
4160 fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
4161 old = context; /* save intermediate work */
4164 * The inverse of the code above.
4166 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4168 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
4169 fr_MD5Final(digest, &context);
4172 if (pwlen > AUTH_PASS_LEN) {
4173 fr_MD5Update(&context, (uint8_t *) passwd,
4177 fr_MD5Final(digest, &context);
4180 if (pwlen > (n + AUTH_PASS_LEN)) {
4181 fr_MD5Update(&context, (uint8_t *) passwd + n,
4186 for (i = 0; i < AUTH_PASS_LEN; i++) {
4187 passwd[i + n] ^= digest[i];
4192 passwd[pwlen] = '\0';
4193 return strlen(passwd);
4198 * @brief Encode Tunnel-Password attributes when sending them out on the wire.
4200 * int *pwlen is updated to the new length of the encrypted
4201 * password - a multiple of 16 bytes.
4203 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4206 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4207 uint8_t const *vector)
4209 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4210 unsigned char digest[AUTH_VECTOR_LEN];
4212 int i, n, secretlen;
4217 if (len > 127) len = 127;
4220 * Shift the password 3 positions right to place a salt and original
4221 * length, tag will be added automatically on packet send
4223 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
4227 * save original password length as first password character;
4234 * Generate salt. The RFC's say:
4236 * The high bit of salt[0] must be set, each salt in a
4237 * packet should be unique, and they should be random
4239 * So, we set the high bit, add in a counter, and then
4240 * add in some CSPRNG data. should be OK..
4242 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4243 (fr_rand() & 0x07));
4244 salt[1] = fr_rand();
4247 * Padd password to multiple of AUTH_PASS_LEN bytes.
4249 n = len % AUTH_PASS_LEN;
4251 n = AUTH_PASS_LEN - n;
4252 for (; n > 0; n--, len++)
4255 /* set new password length */
4259 * Use the secret to setup the decryption digest
4261 secretlen = strlen(secret);
4262 memcpy(buffer, secret, secretlen);
4264 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4266 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4267 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4268 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4270 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4271 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4274 for (i = 0; i < AUTH_PASS_LEN; i++) {
4275 passwd[i + n2] ^= digest[i];
4283 * @brief Decode Tunnel-Password encrypted attributes.
4285 * Defined in RFC-2868, this uses a two char SALT along with the
4286 * initial intermediate value, to differentiate it from the
4289 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4290 uint8_t const *vector)
4292 FR_MD5_CTX context, old;
4293 uint8_t digest[AUTH_VECTOR_LEN];
4295 unsigned i, n, len, reallen;
4300 * We need at least a salt.
4303 fr_strerror_printf("tunnel password is too short");
4308 * There's a salt, but no password. Or, there's a salt
4309 * and a 'data_len' octet. It's wrong, but at least we
4310 * can figure out what it means: the password is empty.
4312 * Note that this means we ignore the 'data_len' field,
4313 * if the attribute length tells us that there's no
4314 * more data. So the 'data_len' field may be wrong,
4323 len -= 2; /* discount the salt */
4326 * Use the secret to setup the decryption digest
4328 secretlen = strlen(secret);
4330 fr_MD5Init(&context);
4331 fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
4332 old = context; /* save intermediate work */
4335 * Set up the initial key:
4337 * b(1) = MD5(secret + vector + salt)
4339 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
4340 fr_MD5Update(&context, passwd, 2);
4343 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4347 fr_MD5Final(digest, &context);
4352 * A quick check: decrypt the first octet
4353 * of the password, which is the
4354 * 'data_len' field. Ensure it's sane.
4356 reallen = passwd[2] ^ digest[0];
4357 if (reallen >= len) {
4358 fr_strerror_printf("tunnel password is too long for the attribute");
4362 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
4366 fr_MD5Final(digest, &context);
4369 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
4372 for (i = base; i < AUTH_PASS_LEN; i++) {
4373 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4378 * See make_tunnel_password, above.
4380 if (reallen > 239) reallen = 239;
4383 passwd[reallen] = 0;
4389 * @brief Encode a CHAP password
4391 * @bug FIXME: might not work with Ascend because
4392 * we use vp->length, and Ascend gear likes
4393 * to send an extra '\0' in the string!
4395 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4396 VALUE_PAIR *password)
4400 uint8_t string[MAX_STRING_LEN * 2 + 1];
4401 VALUE_PAIR *challenge;
4404 * Sanity check the input parameters
4406 if ((packet == NULL) || (password == NULL)) {
4411 * Note that the password VP can be EITHER
4412 * a User-Password attribute (from a check-item list),
4413 * or a CHAP-Password attribute (the client asking
4414 * the library to encode it).
4422 memcpy(ptr, password->vp_strvalue, password->length);
4423 ptr += password->length;
4424 i += password->length;
4427 * Use Chap-Challenge pair if present,
4428 * Request Authenticator otherwise.
4430 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4432 memcpy(ptr, challenge->vp_strvalue, challenge->length);
4433 i += challenge->length;
4435 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4436 i += AUTH_VECTOR_LEN;
4440 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4447 * @brief Seed the random number generator.
4449 * May be called any number of times.
4451 void fr_rand_seed(void const *data, size_t size)
4456 * Ensure that the pool is initialized.
4458 if (!fr_rand_initialized) {
4461 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4463 fd = open("/dev/urandom", O_RDONLY);
4469 while (total < sizeof(fr_rand_pool.randrsl)) {
4470 this = read(fd, fr_rand_pool.randrsl,
4471 sizeof(fr_rand_pool.randrsl) - total);
4472 if ((this < 0) && (errno != EINTR)) break;
4473 if (this > 0) total += this;
4477 fr_rand_pool.randrsl[0] = fd;
4478 fr_rand_pool.randrsl[1] = time(NULL);
4479 fr_rand_pool.randrsl[2] = errno;
4482 fr_randinit(&fr_rand_pool, 1);
4483 fr_rand_pool.randcnt = 0;
4484 fr_rand_initialized = 1;
4490 * Hash the user data
4493 if (!hash) hash = fr_rand();
4494 hash = fr_hash_update(data, size, hash);
4496 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4501 * @brief Return a 32-bit random number.
4503 uint32_t fr_rand(void)
4508 * Ensure that the pool is initialized.
4510 if (!fr_rand_initialized) {
4511 fr_rand_seed(NULL, 0);
4514 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4515 if (fr_rand_pool.randcnt >= 256) {
4516 fr_rand_pool.randcnt = 0;
4517 fr_isaac(&fr_rand_pool);
4524 /** Allocate a new RADIUS_PACKET
4526 * @param ctx the context in which the packet is allocated. May be NULL if
4527 * the packet is not associated with a REQUEST.
4528 * @param newvector if true a new request authenticator will be generated.
4529 * @return a new RADIUS_PACKET or NULL on error.
4531 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, int newvector)
4535 rp = talloc_zero(ctx, RADIUS_PACKET);
4537 fr_strerror_printf("out of memory");
4545 uint32_t hash, base;
4548 * Don't expose the actual contents of the random
4552 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4553 hash = fr_rand() ^ base;
4554 memcpy(rp->vector + i, &hash, sizeof(hash));
4557 fr_rand(); /* stir the pool again */
4562 /** Allocate a new RADIUS_PACKET response
4564 * @param ctx the context in which the packet is allocated. May be NULL if
4565 * the packet is not associated with a REQUEST.
4566 * @param packet The request packet.
4567 * @return a new RADIUS_PACKET or NULL on error.
4569 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4571 RADIUS_PACKET *reply;
4573 if (!packet) return NULL;
4575 reply = rad_alloc(ctx, 0);
4576 if (!reply) return NULL;
4579 * Initialize the fields from the request.
4581 reply->sockfd = packet->sockfd;
4582 reply->dst_ipaddr = packet->src_ipaddr;
4583 reply->src_ipaddr = packet->dst_ipaddr;
4584 reply->dst_port = packet->src_port;
4585 reply->src_port = packet->dst_port;
4586 reply->id = packet->id;
4587 reply->code = 0; /* UNKNOWN code */
4588 memcpy(reply->vector, packet->vector,
4589 sizeof(reply->vector));
4592 reply->data_len = 0;
4599 * @brief Free a RADIUS_PACKET
4601 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4603 RADIUS_PACKET *radius_packet;
4605 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4606 radius_packet = *radius_packet_ptr;
4608 pairfree(&radius_packet->vps);
4610 talloc_free(radius_packet);
4611 *radius_packet_ptr = NULL;