2 * This library is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU Lesser General Public
4 * License as published by the Free Software Foundation; either
5 * version 2.1 of the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
12 * You should have received a copy of the GNU Lesser General Public
13 * License along with this library; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Functions to send/receive radius packets.
23 * @copyright 2000-2003,2006 The FreeRADIUS server project
28 #include <freeradius-devel/libradius.h>
30 #include <freeradius-devel/md5.h>
36 #include <freeradius-devel/udpfromto.h>
40 * Some messages get printed out only in debugging mode.
42 #define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf
45 #define VP_TRACE printf
47 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
51 printf("--- %s ---\n", msg);
52 for (i = 0; i < len; i++) {
53 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
54 printf("%02x ", data[i]);
55 if ((i & 0x0f) == 0x0f) printf("\n");
57 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
62 #define VP_TRACE(_x, ...)
63 #define VP_HEXDUMP(_x, _y, _z)
68 * The RFC says 4096 octets max, and most packets are less than 256.
70 #define MAX_PACKET_LEN 4096
73 * The maximum number of attributes which we allow in an incoming
74 * request. If there are more attributes than this, the request
77 * This helps to minimize the potential for a DoS, when an
78 * attacker spoofs Access-Request packets, which don't have a
79 * Message-Authenticator attribute. This means that the packet
80 * is unsigned, and the attacker can use resources on the server,
81 * even if the end request is rejected.
83 uint32_t fr_max_attributes = 0;
84 FILE *fr_log_fp = NULL;
86 typedef struct radius_packet_t {
90 uint8_t vector[AUTH_VECTOR_LEN];
94 static fr_randctx fr_rand_pool; /* across multiple calls */
95 static int fr_rand_initialized = 0;
96 static unsigned int salt_offset = 0;
97 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
99 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
104 "Accounting-Request",
105 "Accounting-Response",
110 "Accounting-Message", //!< 10
121 "Resource-Free-Request",
122 "Resource-Free-Response",
123 "Resource-Query-Request",
124 "Resource-Query-Response",
125 "Alternate-Resource-Reclaim-Request",
126 "NAS-Reboot-Request",
127 "NAS-Reboot-Response",
140 "Disconnect-Request", //!< 40
150 "IP-Address-Allocate",
151 "IP-Address-Release", //!< 50
155 void fr_printf_log(char const *fmt, ...)
160 if ((fr_debug_lvl == 0) || !fr_log_fp) {
165 vfprintf(fr_log_fp, fmt, ap);
171 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
173 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
177 for (i = 0; i < attrlen; i++) {
178 if ((i > 0) && ((i & 0x0f) == 0x00))
179 fprintf(fr_log_fp, "%.*s", depth, tabs);
180 fprintf(fr_log_fp, "%02x ", ptr[i]);
181 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
183 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
187 void rad_print_hex(RADIUS_PACKET *packet)
191 if (!packet->data || !fr_log_fp) return;
193 fprintf(fr_log_fp, " Socket:\t%d\n", packet->sockfd);
195 fprintf(fr_log_fp, " Proto:\t%d\n", packet->proto);
198 if (packet->src_ipaddr.af == AF_INET) {
201 fprintf(fr_log_fp, " Src IP:\t%s\n",
202 inet_ntop(packet->src_ipaddr.af,
203 &packet->src_ipaddr.ipaddr,
204 buffer, sizeof(buffer)));
205 fprintf(fr_log_fp, " port:\t%u\n", packet->src_port);
207 fprintf(fr_log_fp, " Dst IP:\t%s\n",
208 inet_ntop(packet->dst_ipaddr.af,
209 &packet->dst_ipaddr.ipaddr,
210 buffer, sizeof(buffer)));
211 fprintf(fr_log_fp, " port:\t%u\n", packet->dst_port);
214 if (packet->data[0] < FR_MAX_PACKET_CODE) {
215 fprintf(fr_log_fp, " Code:\t\t(%d) %s\n", packet->data[0], fr_packet_codes[packet->data[0]]);
217 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
219 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
220 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
222 fprintf(fr_log_fp, " Vector:\t");
223 for (i = 4; i < 20; i++) {
224 fprintf(fr_log_fp, "%02x", packet->data[i]);
226 fprintf(fr_log_fp, "\n");
228 if (packet->data_len > 20) {
231 fprintf(fr_log_fp, " Data:");
233 total = packet->data_len - 20;
234 ptr = packet->data + 20;
238 unsigned int vendor = 0;
240 fprintf(fr_log_fp, "\t\t");
241 if (total < 2) { /* too short */
242 fprintf(fr_log_fp, "%02x\n", *ptr);
246 if (ptr[1] > total) { /* too long */
247 for (i = 0; i < total; i++) {
248 fprintf(fr_log_fp, "%02x ", ptr[i]);
253 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
254 attrlen = ptr[1] - 2;
256 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
258 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
259 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
260 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
270 print_hex_data(ptr, attrlen, 3);
279 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
282 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
283 #ifdef WITH_UDPFROMTO
284 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
286 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
288 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
291 struct sockaddr_storage dst;
292 socklen_t sizeof_dst;
294 #ifdef WITH_UDPFROMTO
295 struct sockaddr_storage src;
296 socklen_t sizeof_src;
298 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
301 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
305 #ifdef WITH_UDPFROMTO
307 * And if they don't specify a source IP address, don't
310 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
311 (src_ipaddr->af != AF_UNSPEC) &&
312 !fr_inaddr_any(src_ipaddr)) {
313 rcode = sendfromto(sockfd, data, data_len, flags,
314 (struct sockaddr *)&src, sizeof_src,
315 (struct sockaddr *)&dst, sizeof_dst);
321 * No udpfromto, fail gracefully.
323 rcode = sendto(sockfd, data, data_len, flags,
324 (struct sockaddr *) &dst, sizeof_dst);
325 #ifdef WITH_UDPFROMTO
329 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
336 void rad_recv_discard(int sockfd)
339 struct sockaddr_storage src;
340 socklen_t sizeof_src = sizeof(src);
342 (void) recvfrom(sockfd, header, sizeof(header), 0,
343 (struct sockaddr *)&src, &sizeof_src);
346 /** Basic validation of RADIUS packet header
348 * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
349 * consumed when discarding malformed packet.
351 * @param[in] sockfd we're reading from.
352 * @param[out] src_ipaddr of the packet.
353 * @param[out] src_port of the packet.
354 * @param[out] code Pointer to where to write the packet code.
357 * - 1 on decode error.
358 * - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
360 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
362 ssize_t data_len, packet_len;
364 struct sockaddr_storage src;
365 socklen_t sizeof_src = sizeof(src);
367 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
368 (struct sockaddr *)&src, &sizeof_src);
370 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
375 * Too little data is available, discard the packet.
378 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
379 rad_recv_discard(sockfd);
383 } else { /* we got 4 bytes of data. */
385 * See how long the packet says it is.
387 packet_len = (header[2] * 256) + header[3];
390 * The length in the packet says it's less than
391 * a RADIUS header length: discard it.
393 if (packet_len < RADIUS_HDR_LEN) {
394 FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN) " bytes of packet "
395 "data, got %zu bytes", packet_len);
396 rad_recv_discard(sockfd);
401 * Enforce RFC requirements, for sanity.
402 * Anything after 4k will be discarded.
404 } else if (packet_len > MAX_PACKET_LEN) {
405 FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
406 STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
407 rad_recv_discard(sockfd);
414 * Convert AF. If unknown, discard packet.
416 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
417 FR_DEBUG_STRERROR_PRINTF("Unkown address family");
418 rad_recv_discard(sockfd);
426 * The packet says it's this long, but the actual UDP
427 * size could still be smaller.
433 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
436 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
437 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
438 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
440 struct sockaddr_storage src;
441 struct sockaddr_storage dst;
442 socklen_t sizeof_src = sizeof(src);
443 socklen_t sizeof_dst = sizeof(dst);
449 memset(&src, 0, sizeof_src);
450 memset(&dst, 0, sizeof_dst);
453 * Read the length of the packet, from the packet.
454 * This lets us allocate the buffer to use for
455 * reading the rest of the packet.
457 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
458 (struct sockaddr *)&src, &sizeof_src);
460 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
465 * Too little data is available, discard the packet.
468 rad_recv_discard(sockfd);
472 } else { /* we got 4 bytes of data. */
474 * See how long the packet says it is.
476 len = (header[2] * 256) + header[3];
479 * The length in the packet says it's less than
480 * a RADIUS header length: discard it.
482 if (len < RADIUS_HDR_LEN) {
483 recvfrom(sockfd, header, sizeof(header), flags,
484 (struct sockaddr *)&src, &sizeof_src);
488 * Enforce RFC requirements, for sanity.
489 * Anything after 4k will be discarded.
491 } else if (len > MAX_PACKET_LEN) {
492 recvfrom(sockfd, header, sizeof(header), flags,
493 (struct sockaddr *)&src, &sizeof_src);
498 packet->data = talloc_array(packet, uint8_t, len);
499 if (!packet->data) return -1;
502 * Receive the packet. The OS will discard any data in the
503 * packet after "len" bytes.
505 #ifdef WITH_UDPFROMTO
506 data_len = recvfromto(sockfd, packet->data, len, flags,
507 (struct sockaddr *)&src, &sizeof_src,
508 (struct sockaddr *)&dst, &sizeof_dst);
510 data_len = recvfrom(sockfd, packet->data, len, flags,
511 (struct sockaddr *)&src, &sizeof_src);
514 * Get the destination address, too.
516 if (getsockname(sockfd, (struct sockaddr *)&dst,
517 &sizeof_dst) < 0) return -1;
523 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
524 return -1; /* Unknown address family, Die Die Die! */
528 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
532 * Different address families should never happen.
534 if (src.ss_family != dst.ss_family) {
542 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
543 /** Build an encrypted secret value to return in a reply packet
545 * The secret is hidden by xoring with a MD5 digest created from
546 * the shared secret and the authentication vector.
547 * We put them into MD5 in the reverse order from that used when
548 * encrypting passwords to RADIUS.
550 static void make_secret(uint8_t *digest, uint8_t const *vector,
551 char const *secret, uint8_t const *value)
556 fr_md5_init(&context);
557 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
558 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
559 fr_md5_final(digest, &context);
561 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
562 digest[i] ^= value[i];
566 #define MAX_PASS_LEN (128)
567 static void make_passwd(uint8_t *output, ssize_t *outlen,
568 uint8_t const *input, size_t inlen,
569 char const *secret, uint8_t const *vector)
571 FR_MD5_CTX context, old;
572 uint8_t digest[AUTH_VECTOR_LEN];
573 uint8_t passwd[MAX_PASS_LEN];
578 * If the length is zero, round it up.
582 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
584 memcpy(passwd, input, len);
585 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
591 else if ((len & 0x0f) != 0) {
597 fr_md5_init(&context);
598 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
604 fr_md5_update(&context, vector, AUTH_PASS_LEN);
606 for (n = 0; n < len; n += AUTH_PASS_LEN) {
609 fr_md5_update(&context,
610 passwd + n - AUTH_PASS_LEN,
614 fr_md5_final(digest, &context);
615 for (i = 0; i < AUTH_PASS_LEN; i++) {
616 passwd[i + n] ^= digest[i];
620 memcpy(output, passwd, len);
624 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
625 uint8_t const *input, size_t inlen, size_t room,
626 char const *secret, uint8_t const *vector)
628 FR_MD5_CTX context, old;
629 uint8_t digest[AUTH_VECTOR_LEN];
631 size_t encrypted_len;
634 * The password gets encoded with a 1-byte "length"
635 * field. Ensure that it doesn't overflow.
637 if (room > 253) room = 253;
640 * Limit the maximum size of the input password. 2 bytes
641 * are taken up by the salt, and one by the encoded
642 * "length" field. Note that if we have a tag, the
643 * "room" will be 252 octets, not 253 octets.
645 if (inlen > (room - 3)) inlen = room - 3;
648 * Length of the encrypted data is the clear-text
649 * password length plus one byte which encodes the length
650 * of the password. We round up to the nearest encoding
651 * block. Note that this can result in the encoding
652 * length being more than 253 octets.
654 encrypted_len = inlen + 1;
655 if ((encrypted_len & 0x0f) != 0) {
656 encrypted_len += 0x0f;
657 encrypted_len &= ~0x0f;
661 * We need 2 octets for the salt, followed by the actual
664 if (encrypted_len > (room - 2)) encrypted_len = room - 2;
666 *outlen = encrypted_len + 2; /* account for the salt */
669 * Copy the password over, and zero-fill the remainder.
671 memcpy(output + 3, input, inlen);
672 memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
675 * Generate salt. The RFCs say:
677 * The high bit of salt[0] must be set, each salt in a
678 * packet should be unique, and they should be random
680 * So, we set the high bit, add in a counter, and then
681 * add in some CSPRNG data. should be OK..
683 output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
685 output[1] = fr_rand();
686 output[2] = inlen; /* length of the password string */
688 fr_md5_init(&context);
689 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
692 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
693 fr_md5_update(&context, &output[0], 2);
695 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
700 fr_md5_update(&context,
701 output + 2 + n - AUTH_PASS_LEN,
705 fr_md5_final(digest, &context);
707 if ((2 + n + AUTH_PASS_LEN) < room) {
708 block_len = AUTH_PASS_LEN;
710 block_len = room - 2 - n;
713 for (i = 0; i < block_len; i++) {
714 output[i + 2 + n] ^= digest[i];
719 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
721 unsigned int tlv1, tlv2;
723 if (nest > fr_attr_max_tlv) return 0;
728 * Keep encoding TLVs which have the same scope.
729 * e.g. two attributes of:
730 * ATTR.TLV1.TLV2.TLV3 = data1
731 * ATTR.TLV1.TLV2.TLV4 = data2
732 * both get put into a container of "ATTR.TLV1.TLV2"
736 * Nothing to follow, we're done.
741 * Not from the same vendor, skip it.
743 if (vp->da->vendor != next->da->vendor) return 0;
746 * In a different TLV space, skip it.
749 tlv2 = next->da->attr;
751 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
752 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
754 if (tlv1 != tlv2) return 0;
760 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
761 RADIUS_PACKET const *original,
762 char const *secret, int nest,
763 VALUE_PAIR const **pvp,
764 uint8_t *start, size_t room);
766 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
767 RADIUS_PACKET const *original,
768 char const *secret, VALUE_PAIR const **pvp,
769 unsigned int attribute, uint8_t *ptr, size_t room);
771 /** Encode the *data* portion of the TLV
773 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
774 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
776 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
777 RADIUS_PACKET const *original,
778 char const *secret, int nest,
779 VALUE_PAIR const **pvp,
780 uint8_t *start, size_t room)
784 uint8_t *ptr = start;
785 VALUE_PAIR const *vp = *pvp;
786 VALUE_PAIR const *svp = vp;
791 if (nest > fr_attr_max_tlv) {
792 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
800 if (room <= 2) return ptr - start;
802 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
806 if (room > 255) my_room = 255;
808 len = vp2data_any(packet, original, secret, nest,
809 &vp, ptr + 2, my_room - 2);
810 if (len < 0) return len;
811 if (len == 0) return ptr - start;
812 /* len can NEVER be more than 253 */
817 if ((fr_debug_lvl > 3) && fr_log_fp) {
818 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
819 print_hex_data(ptr + 2, len, 3);
827 if (!do_next_tlv(svp, vp, nest)) break;
831 if ((fr_debug_lvl > 3) && fr_log_fp) {
834 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
835 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
842 /** Encodes the data portion of an attribute
844 * @return -1 on error, or the length of the data portion.
846 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
847 RADIUS_PACKET const *original,
848 char const *secret, int nest,
849 VALUE_PAIR const **pvp,
850 uint8_t *start, size_t room)
855 uint8_t *ptr = start;
858 VALUE_PAIR const *vp = *pvp;
863 * See if we need to encode a TLV. The low portion of
864 * the attribute has already been placed into the packer.
865 * If there are still attribute bytes left, then go
866 * encode them as TLVs.
868 * If we cared about the stack, we could unroll the loop.
870 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
871 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
872 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
877 * Set up the default sources for the data.
881 switch (vp->da->type) {
886 fr_strerror_printf("ERROR: Cannot encode NULL data");
892 case PW_TYPE_IPV4_ADDR:
893 case PW_TYPE_IPV6_ADDR:
894 case PW_TYPE_IPV6_PREFIX:
895 case PW_TYPE_IPV4_PREFIX:
896 case PW_TYPE_ABINARY:
897 case PW_TYPE_ETHERNET: /* just in case */
898 data = (uint8_t const *) &vp->data;
902 len = 1; /* just in case */
903 array[0] = vp->vp_byte;
908 len = 2; /* just in case */
909 array[0] = (vp->vp_short >> 8) & 0xff;
910 array[1] = vp->vp_short & 0xff;
914 case PW_TYPE_INTEGER:
915 len = 4; /* just in case */
916 lvalue = htonl(vp->vp_integer);
917 memcpy(array, &lvalue, sizeof(lvalue));
921 case PW_TYPE_INTEGER64:
922 len = 8; /* just in case */
923 lvalue64 = htonll(vp->vp_integer64);
924 data = (uint8_t *) &lvalue64;
928 * There are no tagged date attributes.
931 lvalue = htonl(vp->vp_date);
932 data = (uint8_t const *) &lvalue;
933 len = 4; /* just in case */
940 len = 4; /* just in case */
941 slvalue = htonl(vp->vp_signed);
942 memcpy(array, &slvalue, sizeof(slvalue));
947 default: /* unknown type: ignore it */
948 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
961 * Bound the data to the calling size
963 if (len > (ssize_t) room) len = room;
966 * Encrypt the various password styles
968 * Attributes with encrypted values MUST be less than
971 switch (vp->da->flags.encrypt) {
972 case FLAG_ENCRYPT_USER_PASSWORD:
973 make_passwd(ptr, &len, data, len,
974 secret, packet->vector);
977 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
979 if (vp->da->flags.has_tag) lvalue = 1;
982 * Check if there's enough room. If there isn't,
983 * we discard the attribute.
985 * This is ONLY a problem if we have multiple VSA's
986 * in one Vendor-Specific, though.
988 if (room < (18 + lvalue)) return 0;
990 switch (packet->code) {
991 case PW_CODE_ACCESS_ACCEPT:
992 case PW_CODE_ACCESS_REJECT:
993 case PW_CODE_ACCESS_CHALLENGE:
996 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
1000 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1001 make_tunnel_passwd(ptr + lvalue, &len, data, len,
1003 secret, original->vector);
1006 case PW_CODE_ACCOUNTING_REQUEST:
1007 case PW_CODE_DISCONNECT_REQUEST:
1008 case PW_CODE_COA_REQUEST:
1009 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1010 make_tunnel_passwd(ptr + 1, &len, data, len, room - 1,
1011 secret, packet->vector);
1018 * The code above ensures that this attribute
1021 case FLAG_ENCRYPT_ASCEND_SECRET:
1022 if (len != 16) return 0;
1023 make_secret(ptr, packet->vector, secret, data);
1024 len = AUTH_VECTOR_LEN;
1029 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
1030 if (vp->da->type == PW_TYPE_STRING) {
1031 if (len > ((ssize_t) (room - 1))) len = room - 1;
1034 } else if (vp->da->type == PW_TYPE_INTEGER) {
1036 } /* else it can't be any other type */
1038 memcpy(ptr, data, len);
1040 } /* switch over encryption flags */
1043 return len + (ptr - start);
1046 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1047 uint8_t *ptr, int hdr_len, ssize_t len,
1048 int flag_offset, int vsa_offset)
1050 int check_len = len - ptr[1];
1051 int total = len + hdr_len;
1054 * Pass 1: Check if the addition of the headers
1055 * overflows the available room. If so, return
1056 * what we were capable of encoding.
1059 while (check_len > (255 - hdr_len)) {
1061 check_len -= (255 - hdr_len);
1065 * Note that this results in a number of attributes maybe
1066 * being marked as "encoded", but which aren't in the
1067 * packet. Oh well. The solution is to fix the
1068 * "vp2data_any" function to take into account the header
1071 if ((ptr + ptr[1] + total) > end) {
1072 return (ptr + ptr[1]) - start;
1076 * Pass 2: Now that we know there's enough room,
1077 * re-arrange the data to form a set of valid
1078 * RADIUS attributes.
1081 int sublen = 255 - ptr[1];
1083 if (len <= sublen) {
1088 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1089 memmove(ptr + 255, ptr, hdr_len);
1091 if (vsa_offset) ptr[vsa_offset] += sublen;
1092 ptr[flag_offset] |= 0x80;
1096 if (vsa_offset) ptr[vsa_offset] = 3;
1100 if (vsa_offset) ptr[vsa_offset] += len;
1102 return (ptr + ptr[1]) - start;
1106 /** Encode an "extended" attribute
1108 int rad_vp2extended(RADIUS_PACKET const *packet,
1109 RADIUS_PACKET const *original,
1110 char const *secret, VALUE_PAIR const **pvp,
1111 uint8_t *ptr, size_t room)
1115 uint8_t *start = ptr;
1116 VALUE_PAIR const *vp = *pvp;
1120 if (!vp->da->flags.extended) {
1121 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1126 * The attribute number is encoded into the upper 8 bits
1129 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1131 if (!vp->da->flags.long_extended) {
1132 if (room < 3) return 0;
1135 ptr[2] = vp->da->attr & fr_attr_mask[0];
1138 if (room < 4) return 0;
1141 ptr[2] = vp->da->attr & fr_attr_mask[0];
1146 * Only "flagged" attributes can be longer than one
1149 if (!vp->da->flags.long_extended && (room > 255)) {
1156 if (vp->da->flags.evs) {
1157 uint8_t *evs = ptr + ptr[1];
1159 if (room < (size_t) (ptr[1] + 5)) return 0;
1163 evs[0] = 0; /* always zero */
1164 evs[1] = (vp->da->vendor >> 16) & 0xff;
1165 evs[2] = (vp->da->vendor >> 8) & 0xff;
1166 evs[3] = vp->da->vendor & 0xff;
1167 evs[4] = vp->da->attr & fr_attr_mask[0];
1173 len = vp2data_any(packet, original, secret, 0,
1174 pvp, ptr + ptr[1], room - hdr_len);
1175 if (len <= 0) return len;
1178 * There may be more than 252 octets of data encoded in
1179 * the attribute. If so, move the data up in the packet,
1180 * and copy the existing header over. Set the "M" flag ONLY
1181 * after copying the rest of the data.
1183 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1184 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1190 if ((fr_debug_lvl > 3) && fr_log_fp) {
1193 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1194 if (!vp->da->flags.long_extended) {
1195 fprintf(fr_log_fp, "%02x ", ptr[2]);
1198 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1202 if (vp->da->flags.evs) {
1203 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1204 ptr[jump], ptr[jump + 1],
1205 ptr[jump + 2], ptr[jump + 3],
1206 ((ptr[jump + 1] << 16) |
1207 (ptr[jump + 2] << 8) |
1213 print_hex_data(ptr + jump, len, 3);
1217 return (ptr + ptr[1]) - start;
1221 /** Encode a WiMAX attribute
1224 int rad_vp2wimax(RADIUS_PACKET const *packet,
1225 RADIUS_PACKET const *original,
1226 char const *secret, VALUE_PAIR const **pvp,
1227 uint8_t *ptr, size_t room)
1232 uint8_t *start = ptr;
1233 VALUE_PAIR const *vp = *pvp;
1238 * Double-check for WiMAX format.
1240 if (!vp->da->flags.wimax) {
1241 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1246 * Not enough room for:
1247 * attr, len, vendor-id, vsa, vsalen, continuation
1249 if (room < 9) return 0;
1252 * Build the Vendor-Specific header
1255 ptr[0] = PW_VENDOR_SPECIFIC;
1257 lvalue = htonl(vp->da->vendor);
1258 memcpy(ptr + 2, &lvalue, 4);
1259 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1261 ptr[8] = 0; /* continuation byte */
1265 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1267 if (len <= 0) return len;
1270 * There may be more than 252 octets of data encoded in
1271 * the attribute. If so, move the data up in the packet,
1272 * and copy the existing header over. Set the "C" flag
1273 * ONLY after copying the rest of the data.
1275 if (len > (255 - ptr[1])) {
1276 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1283 if ((fr_debug_lvl > 3) && fr_log_fp) {
1284 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1286 ptr[2], ptr[3], ptr[4], ptr[5],
1287 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1288 ptr[6], ptr[7], ptr[8]);
1289 print_hex_data(ptr + 9, len, 3);
1293 return (ptr + ptr[1]) - start;
1296 /** Encode an RFC format attribute, with the "concat" flag set
1298 * If there isn't enough room in the packet, the data is
1301 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1302 UNUSED RADIUS_PACKET const *original,
1303 UNUSED char const *secret, VALUE_PAIR const **pvp,
1304 unsigned int attribute, uint8_t *start, size_t room)
1306 uint8_t *ptr = start;
1309 VALUE_PAIR const *vp = *pvp;
1314 len = vp->vp_length;
1317 if (room <= 2) break;
1324 /* no more than 253 octets */
1325 if (left > 253) left = 253;
1327 /* no more than "room" octets */
1328 if (room < (left + 2)) left = room - 2;
1330 memcpy(ptr + 2, p, left);
1333 if ((fr_debug_lvl > 3) && fr_log_fp) {
1334 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1335 print_hex_data(ptr + 2, len, 3);
1349 /** Encode an RFC format TLV.
1351 * This could be a standard attribute, or a TLV data type.
1352 * If it's a standard attribute, then vp->da->attr == attribute.
1353 * Otherwise, attribute may be something else.
1355 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1356 RADIUS_PACKET const *original,
1357 char const *secret, VALUE_PAIR const **pvp,
1358 unsigned int attribute, uint8_t *ptr, size_t room)
1362 if (room <= 2) return 0;
1364 ptr[0] = attribute & 0xff;
1367 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1369 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1370 if (len <= 0) return len;
1375 if ((fr_debug_lvl > 3) && fr_log_fp) {
1376 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1377 print_hex_data(ptr + 2, len, 3);
1385 /** Encode a VSA which is a TLV
1387 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1389 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1390 RADIUS_PACKET const *original,
1391 char const *secret, VALUE_PAIR const **pvp,
1392 unsigned int attribute, unsigned int vendor,
1393 uint8_t *ptr, size_t room)
1397 VALUE_PAIR const *vp = *pvp;
1401 * Unknown vendor: RFC format.
1402 * Known vendor and RFC format: go do that.
1404 dv = dict_vendorbyvalue(vendor);
1406 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1407 return vp2attr_rfc(packet, original, secret, pvp,
1408 attribute, ptr, room);
1413 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1414 " type %u", (unsigned) dv->type);
1418 ptr[0] = 0; /* attr must be 24-bit */
1419 ptr[1] = (attribute >> 16) & 0xff;
1420 ptr[2] = (attribute >> 8) & 0xff;
1421 ptr[3] = attribute & 0xff;
1425 ptr[0] = (attribute >> 8) & 0xff;
1426 ptr[1] = attribute & 0xff;
1430 ptr[0] = attribute & 0xff;
1434 switch (dv->length) {
1436 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1437 " length %u", (unsigned) dv->length);
1445 ptr[dv->type + 1] = dv->type + 2;
1449 ptr[dv->type] = dv->type + 1;
1454 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1455 room = 255 - (dv->type + dv->length);
1458 len = vp2data_any(packet, original, secret, 0, pvp,
1459 ptr + dv->type + dv->length, room);
1460 if (len <= 0) return len;
1462 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1465 if ((fr_debug_lvl > 3) && fr_log_fp) {
1471 if ((fr_debug_lvl > 3) && fr_log_fp)
1472 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1473 ptr[0], ptr[1], ptr[2], ptr[3]);
1477 if ((fr_debug_lvl > 3) && fr_log_fp)
1478 fprintf(fr_log_fp, "\t\t%02x%02x ",
1483 if ((fr_debug_lvl > 3) && fr_log_fp)
1484 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1488 switch (dv->length) {
1493 fprintf(fr_log_fp, " ");
1497 fprintf(fr_log_fp, "%02x ",
1502 fprintf(fr_log_fp, "%02x%02x ",
1503 ptr[dv->type], ptr[dv->type] + 1);
1507 print_hex_data(ptr + dv->type + dv->length, len, 3);
1511 return dv->type + dv->length + len;
1515 /** Encode a Vendor-Specific attribute
1518 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1519 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1524 VALUE_PAIR const *vp = *pvp;
1528 if (vp->da->vendor == 0) {
1529 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1534 * Double-check for WiMAX format.
1536 if (vp->da->flags.wimax) {
1537 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1540 if (vp->da->vendor > FR_MAX_VENDOR) {
1541 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1546 * Not enough room for:
1547 * attr, len, vendor-id
1549 if (room < 6) return 0;
1552 * Build the Vendor-Specific header
1554 ptr[0] = PW_VENDOR_SPECIFIC;
1556 lvalue = htonl(vp->da->vendor);
1557 memcpy(ptr + 2, &lvalue, 4);
1559 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1561 len = vp2attr_vsa(packet, original, secret, pvp,
1562 vp->da->attr, vp->da->vendor,
1563 ptr + ptr[1], room);
1564 if (len < 0) return len;
1567 if ((fr_debug_lvl > 3) && fr_log_fp) {
1568 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1570 ptr[2], ptr[3], ptr[4], ptr[5],
1571 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1572 print_hex_data(ptr + 6, len, 3);
1582 /** Encode an RFC standard attribute 1..255
1585 int rad_vp2rfc(RADIUS_PACKET const *packet,
1586 RADIUS_PACKET const *original,
1587 char const *secret, VALUE_PAIR const **pvp,
1588 uint8_t *ptr, size_t room)
1590 VALUE_PAIR const *vp = *pvp;
1594 if (vp->da->vendor != 0) {
1595 fr_strerror_printf("rad_vp2rfc called with VSA");
1599 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1600 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1605 * Only CUI is allowed to have zero length.
1608 if ((vp->vp_length == 0) &&
1609 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1610 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1618 * Message-Authenticator is hard-coded.
1620 if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1621 if (room < 18) return -1;
1623 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1625 memset(ptr + 2, 0, 16);
1627 if ((fr_debug_lvl > 3) && fr_log_fp) {
1628 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1632 *pvp = (*pvp)->next;
1637 * EAP-Message is special.
1639 if (vp->da->flags.concat && (vp->vp_length > 253)) {
1640 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1644 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1648 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1649 RADIUS_PACKET const *original,
1650 char const *secret, VALUE_PAIR const **pvp,
1651 uint8_t *start, size_t room)
1654 VALUE_PAIR const *vp = *pvp;
1658 if (!vp->da->flags.is_tlv) {
1659 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1663 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1664 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1668 if (room < 5) return 0;
1671 * Encode the first level of TLVs
1673 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1675 start[2] = vp->da->attr & fr_attr_mask[0];
1678 len = vp2data_any(packet, original, secret, 0, pvp,
1679 start + 4, room - 4);
1680 if (len <= 0) return len;
1692 /** Parse a data structure into a RADIUS attribute
1695 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1696 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1699 VALUE_PAIR const *vp;
1701 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1708 * RFC format attributes take the fast path.
1710 if (!vp->da->vendor) {
1711 if (vp->da->attr > 255) return 0;
1713 return rad_vp2rfc(packet, original, secret, pvp,
1717 if (vp->da->flags.extended) {
1718 return rad_vp2extended(packet, original, secret, pvp,
1723 * The upper 8 bits of the vendor number are the standard
1724 * space attribute which is a TLV.
1726 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1727 return rad_vp2rfctlv(packet, original, secret, pvp,
1731 if (vp->da->flags.wimax) {
1732 return rad_vp2wimax(packet, original, secret, pvp,
1736 return rad_vp2vsa(packet, original, secret, pvp, start, room);
1743 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1746 radius_packet_t *hdr;
1748 uint16_t total_length;
1750 VALUE_PAIR const *reply;
1753 * A 4K packet, aligned on 64-bits.
1755 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1758 * Double-check some things based on packet code.
1760 switch (packet->code) {
1761 case PW_CODE_ACCESS_ACCEPT:
1762 case PW_CODE_ACCESS_REJECT:
1763 case PW_CODE_ACCESS_CHALLENGE:
1765 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1771 * These packet vectors start off as all zero.
1773 case PW_CODE_ACCOUNTING_REQUEST:
1774 case PW_CODE_DISCONNECT_REQUEST:
1775 case PW_CODE_COA_REQUEST:
1776 memset(packet->vector, 0, sizeof(packet->vector));
1784 * Use memory on the stack, until we know how
1785 * large the packet will be.
1787 hdr = (radius_packet_t *) data;
1790 * Build standard header
1792 hdr->code = packet->code;
1793 hdr->id = packet->id;
1795 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1797 total_length = RADIUS_HDR_LEN;
1800 * Load up the configuration values for the user
1806 * FIXME: Loop twice over the reply list. The first time,
1807 * calculate the total length of data. The second time,
1808 * allocate the memory, and fill in the VP's.
1810 * Hmm... this may be slower than just doing a small
1815 * Loop over the reply attributes for the packet.
1817 reply = packet->vps;
1820 char const *last_name = NULL;
1825 * Ignore non-wire attributes, but allow extended
1828 if ((reply->da->vendor == 0) &&
1829 ((reply->da->attr & 0xFFFF) >= 256) &&
1830 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1833 * Permit the admin to send BADLY formatted
1834 * attributes with a debug build.
1836 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1837 memcpy(ptr, reply->vp_octets, reply->vp_length);
1838 len = reply->vp_length;
1839 reply = reply->next;
1843 reply = reply->next;
1848 * Set the Message-Authenticator to the correct
1849 * length and initial value.
1851 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1853 * Cache the offset to the
1854 * Message-Authenticator
1856 packet->offset = total_length;
1859 last_len = reply->vp_length;
1861 last_name = reply->da->name;
1863 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1864 ((uint8_t *) data) + sizeof(data) - ptr);
1865 if (len < 0) return -1;
1868 * Failed to encode the attribute, likely because
1869 * the packet is full.
1872 if (last_len != 0) {
1873 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1876 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1881 next: /* Used only for Raw-Attribute */
1884 total_length += len;
1885 } /* done looping over all attributes */
1888 * Fill in the rest of the fields, and copy the data over
1889 * from the local stack to the newly allocated memory.
1891 * Yes, all this 'memcpy' is slow, but it means
1892 * that we only allocate the minimum amount of
1893 * memory for a request.
1895 packet->data_len = total_length;
1896 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1897 if (!packet->data) {
1898 fr_strerror_printf("Out of memory");
1902 memcpy(packet->data, hdr, packet->data_len);
1903 hdr = (radius_packet_t *) packet->data;
1905 total_length = htons(total_length);
1906 memcpy(hdr->length, &total_length, sizeof(total_length));
1912 /** Sign a previously encoded packet
1915 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1918 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1921 * It wasn't assigned an Id, this is bad!
1923 if (packet->id < 0) {
1924 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1928 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1929 (packet->offset < 0)) {
1930 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1935 * If there's a Message-Authenticator, update it
1936 * now, BEFORE updating the authentication vector.
1938 if (packet->offset > 0) {
1939 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1941 switch (packet->code) {
1942 case PW_CODE_ACCOUNTING_RESPONSE:
1943 if (original && original->code == PW_CODE_STATUS_SERVER) {
1947 case PW_CODE_ACCOUNTING_REQUEST:
1948 case PW_CODE_DISCONNECT_REQUEST:
1949 case PW_CODE_DISCONNECT_ACK:
1950 case PW_CODE_DISCONNECT_NAK:
1951 case PW_CODE_COA_REQUEST:
1952 case PW_CODE_COA_ACK:
1953 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1957 case PW_CODE_ACCESS_ACCEPT:
1958 case PW_CODE_ACCESS_REJECT:
1959 case PW_CODE_ACCESS_CHALLENGE:
1961 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1964 memcpy(hdr->vector, original->vector,
1968 default: /* others have vector already set to zero */
1974 * Set the authentication vector to zero,
1975 * calculate the HMAC, and put it
1976 * into the Message-Authenticator
1979 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1980 (uint8_t const *) secret, strlen(secret));
1981 memcpy(packet->data + packet->offset + 2,
1982 calc_auth_vector, AUTH_VECTOR_LEN);
1985 * Copy the original request vector back
1986 * to the raw packet.
1988 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1992 * Switch over the packet code, deciding how to
1995 switch (packet->code) {
1997 * Request packets are not signed, bur
1998 * have a random authentication vector.
2000 case PW_CODE_ACCESS_REQUEST:
2001 case PW_CODE_STATUS_SERVER:
2005 * Reply packets are signed with the
2006 * authentication vector of the request.
2013 fr_md5_init(&context);
2014 fr_md5_update(&context, packet->data, packet->data_len);
2015 fr_md5_update(&context, (uint8_t const *) secret,
2017 fr_md5_final(digest, &context);
2019 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2020 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2023 }/* switch over packet codes */
2028 /** Reply to the request
2030 * Also attach reply attribute value pairs and any user message provided.
2032 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2036 * Maybe it's a fake packet. Don't send it.
2038 if (!packet || (packet->sockfd < 0)) {
2043 * First time through, allocate room for the packet
2045 if (!packet->data) {
2047 * Encode the packet.
2049 if (rad_encode(packet, original, secret) < 0) {
2054 * Re-sign it, including updating the
2055 * Message-Authenticator.
2057 if (rad_sign(packet, original, secret) < 0) {
2062 * If packet->data points to data, then we print out
2063 * the VP list again only for debugging.
2068 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2073 * If the socket is TCP, call write(). Calling sendto()
2074 * is allowed on some platforms, but it's not nice. Even
2075 * worse, if UDPFROMTO is defined, we *can't* use it on
2076 * TCP sockets. So... just call write().
2078 if (packet->proto == IPPROTO_TCP) {
2081 rcode = write(packet->sockfd, packet->data, packet->data_len);
2082 if (rcode >= 0) return rcode;
2084 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2090 * And send it on it's way.
2092 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2093 &packet->src_ipaddr, packet->src_port,
2094 &packet->dst_ipaddr, packet->dst_port);
2097 /** Do a comparison of two authentication digests by comparing the FULL digest
2099 * Otherwise, the server can be subject to timing attacks that allow attackers
2100 * find a valid message authenticator.
2102 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2104 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2109 for (i = 0; i < length; i++) {
2110 result |= a[i] ^ b[i];
2113 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2117 /** Validates the requesting client NAS
2119 * Calculates the request Authenticator based on the clients private key.
2121 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2123 uint8_t digest[AUTH_VECTOR_LEN];
2127 * Zero out the auth_vector in the received packet.
2128 * Then append the shared secret to the received packet,
2129 * and calculate the MD5 sum. This must be the same
2130 * as the original MD5 sum (packet->vector).
2132 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2135 * MD5(packet + secret);
2137 fr_md5_init(&context);
2138 fr_md5_update(&context, packet->data, packet->data_len);
2139 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2140 fr_md5_final(digest, &context);
2143 * Return 0 if OK, 2 if not OK.
2145 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2150 /** Validates the requesting client NAS
2152 * Calculates the response Authenticator based on the clients
2155 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2158 uint8_t calc_digest[AUTH_VECTOR_LEN];
2164 if (original == NULL) {
2169 * Copy the original vector in place.
2171 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2174 * MD5(packet + secret);
2176 fr_md5_init(&context);
2177 fr_md5_update(&context, packet->data, packet->data_len);
2178 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2179 fr_md5_final(calc_digest, &context);
2182 * Copy the packet's vector back to the packet.
2184 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2187 * Return 0 if OK, 2 if not OK.
2189 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2193 /** Check if a set of RADIUS formatted TLVs are OK
2196 int rad_tlv_ok(uint8_t const *data, size_t length,
2197 size_t dv_type, size_t dv_length)
2199 uint8_t const *end = data + length;
2201 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2203 VP_HEXDUMP("tlv_ok", data, length);
2205 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2206 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2210 while (data < end) {
2213 if ((data + dv_type + dv_length) > end) {
2214 fr_strerror_printf("Attribute header overflow");
2220 if ((data[0] == 0) && (data[1] == 0) &&
2221 (data[2] == 0) && (data[3] == 0)) {
2223 fr_strerror_printf("Invalid attribute 0");
2228 fr_strerror_printf("Invalid attribute > 2^24");
2234 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2239 * Zero is allowed, because the Colubris
2240 * people are dumb and use it.
2245 fr_strerror_printf("Internal sanity check failed");
2249 switch (dv_length) {
2254 if (data[dv_type] != 0) {
2255 fr_strerror_printf("Attribute is longer than 256 octets");
2260 attrlen = data[dv_type + dv_length - 1];
2265 fr_strerror_printf("Internal sanity check failed");
2269 if (attrlen < (dv_type + dv_length)) {
2270 fr_strerror_printf("Attribute header has invalid length");
2274 if (attrlen > length) {
2275 fr_strerror_printf("Attribute overflows container");
2287 /** See if the data pointed to by PTR is a valid RADIUS packet.
2289 * Packet is not 'const * const' because we may update data_len, if there's more data
2290 * in the UDP packet than in the RADIUS packet.
2292 * @param packet to check
2293 * @param flags to control decoding
2294 * @param reason if not NULL, will have the failure reason written to where it points.
2295 * @return bool, true on success, false on failure.
2297 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2302 radius_packet_t *hdr;
2303 char host_ipaddr[128];
2304 bool require_ma = false;
2305 bool seen_ma = false;
2306 uint32_t num_attributes;
2307 decode_fail_t failure = DECODE_FAIL_NONE;
2310 * Check for packets smaller than the packet header.
2312 * RFC 2865, Section 3., subsection 'length' says:
2314 * "The minimum length is 20 ..."
2316 if (packet->data_len < RADIUS_HDR_LEN) {
2317 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2318 inet_ntop(packet->src_ipaddr.af,
2319 &packet->src_ipaddr.ipaddr,
2320 host_ipaddr, sizeof(host_ipaddr)),
2321 packet->data_len, RADIUS_HDR_LEN);
2322 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2328 * Check for packets with mismatched size.
2329 * i.e. We've received 128 bytes, and the packet header
2330 * says it's 256 bytes long.
2332 totallen = (packet->data[2] << 8) | packet->data[3];
2333 hdr = (radius_packet_t *)packet->data;
2336 * Code of 0 is not understood.
2337 * Code of 16 or greate is not understood.
2339 if ((hdr->code == 0) ||
2340 (hdr->code >= FR_MAX_PACKET_CODE)) {
2341 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2342 inet_ntop(packet->src_ipaddr.af,
2343 &packet->src_ipaddr.ipaddr,
2344 host_ipaddr, sizeof(host_ipaddr)),
2346 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2351 * Message-Authenticator is required in Status-Server
2352 * packets, otherwise they can be trivially forged.
2354 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2357 * It's also required if the caller asks for it.
2359 if (flags) require_ma = true;
2362 * Repeat the length checks. This time, instead of
2363 * looking at the data we received, look at the value
2364 * of the 'length' field inside of the packet.
2366 * Check for packets smaller than the packet header.
2368 * RFC 2865, Section 3., subsection 'length' says:
2370 * "The minimum length is 20 ..."
2372 if (totallen < RADIUS_HDR_LEN) {
2373 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2374 inet_ntop(packet->src_ipaddr.af,
2375 &packet->src_ipaddr.ipaddr,
2376 host_ipaddr, sizeof(host_ipaddr)),
2377 totallen, RADIUS_HDR_LEN);
2378 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2383 * And again, for the value of the 'length' field.
2385 * RFC 2865, Section 3., subsection 'length' says:
2387 * " ... and maximum length is 4096."
2389 * HOWEVER. This requirement is for the network layer.
2390 * If the code gets here, we assume that a well-formed
2391 * packet is an OK packet.
2393 * We allow both the UDP data length, and the RADIUS
2394 * "length" field to contain up to 64K of data.
2398 * RFC 2865, Section 3., subsection 'length' says:
2400 * "If the packet is shorter than the Length field
2401 * indicates, it MUST be silently discarded."
2403 * i.e. No response to the NAS.
2405 if (packet->data_len < totallen) {
2406 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2407 inet_ntop(packet->src_ipaddr.af,
2408 &packet->src_ipaddr.ipaddr,
2409 host_ipaddr, sizeof(host_ipaddr)),
2410 packet->data_len, totallen);
2411 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2416 * RFC 2865, Section 3., subsection 'length' says:
2418 * "Octets outside the range of the Length field MUST be
2419 * treated as padding and ignored on reception."
2421 if (packet->data_len > totallen) {
2423 * We're shortening the packet below, but just
2424 * to be paranoid, zero out the extra data.
2426 memset(packet->data + totallen, 0, packet->data_len - totallen);
2427 packet->data_len = totallen;
2431 * Walk through the packet's attributes, ensuring that
2432 * they add up EXACTLY to the size of the packet.
2434 * If they don't, then the attributes either under-fill
2435 * or over-fill the packet. Any parsing of the packet
2436 * is impossible, and will result in unknown side effects.
2438 * This would ONLY happen with buggy RADIUS implementations,
2439 * or with an intentional attack. Either way, we do NOT want
2440 * to be vulnerable to this problem.
2443 count = totallen - RADIUS_HDR_LEN;
2448 * We need at least 2 bytes to check the
2452 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2453 inet_ntop(packet->src_ipaddr.af,
2454 &packet->src_ipaddr.ipaddr,
2455 host_ipaddr, sizeof(host_ipaddr)));
2456 failure = DECODE_FAIL_HEADER_OVERFLOW;
2461 * Attribute number zero is NOT defined.
2464 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2465 inet_ntop(packet->src_ipaddr.af,
2466 &packet->src_ipaddr.ipaddr,
2467 host_ipaddr, sizeof(host_ipaddr)));
2468 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2473 * Attributes are at LEAST as long as the ID & length
2474 * fields. Anything shorter is an invalid attribute.
2477 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2478 inet_ntop(packet->src_ipaddr.af,
2479 &packet->src_ipaddr.ipaddr,
2480 host_ipaddr, sizeof(host_ipaddr)),
2482 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2487 * If there are fewer bytes in the packet than in the
2488 * attribute, it's a bad packet.
2490 if (count < attr[1]) {
2491 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2492 inet_ntop(packet->src_ipaddr.af,
2493 &packet->src_ipaddr.ipaddr,
2494 host_ipaddr, sizeof(host_ipaddr)),
2496 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2501 * Sanity check the attributes for length.
2504 default: /* don't do anything by default */
2508 * If there's an EAP-Message, we require
2509 * a Message-Authenticator.
2511 case PW_EAP_MESSAGE:
2515 case PW_MESSAGE_AUTHENTICATOR:
2516 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2517 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2518 inet_ntop(packet->src_ipaddr.af,
2519 &packet->src_ipaddr.ipaddr,
2520 host_ipaddr, sizeof(host_ipaddr)),
2522 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2530 * FIXME: Look up the base 255 attributes in the
2531 * dictionary, and switch over their type. For
2532 * integer/date/ip, the attribute length SHOULD
2535 count -= attr[1]; /* grab the attribute length */
2537 num_attributes++; /* seen one more attribute */
2541 * If the attributes add up to a packet, it's allowed.
2543 * If not, we complain, and throw the packet away.
2546 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2547 inet_ntop(packet->src_ipaddr.af,
2548 &packet->src_ipaddr.ipaddr,
2549 host_ipaddr, sizeof(host_ipaddr)));
2550 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2555 * If we're configured to look for a maximum number of
2556 * attributes, and we've seen more than that maximum,
2557 * then throw the packet away, as a possible DoS.
2559 if ((fr_max_attributes > 0) &&
2560 (num_attributes > fr_max_attributes)) {
2561 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2562 inet_ntop(packet->src_ipaddr.af,
2563 &packet->src_ipaddr.ipaddr,
2564 host_ipaddr, sizeof(host_ipaddr)),
2565 num_attributes, fr_max_attributes);
2566 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2571 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2573 * A packet with an EAP-Message attribute MUST also have
2574 * a Message-Authenticator attribute.
2576 * A Message-Authenticator all by itself is OK, though.
2578 * Similarly, Status-Server packets MUST contain
2579 * Message-Authenticator attributes.
2581 if (require_ma && !seen_ma) {
2582 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2583 inet_ntop(packet->src_ipaddr.af,
2584 &packet->src_ipaddr.ipaddr,
2585 host_ipaddr, sizeof(host_ipaddr)));
2586 failure = DECODE_FAIL_MA_MISSING;
2591 * Fill RADIUS header fields
2593 packet->code = hdr->code;
2594 packet->id = hdr->id;
2595 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2603 return (failure == DECODE_FAIL_NONE);
2607 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2610 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2614 RADIUS_PACKET *packet;
2617 * Allocate the new request data structure
2619 packet = rad_alloc(ctx, false);
2621 fr_strerror_printf("out of memory");
2626 sock_flags = MSG_PEEK;
2630 data_len = rad_recvfrom(fd, packet, sock_flags,
2631 &packet->src_ipaddr, &packet->src_port,
2632 &packet->dst_ipaddr, &packet->dst_port);
2635 * Check for socket errors.
2638 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2639 /* packet->data is NULL */
2643 packet->data_len = data_len; /* unsigned vs signed */
2646 * If the packet is too big, then rad_recvfrom did NOT
2647 * allocate memory. Instead, it just discarded the
2650 if (packet->data_len > MAX_PACKET_LEN) {
2651 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2652 /* packet->data is NULL */
2658 * Read no data. Continue.
2659 * This check is AFTER the MAX_PACKET_LEN check above, because
2660 * if the packet is larger than MAX_PACKET_LEN, we also have
2661 * packet->data == NULL
2663 if ((packet->data_len == 0) || !packet->data) {
2664 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2670 * See if it's a well-formed RADIUS packet.
2672 if (!rad_packet_ok(packet, flags, NULL)) {
2678 * Remember which socket we read the packet from.
2680 packet->sockfd = fd;
2683 * FIXME: Do even more filtering by only permitting
2684 * certain IP's. The problem is that we don't know
2685 * how to do this properly for all possible clients...
2689 * Explicitely set the VP list to empty.
2694 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2701 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2704 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2712 if (!packet || !packet->data) return -1;
2715 * Before we allocate memory for the attributes, do more
2718 ptr = packet->data + RADIUS_HDR_LEN;
2719 length = packet->data_len - RADIUS_HDR_LEN;
2720 while (length > 0) {
2721 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2722 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2727 default: /* don't do anything. */
2731 * Note that more than one Message-Authenticator
2732 * attribute is invalid.
2734 case PW_MESSAGE_AUTHENTICATOR:
2735 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2736 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2738 switch (packet->code) {
2742 case PW_CODE_ACCOUNTING_RESPONSE:
2744 (original->code == PW_CODE_STATUS_SERVER)) {
2748 case PW_CODE_ACCOUNTING_REQUEST:
2749 case PW_CODE_DISCONNECT_REQUEST:
2750 case PW_CODE_COA_REQUEST:
2751 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2755 case PW_CODE_ACCESS_ACCEPT:
2756 case PW_CODE_ACCESS_REJECT:
2757 case PW_CODE_ACCESS_CHALLENGE:
2758 case PW_CODE_DISCONNECT_ACK:
2759 case PW_CODE_DISCONNECT_NAK:
2760 case PW_CODE_COA_ACK:
2761 case PW_CODE_COA_NAK:
2763 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2764 "packet without a request packet");
2767 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2771 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2772 (uint8_t const *) secret, strlen(secret));
2773 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2774 sizeof(calc_auth_vector)) != 0) {
2775 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2776 "(Shared secret is incorrect.)",
2777 inet_ntop(packet->src_ipaddr.af,
2778 &packet->src_ipaddr.ipaddr,
2779 buffer, sizeof(buffer)));
2780 /* Silently drop packet, according to RFC 3579 */
2782 } /* else the message authenticator was good */
2785 * Reinitialize Authenticators.
2787 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2788 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2790 } /* switch over the attributes */
2794 } /* loop over the packet, sanity checking the attributes */
2797 * It looks like a RADIUS packet, but we don't know what it is
2798 * so can't validate the authenticators.
2800 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2801 fr_strerror_printf("Received Unknown packet code %d "
2802 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2804 inet_ntop(packet->src_ipaddr.af,
2805 &packet->src_ipaddr.ipaddr,
2806 buffer, sizeof(buffer)),
2812 * Calculate and/or verify Request or Response Authenticator.
2814 switch (packet->code) {
2815 case PW_CODE_ACCESS_REQUEST:
2816 case PW_CODE_STATUS_SERVER:
2818 * The authentication vector is random
2819 * nonsense, invented by the client.
2823 case PW_CODE_COA_REQUEST:
2824 case PW_CODE_DISCONNECT_REQUEST:
2825 case PW_CODE_ACCOUNTING_REQUEST:
2826 if (calc_acctdigest(packet, secret) > 1) {
2827 fr_strerror_printf("Received %s packet "
2828 "from client %s with invalid Request Authenticator! "
2829 "(Shared secret is incorrect.)",
2830 fr_packet_codes[packet->code],
2831 inet_ntop(packet->src_ipaddr.af,
2832 &packet->src_ipaddr.ipaddr,
2833 buffer, sizeof(buffer)));
2838 /* Verify the reply digest */
2839 case PW_CODE_ACCESS_ACCEPT:
2840 case PW_CODE_ACCESS_REJECT:
2841 case PW_CODE_ACCESS_CHALLENGE:
2842 case PW_CODE_ACCOUNTING_RESPONSE:
2843 case PW_CODE_DISCONNECT_ACK:
2844 case PW_CODE_DISCONNECT_NAK:
2845 case PW_CODE_COA_ACK:
2846 case PW_CODE_COA_NAK:
2847 rcode = calc_replydigest(packet, original, secret);
2849 fr_strerror_printf("Received %s packet "
2850 "from home server %s port %d with invalid Response Authenticator! "
2851 "(Shared secret is incorrect.)",
2852 fr_packet_codes[packet->code],
2853 inet_ntop(packet->src_ipaddr.af,
2854 &packet->src_ipaddr.ipaddr,
2855 buffer, sizeof(buffer)),
2862 fr_strerror_printf("Received Unknown packet code %d "
2863 "from client %s port %d: Cannot validate Request/Response Authenticator",
2865 inet_ntop(packet->src_ipaddr.af,
2866 &packet->src_ipaddr.ipaddr,
2867 buffer, sizeof(buffer)),
2876 /** Convert a "concatenated" attribute to one long VP
2879 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2880 DICT_ATTR const *da, uint8_t const *start,
2881 size_t const packetlen, VALUE_PAIR **pvp)
2885 uint8_t const *ptr = start;
2886 uint8_t const *end = start + packetlen;
2894 * The packet has already been sanity checked, so we
2895 * don't care about walking off of the end of it.
2898 total += ptr[1] - 2;
2903 * Attributes MUST be consecutive.
2905 if (ptr[0] != attr) break;
2908 vp = fr_pair_afrom_da(ctx, da);
2911 vp->vp_length = total;
2912 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2914 fr_pair_list_free(&vp);
2920 while (total < vp->vp_length) {
2921 memcpy(p, ptr + 2, ptr[1] - 2);
2923 total += ptr[1] - 2;
2932 /** Convert TLVs to one or more VPs
2935 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2936 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2937 char const *secret, DICT_ATTR const *da,
2938 uint8_t const *start, size_t length,
2941 uint8_t const *data = start;
2942 DICT_ATTR const *child;
2943 VALUE_PAIR *head, **tail;
2945 if (length < 3) return -1; /* type, length, value */
2947 VP_HEXDUMP("tlvs", data, length);
2949 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2954 while (data < (start + length)) {
2957 child = dict_attrbyparent(da, data[0], da->vendor);
2959 unsigned int my_attr, my_vendor;
2961 VP_TRACE("Failed to find child %u of TLV %s\n",
2965 * Get child attr/vendor so that
2966 * we can call unknown attr.
2969 my_vendor = da->vendor;
2971 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2972 fr_pair_list_free(&head);
2976 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2978 fr_pair_list_free(&head);
2983 tlv_len = data2vp(ctx, packet, original, secret, child,
2984 data + 2, data[1] - 2, data[1] - 2, tail);
2986 fr_pair_list_free(&head);
2989 if (*tail) tail = &((*tail)->next);
2997 /** Convert a top-level VSA to a VP.
2999 * "length" can be LONGER than just this sub-vsa.
3001 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3002 RADIUS_PACKET const *original,
3003 char const *secret, DICT_VENDOR *dv,
3004 uint8_t const *data, size_t length,
3007 unsigned int attribute;
3008 ssize_t attrlen, my_len;
3009 DICT_ATTR const *da;
3011 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3014 if (length <= (dv->type + dv->length)) {
3015 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3022 /* data[0] must be zero */
3023 attribute = data[1] << 16;
3024 attribute |= data[2] << 8;
3025 attribute |= data[3];
3029 attribute = data[0] << 8;
3030 attribute |= data[1];
3034 attribute = data[0];
3038 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3042 switch (dv->length) {
3044 /* data[dv->type] must be zero, from rad_tlv_ok() */
3045 attrlen = data[dv->type + 1];
3049 attrlen = data[dv->type];
3057 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3062 * See if the VSA is known.
3064 da = dict_attrbyvalue(attribute, dv->vendorpec);
3065 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3068 my_len = data2vp(ctx, packet, original, secret, da,
3069 data + dv->type + dv->length,
3070 attrlen - (dv->type + dv->length),
3071 attrlen - (dv->type + dv->length),
3073 if (my_len < 0) return my_len;
3079 /** Convert a fragmented extended attr to a VP
3089 * But for the first fragment, we get passed a pointer to the "extended-attr"
3091 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3092 RADIUS_PACKET const *original,
3093 char const *secret, DICT_ATTR const *da,
3094 uint8_t const *data,
3095 size_t attrlen, size_t packetlen,
3100 uint8_t *head, *tail;
3101 uint8_t const *frag, *end;
3102 uint8_t const *attr;
3106 if (attrlen < 3) return -1;
3109 * Calculate the length of all of the fragments. For
3110 * now, they MUST be contiguous in the packet, and they
3111 * MUST be all of the same TYPE and EXTENDED-TYPE
3114 fraglen = attrlen - 2;
3115 frag = data + attrlen;
3116 end = data + packetlen;
3120 while (frag < end) {
3122 (frag[0] != attr[0]) ||
3123 (frag[1] < 4) || /* too short for long-extended */
3124 (frag[2] != attr[2]) ||
3125 ((frag + frag[1]) > end)) { /* overflow */
3130 last_frag = ((frag[3] & 0x80) == 0);
3132 fraglen += frag[1] - 4;
3137 head = tail = malloc(fraglen);
3138 if (!head) return -1;
3140 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3143 * And again, but faster and looser.
3145 * We copy the first fragment, followed by the rest of
3150 while (fragments > 0) {
3151 memcpy(tail, frag + 4, frag[1] - 4);
3152 tail += frag[1] - 4;
3157 VP_HEXDUMP("long-extended fragments", head, fraglen);
3159 rcode = data2vp(ctx, packet, original, secret, da,
3160 head, fraglen, fraglen, pvp);
3162 if (rcode < 0) return rcode;
3167 /** Convert a Vendor-Specific WIMAX to vps
3169 * @note Called ONLY for Vendor-Specific
3171 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3172 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3173 char const *secret, uint32_t vendor,
3174 uint8_t const *data,
3175 size_t attrlen, size_t packetlen,
3181 uint8_t *head, *tail;
3182 uint8_t const *frag, *end;
3183 DICT_ATTR const *child;
3185 if (attrlen < 8) return -1;
3187 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3189 child = dict_attrbyvalue(data[4], vendor);
3190 if (!child) return -1;
3192 if ((data[6] & 0x80) == 0) {
3193 rcode = data2vp(ctx, packet, original, secret, child,
3194 data + 7, data[5] - 3, data[5] - 3,
3196 if (rcode < 0) return -1;
3201 * Calculate the length of all of the fragments. For
3202 * now, they MUST be contiguous in the packet, and they
3203 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3205 * The first fragment doesn't have a RADIUS attribute
3206 * header, so it needs to be treated a little special.
3208 fraglen = data[5] - 3;
3209 frag = data + attrlen;
3210 end = data + packetlen;
3213 while (frag < end) {
3215 (frag[0] != PW_VENDOR_SPECIFIC) ||
3216 (frag[1] < 9) || /* too short for wimax */
3217 ((frag + frag[1]) > end) || /* overflow */
3218 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3219 (frag[6] != data[4]) || /* not the same wimax attr */
3220 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3225 last_frag = ((frag[8] & 0x80) == 0);
3227 fraglen += frag[7] - 3;
3231 head = tail = malloc(fraglen);
3232 if (!head) return -1;
3235 * And again, but faster and looser.
3237 * We copy the first fragment, followed by the rest of
3242 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3243 tail += frag[4 + 1] - 3;
3244 frag += attrlen; /* should be frag[1] - 7 */
3247 * frag now points to RADIUS attributes
3250 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3251 tail += frag[2 + 4 + 1] - 3;
3253 } while (frag < end);
3255 VP_HEXDUMP("wimax fragments", head, fraglen);
3257 rcode = data2vp(ctx, packet, original, secret, child,
3258 head, fraglen, fraglen, pvp);
3260 if (rcode < 0) return rcode;
3266 /** Convert a top-level VSA to one or more VPs
3269 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3270 RADIUS_PACKET const *original,
3271 char const *secret, uint8_t const *data,
3272 size_t attrlen, size_t packetlen,
3279 VALUE_PAIR *head, **tail;
3282 if (attrlen > packetlen) return -1;
3283 if (attrlen < 5) return -1; /* vid, value */
3284 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3286 VP_TRACE("data2vp_vsas\n");
3288 memcpy(&vendor, data, 4);
3289 vendor = ntohl(vendor);
3290 dv = dict_vendorbyvalue(vendor);
3293 * RFC format is 1 octet type, 1 octet length
3295 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3296 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3301 * It's a known unknown.
3303 memset(&my_dv, 0, sizeof(my_dv));
3307 * Fill in the fields. Note that the name is empty!
3309 dv->vendorpec = vendor;
3319 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3320 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3321 data, attrlen, packetlen, pvp);
3326 * VSAs should normally be in TLV format.
3328 if (rad_tlv_ok(data + 4, attrlen - 4,
3329 dv->type, dv->length) < 0) {
3330 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3335 * There may be more than one VSA in the
3336 * Vendor-Specific. If so, loop over them all.
3346 while (attrlen > 0) {
3349 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3350 data, attrlen, tail);
3352 fr_pair_list_free(&head);
3353 fr_strerror_printf("Internal sanity check %d", __LINE__);
3358 * Vendors can send zero-length VSAs.
3360 if (*tail) tail = &((*tail)->next);
3364 packetlen -= vsa_len;
3372 /** Create any kind of VP from the attribute contents
3374 * "length" is AT LEAST the length of this attribute, as we
3375 * expect the caller to have verified the data with
3376 * rad_packet_ok(). "length" may be up to the length of the
3379 * @return -1 on error, or "length".
3381 ssize_t data2vp(TALLOC_CTX *ctx,
3382 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3384 DICT_ATTR const *da, uint8_t const *start,
3385 size_t const attrlen, size_t const packetlen,
3388 int8_t tag = TAG_NONE;
3392 DICT_ATTR const *child;
3394 uint8_t const *data = start;
3396 uint8_t buffer[256];
3399 * FIXME: Attrlen can be larger than 253 for extended attrs!
3401 if (!da || (attrlen > packetlen) ||
3402 ((attrlen > 253) && (attrlen != packetlen)) ||
3403 (attrlen > 128*1024)) {
3404 fr_strerror_printf("data2vp: invalid arguments");
3408 VP_HEXDUMP("data2vp", start, attrlen);
3410 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3415 * Hacks for CUI. The WiMAX spec says that it can be
3416 * zero length, even though this is forbidden by the
3417 * RADIUS specs. So... we make a special case for it.
3420 if (!((da->vendor == 0) &&
3421 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3428 * Hacks for Coverity. Editing the dictionary
3429 * will break assumptions about CUI. We know
3430 * this, but Coverity doesn't.
3432 if (da->type != PW_TYPE_OCTETS) return -1;
3437 goto alloc_cui; /* skip everything */
3441 * Hacks for tags. If the attribute is capable of
3442 * encoding a tag, and there's room for the tag, and
3443 * there is a tag, or it's encrypted with Tunnel-Password,
3444 * then decode the tag.
3446 if (da->flags.has_tag && (datalen > 1) &&
3447 ((data[0] < 0x20) ||
3448 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3450 * Only "short" attributes can be encrypted.
3452 if (datalen >= sizeof(buffer)) return -1;
3454 if (da->type == PW_TYPE_STRING) {
3455 memcpy(buffer, data + 1, datalen - 1);
3459 } else if (da->type == PW_TYPE_INTEGER) {
3460 memcpy(buffer, data, attrlen);
3465 return -1; /* only string and integer can have tags */
3472 * Decrypt the attribute.
3474 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3475 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3477 * Encrypted attributes can only exist for the
3478 * old-style format. Extended attributes CANNOT
3481 if (attrlen > 253) {
3485 if (data == start) {
3486 memcpy(buffer, data, attrlen);
3490 switch (da->flags.encrypt) { /* can't be tagged */
3494 case FLAG_ENCRYPT_USER_PASSWORD:
3496 rad_pwdecode((char *) buffer,
3500 rad_pwdecode((char *) buffer,
3507 * MS-CHAP-MPPE-Keys are 24 octets, and
3508 * encrypted. Since it's binary, we can't
3509 * look for trailing zeros.
3511 if (da->flags.length) {
3512 if (datalen > da->flags.length) {
3513 datalen = da->flags.length;
3514 } /* else leave datalen alone */
3517 * Take off trailing zeros from the END.
3518 * This allows passwords to have zeros in
3519 * the middle of a field.
3521 * However, if the password has a zero at
3522 * the end, it will get mashed by this
3523 * code. There's really no way around
3526 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3531 * Tunnel-Password's may go ONLY in response
3532 * packets. They can have a tag, so datalen is
3533 * not the same as attrlen.
3535 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3536 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3537 original ? original->vector : nullvector) < 0) {
3543 * Ascend-Send-Secret
3544 * Ascend-Receive-Secret
3546 case FLAG_ENCRYPT_ASCEND_SECRET:
3550 uint8_t my_digest[AUTH_VECTOR_LEN];
3551 make_secret(my_digest,
3554 memcpy(buffer, my_digest,
3556 buffer[AUTH_VECTOR_LEN] = '\0';
3557 datalen = strlen((char *) buffer);
3563 } /* switch over encryption flags */
3567 * Double-check the length after decrypting the
3570 VP_TRACE("data2vp: type %u\n", da->type);
3572 case PW_TYPE_STRING:
3573 case PW_TYPE_OCTETS:
3576 case PW_TYPE_ABINARY:
3577 if (datalen > sizeof(vp->vp_filter)) goto raw;
3580 case PW_TYPE_INTEGER:
3581 case PW_TYPE_IPV4_ADDR:
3583 case PW_TYPE_SIGNED:
3584 if (datalen != 4) goto raw;
3587 case PW_TYPE_INTEGER64:
3589 if (datalen != 8) goto raw;
3592 case PW_TYPE_IPV6_ADDR:
3593 if (datalen != 16) goto raw;
3596 case PW_TYPE_IPV6_PREFIX:
3597 if ((datalen < 2) || (datalen > 18)) goto raw;
3598 if (data[1] > 128) goto raw;
3602 if (datalen != 1) goto raw;
3606 if (datalen != 2) goto raw;
3609 case PW_TYPE_ETHERNET:
3610 if (datalen != 6) goto raw;
3613 case PW_TYPE_COMBO_IP_ADDR:
3615 child = dict_attrbytype(da->attr, da->vendor,
3617 } else if (datalen == 16) {
3618 child = dict_attrbytype(da->attr, da->vendor,
3623 if (!child) goto raw;
3624 da = child; /* re-write it */
3627 case PW_TYPE_IPV4_PREFIX:
3628 if (datalen != 6) goto raw;
3629 if ((data[1] & 0x3f) > 32) goto raw;
3633 * The rest of the data types can cause
3634 * recursion! Ask yourself, "is recursion OK?"
3637 case PW_TYPE_EXTENDED:
3638 if (datalen < 2) goto raw; /* etype, value */
3640 child = dict_attrbyparent(da, data[0], 0);
3641 if (!child) goto raw;
3644 * Recurse to decode the contents, which could be
3645 * a TLV, IPaddr, etc. Note that we decode only
3646 * the current attribute, and we ignore any extra
3649 rcode = data2vp(ctx, packet, original, secret, child,
3650 data + 1, attrlen - 1, attrlen - 1, pvp);
3651 if (rcode < 0) goto raw;
3654 case PW_TYPE_LONG_EXTENDED:
3655 if (datalen < 3) goto raw; /* etype, flags, value */
3657 child = dict_attrbyparent(da, data[0], 0);
3659 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3660 (datalen < (3 + 4 + 1))) {
3661 /* da->attr < 255, da->vendor == 0 */
3662 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3665 * Try to find the VSA.
3667 memcpy(&vendor, data + 3, 4);
3668 vendor = ntohl(vendor);
3670 if (vendor == 0) goto raw;
3672 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3676 fr_strerror_printf("Internal sanity check %d", __LINE__);
3682 * If there no more fragments, then the contents
3683 * have to be a well-known data type.
3686 if ((data[1] & 0x80) == 0) {
3687 rcode = data2vp(ctx, packet, original, secret, child,
3688 data + 2, attrlen - 2, attrlen - 2,
3690 if (rcode < 0) goto raw;
3695 * This requires a whole lot more work.
3697 return data2vp_extended(ctx, packet, original, secret, child,
3698 start, attrlen, packetlen, pvp);
3701 if (datalen < 6) goto raw; /* vid, vtype, value */
3703 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3705 memcpy(&vendor, data, 4);
3706 vendor = ntohl(vendor);
3707 vendor |= da->vendor;
3709 child = dict_attrbyvalue(data[4], vendor);
3712 * Create a "raw" attribute from the
3713 * contents of the EVS VSA.
3715 da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3721 rcode = data2vp(ctx, packet, original, secret, child,
3722 data + 5, attrlen - 5, attrlen - 5, pvp);
3723 if (rcode < 0) goto raw;
3728 * We presume that the TLVs all fit into one
3729 * attribute, OR they've already been grouped
3730 * into a contiguous memory buffer.
3732 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3733 data, attrlen, pvp);
3734 if (rcode < 0) goto raw;
3739 * VSAs can be WiMAX, in which case they don't
3740 * fit into one attribute.
3742 rcode = data2vp_vsas(ctx, packet, original, secret,
3743 data, attrlen, packetlen, pvp);
3744 if (rcode < 0) goto raw;
3750 * Re-write the attribute to be "raw". It is
3751 * therefore of type "octets", and will be
3754 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3756 fr_strerror_printf("Internal sanity check %d", __LINE__);
3764 if (da->type != PW_TYPE_OCTETS) {
3765 dict_attr_free(&da);
3773 * And now that we've verified the basic type
3774 * information, decode the actual data.
3777 vp = fr_pair_afrom_da(ctx, da);
3780 vp->vp_length = datalen;
3784 case PW_TYPE_STRING:
3785 p = talloc_array(vp, char, vp->vp_length + 1);
3786 memcpy(p, data, vp->vp_length);
3787 p[vp->vp_length] = '\0';
3788 vp->vp_strvalue = p;
3791 case PW_TYPE_OCTETS:
3792 fr_pair_value_memcpy(vp, data, vp->vp_length);
3795 case PW_TYPE_ABINARY:
3796 if (vp->vp_length > sizeof(vp->vp_filter)) {
3797 vp->vp_length = sizeof(vp->vp_filter);
3799 memcpy(vp->vp_filter, data, vp->vp_length);
3803 vp->vp_byte = data[0];
3807 vp->vp_short = (data[0] << 8) | data[1];
3810 case PW_TYPE_INTEGER:
3811 memcpy(&vp->vp_integer, data, 4);
3812 vp->vp_integer = ntohl(vp->vp_integer);
3815 case PW_TYPE_INTEGER64:
3816 memcpy(&vp->vp_integer64, data, 8);
3817 vp->vp_integer64 = ntohll(vp->vp_integer64);
3821 memcpy(&vp->vp_date, data, 4);
3822 vp->vp_date = ntohl(vp->vp_date);
3825 case PW_TYPE_ETHERNET:
3826 memcpy(vp->vp_ether, data, 6);
3829 case PW_TYPE_IPV4_ADDR:
3830 memcpy(&vp->vp_ipaddr, data, 4);
3834 memcpy(vp->vp_ifid, data, 8);
3837 case PW_TYPE_IPV6_ADDR:
3838 memcpy(&vp->vp_ipv6addr, data, 16);
3841 case PW_TYPE_IPV6_PREFIX:
3843 * FIXME: double-check that
3844 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3846 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3847 if (vp->vp_length < 18) {
3848 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3849 18 - vp->vp_length);
3853 case PW_TYPE_IPV4_PREFIX:
3854 /* FIXME: do the same double-check as for IPv6Prefix */
3855 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3858 * /32 means "keep all bits". Otherwise, mask
3861 if ((data[1] & 0x3f) > 32) {
3862 uint32_t addr, mask;
3864 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3866 mask <<= (32 - (data[1] & 0x3f));
3871 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3875 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3876 memcpy(&vp->vp_integer, buffer, 4);
3877 vp->vp_integer = ntohl(vp->vp_integer);
3881 fr_pair_list_free(&vp);
3882 fr_strerror_printf("Internal sanity check %d", __LINE__);
3892 /** Create a "normal" VALUE_PAIR from the given data
3895 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3896 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3898 uint8_t const *data, size_t length,
3903 DICT_ATTR const *da;
3905 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3906 fr_strerror_printf("rad_attr2vp: Insufficient data");
3910 da = dict_attrbyvalue(data[0], 0);
3912 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3913 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3918 * Pass the entire thing to the decoding function
3920 if (da->flags.concat) {
3921 VP_TRACE("attr2vp: concat attribute\n");
3922 return data2vp_concat(ctx, da, data, length, pvp);
3926 * Note that we pass the entire length, not just the
3927 * length of this attribute. The Extended or WiMAX
3928 * attributes may have the "continuation" bit set, and
3929 * will thus be more than one attribute in length.
3931 rcode = data2vp(ctx, packet, original, secret, da,
3932 data + 2, data[1] - 2, length - 2, pvp);
3933 if (rcode < 0) return rcode;
3938 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3940 /** Converts vp_data to network byte order
3942 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3943 * in an architecture independent format.
3945 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3946 * as the source VALUE_PAIR is not freed.
3948 * @param out where to write the pointer to the value.
3949 * @param vp to get the value from.
3950 * @return -1 on error, or the length of the value
3952 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3960 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3964 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3966 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3970 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3972 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3980 switch (vp->da->type) {
3981 case PW_TYPE_STRING:
3982 case PW_TYPE_OCTETS:
3983 memcpy(out, &vp->data.ptr, sizeof(*out));
3987 * All of these values are at the same location.
3990 case PW_TYPE_IPV4_ADDR:
3991 case PW_TYPE_IPV6_ADDR:
3992 case PW_TYPE_IPV6_PREFIX:
3993 case PW_TYPE_IPV4_PREFIX:
3994 case PW_TYPE_ABINARY:
3995 case PW_TYPE_ETHERNET:
3996 case PW_TYPE_COMBO_IP_ADDR:
3997 case PW_TYPE_COMBO_IP_PREFIX:
3999 void const *p = &vp->data;
4000 memcpy(out, &p, sizeof(*out));
4004 case PW_TYPE_BOOLEAN:
4005 buffer[0] = vp->vp_byte & 0x01;
4010 buffer[0] = vp->vp_byte & 0xff;
4015 buffer[0] = (vp->vp_short >> 8) & 0xff;
4016 buffer[1] = vp->vp_short & 0xff;
4020 case PW_TYPE_INTEGER:
4021 lvalue = htonl(vp->vp_integer);
4022 memcpy(buffer, &lvalue, sizeof(lvalue));
4026 case PW_TYPE_INTEGER64:
4027 lvalue64 = htonll(vp->vp_integer64);
4028 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4033 lvalue = htonl(vp->vp_date);
4034 memcpy(buffer, &lvalue, sizeof(lvalue));
4038 case PW_TYPE_SIGNED:
4040 int32_t slvalue = htonl(vp->vp_signed);
4041 memcpy(buffer, &slvalue, sizeof(slvalue));
4046 case PW_TYPE_INVALID:
4047 case PW_TYPE_EXTENDED:
4048 case PW_TYPE_LONG_EXTENDED:
4052 case PW_TYPE_TIMEVAL:
4054 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4057 /* Don't add default */
4060 return vp->vp_length;
4063 /** Calculate/check digest, and decode radius attributes
4065 * @return -1 on decoding error, 0 on success
4067 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4071 uint32_t num_attributes;
4073 radius_packet_t *hdr;
4074 VALUE_PAIR *head, **tail, *vp;
4077 * Extract attribute-value pairs
4079 hdr = (radius_packet_t *)packet->data;
4081 packet_length = packet->data_len - RADIUS_HDR_LEN;
4088 * Loop over the attributes, decoding them into VPs.
4090 while (packet_length > 0) {
4094 * This may return many VPs
4096 my_len = rad_attr2vp(packet, packet, original, secret,
4097 ptr, packet_length, &vp);
4099 fr_pair_list_free(&head);
4111 * VSA's may not have been counted properly in
4112 * rad_packet_ok() above, as it is hard to count
4113 * then without using the dictionary. We
4114 * therefore enforce the limits here, too.
4116 if ((fr_max_attributes > 0) &&
4117 (num_attributes > fr_max_attributes)) {
4118 char host_ipaddr[128];
4120 fr_pair_list_free(&head);
4121 fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4122 inet_ntop(packet->src_ipaddr.af,
4123 &packet->src_ipaddr.ipaddr,
4124 host_ipaddr, sizeof(host_ipaddr)),
4125 num_attributes, fr_max_attributes);
4130 packet_length -= my_len;
4134 * Merge information from the outside world into our
4137 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4140 * There may be VP's already in the packet. Don't
4141 * destroy them. Instead, add the decoded attributes to
4142 * the tail of the list.
4144 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4155 * We assume that the passwd buffer passed is big enough.
4156 * RFC2138 says the password is max 128 chars, so the size
4157 * of the passwd buffer must be at least 129 characters.
4158 * Preferably it's just MAX_STRING_LEN.
4160 * int *pwlen is updated to the new length of the encrypted
4161 * password - a multiple of 16 bytes.
4163 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4164 uint8_t const *vector)
4166 FR_MD5_CTX context, old;
4167 uint8_t digest[AUTH_VECTOR_LEN];
4168 int i, n, secretlen;
4172 * RFC maximum is 128 bytes.
4174 * If length is zero, pad it out with zeros.
4176 * If the length isn't aligned to 16 bytes,
4177 * zero out the extra data.
4181 if (len > 128) len = 128;
4184 memset(passwd, 0, AUTH_PASS_LEN);
4185 len = AUTH_PASS_LEN;
4186 } else if ((len % AUTH_PASS_LEN) != 0) {
4187 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4188 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4193 * Use the secret to setup the decryption digest
4195 secretlen = strlen(secret);
4197 fr_md5_init(&context);
4198 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4199 old = context; /* save intermediate work */
4202 * Encrypt it in place. Don't bother checking
4203 * len, as we've ensured above that it's OK.
4205 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4207 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4208 fr_md5_final(digest, &context);
4211 fr_md5_update(&context,
4212 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4214 fr_md5_final(digest, &context);
4217 for (i = 0; i < AUTH_PASS_LEN; i++) {
4218 passwd[i + n] ^= digest[i];
4228 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4229 uint8_t const *vector)
4231 FR_MD5_CTX context, old;
4232 uint8_t digest[AUTH_VECTOR_LEN];
4234 size_t n, secretlen;
4237 * The RFC's say that the maximum is 128.
4238 * The buffer we're putting it into above is 254, so
4239 * we don't need to do any length checking.
4241 if (pwlen > 128) pwlen = 128;
4246 if (pwlen == 0) goto done;
4249 * Use the secret to setup the decryption digest
4251 secretlen = strlen(secret);
4253 fr_md5_init(&context);
4254 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4255 old = context; /* save intermediate work */
4258 * The inverse of the code above.
4260 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4262 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4263 fr_md5_final(digest, &context);
4266 if (pwlen > AUTH_PASS_LEN) {
4267 fr_md5_update(&context, (uint8_t *) passwd,
4271 fr_md5_final(digest, &context);
4274 if (pwlen > (n + AUTH_PASS_LEN)) {
4275 fr_md5_update(&context, (uint8_t *) passwd + n,
4280 for (i = 0; i < AUTH_PASS_LEN; i++) {
4281 passwd[i + n] ^= digest[i];
4286 passwd[pwlen] = '\0';
4287 return strlen(passwd);
4291 /** Encode Tunnel-Password attributes when sending them out on the wire
4293 * int *pwlen is updated to the new length of the encrypted
4294 * password - a multiple of 16 bytes.
4296 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4299 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4300 uint8_t const *vector)
4302 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4303 unsigned char digest[AUTH_VECTOR_LEN];
4305 int i, n, secretlen;
4310 if (len > 127) len = 127;
4313 * Shift the password 3 positions right to place a salt and original
4314 * length, tag will be added automatically on packet send.
4316 for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4321 * save original password length as first password character;
4328 * Generate salt. The RFC's say:
4330 * The high bit of salt[0] must be set, each salt in a
4331 * packet should be unique, and they should be random
4333 * So, we set the high bit, add in a counter, and then
4334 * add in some CSPRNG data. should be OK..
4336 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4337 (fr_rand() & 0x07));
4338 salt[1] = fr_rand();
4341 * Padd password to multiple of AUTH_PASS_LEN bytes.
4343 n = len % AUTH_PASS_LEN;
4345 n = AUTH_PASS_LEN - n;
4346 for (; n > 0; n--, len++)
4349 /* set new password length */
4353 * Use the secret to setup the decryption digest
4355 secretlen = strlen(secret);
4356 memcpy(buffer, secret, secretlen);
4358 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4360 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4361 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4362 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4364 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4365 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4368 for (i = 0; i < AUTH_PASS_LEN; i++) {
4369 passwd[i + n2] ^= digest[i];
4376 /** Decode Tunnel-Password encrypted attributes
4378 * Defined in RFC-2868, this uses a two char SALT along with the
4379 * initial intermediate value, to differentiate it from the
4382 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4383 uint8_t const *vector)
4385 FR_MD5_CTX context, old;
4386 uint8_t digest[AUTH_VECTOR_LEN];
4388 size_t i, n, encrypted_len, reallen;
4390 encrypted_len = *pwlen;
4393 * We need at least a salt.
4395 if (encrypted_len < 2) {
4396 fr_strerror_printf("tunnel password is too short");
4401 * There's a salt, but no password. Or, there's a salt
4402 * and a 'data_len' octet. It's wrong, but at least we
4403 * can figure out what it means: the password is empty.
4405 * Note that this means we ignore the 'data_len' field,
4406 * if the attribute length tells us that there's no
4407 * more data. So the 'data_len' field may be wrong,
4410 if (encrypted_len <= 3) {
4416 encrypted_len -= 2; /* discount the salt */
4419 * Use the secret to setup the decryption digest
4421 secretlen = strlen(secret);
4423 fr_md5_init(&context);
4424 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4425 old = context; /* save intermediate work */
4428 * Set up the initial key:
4430 * b(1) = MD5(secret + vector + salt)
4432 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4433 fr_md5_update(&context, passwd, 2);
4436 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4438 size_t block_len = AUTH_PASS_LEN;
4441 * Ensure we don't overflow the input on MD5
4443 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4444 block_len = *pwlen - n - 2;
4450 fr_md5_final(digest, &context);
4455 * A quick check: decrypt the first octet
4456 * of the password, which is the
4457 * 'data_len' field. Ensure it's sane.
4459 reallen = passwd[2] ^ digest[0];
4460 if (reallen > encrypted_len) {
4461 fr_strerror_printf("tunnel password is too long for the attribute");
4465 fr_md5_update(&context, passwd + 2, block_len);
4470 fr_md5_final(digest, &context);
4473 fr_md5_update(&context, passwd + n + 2, block_len);
4476 for (i = base; i < block_len; i++) {
4477 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4482 passwd[reallen] = 0;
4487 /** Encode a CHAP password
4489 * @bug FIXME: might not work with Ascend because
4490 * we use vp->vp_length, and Ascend gear likes
4491 * to send an extra '\0' in the string!
4493 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4494 VALUE_PAIR *password)
4498 uint8_t string[MAX_STRING_LEN * 2 + 1];
4499 VALUE_PAIR *challenge;
4502 * Sanity check the input parameters
4504 if ((packet == NULL) || (password == NULL)) {
4509 * Note that the password VP can be EITHER
4510 * a User-Password attribute (from a check-item list),
4511 * or a CHAP-Password attribute (the client asking
4512 * the library to encode it).
4520 memcpy(ptr, password->vp_strvalue, password->vp_length);
4521 ptr += password->vp_length;
4522 i += password->vp_length;
4525 * Use Chap-Challenge pair if present,
4526 * Request Authenticator otherwise.
4528 challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4530 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4531 i += challenge->vp_length;
4533 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4534 i += AUTH_VECTOR_LEN;
4538 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4544 /** Seed the random number generator
4546 * May be called any number of times.
4548 void fr_rand_seed(void const *data, size_t size)
4553 * Ensure that the pool is initialized.
4555 if (!fr_rand_initialized) {
4558 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4560 fd = open("/dev/urandom", O_RDONLY);
4566 while (total < sizeof(fr_rand_pool.randrsl)) {
4567 this = read(fd, fr_rand_pool.randrsl,
4568 sizeof(fr_rand_pool.randrsl) - total);
4569 if ((this < 0) && (errno != EINTR)) break;
4570 if (this > 0) total += this;
4574 fr_rand_pool.randrsl[0] = fd;
4575 fr_rand_pool.randrsl[1] = time(NULL);
4576 fr_rand_pool.randrsl[2] = errno;
4579 fr_randinit(&fr_rand_pool, 1);
4580 fr_rand_pool.randcnt = 0;
4581 fr_rand_initialized = 1;
4587 * Hash the user data
4590 if (!hash) hash = fr_rand();
4591 hash = fr_hash_update(data, size, hash);
4593 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4597 /** Return a 32-bit random number
4600 uint32_t fr_rand(void)
4605 * Ensure that the pool is initialized.
4607 if (!fr_rand_initialized) {
4608 fr_rand_seed(NULL, 0);
4611 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4612 if (fr_rand_pool.randcnt >= 256) {
4613 fr_rand_pool.randcnt = 0;
4614 fr_isaac(&fr_rand_pool);
4621 /** Allocate a new RADIUS_PACKET
4623 * @param ctx the context in which the packet is allocated. May be NULL if
4624 * the packet is not associated with a REQUEST.
4625 * @param new_vector if true a new request authenticator will be generated.
4626 * @return a new RADIUS_PACKET or NULL on error.
4628 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4632 rp = talloc_zero(ctx, RADIUS_PACKET);
4634 fr_strerror_printf("out of memory");
4642 uint32_t hash, base;
4645 * Don't expose the actual contents of the random
4649 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4650 hash = fr_rand() ^ base;
4651 memcpy(rp->vector + i, &hash, sizeof(hash));
4654 fr_rand(); /* stir the pool again */
4659 /** Allocate a new RADIUS_PACKET response
4661 * @param ctx the context in which the packet is allocated. May be NULL if
4662 * the packet is not associated with a REQUEST.
4663 * @param packet The request packet.
4664 * @return a new RADIUS_PACKET or NULL on error.
4666 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4668 RADIUS_PACKET *reply;
4670 if (!packet) return NULL;
4672 reply = rad_alloc(ctx, false);
4673 if (!reply) return NULL;
4676 * Initialize the fields from the request.
4678 reply->sockfd = packet->sockfd;
4679 reply->dst_ipaddr = packet->src_ipaddr;
4680 reply->src_ipaddr = packet->dst_ipaddr;
4681 reply->dst_port = packet->src_port;
4682 reply->src_port = packet->dst_port;
4683 reply->id = packet->id;
4684 reply->code = 0; /* UNKNOWN code */
4685 memcpy(reply->vector, packet->vector,
4686 sizeof(reply->vector));
4689 reply->data_len = 0;
4692 reply->proto = packet->proto;
4698 /** Free a RADIUS_PACKET
4701 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4703 RADIUS_PACKET *radius_packet;
4705 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4706 radius_packet = *radius_packet_ptr;
4708 VERIFY_PACKET(radius_packet);
4710 fr_pair_list_free(&radius_packet->vps);
4712 talloc_free(radius_packet);
4713 *radius_packet_ptr = NULL;
4716 /** Duplicate a RADIUS_PACKET
4718 * @param ctx the context in which the packet is allocated. May be NULL if
4719 * the packet is not associated with a REQUEST.
4720 * @param in The packet to copy
4721 * @return a new RADIUS_PACKET or NULL on error.
4723 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4727 out = rad_alloc(ctx, false);
4728 if (!out) return NULL;
4731 * Bootstrap by copying everything.
4733 memcpy(out, in, sizeof(*out));
4736 * Then reset necessary fields
4743 out->vps = fr_pair_list_copy(out, in->vps);