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 maximum number of attributes which we allow in an incoming
69 * request. If there are more attributes than this, the request
72 * This helps to minimize the potential for a DoS, when an
73 * attacker spoofs Access-Request packets, which don't have a
74 * Message-Authenticator attribute. This means that the packet
75 * is unsigned, and the attacker can use resources on the server,
76 * even if the end request is rejected.
78 uint32_t fr_max_attributes = 0;
79 FILE *fr_log_fp = NULL;
81 typedef struct radius_packet_t {
85 uint8_t vector[AUTH_VECTOR_LEN];
89 static fr_randctx fr_rand_pool; /* across multiple calls */
90 static int fr_rand_initialized = 0;
91 static unsigned int salt_offset = 0;
92 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
94 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
100 "Accounting-Response",
105 "Accounting-Message", //!< 10
116 "Resource-Free-Request",
117 "Resource-Free-Response",
118 "Resource-Query-Request",
119 "Resource-Query-Response",
120 "Alternate-Resource-Reclaim-Request",
121 "NAS-Reboot-Request",
122 "NAS-Reboot-Response",
135 "Disconnect-Request", //!< 40
145 "IP-Address-Allocate",
146 "IP-Address-Release", //!< 50
150 void fr_printf_log(char const *fmt, ...)
155 if ((fr_debug_lvl == 0) || !fr_log_fp) {
160 vfprintf(fr_log_fp, fmt, ap);
166 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
168 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
172 for (i = 0; i < attrlen; i++) {
173 if ((i > 0) && ((i & 0x0f) == 0x00))
174 fprintf(fr_log_fp, "%.*s", depth, tabs);
175 fprintf(fr_log_fp, "%02x ", ptr[i]);
176 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
178 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
182 void rad_print_hex(RADIUS_PACKET const *packet)
186 if (!packet->data || !fr_log_fp) return;
188 fprintf(fr_log_fp, " Socket:\t%d\n", packet->sockfd);
190 fprintf(fr_log_fp, " Proto:\t%d\n", packet->proto);
193 if (packet->src_ipaddr.af == AF_INET) {
196 fprintf(fr_log_fp, " Src IP:\t%s\n",
197 inet_ntop(packet->src_ipaddr.af,
198 &packet->src_ipaddr.ipaddr,
199 buffer, sizeof(buffer)));
200 fprintf(fr_log_fp, " port:\t%u\n", packet->src_port);
202 fprintf(fr_log_fp, " Dst IP:\t%s\n",
203 inet_ntop(packet->dst_ipaddr.af,
204 &packet->dst_ipaddr.ipaddr,
205 buffer, sizeof(buffer)));
206 fprintf(fr_log_fp, " port:\t%u\n", packet->dst_port);
209 if (packet->data[0] < FR_MAX_PACKET_CODE) {
210 fprintf(fr_log_fp, " Code:\t\t(%d) %s\n", packet->data[0], fr_packet_codes[packet->data[0]]);
212 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
214 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
215 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
217 fprintf(fr_log_fp, " Vector:\t");
218 for (i = 4; i < 20; i++) {
219 fprintf(fr_log_fp, "%02x", packet->data[i]);
221 fprintf(fr_log_fp, "\n");
223 if (packet->data_len > 20) {
226 fprintf(fr_log_fp, " Data:");
228 total = packet->data_len - 20;
229 ptr = packet->data + 20;
233 unsigned int vendor = 0;
235 fprintf(fr_log_fp, "\t\t");
236 if (total < 2) { /* too short */
237 fprintf(fr_log_fp, "%02x\n", *ptr);
241 if (ptr[1] > total) { /* too long */
242 for (i = 0; i < total; i++) {
243 fprintf(fr_log_fp, "%02x ", ptr[i]);
248 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
249 attrlen = ptr[1] - 2;
251 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
253 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
254 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
255 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
265 print_hex_data(ptr, attrlen, 3);
274 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
277 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
278 #ifdef WITH_UDPFROMTO
279 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
281 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
283 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
286 struct sockaddr_storage dst;
287 socklen_t sizeof_dst;
289 #ifdef WITH_UDPFROMTO
290 struct sockaddr_storage src;
291 socklen_t sizeof_src;
293 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
296 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
300 #ifdef WITH_UDPFROMTO
302 * And if they don't specify a source IP address, don't
305 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
306 (src_ipaddr->af != AF_UNSPEC) &&
307 !fr_inaddr_any(src_ipaddr)) {
308 rcode = sendfromto(sockfd, data, data_len, flags,
309 (struct sockaddr *)&src, sizeof_src,
310 (struct sockaddr *)&dst, sizeof_dst);
316 * No udpfromto, fail gracefully.
318 rcode = sendto(sockfd, data, data_len, flags,
319 (struct sockaddr *) &dst, sizeof_dst);
320 #ifdef WITH_UDPFROMTO
324 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
331 void rad_recv_discard(int sockfd)
334 struct sockaddr_storage src;
335 socklen_t sizeof_src = sizeof(src);
337 (void) recvfrom(sockfd, header, sizeof(header), 0,
338 (struct sockaddr *)&src, &sizeof_src);
341 /** Basic validation of RADIUS packet header
343 * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
344 * consumed when discarding malformed packet.
346 * @param[in] sockfd we're reading from.
347 * @param[out] src_ipaddr of the packet.
348 * @param[out] src_port of the packet.
349 * @param[out] code Pointer to where to write the packet code.
352 * - 1 on decode error.
353 * - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
355 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
357 ssize_t data_len, packet_len;
359 struct sockaddr_storage src;
360 socklen_t sizeof_src = sizeof(src);
362 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK, (struct sockaddr *)&src, &sizeof_src);
364 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
369 * Convert AF. If unknown, discard packet.
371 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
372 FR_DEBUG_STRERROR_PRINTF("Unknown address family");
373 rad_recv_discard(sockfd);
379 * Too little data is available, discard the packet.
382 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
384 FR_DEBUG_STRERROR_PRINTF("Invalid data from %s: %s",
385 fr_inet_ntop(src_ipaddr->af, &src_ipaddr->ipaddr),
387 rad_recv_discard(sockfd);
393 * See how long the packet says it is.
395 packet_len = (header[2] * 256) + header[3];
398 * The length in the packet says it's less than
399 * a RADIUS header length: discard it.
401 if (packet_len < RADIUS_HDR_LEN) {
402 FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN) " bytes of packet "
403 "data, got %zu bytes", packet_len);
408 * Enforce RFC requirements, for sanity.
409 * Anything after 4k will be discarded.
411 if (packet_len > MAX_PACKET_LEN) {
412 FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
413 STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
420 * The packet says it's this long, but the actual UDP
421 * size could still be smaller.
427 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
430 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
431 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
432 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
434 struct sockaddr_storage src;
435 struct sockaddr_storage dst;
436 socklen_t sizeof_src = sizeof(src);
437 socklen_t sizeof_dst = sizeof(dst);
443 memset(&src, 0, sizeof_src);
444 memset(&dst, 0, sizeof_dst);
447 * Read the length of the packet, from the packet.
448 * This lets us allocate the buffer to use for
449 * reading the rest of the packet.
451 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
452 (struct sockaddr *)&src, &sizeof_src);
454 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
459 * Too little data is available, discard the packet.
462 rad_recv_discard(sockfd);
466 } else { /* we got 4 bytes of data. */
468 * See how long the packet says it is.
470 len = (header[2] * 256) + header[3];
473 * The length in the packet says it's less than
474 * a RADIUS header length: discard it.
476 if (len < RADIUS_HDR_LEN) {
477 recvfrom(sockfd, header, sizeof(header), flags,
478 (struct sockaddr *)&src, &sizeof_src);
482 * Enforce RFC requirements, for sanity.
483 * Anything after 4k will be discarded.
485 } else if (len > MAX_PACKET_LEN) {
486 recvfrom(sockfd, header, sizeof(header), flags,
487 (struct sockaddr *)&src, &sizeof_src);
492 packet->data = talloc_array(packet, uint8_t, len);
493 if (!packet->data) return -1;
496 * Receive the packet. The OS will discard any data in the
497 * packet after "len" bytes.
499 #ifdef WITH_UDPFROMTO
500 data_len = recvfromto(sockfd, packet->data, len, flags,
501 (struct sockaddr *)&src, &sizeof_src,
502 (struct sockaddr *)&dst, &sizeof_dst);
504 data_len = recvfrom(sockfd, packet->data, len, flags,
505 (struct sockaddr *)&src, &sizeof_src);
508 * Get the destination address, too.
510 if (getsockname(sockfd, (struct sockaddr *)&dst,
511 &sizeof_dst) < 0) return -1;
517 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
518 return -1; /* Unknown address family, Die Die Die! */
522 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
526 * Different address families should never happen.
528 if (src.ss_family != dst.ss_family) {
536 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
537 /** Build an encrypted secret value to return in a reply packet
539 * The secret is hidden by xoring with a MD5 digest created from
540 * the shared secret and the authentication vector.
541 * We put them into MD5 in the reverse order from that used when
542 * encrypting passwords to RADIUS.
544 static void make_secret(uint8_t *digest, uint8_t const *vector,
545 char const *secret, uint8_t const *value, size_t length)
550 fr_md5_init(&context);
551 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
552 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
553 fr_md5_final(digest, &context);
555 for ( i = 0; i < length; i++ ) {
556 digest[i] ^= value[i];
560 #define MAX_PASS_LEN (128)
561 static void make_passwd(uint8_t *output, ssize_t *outlen,
562 uint8_t const *input, size_t inlen,
563 char const *secret, uint8_t const *vector)
565 FR_MD5_CTX context, old;
566 uint8_t digest[AUTH_VECTOR_LEN];
567 uint8_t passwd[MAX_PASS_LEN];
572 * If the length is zero, round it up.
576 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
578 memcpy(passwd, input, len);
579 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
585 else if ((len & 0x0f) != 0) {
591 fr_md5_init(&context);
592 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
598 fr_md5_update(&context, vector, AUTH_PASS_LEN);
600 for (n = 0; n < len; n += AUTH_PASS_LEN) {
603 fr_md5_update(&context,
604 passwd + n - AUTH_PASS_LEN,
608 fr_md5_final(digest, &context);
609 for (i = 0; i < AUTH_PASS_LEN; i++) {
610 passwd[i + n] ^= digest[i];
614 memcpy(output, passwd, len);
618 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
619 uint8_t const *input, size_t inlen, size_t room,
620 char const *secret, uint8_t const *vector)
622 FR_MD5_CTX context, old;
623 uint8_t digest[AUTH_VECTOR_LEN];
625 size_t encrypted_len;
628 * The password gets encoded with a 1-byte "length"
629 * field. Ensure that it doesn't overflow.
631 if (room > 253) room = 253;
634 * Limit the maximum size of the input password. 2 bytes
635 * are taken up by the salt, and one by the encoded
636 * "length" field. Note that if we have a tag, the
637 * "room" will be 252 octets, not 253 octets.
639 if (inlen > (room - 3)) inlen = room - 3;
642 * Length of the encrypted data is the clear-text
643 * password length plus one byte which encodes the length
644 * of the password. We round up to the nearest encoding
645 * block. Note that this can result in the encoding
646 * length being more than 253 octets.
648 encrypted_len = inlen + 1;
649 if ((encrypted_len & 0x0f) != 0) {
650 encrypted_len += 0x0f;
651 encrypted_len &= ~0x0f;
655 * We need 2 octets for the salt, followed by the actual
658 if (encrypted_len > (room - 2)) encrypted_len = room - 2;
660 *outlen = encrypted_len + 2; /* account for the salt */
663 * Copy the password over, and zero-fill the remainder.
665 memcpy(output + 3, input, inlen);
666 memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
669 * Generate salt. The RFCs say:
671 * The high bit of salt[0] must be set, each salt in a
672 * packet should be unique, and they should be random
674 * So, we set the high bit, add in a counter, and then
675 * add in some CSPRNG data. should be OK..
677 output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
679 output[1] = fr_rand();
680 output[2] = inlen; /* length of the password string */
682 fr_md5_init(&context);
683 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
686 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
687 fr_md5_update(&context, &output[0], 2);
689 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
694 fr_md5_update(&context,
695 output + 2 + n - AUTH_PASS_LEN,
699 fr_md5_final(digest, &context);
701 if ((2 + n + AUTH_PASS_LEN) < room) {
702 block_len = AUTH_PASS_LEN;
704 block_len = room - 2 - n;
707 for (i = 0; i < block_len; i++) {
708 output[i + 2 + n] ^= digest[i];
713 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
715 unsigned int tlv1, tlv2;
717 if (nest > fr_attr_max_tlv) return 0;
722 * Keep encoding TLVs which have the same scope.
723 * e.g. two attributes of:
724 * ATTR.TLV1.TLV2.TLV3 = data1
725 * ATTR.TLV1.TLV2.TLV4 = data2
726 * both get put into a container of "ATTR.TLV1.TLV2"
730 * Nothing to follow, we're done.
735 * Not from the same vendor, skip it.
737 if (vp->da->vendor != next->da->vendor) return 0;
740 * In a different TLV space, skip it.
743 tlv2 = next->da->attr;
745 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
746 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
748 if (tlv1 != tlv2) return 0;
754 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
755 RADIUS_PACKET const *original,
756 char const *secret, int nest,
757 VALUE_PAIR const **pvp,
758 uint8_t *start, size_t room);
760 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
761 RADIUS_PACKET const *original,
762 char const *secret, VALUE_PAIR const **pvp,
763 unsigned int attribute, uint8_t *ptr, size_t room);
765 /** Encode the *data* portion of the TLV
767 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
768 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
770 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
771 RADIUS_PACKET const *original,
772 char const *secret, int nest,
773 VALUE_PAIR const **pvp,
774 uint8_t *start, size_t room)
778 uint8_t *ptr = start;
779 VALUE_PAIR const *vp = *pvp;
780 VALUE_PAIR const *svp = vp;
785 if (nest > fr_attr_max_tlv) {
786 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
794 if (room <= 2) return ptr - start;
796 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
800 if (room > 255) my_room = 255;
802 len = vp2data_any(packet, original, secret, nest,
803 &vp, ptr + 2, my_room - 2);
804 if (len < 0) return len;
805 if (len == 0) return ptr - start;
806 /* len can NEVER be more than 253 */
811 if ((fr_debug_lvl > 3) && fr_log_fp) {
812 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
813 print_hex_data(ptr + 2, len, 3);
821 if (!do_next_tlv(svp, vp, nest)) break;
825 if ((fr_debug_lvl > 3) && fr_log_fp) {
828 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
829 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
836 /** Encodes the data portion of an attribute
838 * @return -1 on error, or the length of the data portion.
840 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
841 RADIUS_PACKET const *original,
842 char const *secret, int nest,
843 VALUE_PAIR const **pvp,
844 uint8_t *start, size_t room)
849 uint8_t *ptr = start;
852 VALUE_PAIR const *vp = *pvp;
857 * See if we need to encode a TLV. The low portion of
858 * the attribute has already been placed into the packer.
859 * If there are still attribute bytes left, then go
860 * encode them as TLVs.
862 * If we cared about the stack, we could unroll the loop.
864 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
865 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
866 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
871 * Set up the default sources for the data.
875 switch (vp->da->type) {
883 case PW_TYPE_IPV4_ADDR:
884 case PW_TYPE_IPV6_ADDR:
885 case PW_TYPE_IPV6_PREFIX:
886 case PW_TYPE_IPV4_PREFIX:
887 case PW_TYPE_ABINARY:
888 case PW_TYPE_ETHERNET: /* just in case */
889 data = (uint8_t const *) &vp->data;
893 len = 1; /* just in case */
894 array[0] = vp->vp_byte;
899 len = 2; /* just in case */
900 array[0] = (vp->vp_short >> 8) & 0xff;
901 array[1] = vp->vp_short & 0xff;
905 case PW_TYPE_INTEGER:
906 len = 4; /* just in case */
907 lvalue = htonl(vp->vp_integer);
908 memcpy(array, &lvalue, sizeof(lvalue));
912 case PW_TYPE_INTEGER64:
913 len = 8; /* just in case */
914 lvalue64 = htonll(vp->vp_integer64);
915 data = (uint8_t *) &lvalue64;
919 * There are no tagged date attributes.
922 lvalue = htonl(vp->vp_date);
923 data = (uint8_t const *) &lvalue;
924 len = 4; /* just in case */
931 len = 4; /* just in case */
932 slvalue = htonl(vp->vp_signed);
933 memcpy(array, &slvalue, sizeof(slvalue));
938 default: /* unknown type: ignore it */
939 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
952 * Bound the data to the calling size
954 if (len > (ssize_t) room) len = room;
957 * Encrypt the various password styles
959 * Attributes with encrypted values MUST be less than
962 switch (vp->da->flags.encrypt) {
963 case FLAG_ENCRYPT_USER_PASSWORD:
964 make_passwd(ptr, &len, data, len,
965 secret, packet->vector);
968 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
970 if (vp->da->flags.has_tag) lvalue = 1;
973 * Check if there's enough room. If there isn't,
974 * we discard the attribute.
976 * This is ONLY a problem if we have multiple VSA's
977 * in one Vendor-Specific, though.
979 if (room < (18 + lvalue)) return 0;
981 switch (packet->code) {
982 case PW_CODE_ACCESS_ACCEPT:
983 case PW_CODE_ACCESS_REJECT:
984 case PW_CODE_ACCESS_CHALLENGE:
987 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
991 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
992 make_tunnel_passwd(ptr + lvalue, &len, data, len,
994 secret, original->vector);
997 case PW_CODE_ACCOUNTING_REQUEST:
998 case PW_CODE_DISCONNECT_REQUEST:
999 case PW_CODE_COA_REQUEST:
1000 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1001 make_tunnel_passwd(ptr + 1, &len, data, len, room - 1,
1002 secret, packet->vector);
1009 * The code above ensures that this attribute
1012 case FLAG_ENCRYPT_ASCEND_SECRET:
1013 if (len > AUTH_VECTOR_LEN) len = AUTH_VECTOR_LEN;
1014 make_secret(ptr, packet->vector, secret, data, len);
1015 len = AUTH_VECTOR_LEN;
1020 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
1021 if (vp->da->type == PW_TYPE_STRING) {
1022 if (len > ((ssize_t) (room - 1))) len = room - 1;
1025 } else if (vp->da->type == PW_TYPE_INTEGER) {
1027 } /* else it can't be any other type */
1029 memcpy(ptr, data, len);
1031 } /* switch over encryption flags */
1034 return len + (ptr - start);
1037 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1038 uint8_t *ptr, int hdr_len, ssize_t len,
1039 int flag_offset, int vsa_offset)
1041 int check_len = len - ptr[1];
1042 int total = len + hdr_len;
1045 * Pass 1: Check if the addition of the headers
1046 * overflows the available room. If so, return
1047 * what we were capable of encoding.
1050 while (check_len > (255 - hdr_len)) {
1052 check_len -= (255 - hdr_len);
1056 * Note that this results in a number of attributes maybe
1057 * being marked as "encoded", but which aren't in the
1058 * packet. Oh well. The solution is to fix the
1059 * "vp2data_any" function to take into account the header
1062 if ((ptr + ptr[1] + total) > end) {
1063 return (ptr + ptr[1]) - start;
1067 * Pass 2: Now that we know there's enough room,
1068 * re-arrange the data to form a set of valid
1069 * RADIUS attributes.
1072 int sublen = 255 - ptr[1];
1074 if (len <= sublen) {
1079 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1080 memmove(ptr + 255, ptr, hdr_len);
1082 if (vsa_offset) ptr[vsa_offset] += sublen;
1083 ptr[flag_offset] |= 0x80;
1087 if (vsa_offset) ptr[vsa_offset] = 3;
1091 if (vsa_offset) ptr[vsa_offset] += len;
1093 return (ptr + ptr[1]) - start;
1097 /** Encode an "extended" attribute
1099 int rad_vp2extended(RADIUS_PACKET const *packet,
1100 RADIUS_PACKET const *original,
1101 char const *secret, VALUE_PAIR const **pvp,
1102 uint8_t *ptr, size_t room)
1106 uint8_t *start = ptr;
1107 VALUE_PAIR const *vp = *pvp;
1111 if (!vp->da->flags.extended) {
1112 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1117 * The attribute number is encoded into the upper 8 bits
1120 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1122 if (!vp->da->flags.long_extended) {
1123 if (room < 3) return 0;
1126 ptr[2] = vp->da->attr & fr_attr_mask[0];
1129 if (room < 4) return 0;
1132 ptr[2] = vp->da->attr & fr_attr_mask[0];
1137 * Only "flagged" attributes can be longer than one
1140 if (!vp->da->flags.long_extended && (room > 255)) {
1147 if (vp->da->flags.evs) {
1148 uint8_t *evs = ptr + ptr[1];
1150 if (room < (size_t) (ptr[1] + 5)) return 0;
1154 evs[0] = 0; /* always zero */
1155 evs[1] = (vp->da->vendor >> 16) & 0xff;
1156 evs[2] = (vp->da->vendor >> 8) & 0xff;
1157 evs[3] = vp->da->vendor & 0xff;
1158 evs[4] = vp->da->attr & fr_attr_mask[0];
1164 len = vp2data_any(packet, original, secret, 0,
1165 pvp, ptr + ptr[1], room - hdr_len);
1166 if (len <= 0) return len;
1169 * There may be more than 252 octets of data encoded in
1170 * the attribute. If so, move the data up in the packet,
1171 * and copy the existing header over. Set the "M" flag ONLY
1172 * after copying the rest of the data.
1174 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1175 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1181 if ((fr_debug_lvl > 3) && fr_log_fp) {
1184 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1185 if (!vp->da->flags.long_extended) {
1186 fprintf(fr_log_fp, "%02x ", ptr[2]);
1189 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1193 if (vp->da->flags.evs) {
1194 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1195 ptr[jump], ptr[jump + 1],
1196 ptr[jump + 2], ptr[jump + 3],
1197 ((ptr[jump + 1] << 16) |
1198 (ptr[jump + 2] << 8) |
1204 print_hex_data(ptr + jump, len, 3);
1208 return (ptr + ptr[1]) - start;
1212 /** Encode a WiMAX attribute
1215 int rad_vp2wimax(RADIUS_PACKET const *packet,
1216 RADIUS_PACKET const *original,
1217 char const *secret, VALUE_PAIR const **pvp,
1218 uint8_t *ptr, size_t room)
1223 uint8_t *start = ptr;
1224 VALUE_PAIR const *vp = *pvp;
1229 * Double-check for WiMAX format.
1231 if (!vp->da->flags.wimax) {
1232 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1237 * Not enough room for:
1238 * attr, len, vendor-id, vsa, vsalen, continuation
1240 if (room < 9) return 0;
1243 * Build the Vendor-Specific header
1246 ptr[0] = PW_VENDOR_SPECIFIC;
1248 lvalue = htonl(vp->da->vendor);
1249 memcpy(ptr + 2, &lvalue, 4);
1250 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1252 ptr[8] = 0; /* continuation byte */
1256 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1258 if (len <= 0) return len;
1261 * There may be more than 252 octets of data encoded in
1262 * the attribute. If so, move the data up in the packet,
1263 * and copy the existing header over. Set the "C" flag
1264 * ONLY after copying the rest of the data.
1266 if (len > (255 - ptr[1])) {
1267 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1274 if ((fr_debug_lvl > 3) && fr_log_fp) {
1275 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1277 ptr[2], ptr[3], ptr[4], ptr[5],
1278 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1279 ptr[6], ptr[7], ptr[8]);
1280 print_hex_data(ptr + 9, len, 3);
1284 return (ptr + ptr[1]) - start;
1287 /** Encode an RFC format attribute, with the "concat" flag set
1289 * If there isn't enough room in the packet, the data is
1292 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1293 UNUSED RADIUS_PACKET const *original,
1294 UNUSED char const *secret, VALUE_PAIR const **pvp,
1295 unsigned int attribute, uint8_t *start, size_t room)
1297 uint8_t *ptr = start;
1300 VALUE_PAIR const *vp = *pvp;
1305 len = vp->vp_length;
1308 if (room <= 2) break;
1315 /* no more than 253 octets */
1316 if (left > 253) left = 253;
1318 /* no more than "room" octets */
1319 if (room < (left + 2)) left = room - 2;
1321 memcpy(ptr + 2, p, left);
1324 if ((fr_debug_lvl > 3) && fr_log_fp) {
1325 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1326 print_hex_data(ptr + 2, len, 3);
1340 /** Encode an RFC format TLV.
1342 * This could be a standard attribute, or a TLV data type.
1343 * If it's a standard attribute, then vp->da->attr == attribute.
1344 * Otherwise, attribute may be something else.
1346 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1347 RADIUS_PACKET const *original,
1348 char const *secret, VALUE_PAIR const **pvp,
1349 unsigned int attribute, uint8_t *ptr, size_t room)
1353 if (room <= 2) return 0;
1355 ptr[0] = attribute & 0xff;
1358 if (room > 255) room = 255;
1360 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room - ptr[1]);
1361 if (len <= 0) return len;
1366 if ((fr_debug_lvl > 3) && fr_log_fp) {
1367 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1368 print_hex_data(ptr + 2, len, 3);
1376 /** Encode a VSA which is a TLV
1378 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1380 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1381 RADIUS_PACKET const *original,
1382 char const *secret, VALUE_PAIR const **pvp,
1383 unsigned int attribute, unsigned int vendor,
1384 uint8_t *ptr, size_t room)
1388 VALUE_PAIR const *vp = *pvp;
1392 * Unknown vendor: RFC format.
1393 * Known vendor and RFC format: go do that.
1395 dv = dict_vendorbyvalue(vendor);
1397 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1398 return vp2attr_rfc(packet, original, secret, pvp,
1399 attribute, ptr, room);
1404 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1405 " type %u", (unsigned) dv->type);
1409 ptr[0] = 0; /* attr must be 24-bit */
1410 ptr[1] = (attribute >> 16) & 0xff;
1411 ptr[2] = (attribute >> 8) & 0xff;
1412 ptr[3] = attribute & 0xff;
1416 ptr[0] = (attribute >> 8) & 0xff;
1417 ptr[1] = attribute & 0xff;
1421 ptr[0] = attribute & 0xff;
1425 switch (dv->length) {
1427 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1428 " length %u", (unsigned) dv->length);
1436 ptr[dv->type + 1] = dv->type + 2;
1440 ptr[dv->type] = dv->type + 1;
1445 if (room > 255) room = 255;
1447 len = vp2data_any(packet, original, secret, 0, pvp,
1448 ptr + dv->type + dv->length, room - (dv->type + dv->length));
1449 if (len <= 0) return len;
1451 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1454 if ((fr_debug_lvl > 3) && fr_log_fp) {
1460 if ((fr_debug_lvl > 3) && fr_log_fp)
1461 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1462 ptr[0], ptr[1], ptr[2], ptr[3]);
1466 if ((fr_debug_lvl > 3) && fr_log_fp)
1467 fprintf(fr_log_fp, "\t\t%02x%02x ",
1472 if ((fr_debug_lvl > 3) && fr_log_fp)
1473 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1477 switch (dv->length) {
1482 fprintf(fr_log_fp, " ");
1486 fprintf(fr_log_fp, "%02x ",
1491 fprintf(fr_log_fp, "%02x%02x ",
1492 ptr[dv->type], ptr[dv->type] + 1);
1496 print_hex_data(ptr + dv->type + dv->length, len, 3);
1500 return dv->type + dv->length + len;
1504 /** Encode a Vendor-Specific attribute
1507 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1508 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1513 VALUE_PAIR const *vp = *pvp;
1517 if (vp->da->vendor == 0) {
1518 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1523 * Double-check for WiMAX format.
1525 if (vp->da->flags.wimax) {
1526 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1529 if (vp->da->vendor > FR_MAX_VENDOR) {
1530 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1535 * Not enough room for:
1536 * attr, len, vendor-id
1538 if (room < 6) return 0;
1541 * Build the Vendor-Specific header
1543 ptr[0] = PW_VENDOR_SPECIFIC;
1545 lvalue = htonl(vp->da->vendor);
1546 memcpy(ptr + 2, &lvalue, 4);
1548 if (room > 255) room = 255;
1550 len = vp2attr_vsa(packet, original, secret, pvp,
1551 vp->da->attr, vp->da->vendor,
1552 ptr + ptr[1], room - ptr[1]);
1553 if (len < 0) return len;
1556 if ((fr_debug_lvl > 3) && fr_log_fp) {
1557 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1559 ptr[2], ptr[3], ptr[4], ptr[5],
1560 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1561 print_hex_data(ptr + 6, len, 3);
1571 /** Encode an RFC standard attribute 1..255
1574 int rad_vp2rfc(RADIUS_PACKET const *packet,
1575 RADIUS_PACKET const *original,
1576 char const *secret, VALUE_PAIR const **pvp,
1577 uint8_t *ptr, size_t room)
1579 VALUE_PAIR const *vp = *pvp;
1583 if (vp->da->vendor != 0) {
1584 fr_strerror_printf("rad_vp2rfc called with VSA");
1588 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1589 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1594 * Only CUI is allowed to have zero length.
1597 if ((vp->vp_length == 0) &&
1598 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1599 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1607 * Message-Authenticator is hard-coded.
1609 if (vp->da->attr == PW_MESSAGE_AUTHENTICATOR) {
1610 if (room < 18) return -1;
1612 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1614 memset(ptr + 2, 0, 16);
1616 if ((fr_debug_lvl > 3) && fr_log_fp) {
1617 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1621 *pvp = (*pvp)->next;
1626 * EAP-Message is special.
1628 if (vp->da->flags.concat && (vp->vp_length > 253)) {
1629 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1633 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1637 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1638 RADIUS_PACKET const *original,
1639 char const *secret, VALUE_PAIR const **pvp,
1640 uint8_t *start, size_t room)
1643 VALUE_PAIR const *vp = *pvp;
1647 if (!vp->da->flags.is_tlv) {
1648 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1652 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1653 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1657 if (room < 5) return 0;
1660 * Encode the first level of TLVs
1662 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1664 start[2] = vp->da->attr & fr_attr_mask[0];
1667 len = vp2data_any(packet, original, secret, 0, pvp,
1668 start + 4, room - 4);
1669 if (len <= 0) return len;
1681 /** Parse a data structure into a RADIUS attribute
1684 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1685 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1688 VALUE_PAIR const *vp;
1690 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1697 * RFC format attributes take the fast path.
1699 if (!vp->da->vendor) {
1700 if (vp->da->attr > 255) {
1705 return rad_vp2rfc(packet, original, secret, pvp,
1709 if (vp->da->flags.extended) {
1710 return rad_vp2extended(packet, original, secret, pvp,
1715 * The upper 8 bits of the vendor number are the standard
1716 * space attribute which is a TLV.
1718 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1719 return rad_vp2rfctlv(packet, original, secret, pvp,
1723 if (vp->da->flags.wimax) {
1724 return rad_vp2wimax(packet, original, secret, pvp,
1728 return rad_vp2vsa(packet, original, secret, pvp, start, room);
1735 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1738 radius_packet_t *hdr;
1740 uint16_t total_length;
1742 VALUE_PAIR const *reply;
1745 * A 4K packet, aligned on 64-bits.
1747 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1750 * Double-check some things based on packet code.
1752 switch (packet->code) {
1753 case PW_CODE_ACCESS_ACCEPT:
1754 case PW_CODE_ACCESS_REJECT:
1755 case PW_CODE_ACCESS_CHALLENGE:
1757 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1763 * These packet vectors start off as all zero.
1765 case PW_CODE_ACCOUNTING_REQUEST:
1766 case PW_CODE_DISCONNECT_REQUEST:
1767 case PW_CODE_COA_REQUEST:
1768 memset(packet->vector, 0, sizeof(packet->vector));
1776 * Use memory on the stack, until we know how
1777 * large the packet will be.
1779 hdr = (radius_packet_t *) data;
1782 * Build standard header
1784 hdr->code = packet->code;
1785 hdr->id = packet->id;
1787 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1789 total_length = RADIUS_HDR_LEN;
1792 * Load up the configuration values for the user
1798 * FIXME: Loop twice over the reply list. The first time,
1799 * calculate the total length of data. The second time,
1800 * allocate the memory, and fill in the VP's.
1802 * Hmm... this may be slower than just doing a small
1807 * Loop over the reply attributes for the packet.
1809 reply = packet->vps;
1811 size_t last_len, room;
1812 char const *last_name = NULL;
1817 * Ignore non-wire attributes, but allow extended
1820 if ((reply->da->vendor == 0) &&
1821 ((reply->da->attr & 0xFFFF) >= 256) &&
1822 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1825 * Permit the admin to send BADLY formatted
1826 * attributes with a debug build.
1828 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1829 memcpy(ptr, reply->vp_octets, reply->vp_length);
1830 len = reply->vp_length;
1831 reply = reply->next;
1835 reply = reply->next;
1840 * We allow zero-length strings in "unlang", but
1841 * skip them (except for CUI, thanks WiMAX!) on
1842 * all other attributes.
1844 if (reply->vp_length == 0) {
1845 if ((reply->da->vendor != 0) ||
1846 ((reply->da->attr != PW_CHARGEABLE_USER_IDENTITY) &&
1847 (reply->da->attr != PW_MESSAGE_AUTHENTICATOR))) {
1848 reply = reply->next;
1854 * Set the Message-Authenticator to the correct
1855 * length and initial value.
1857 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1859 * Cache the offset to the
1860 * Message-Authenticator
1862 packet->offset = total_length;
1865 last_len = reply->vp_length;
1867 last_name = reply->da->name;
1869 room = ((uint8_t *) data) + sizeof(data) - ptr;
1871 if (room <= 2) break;
1873 len = rad_vp2attr(packet, original, secret, &reply, ptr, room);
1874 if (len < 0) return -1;
1877 * Failed to encode the attribute, likely because
1878 * the packet is full.
1881 if (last_len != 0) {
1882 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1885 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1890 next: /* Used only for Raw-Attribute */
1893 total_length += len;
1894 } /* done looping over all attributes */
1897 * Fill in the rest of the fields, and copy the data over
1898 * from the local stack to the newly allocated memory.
1900 * Yes, all this 'memcpy' is slow, but it means
1901 * that we only allocate the minimum amount of
1902 * memory for a request.
1904 packet->data_len = total_length;
1905 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1906 if (!packet->data) {
1907 fr_strerror_printf("Out of memory");
1911 memcpy(packet->data, hdr, packet->data_len);
1912 hdr = (radius_packet_t *) packet->data;
1914 total_length = htons(total_length);
1915 memcpy(hdr->length, &total_length, sizeof(total_length));
1921 /** Sign a previously encoded packet
1924 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1927 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1930 * It wasn't assigned an Id, this is bad!
1932 if (packet->id < 0) {
1933 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1937 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1938 (packet->offset < 0)) {
1939 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1944 * Set up the authentication vector with zero, or with
1945 * the original vector, prior to signing.
1947 switch (packet->code) {
1948 case PW_CODE_ACCOUNTING_REQUEST:
1949 case PW_CODE_DISCONNECT_REQUEST:
1950 case PW_CODE_COA_REQUEST:
1951 memset(packet->vector, 0, AUTH_VECTOR_LEN);
1954 case PW_CODE_ACCESS_ACCEPT:
1955 case PW_CODE_ACCESS_REJECT:
1956 case PW_CODE_ACCESS_CHALLENGE:
1957 case PW_CODE_ACCOUNTING_RESPONSE:
1958 case PW_CODE_DISCONNECT_ACK:
1959 case PW_CODE_DISCONNECT_NAK:
1960 case PW_CODE_COA_ACK:
1961 case PW_CODE_COA_NAK:
1963 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1966 memcpy(packet->vector, original->vector, AUTH_VECTOR_LEN);
1969 case PW_CODE_ACCESS_REQUEST:
1970 case PW_CODE_STATUS_SERVER:
1972 break; /* packet->vector is already random bytes */
1976 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
1980 * If there's a Message-Authenticator, update it
1983 if (packet->offset > 0) {
1984 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1986 switch (packet->code) {
1987 case PW_CODE_ACCOUNTING_RESPONSE:
1988 if (original && original->code == PW_CODE_STATUS_SERVER) {
1992 case PW_CODE_ACCOUNTING_REQUEST:
1993 case PW_CODE_DISCONNECT_REQUEST:
1994 case PW_CODE_DISCONNECT_ACK:
1995 case PW_CODE_DISCONNECT_NAK:
1996 case PW_CODE_COA_REQUEST:
1997 case PW_CODE_COA_ACK:
1998 case PW_CODE_COA_NAK:
1999 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
2003 case PW_CODE_ACCESS_ACCEPT:
2004 case PW_CODE_ACCESS_REJECT:
2005 case PW_CODE_ACCESS_CHALLENGE:
2006 memcpy(hdr->vector, original->vector, AUTH_VECTOR_LEN);
2014 * Set the authentication vector to zero,
2015 * calculate the HMAC, and put it
2016 * into the Message-Authenticator
2019 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2020 (uint8_t const *) secret, strlen(secret));
2021 memcpy(packet->data + packet->offset + 2,
2022 calc_auth_vector, AUTH_VECTOR_LEN);
2026 * Copy the request authenticator over to the packet.
2028 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
2031 * Switch over the packet code, deciding how to
2034 switch (packet->code) {
2036 * Request packets are not signed, but
2037 * have a random authentication vector.
2039 case PW_CODE_ACCESS_REQUEST:
2040 case PW_CODE_STATUS_SERVER:
2044 * Reply packets are signed with the
2045 * authentication vector of the request.
2052 fr_md5_init(&context);
2053 fr_md5_update(&context, packet->data, packet->data_len);
2054 fr_md5_update(&context, (uint8_t const *) secret,
2056 fr_md5_final(digest, &context);
2058 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2059 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2062 }/* switch over packet codes */
2067 /** Reply to the request
2069 * Also attach reply attribute value pairs and any user message provided.
2071 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2075 * Maybe it's a fake packet. Don't send it.
2077 if (!packet || (packet->sockfd < 0)) {
2082 * First time through, allocate room for the packet
2084 if (!packet->data) {
2086 * Encode the packet.
2088 if (rad_encode(packet, original, secret) < 0) {
2093 * Re-sign it, including updating the
2094 * Message-Authenticator.
2096 if (rad_sign(packet, original, secret) < 0) {
2101 * If packet->data points to data, then we print out
2102 * the VP list again only for debugging.
2107 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2112 * If the socket is TCP, call write(). Calling sendto()
2113 * is allowed on some platforms, but it's not nice. Even
2114 * worse, if UDPFROMTO is defined, we *can't* use it on
2115 * TCP sockets. So... just call write().
2117 if (packet->proto == IPPROTO_TCP) {
2120 rcode = write(packet->sockfd, packet->data, packet->data_len);
2121 if (rcode >= 0) return rcode;
2123 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2129 * And send it on it's way.
2131 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2132 &packet->src_ipaddr, packet->src_port,
2133 &packet->dst_ipaddr, packet->dst_port);
2136 /** Do a comparison of two authentication digests by comparing the FULL digest
2138 * Otherwise, the server can be subject to timing attacks that allow attackers
2139 * find a valid message authenticator.
2141 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2143 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2148 for (i = 0; i < length; i++) {
2149 result |= a[i] ^ b[i];
2152 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2156 /** Validates the requesting client NAS
2158 * Calculates the request Authenticator based on the clients private key.
2160 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2162 uint8_t digest[AUTH_VECTOR_LEN];
2166 * Zero out the auth_vector in the received packet.
2167 * Then append the shared secret to the received packet,
2168 * and calculate the MD5 sum. This must be the same
2169 * as the original MD5 sum (packet->vector).
2171 memset(packet->data + 4, 0, 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(digest, &context);
2182 * Return 0 if OK, 2 if not OK.
2184 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2189 /** Validates the requesting client NAS
2191 * Calculates the response Authenticator based on the clients
2194 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2197 uint8_t calc_digest[AUTH_VECTOR_LEN];
2203 if (original == NULL) {
2208 * Copy the original vector in place.
2210 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2213 * MD5(packet + secret);
2215 fr_md5_init(&context);
2216 fr_md5_update(&context, packet->data, packet->data_len);
2217 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2218 fr_md5_final(calc_digest, &context);
2221 * Copy the packet's vector back to the packet.
2223 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2226 * Return 0 if OK, 2 if not OK.
2228 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2232 /** Check if a set of RADIUS formatted TLVs are OK
2235 int rad_tlv_ok(uint8_t const *data, size_t length,
2236 size_t dv_type, size_t dv_length)
2238 uint8_t const *end = data + length;
2240 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2242 VP_HEXDUMP("tlv_ok", data, length);
2244 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2245 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2249 while (data < end) {
2252 if ((data + dv_type + dv_length) > end) {
2253 fr_strerror_printf("Attribute header overflow");
2259 if ((data[0] == 0) && (data[1] == 0) &&
2260 (data[2] == 0) && (data[3] == 0)) {
2262 fr_strerror_printf("Invalid attribute 0");
2267 fr_strerror_printf("Invalid attribute > 2^24");
2273 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2278 * Zero is allowed, because the Colubris
2279 * people are dumb and use it.
2284 fr_strerror_printf("Internal sanity check failed");
2288 switch (dv_length) {
2293 if (data[dv_type] != 0) {
2294 fr_strerror_printf("Attribute is longer than 256 octets");
2299 attrlen = data[dv_type + dv_length - 1];
2304 fr_strerror_printf("Internal sanity check failed");
2308 if (attrlen < (dv_type + dv_length)) {
2309 fr_strerror_printf("Attribute header has invalid length");
2313 if (attrlen > length) {
2314 fr_strerror_printf("Attribute overflows container");
2326 /** See if the data pointed to by PTR is a valid RADIUS packet.
2328 * Packet is not 'const * const' because we may update data_len, if there's more data
2329 * in the UDP packet than in the RADIUS packet.
2331 * @param packet to check
2332 * @param flags to control decoding
2333 * @param reason if not NULL, will have the failure reason written to where it points.
2334 * @return bool, true on success, false on failure.
2336 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2341 radius_packet_t *hdr;
2342 char host_ipaddr[128];
2343 bool require_ma = false;
2344 bool seen_ma = false;
2345 uint32_t num_attributes;
2346 decode_fail_t failure = DECODE_FAIL_NONE;
2348 bool non_eap = false;
2351 * Check for packets smaller than the packet header.
2353 * RFC 2865, Section 3., subsection 'length' says:
2355 * "The minimum length is 20 ..."
2357 if (packet->data_len < RADIUS_HDR_LEN) {
2358 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2359 inet_ntop(packet->src_ipaddr.af,
2360 &packet->src_ipaddr.ipaddr,
2361 host_ipaddr, sizeof(host_ipaddr)),
2362 packet->data_len, RADIUS_HDR_LEN);
2363 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2369 * Check for packets with mismatched size.
2370 * i.e. We've received 128 bytes, and the packet header
2371 * says it's 256 bytes long.
2373 totallen = (packet->data[2] << 8) | packet->data[3];
2374 hdr = (radius_packet_t *)packet->data;
2377 * Code of 0 is not understood.
2378 * Code of 16 or greate is not understood.
2380 if ((hdr->code == 0) ||
2381 (hdr->code >= FR_MAX_PACKET_CODE)) {
2382 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2383 inet_ntop(packet->src_ipaddr.af,
2384 &packet->src_ipaddr.ipaddr,
2385 host_ipaddr, sizeof(host_ipaddr)),
2387 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2392 * Message-Authenticator is required in Status-Server
2393 * packets, otherwise they can be trivially forged.
2395 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2398 * It's also required if the caller asks for it.
2400 if (flags) require_ma = true;
2403 * Repeat the length checks. This time, instead of
2404 * looking at the data we received, look at the value
2405 * of the 'length' field inside of the packet.
2407 * Check for packets smaller than the packet header.
2409 * RFC 2865, Section 3., subsection 'length' says:
2411 * "The minimum length is 20 ..."
2413 if (totallen < RADIUS_HDR_LEN) {
2414 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2415 inet_ntop(packet->src_ipaddr.af,
2416 &packet->src_ipaddr.ipaddr,
2417 host_ipaddr, sizeof(host_ipaddr)),
2418 totallen, RADIUS_HDR_LEN);
2419 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2424 * And again, for the value of the 'length' field.
2426 * RFC 2865, Section 3., subsection 'length' says:
2428 * " ... and maximum length is 4096."
2430 * HOWEVER. This requirement is for the network layer.
2431 * If the code gets here, we assume that a well-formed
2432 * packet is an OK packet.
2434 * We allow both the UDP data length, and the RADIUS
2435 * "length" field to contain up to 64K of data.
2439 * RFC 2865, Section 3., subsection 'length' says:
2441 * "If the packet is shorter than the Length field
2442 * indicates, it MUST be silently discarded."
2444 * i.e. No response to the NAS.
2446 if (packet->data_len < totallen) {
2447 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2448 inet_ntop(packet->src_ipaddr.af,
2449 &packet->src_ipaddr.ipaddr,
2450 host_ipaddr, sizeof(host_ipaddr)),
2451 packet->data_len, totallen);
2452 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2457 * RFC 2865, Section 3., subsection 'length' says:
2459 * "Octets outside the range of the Length field MUST be
2460 * treated as padding and ignored on reception."
2462 if (packet->data_len > totallen) {
2464 * We're shortening the packet below, but just
2465 * to be paranoid, zero out the extra data.
2467 memset(packet->data + totallen, 0, packet->data_len - totallen);
2468 packet->data_len = totallen;
2472 * Walk through the packet's attributes, ensuring that
2473 * they add up EXACTLY to the size of the packet.
2475 * If they don't, then the attributes either under-fill
2476 * or over-fill the packet. Any parsing of the packet
2477 * is impossible, and will result in unknown side effects.
2479 * This would ONLY happen with buggy RADIUS implementations,
2480 * or with an intentional attack. Either way, we do NOT want
2481 * to be vulnerable to this problem.
2484 count = totallen - RADIUS_HDR_LEN;
2489 * We need at least 2 bytes to check the
2493 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2494 inet_ntop(packet->src_ipaddr.af,
2495 &packet->src_ipaddr.ipaddr,
2496 host_ipaddr, sizeof(host_ipaddr)));
2497 failure = DECODE_FAIL_HEADER_OVERFLOW;
2502 * Attribute number zero is NOT defined.
2505 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2506 inet_ntop(packet->src_ipaddr.af,
2507 &packet->src_ipaddr.ipaddr,
2508 host_ipaddr, sizeof(host_ipaddr)));
2509 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2514 * Attributes are at LEAST as long as the ID & length
2515 * fields. Anything shorter is an invalid attribute.
2518 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2519 inet_ntop(packet->src_ipaddr.af,
2520 &packet->src_ipaddr.ipaddr,
2521 host_ipaddr, sizeof(host_ipaddr)),
2523 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2528 * If there are fewer bytes in the packet than in the
2529 * attribute, it's a bad packet.
2531 if (count < attr[1]) {
2532 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2533 inet_ntop(packet->src_ipaddr.af,
2534 &packet->src_ipaddr.ipaddr,
2535 host_ipaddr, sizeof(host_ipaddr)),
2537 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2542 * Sanity check the attributes for length.
2545 default: /* don't do anything by default */
2549 * If there's an EAP-Message, we require
2550 * a Message-Authenticator.
2552 case PW_EAP_MESSAGE:
2557 case PW_USER_PASSWORD:
2558 case PW_CHAP_PASSWORD:
2559 case PW_ARAP_PASSWORD:
2563 case PW_MESSAGE_AUTHENTICATOR:
2564 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2565 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2566 inet_ntop(packet->src_ipaddr.af,
2567 &packet->src_ipaddr.ipaddr,
2568 host_ipaddr, sizeof(host_ipaddr)),
2570 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2578 * FIXME: Look up the base 255 attributes in the
2579 * dictionary, and switch over their type. For
2580 * integer/date/ip, the attribute length SHOULD
2583 count -= attr[1]; /* grab the attribute length */
2585 num_attributes++; /* seen one more attribute */
2589 * If the attributes add up to a packet, it's allowed.
2591 * If not, we complain, and throw the packet away.
2594 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2595 inet_ntop(packet->src_ipaddr.af,
2596 &packet->src_ipaddr.ipaddr,
2597 host_ipaddr, sizeof(host_ipaddr)));
2598 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2603 * If we're configured to look for a maximum number of
2604 * attributes, and we've seen more than that maximum,
2605 * then throw the packet away, as a possible DoS.
2607 if ((fr_max_attributes > 0) &&
2608 (num_attributes > fr_max_attributes)) {
2609 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2610 inet_ntop(packet->src_ipaddr.af,
2611 &packet->src_ipaddr.ipaddr,
2612 host_ipaddr, sizeof(host_ipaddr)),
2613 num_attributes, fr_max_attributes);
2614 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2619 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2621 * A packet with an EAP-Message attribute MUST also have
2622 * a Message-Authenticator attribute.
2624 * A Message-Authenticator all by itself is OK, though.
2626 * Similarly, Status-Server packets MUST contain
2627 * Message-Authenticator attributes.
2629 if (require_ma && !seen_ma) {
2630 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2631 inet_ntop(packet->src_ipaddr.af,
2632 &packet->src_ipaddr.ipaddr,
2633 host_ipaddr, sizeof(host_ipaddr)));
2634 failure = DECODE_FAIL_MA_MISSING;
2638 if (eap && non_eap) {
2639 FR_DEBUG_STRERROR_PRINTF("Bad packet from host %s: Packet contains EAP-Message and non-EAP authentication attribute",
2640 inet_ntop(packet->src_ipaddr.af,
2641 &packet->src_ipaddr.ipaddr,
2642 host_ipaddr, sizeof(host_ipaddr)));
2643 failure = DECODE_FAIL_TOO_MANY_AUTH;
2648 * Fill RADIUS header fields
2650 packet->code = hdr->code;
2651 packet->id = hdr->id;
2652 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2660 return (failure == DECODE_FAIL_NONE);
2664 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2667 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2671 RADIUS_PACKET *packet;
2674 * Allocate the new request data structure
2676 packet = rad_alloc(ctx, false);
2678 fr_strerror_printf("out of memory");
2683 sock_flags = MSG_PEEK;
2687 data_len = rad_recvfrom(fd, packet, sock_flags,
2688 &packet->src_ipaddr, &packet->src_port,
2689 &packet->dst_ipaddr, &packet->dst_port);
2692 * Check for socket errors.
2695 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2696 /* packet->data is NULL */
2700 packet->data_len = data_len; /* unsigned vs signed */
2703 * If the packet is too big, then rad_recvfrom did NOT
2704 * allocate memory. Instead, it just discarded the
2707 if (packet->data_len > MAX_PACKET_LEN) {
2708 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2709 /* packet->data is NULL */
2715 * Read no data. Continue.
2716 * This check is AFTER the MAX_PACKET_LEN check above, because
2717 * if the packet is larger than MAX_PACKET_LEN, we also have
2718 * packet->data == NULL
2720 if ((packet->data_len == 0) || !packet->data) {
2721 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2727 * See if it's a well-formed RADIUS packet.
2729 if (!rad_packet_ok(packet, flags, NULL)) {
2735 * Remember which socket we read the packet from.
2737 packet->sockfd = fd;
2740 * FIXME: Do even more filtering by only permitting
2741 * certain IP's. The problem is that we don't know
2742 * how to do this properly for all possible clients...
2746 * Explicitely set the VP list to empty.
2751 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2758 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2761 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2769 if (!packet || !packet->data) return -1;
2772 * Before we allocate memory for the attributes, do more
2775 ptr = packet->data + RADIUS_HDR_LEN;
2776 length = packet->data_len - RADIUS_HDR_LEN;
2777 while (length > 0) {
2778 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2779 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2784 default: /* don't do anything. */
2788 * Note that more than one Message-Authenticator
2789 * attribute is invalid.
2791 case PW_MESSAGE_AUTHENTICATOR:
2792 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2793 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2795 switch (packet->code) {
2799 case PW_CODE_ACCOUNTING_RESPONSE:
2801 (original->code == PW_CODE_STATUS_SERVER)) {
2805 case PW_CODE_ACCOUNTING_REQUEST:
2806 case PW_CODE_DISCONNECT_REQUEST:
2807 case PW_CODE_COA_REQUEST:
2808 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2812 case PW_CODE_ACCESS_ACCEPT:
2813 case PW_CODE_ACCESS_REJECT:
2814 case PW_CODE_ACCESS_CHALLENGE:
2815 case PW_CODE_DISCONNECT_ACK:
2816 case PW_CODE_DISCONNECT_NAK:
2817 case PW_CODE_COA_ACK:
2818 case PW_CODE_COA_NAK:
2820 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2821 "packet without a request packet");
2824 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2828 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2829 (uint8_t const *) secret, strlen(secret));
2830 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2831 sizeof(calc_auth_vector)) != 0) {
2832 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2833 "(Shared secret is incorrect.)",
2834 inet_ntop(packet->src_ipaddr.af,
2835 &packet->src_ipaddr.ipaddr,
2836 buffer, sizeof(buffer)));
2837 /* Silently drop packet, according to RFC 3579 */
2839 } /* else the message authenticator was good */
2842 * Reinitialize Authenticators.
2844 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2845 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2847 } /* switch over the attributes */
2851 } /* loop over the packet, sanity checking the attributes */
2854 * It looks like a RADIUS packet, but we don't know what it is
2855 * so can't validate the authenticators.
2857 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2858 fr_strerror_printf("Received Unknown packet code %d "
2859 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2861 inet_ntop(packet->src_ipaddr.af,
2862 &packet->src_ipaddr.ipaddr,
2863 buffer, sizeof(buffer)),
2869 * Calculate and/or verify Request or Response Authenticator.
2871 switch (packet->code) {
2872 case PW_CODE_ACCESS_REQUEST:
2873 case PW_CODE_STATUS_SERVER:
2875 * The authentication vector is random
2876 * nonsense, invented by the client.
2880 case PW_CODE_COA_REQUEST:
2881 case PW_CODE_DISCONNECT_REQUEST:
2882 case PW_CODE_ACCOUNTING_REQUEST:
2883 if (calc_acctdigest(packet, secret) > 1) {
2884 fr_strerror_printf("Received %s packet "
2885 "from client %s with invalid Request Authenticator! "
2886 "(Shared secret is incorrect.)",
2887 fr_packet_codes[packet->code],
2888 inet_ntop(packet->src_ipaddr.af,
2889 &packet->src_ipaddr.ipaddr,
2890 buffer, sizeof(buffer)));
2895 /* Verify the reply digest */
2896 case PW_CODE_ACCESS_ACCEPT:
2897 case PW_CODE_ACCESS_REJECT:
2898 case PW_CODE_ACCESS_CHALLENGE:
2899 case PW_CODE_ACCOUNTING_RESPONSE:
2900 case PW_CODE_DISCONNECT_ACK:
2901 case PW_CODE_DISCONNECT_NAK:
2902 case PW_CODE_COA_ACK:
2903 case PW_CODE_COA_NAK:
2904 rcode = calc_replydigest(packet, original, secret);
2906 fr_strerror_printf("Received %s packet "
2907 "from home server %s port %d with invalid Response Authenticator! "
2908 "(Shared secret is incorrect.)",
2909 fr_packet_codes[packet->code],
2910 inet_ntop(packet->src_ipaddr.af,
2911 &packet->src_ipaddr.ipaddr,
2912 buffer, sizeof(buffer)),
2919 fr_strerror_printf("Received Unknown packet code %d "
2920 "from client %s port %d: Cannot validate Request/Response Authenticator",
2922 inet_ntop(packet->src_ipaddr.af,
2923 &packet->src_ipaddr.ipaddr,
2924 buffer, sizeof(buffer)),
2933 /** Convert a "concatenated" attribute to one long VP
2936 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2937 DICT_ATTR const *da, uint8_t const *start,
2938 size_t const packetlen, VALUE_PAIR **pvp)
2942 uint8_t const *ptr = start;
2943 uint8_t const *end = start + packetlen;
2951 * The packet has already been sanity checked, so we
2952 * don't care about walking off of the end of it.
2955 total += ptr[1] - 2;
2960 * Attributes MUST be consecutive.
2962 if (ptr[0] != attr) break;
2965 vp = fr_pair_afrom_da(ctx, da);
2968 vp->vp_length = total;
2969 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2971 fr_pair_list_free(&vp);
2977 while (total < vp->vp_length) {
2978 memcpy(p, ptr + 2, ptr[1] - 2);
2980 total += ptr[1] - 2;
2989 /** Convert TLVs to one or more VPs
2992 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2993 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2994 char const *secret, DICT_ATTR const *da,
2995 uint8_t const *start, size_t length,
2998 uint8_t const *data = start;
2999 DICT_ATTR const *child;
3000 VALUE_PAIR *head, **tail;
3002 if (length < 3) return -1; /* type, length, value */
3004 VP_HEXDUMP("tlvs", data, length);
3006 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
3011 while (data < (start + length)) {
3014 child = dict_attrbyparent(da, data[0], da->vendor);
3016 unsigned int my_attr, my_vendor;
3018 VP_TRACE("Failed to find child %u of TLV %s\n",
3022 * Get child attr/vendor so that
3023 * we can call unknown attr.
3026 my_vendor = da->vendor;
3028 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
3029 fr_pair_list_free(&head);
3033 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
3035 fr_pair_list_free(&head);
3040 tlv_len = data2vp(ctx, packet, original, secret, child,
3041 data + 2, data[1] - 2, data[1] - 2, tail);
3043 fr_pair_list_free(&head);
3046 if (*tail) tail = &((*tail)->next);
3054 /** Convert a top-level VSA to a VP.
3056 * "length" can be LONGER than just this sub-vsa.
3058 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3059 RADIUS_PACKET const *original,
3060 char const *secret, DICT_VENDOR *dv,
3061 uint8_t const *data, size_t length,
3064 unsigned int attribute;
3065 ssize_t attrlen, my_len;
3066 DICT_ATTR const *da;
3068 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3071 if (length <= (dv->type + dv->length)) {
3072 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3079 /* data[0] must be zero */
3080 attribute = data[1] << 16;
3081 attribute |= data[2] << 8;
3082 attribute |= data[3];
3086 attribute = data[0] << 8;
3087 attribute |= data[1];
3091 attribute = data[0];
3095 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3099 switch (dv->length) {
3101 /* data[dv->type] must be zero, from rad_tlv_ok() */
3102 attrlen = data[dv->type + 1];
3106 attrlen = data[dv->type];
3114 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3119 * See if the VSA is known.
3121 da = dict_attrbyvalue(attribute, dv->vendorpec);
3122 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3125 my_len = data2vp(ctx, packet, original, secret, da,
3126 data + dv->type + dv->length,
3127 attrlen - (dv->type + dv->length),
3128 attrlen - (dv->type + dv->length),
3130 if (my_len < 0) return my_len;
3136 /** Convert a fragmented extended attr to a VP
3146 * But for the first fragment, we get passed a pointer to the "extended-attr"
3148 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3149 RADIUS_PACKET const *original,
3150 char const *secret, DICT_ATTR const *da,
3151 uint8_t const *data,
3152 size_t attrlen, size_t packetlen,
3158 uint8_t *head, *tail;
3159 uint8_t const *attr, *end;
3160 DICT_ATTR const *child;
3163 * data = Ext-Attr Flag ...
3167 * Not enough room for Ext-Attr + Flag + data, it's a bad
3173 * It's not an Extended attribute, it's unknown...
3175 child = dict_unknown_afrom_fields(ctx, (da->vendor/ FR_MAX_VENDOR) & 0xff, 0);
3177 fr_strerror_printf("Internal sanity check %d", __LINE__);
3181 rcode = data2vp(ctx, packet, original, secret, child,
3182 data, attrlen, attrlen, pvp);
3183 if (rcode < 0) return rcode;
3188 * No continued data, just decode the attribute in place.
3190 if ((data[1] & 0x80) == 0) {
3191 rcode = data2vp(ctx, packet, original, secret, da,
3192 data + 2, attrlen - 2, attrlen - 2,
3195 if ((rcode < 0) || (((size_t) rcode + 2) != attrlen)) goto raw; /* didn't decode all of the data */
3200 * It's continued, but there are no subsequent fragments,
3203 if (attrlen >= packetlen) goto raw;
3206 * Calculate the length of all of the fragments. For
3207 * now, they MUST be contiguous in the packet, and they
3208 * MUST be all of the same Type and Ext-Type
3210 * We skip the first fragment, which doesn't have a
3211 * RADIUS attribute header.
3213 ext_len = attrlen - 2;
3214 attr = data + attrlen;
3215 end = data + packetlen;
3217 while (attr < end) {
3219 * Not enough room for Attr + length + Ext-Attr
3220 * continuation, it's bad.
3222 if ((end - attr) < 4) goto raw;
3224 if (attr[1] < 4) goto raw;
3227 * If the attribute overflows the packet, it's
3230 if ((attr + attr[1]) > end) goto raw;
3232 if (attr[0] != ((da->vendor / FR_MAX_VENDOR) & 0xff)) goto raw; /* not the same Extended-Attribute-X */
3234 if (attr[2] != data[0]) goto raw; /* Not the same Ext-Attr */
3237 * Check the continuation flag.
3239 more = ((attr[2] & 0x80) != 0);
3242 * Or, there's no more data, in which case we
3243 * shorten "end" to finish at this attribute.
3245 if (!more) end = attr + attr[1];
3248 * There's more data, but we're at the end of the
3249 * packet. The attribute is malformed!
3251 if (more && ((attr + attr[1]) == end)) goto raw;
3254 * Add in the length of the data we need to
3255 * concatenate together.
3257 ext_len += attr[1] - 4;
3260 * Go to the next attribute, and stop if there's
3267 if (!ext_len) goto raw;
3269 head = tail = malloc(ext_len);
3270 if (!head) goto raw;
3273 * Copy the data over, this time trusting the attribute
3277 memcpy(tail, attr + 2, attrlen - 2);
3278 tail += attrlen - 2;
3281 while (attr < end) {
3282 memcpy(tail, attr + 4, attr[1] - 4);
3283 tail += attr[1] - 4;
3284 attr += attr[1]; /* skip VID+WiMax header */
3287 VP_HEXDUMP("long-extended fragments", head, ext_len);
3289 rcode = data2vp(ctx, packet, original, secret, da,
3290 head, ext_len, ext_len, pvp);
3292 if (rcode < 0) goto raw;
3297 /** Convert a Vendor-Specific WIMAX to VPs
3299 * @note Called ONLY for Vendor-Specific
3301 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3302 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3303 char const *secret, uint32_t vendor,
3304 uint8_t const *data,
3305 size_t attrlen, size_t packetlen,
3311 uint8_t *head, *tail;
3312 uint8_t const *attr, *end;
3313 DICT_ATTR const *child;
3316 * data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3320 * Not enough room for WiMAX Vendor + Wimax attr + length
3321 * + continuation, it's a bad attribute.
3326 * It's not a Vendor-Specific, it's unknown...
3328 child = dict_unknown_afrom_fields(ctx, PW_VENDOR_SPECIFIC, 0);
3330 fr_strerror_printf("Internal sanity check %d", __LINE__);
3334 rcode = data2vp(ctx, packet, original, secret, child,
3335 data, attrlen, attrlen, pvp);
3336 if (rcode < 0) return rcode;
3340 if (data[5] < 3) goto raw; /* WiMAX-Length is too small */
3342 child = dict_attrbyvalue(data[4], vendor);
3343 if (!child) goto raw;
3346 * No continued data, just decode the attribute in place.
3348 if ((data[6] & 0x80) == 0) {
3349 if ((data[5] + 4) != attrlen) goto raw; /* WiMAX attribute doesn't fill Vendor-Specific */
3351 rcode = data2vp(ctx, packet, original, secret, child,
3352 data + 7, data[5] - 3, data[5] - 3,
3355 if ((rcode < 0) || (((size_t) rcode + 7) != attrlen)) goto raw; /* didn't decode all of the data */
3360 * Calculate the length of all of the fragments. For
3361 * now, they MUST be contiguous in the packet, and they
3362 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3364 * The first fragment doesn't have a RADIUS attribute
3369 end = data + packetlen;
3371 while (attr < end) {
3373 * Not enough room for Attribute + length +
3374 * continuation, it's bad.
3376 if ((end - attr) < 3) goto raw;
3379 * Must have non-zero data in the attribute.
3381 if (attr[1] <= 3) goto raw;
3384 * If the WiMAX attribute overflows the packet,
3387 if ((attr + attr[1]) > end) goto raw;
3390 * Check the continuation flag.
3392 more = ((attr[2] & 0x80) != 0);
3395 * Or, there's no more data, in which case we
3396 * shorten "end" to finish at this attribute.
3398 if (!more) end = attr + attr[1];
3401 * There's more data, but we're at the end of the
3402 * packet. The attribute is malformed!
3404 if (more && ((attr + attr[1]) == end)) goto raw;
3407 * Add in the length of the data we need to
3408 * concatenate together.
3410 wimax_len += attr[1] - 3;
3413 * Go to the next attribute, and stop if there's
3420 * data = VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3422 * attr = Vendor-Specific VSA-Length VID VID VID VID WiMAX-Attr WimAX-Len Continuation ...
3427 * No room for Vendor-Specific + length +
3428 * Vendor(4) + attr + length + continuation + data
3430 if ((end - attr) < 9) goto raw;
3432 if (attr[0] != PW_VENDOR_SPECIFIC) goto raw;
3433 if (attr[1] < 9) goto raw;
3434 if ((attr + attr[1]) > end) goto raw;
3435 if (memcmp(data, attr + 2, 4) != 0) goto raw; /* not WiMAX Vendor ID */
3437 if (attr[1] != (attr[7] + 6)) goto raw; /* WiMAX attr doesn't exactly fill the VSA */
3439 if (data[4] != attr[6]) goto raw; /* different WiMAX attribute */
3442 * Skip over the Vendor-Specific header, and
3443 * continue with the WiMAX attributes.
3449 * No data in the WiMAX attribute, make a "raw" one.
3451 if (!wimax_len) goto raw;
3453 head = tail = malloc(wimax_len);
3454 if (!head) return -1;
3457 * Copy the data over, this time trusting the attribute
3461 while (attr < end) {
3462 memcpy(tail, attr + 4 + 3, attr[4 + 1] - 3);
3463 tail += attr[4 + 1] - 3;
3464 attr += 4 + attr[4 + 1]; /* skip VID+WiMax header */
3465 attr += 2; /* skip Vendor-Specific header */
3468 VP_HEXDUMP("wimax fragments", head, wimax_len);
3470 rcode = data2vp(ctx, packet, original, secret, child,
3471 head, wimax_len, wimax_len, pvp);
3473 if (rcode < 0) goto raw;
3479 /** Convert a top-level VSA to one or more VPs
3482 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3483 RADIUS_PACKET const *original,
3484 char const *secret, uint8_t const *data,
3485 size_t attrlen, size_t packetlen,
3492 VALUE_PAIR *head, **tail;
3495 if (attrlen > packetlen) return -1;
3496 if (attrlen < 5) return -1; /* vid, value */
3497 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3499 VP_TRACE("data2vp_vsas\n");
3501 memcpy(&vendor, data, 4);
3502 vendor = ntohl(vendor);
3503 dv = dict_vendorbyvalue(vendor);
3506 * RFC format is 1 octet type, 1 octet length
3508 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3509 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3514 * It's a known unknown.
3516 memset(&my_dv, 0, sizeof(my_dv));
3520 * Fill in the fields. Note that the name is empty!
3522 dv->vendorpec = vendor;
3532 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3533 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3534 data, attrlen, packetlen, pvp);
3539 * VSAs should normally be in TLV format.
3541 if (rad_tlv_ok(data + 4, attrlen - 4,
3542 dv->type, dv->length) < 0) {
3543 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3548 * There may be more than one VSA in the
3549 * Vendor-Specific. If so, loop over them all.
3559 while (attrlen > 0) {
3562 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3563 data, attrlen, tail);
3565 fr_pair_list_free(&head);
3566 fr_strerror_printf("Internal sanity check %d", __LINE__);
3571 * Vendors can send zero-length VSAs.
3573 if (*tail) tail = &((*tail)->next);
3577 packetlen -= vsa_len;
3585 /** Create any kind of VP from the attribute contents
3587 * "length" is AT LEAST the length of this attribute, as we
3588 * expect the caller to have verified the data with
3589 * rad_packet_ok(). "length" may be up to the length of the
3592 * @return -1 on error, or "length".
3594 ssize_t data2vp(TALLOC_CTX *ctx,
3595 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3597 DICT_ATTR const *da, uint8_t const *start,
3598 size_t const attrlen, size_t const packetlen,
3601 int8_t tag = TAG_NONE;
3605 DICT_ATTR const *child;
3607 uint8_t const *data = start;
3609 uint8_t buffer[256];
3612 * FIXME: Attrlen can be larger than 253 for extended attrs!
3614 if (!da || (attrlen > packetlen) ||
3615 ((attrlen > 253) && (attrlen != packetlen)) ||
3616 (attrlen > 128*1024)) {
3617 fr_strerror_printf("data2vp: invalid arguments");
3621 VP_HEXDUMP("data2vp", start, attrlen);
3623 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3628 * Hacks for CUI. The WiMAX spec says that it can be
3629 * zero length, even though this is forbidden by the
3630 * RADIUS specs. So... we make a special case for it.
3633 if (!((da->vendor == 0) &&
3634 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3641 * Hacks for Coverity. Editing the dictionary
3642 * will break assumptions about CUI. We know
3643 * this, but Coverity doesn't.
3645 if (da->type != PW_TYPE_OCTETS) return -1;
3650 goto alloc_cui; /* skip everything */
3654 * Hacks for tags. If the attribute is capable of
3655 * encoding a tag, and there's room for the tag, and
3656 * there is a tag, or it's encrypted with Tunnel-Password,
3657 * then decode the tag.
3659 if (da->flags.has_tag && (datalen > 1) &&
3660 ((data[0] < 0x20) ||
3661 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3663 * Only "short" attributes can be encrypted.
3665 if (datalen >= sizeof(buffer)) return -1;
3667 if (da->type == PW_TYPE_STRING) {
3668 memcpy(buffer, data + 1, datalen - 1);
3672 } else if (da->type == PW_TYPE_INTEGER) {
3673 memcpy(buffer, data, attrlen);
3678 return -1; /* only string and integer can have tags */
3685 * Decrypt the attribute.
3687 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3688 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3690 * Encrypted attributes can only exist for the
3691 * old-style format. Extended attributes CANNOT
3694 if (attrlen > 253) {
3698 if (data == start) {
3699 memcpy(buffer, data, attrlen);
3703 switch (da->flags.encrypt) { /* can't be tagged */
3707 case FLAG_ENCRYPT_USER_PASSWORD:
3709 rad_pwdecode((char *) buffer,
3713 rad_pwdecode((char *) buffer,
3720 * MS-CHAP-MPPE-Keys are 24 octets, and
3721 * encrypted. Since it's binary, we can't
3722 * look for trailing zeros.
3724 if (da->flags.length) {
3725 if (datalen > da->flags.length) {
3726 datalen = da->flags.length;
3727 } /* else leave datalen alone */
3730 * Take off trailing zeros from the END.
3731 * This allows passwords to have zeros in
3732 * the middle of a field.
3734 * However, if the password has a zero at
3735 * the end, it will get mashed by this
3736 * code. There's really no way around
3739 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3744 * Tunnel-Password's may go ONLY in response
3745 * packets. They can have a tag, so datalen is
3746 * not the same as attrlen.
3748 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3749 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3750 original ? original->vector : nullvector) < 0) {
3756 * Ascend-Send-Secret
3757 * Ascend-Receive-Secret
3759 case FLAG_ENCRYPT_ASCEND_SECRET:
3763 uint8_t my_digest[AUTH_VECTOR_LEN];
3766 secret_len = datalen;
3767 if (secret_len > AUTH_VECTOR_LEN) secret_len = AUTH_VECTOR_LEN;
3769 make_secret(my_digest,
3771 secret, data, secret_len);
3772 memcpy(buffer, my_digest,
3774 buffer[AUTH_VECTOR_LEN] = '\0';
3775 datalen = strlen((char *) buffer);
3781 } /* switch over encryption flags */
3785 * Double-check the length after decrypting the
3788 VP_TRACE("data2vp: type %u\n", da->type);
3790 case PW_TYPE_STRING:
3791 case PW_TYPE_OCTETS:
3794 case PW_TYPE_ABINARY:
3795 if (datalen > sizeof(vp->vp_filter)) goto raw;
3798 case PW_TYPE_INTEGER:
3799 case PW_TYPE_IPV4_ADDR:
3801 case PW_TYPE_SIGNED:
3802 if (datalen != 4) goto raw;
3805 case PW_TYPE_INTEGER64:
3807 if (datalen != 8) goto raw;
3810 case PW_TYPE_IPV6_ADDR:
3811 if (datalen != 16) goto raw;
3814 case PW_TYPE_IPV6_PREFIX:
3815 if ((datalen < 2) || (datalen > 18)) goto raw;
3816 if (data[1] > 128) goto raw;
3820 if (datalen != 1) goto raw;
3824 if (datalen != 2) goto raw;
3827 case PW_TYPE_ETHERNET:
3828 if (datalen != 6) goto raw;
3831 case PW_TYPE_COMBO_IP_ADDR:
3833 child = dict_attrbytype(da->attr, da->vendor,
3835 } else if (datalen == 16) {
3836 child = dict_attrbytype(da->attr, da->vendor,
3841 if (!child) goto raw;
3842 da = child; /* re-write it */
3845 case PW_TYPE_IPV4_PREFIX:
3846 if (datalen != 6) goto raw;
3847 if ((data[1] & 0x3f) > 32) goto raw;
3851 * The rest of the data types can cause
3852 * recursion! Ask yourself, "is recursion OK?"
3855 case PW_TYPE_EXTENDED:
3856 if (datalen < 2) goto raw; /* etype, value */
3858 child = dict_attrbyparent(da, data[0], 0);
3859 if (!child) goto raw;
3862 * Recurse to decode the contents, which could be
3863 * a TLV, IPaddr, etc. Note that we decode only
3864 * the current attribute, and we ignore any extra
3867 rcode = data2vp(ctx, packet, original, secret, child,
3868 data + 1, attrlen - 1, attrlen - 1, pvp);
3869 if (rcode < 0) goto raw;
3872 case PW_TYPE_LONG_EXTENDED:
3873 if (datalen < 3) goto raw; /* etype, flags, value */
3875 child = dict_attrbyparent(da, data[0], 0);
3877 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3878 (datalen < (3 + 4 + 1))) {
3879 /* da->attr < 255, da->vendor == 0 */
3880 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3883 * Try to find the VSA.
3885 memcpy(&vendor, data + 3, 4);
3886 vendor = ntohl(vendor);
3888 if (vendor == 0) goto raw;
3890 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3894 fr_strerror_printf("Internal sanity check %d", __LINE__);
3900 * This requires a whole lot more work.
3902 return data2vp_extended(ctx, packet, original, secret, child,
3903 start, attrlen, packetlen, pvp);
3906 if (datalen < 6) goto raw; /* vid, vtype, value */
3908 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3910 memcpy(&vendor, data, 4);
3911 vendor = ntohl(vendor);
3912 vendor |= da->vendor;
3914 child = dict_attrbyvalue(data[4], vendor);
3917 * Create a "raw" attribute from the
3918 * contents of the EVS VSA.
3920 da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3926 rcode = data2vp(ctx, packet, original, secret, child,
3927 data + 5, attrlen - 5, attrlen - 5, pvp);
3928 if (rcode < 0) goto raw;
3933 * We presume that the TLVs all fit into one
3934 * attribute, OR they've already been grouped
3935 * into a contiguous memory buffer.
3937 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3938 data, attrlen, pvp);
3939 if (rcode < 0) goto raw;
3944 * VSAs can be WiMAX, in which case they don't
3945 * fit into one attribute.
3947 rcode = data2vp_vsas(ctx, packet, original, secret,
3948 data, attrlen, packetlen, pvp);
3949 if (rcode < 0) goto raw;
3955 * Re-write the attribute to be "raw". It is
3956 * therefore of type "octets", and will be
3959 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3961 fr_strerror_printf("Internal sanity check %d", __LINE__);
3969 if (da->type != PW_TYPE_OCTETS) {
3970 dict_attr_free(&da);
3978 * And now that we've verified the basic type
3979 * information, decode the actual data.
3982 vp = fr_pair_afrom_da(ctx, da);
3985 vp->vp_length = datalen;
3989 case PW_TYPE_STRING:
3990 p = talloc_array(vp, char, vp->vp_length + 1);
3991 memcpy(p, data, vp->vp_length);
3992 p[vp->vp_length] = '\0';
3993 vp->vp_strvalue = p;
3996 case PW_TYPE_OCTETS:
3997 fr_pair_value_memcpy(vp, data, vp->vp_length);
4000 case PW_TYPE_ABINARY:
4001 if (vp->vp_length > sizeof(vp->vp_filter)) {
4002 vp->vp_length = sizeof(vp->vp_filter);
4004 memcpy(vp->vp_filter, data, vp->vp_length);
4008 vp->vp_byte = data[0];
4012 vp->vp_short = (data[0] << 8) | data[1];
4015 case PW_TYPE_INTEGER:
4016 memcpy(&vp->vp_integer, data, 4);
4017 vp->vp_integer = ntohl(vp->vp_integer);
4020 case PW_TYPE_INTEGER64:
4021 memcpy(&vp->vp_integer64, data, 8);
4022 vp->vp_integer64 = ntohll(vp->vp_integer64);
4026 memcpy(&vp->vp_date, data, 4);
4027 vp->vp_date = ntohl(vp->vp_date);
4030 case PW_TYPE_ETHERNET:
4031 memcpy(vp->vp_ether, data, 6);
4034 case PW_TYPE_IPV4_ADDR:
4035 memcpy(&vp->vp_ipaddr, data, 4);
4039 memcpy(vp->vp_ifid, data, 8);
4042 case PW_TYPE_IPV6_ADDR:
4043 memcpy(&vp->vp_ipv6addr, data, 16);
4046 case PW_TYPE_IPV6_PREFIX:
4048 * FIXME: double-check that
4049 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
4051 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
4052 if (vp->vp_length < 18) {
4053 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
4054 18 - vp->vp_length);
4058 case PW_TYPE_IPV4_PREFIX:
4059 /* FIXME: do the same double-check as for IPv6Prefix */
4060 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
4063 * /32 means "keep all bits". Otherwise, mask
4066 if ((data[1] & 0x3f) > 32) {
4067 uint32_t addr, mask;
4069 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
4071 mask <<= (32 - (data[1] & 0x3f));
4076 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
4080 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
4081 memcpy(&vp->vp_integer, buffer, 4);
4082 vp->vp_integer = ntohl(vp->vp_integer);
4086 fr_pair_list_free(&vp);
4087 fr_strerror_printf("Internal sanity check %d", __LINE__);
4097 /** Create a "normal" VALUE_PAIR from the given data
4100 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
4101 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
4103 uint8_t const *data, size_t length,
4108 DICT_ATTR const *da;
4110 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
4111 fr_strerror_printf("rad_attr2vp: Insufficient data");
4115 da = dict_attrbyvalue(data[0], 0);
4117 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
4118 da = dict_unknown_afrom_fields(ctx, data[0], 0);
4123 * Pass the entire thing to the decoding function
4125 if (da->flags.concat) {
4126 VP_TRACE("attr2vp: concat attribute\n");
4127 return data2vp_concat(ctx, da, data, length, pvp);
4131 * Note that we pass the entire length, not just the
4132 * length of this attribute. The Extended or WiMAX
4133 * attributes may have the "continuation" bit set, and
4134 * will thus be more than one attribute in length.
4136 rcode = data2vp(ctx, packet, original, secret, da,
4137 data + 2, data[1] - 2, length - 2, pvp);
4138 if (rcode < 0) return rcode;
4143 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
4145 /** Converts vp_data to network byte order
4147 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
4148 * in an architecture independent format.
4150 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
4151 * as the source VALUE_PAIR is not freed.
4153 * @param out where to write the pointer to the value.
4154 * @param vp to get the value from.
4155 * @return -1 on error, or the length of the value
4157 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
4165 buffer = fr_thread_local_init(rad_vp2data_buff, free);
4169 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
4171 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
4175 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
4177 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
4185 switch (vp->da->type) {
4186 case PW_TYPE_STRING:
4187 case PW_TYPE_OCTETS:
4188 memcpy(out, &vp->data.ptr, sizeof(*out));
4192 * All of these values are at the same location.
4195 case PW_TYPE_IPV4_ADDR:
4196 case PW_TYPE_IPV6_ADDR:
4197 case PW_TYPE_IPV6_PREFIX:
4198 case PW_TYPE_IPV4_PREFIX:
4199 case PW_TYPE_ABINARY:
4200 case PW_TYPE_ETHERNET:
4201 case PW_TYPE_COMBO_IP_ADDR:
4202 case PW_TYPE_COMBO_IP_PREFIX:
4204 void const *p = &vp->data;
4205 memcpy(out, &p, sizeof(*out));
4209 case PW_TYPE_BOOLEAN:
4210 buffer[0] = vp->vp_byte & 0x01;
4215 buffer[0] = vp->vp_byte & 0xff;
4220 buffer[0] = (vp->vp_short >> 8) & 0xff;
4221 buffer[1] = vp->vp_short & 0xff;
4225 case PW_TYPE_INTEGER:
4226 lvalue = htonl(vp->vp_integer);
4227 memcpy(buffer, &lvalue, sizeof(lvalue));
4231 case PW_TYPE_INTEGER64:
4232 lvalue64 = htonll(vp->vp_integer64);
4233 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4238 lvalue = htonl(vp->vp_date);
4239 memcpy(buffer, &lvalue, sizeof(lvalue));
4243 case PW_TYPE_SIGNED:
4245 int32_t slvalue = htonl(vp->vp_signed);
4246 memcpy(buffer, &slvalue, sizeof(slvalue));
4251 case PW_TYPE_INVALID:
4252 case PW_TYPE_EXTENDED:
4253 case PW_TYPE_LONG_EXTENDED:
4257 case PW_TYPE_TIMEVAL:
4259 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4262 /* Don't add default */
4265 return vp->vp_length;
4268 /** Calculate/check digest, and decode radius attributes
4270 * @return -1 on decoding error, 0 on success
4272 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4276 uint32_t num_attributes;
4278 radius_packet_t *hdr;
4279 VALUE_PAIR *head, **tail, *vp;
4282 * Extract attribute-value pairs
4284 hdr = (radius_packet_t *)packet->data;
4286 packet_length = packet->data_len - RADIUS_HDR_LEN;
4293 * Loop over the attributes, decoding them into VPs.
4295 while (packet_length > 0) {
4299 * This may return many VPs
4301 my_len = rad_attr2vp(packet, packet, original, secret,
4302 ptr, packet_length, &vp);
4304 fr_pair_list_free(&head);
4316 * VSA's may not have been counted properly in
4317 * rad_packet_ok() above, as it is hard to count
4318 * then without using the dictionary. We
4319 * therefore enforce the limits here, too.
4321 if ((fr_max_attributes > 0) &&
4322 (num_attributes > fr_max_attributes)) {
4323 char host_ipaddr[128];
4325 fr_pair_list_free(&head);
4326 fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4327 inet_ntop(packet->src_ipaddr.af,
4328 &packet->src_ipaddr.ipaddr,
4329 host_ipaddr, sizeof(host_ipaddr)),
4330 num_attributes, fr_max_attributes);
4335 packet_length -= my_len;
4339 * Merge information from the outside world into our
4342 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4345 * There may be VP's already in the packet. Don't
4346 * destroy them. Instead, add the decoded attributes to
4347 * the tail of the list.
4349 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4360 * We assume that the passwd buffer passed is big enough.
4361 * RFC2138 says the password is max 128 chars, so the size
4362 * of the passwd buffer must be at least 129 characters.
4363 * Preferably it's just MAX_STRING_LEN.
4365 * int *pwlen is updated to the new length of the encrypted
4366 * password - a multiple of 16 bytes.
4368 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4369 uint8_t const *vector)
4371 FR_MD5_CTX context, old;
4372 uint8_t digest[AUTH_VECTOR_LEN];
4373 int i, n, secretlen;
4377 * RFC maximum is 128 bytes.
4379 * If length is zero, pad it out with zeros.
4381 * If the length isn't aligned to 16 bytes,
4382 * zero out the extra data.
4386 if (len > 128) len = 128;
4389 memset(passwd, 0, AUTH_PASS_LEN);
4390 len = AUTH_PASS_LEN;
4391 } else if ((len % AUTH_PASS_LEN) != 0) {
4392 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4393 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4398 * Use the secret to setup the decryption digest
4400 secretlen = strlen(secret);
4402 fr_md5_init(&context);
4403 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4404 old = context; /* save intermediate work */
4407 * Encrypt it in place. Don't bother checking
4408 * len, as we've ensured above that it's OK.
4410 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4412 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4413 fr_md5_final(digest, &context);
4416 fr_md5_update(&context,
4417 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4419 fr_md5_final(digest, &context);
4422 for (i = 0; i < AUTH_PASS_LEN; i++) {
4423 passwd[i + n] ^= digest[i];
4433 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4434 uint8_t const *vector)
4436 FR_MD5_CTX context, old;
4437 uint8_t digest[AUTH_VECTOR_LEN];
4439 size_t n, secretlen;
4442 * The RFC's say that the maximum is 128.
4443 * The buffer we're putting it into above is 254, so
4444 * we don't need to do any length checking.
4446 if (pwlen > 128) pwlen = 128;
4451 if (pwlen == 0) goto done;
4454 * Use the secret to setup the decryption digest
4456 secretlen = strlen(secret);
4458 fr_md5_init(&context);
4459 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4460 old = context; /* save intermediate work */
4463 * The inverse of the code above.
4465 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4467 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4468 fr_md5_final(digest, &context);
4471 if (pwlen > AUTH_PASS_LEN) {
4472 fr_md5_update(&context, (uint8_t *) passwd,
4476 fr_md5_final(digest, &context);
4479 if (pwlen > (n + AUTH_PASS_LEN)) {
4480 fr_md5_update(&context, (uint8_t *) passwd + n,
4485 for (i = 0; i < AUTH_PASS_LEN; i++) {
4486 passwd[i + n] ^= digest[i];
4491 passwd[pwlen] = '\0';
4492 return strlen(passwd);
4496 /** Encode Tunnel-Password attributes when sending them out on the wire
4498 * int *pwlen is updated to the new length of the encrypted
4499 * password - a multiple of 16 bytes.
4501 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4504 ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4506 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4507 unsigned char digest[AUTH_VECTOR_LEN];
4509 int i, n, secretlen;
4514 if (len > 127) len = 127;
4517 * Shift the password 3 positions right to place a salt and original
4518 * length, tag will be added automatically on packet send.
4520 for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4525 * save original password length as first password character;
4532 * Generate salt. The RFC's say:
4534 * The high bit of salt[0] must be set, each salt in a
4535 * packet should be unique, and they should be random
4537 * So, we set the high bit, add in a counter, and then
4538 * add in some CSPRNG data. should be OK..
4540 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4541 (fr_rand() & 0x07));
4542 salt[1] = fr_rand();
4545 * Padd password to multiple of AUTH_PASS_LEN bytes.
4547 n = len % AUTH_PASS_LEN;
4549 n = AUTH_PASS_LEN - n;
4550 for (; n > 0; n--, len++)
4553 /* set new password length */
4557 * Use the secret to setup the decryption digest
4559 secretlen = strlen(secret);
4560 memcpy(buffer, secret, secretlen);
4562 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4564 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4565 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4566 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4568 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4569 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4572 for (i = 0; i < AUTH_PASS_LEN; i++) {
4573 passwd[i + n2] ^= digest[i];
4580 /** Decode Tunnel-Password encrypted attributes
4582 * Defined in RFC-2868, this uses a two char SALT along with the
4583 * initial intermediate value, to differentiate it from the
4586 ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4588 FR_MD5_CTX context, old;
4589 uint8_t digest[AUTH_VECTOR_LEN];
4591 size_t i, n, encrypted_len, reallen;
4593 encrypted_len = *pwlen;
4596 * We need at least a salt.
4598 if (encrypted_len < 2) {
4599 fr_strerror_printf("tunnel password is too short");
4604 * There's a salt, but no password. Or, there's a salt
4605 * and a 'data_len' octet. It's wrong, but at least we
4606 * can figure out what it means: the password is empty.
4608 * Note that this means we ignore the 'data_len' field,
4609 * if the attribute length tells us that there's no
4610 * more data. So the 'data_len' field may be wrong,
4613 if (encrypted_len <= 3) {
4619 encrypted_len -= 2; /* discount the salt */
4622 * Use the secret to setup the decryption digest
4624 secretlen = strlen(secret);
4626 fr_md5_init(&context);
4627 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4628 old = context; /* save intermediate work */
4631 * Set up the initial key:
4633 * b(1) = MD5(secret + vector + salt)
4635 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4636 fr_md5_update(&context, passwd, 2);
4639 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4641 size_t block_len = AUTH_PASS_LEN;
4644 * Ensure we don't overflow the input on MD5
4646 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4647 block_len = *pwlen - n - 2;
4653 fr_md5_final(digest, &context);
4658 * A quick check: decrypt the first octet
4659 * of the password, which is the
4660 * 'data_len' field. Ensure it's sane.
4662 reallen = passwd[2] ^ digest[0];
4663 if (reallen > encrypted_len) {
4664 fr_strerror_printf("tunnel password is too long for the attribute");
4668 fr_md5_update(&context, passwd + 2, block_len);
4673 fr_md5_final(digest, &context);
4676 fr_md5_update(&context, passwd + n + 2, block_len);
4679 for (i = base; i < block_len; i++) {
4680 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4685 passwd[reallen] = 0;
4690 /** Encode a CHAP password
4692 * @bug FIXME: might not work with Ascend because
4693 * we use vp->vp_length, and Ascend gear likes
4694 * to send an extra '\0' in the string!
4696 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4697 VALUE_PAIR *password)
4701 uint8_t string[MAX_STRING_LEN * 2 + 1];
4702 VALUE_PAIR *challenge;
4705 * Sanity check the input parameters
4707 if ((packet == NULL) || (password == NULL)) {
4712 * Note that the password VP can be EITHER
4713 * a User-Password attribute (from a check-item list),
4714 * or a CHAP-Password attribute (the client asking
4715 * the library to encode it).
4723 memcpy(ptr, password->vp_strvalue, password->vp_length);
4724 ptr += password->vp_length;
4725 i += password->vp_length;
4728 * Use Chap-Challenge pair if present,
4729 * Request Authenticator otherwise.
4731 challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4733 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4734 i += challenge->vp_length;
4736 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4737 i += AUTH_VECTOR_LEN;
4741 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4747 /** Seed the random number generator
4749 * May be called any number of times.
4751 void fr_rand_seed(void const *data, size_t size)
4756 * Ensure that the pool is initialized.
4758 if (!fr_rand_initialized) {
4761 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4763 fd = open("/dev/urandom", O_RDONLY);
4769 while (total < sizeof(fr_rand_pool.randrsl)) {
4770 this = read(fd, fr_rand_pool.randrsl,
4771 sizeof(fr_rand_pool.randrsl) - total);
4772 if ((this < 0) && (errno != EINTR)) break;
4773 if (this > 0) total += this;
4777 fr_rand_pool.randrsl[0] = fd;
4778 fr_rand_pool.randrsl[1] = time(NULL);
4779 fr_rand_pool.randrsl[2] = errno;
4782 fr_randinit(&fr_rand_pool, 1);
4783 fr_rand_pool.randcnt = 0;
4784 fr_rand_initialized = 1;
4790 * Hash the user data
4793 if (!hash) hash = fr_rand();
4794 hash = fr_hash_update(data, size, hash);
4796 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4800 /** Return a 32-bit random number
4803 uint32_t fr_rand(void)
4808 * Ensure that the pool is initialized.
4810 if (!fr_rand_initialized) {
4811 fr_rand_seed(NULL, 0);
4814 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4815 if (fr_rand_pool.randcnt >= 256) {
4816 fr_rand_pool.randcnt = 0;
4817 fr_isaac(&fr_rand_pool);
4824 /** Allocate a new RADIUS_PACKET
4826 * @param ctx the context in which the packet is allocated. May be NULL if
4827 * the packet is not associated with a REQUEST.
4828 * @param new_vector if true a new request authenticator will be generated.
4829 * @return a new RADIUS_PACKET or NULL on error.
4831 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4835 rp = talloc_zero(ctx, RADIUS_PACKET);
4837 fr_strerror_printf("out of memory");
4845 uint32_t hash, base;
4848 * Don't expose the actual contents of the random
4852 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4853 hash = fr_rand() ^ base;
4854 memcpy(rp->vector + i, &hash, sizeof(hash));
4857 fr_rand(); /* stir the pool again */
4862 /** Allocate a new RADIUS_PACKET response
4864 * @param ctx the context in which the packet is allocated. May be NULL if
4865 * the packet is not associated with a REQUEST.
4866 * @param packet The request packet.
4867 * @return a new RADIUS_PACKET or NULL on error.
4869 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4871 RADIUS_PACKET *reply;
4873 if (!packet) return NULL;
4875 reply = rad_alloc(ctx, false);
4876 if (!reply) return NULL;
4879 * Initialize the fields from the request.
4881 reply->sockfd = packet->sockfd;
4882 reply->dst_ipaddr = packet->src_ipaddr;
4883 reply->src_ipaddr = packet->dst_ipaddr;
4884 reply->dst_port = packet->src_port;
4885 reply->src_port = packet->dst_port;
4886 reply->id = packet->id;
4887 reply->code = 0; /* UNKNOWN code */
4888 memcpy(reply->vector, packet->vector,
4889 sizeof(reply->vector));
4892 reply->data_len = 0;
4895 reply->proto = packet->proto;
4901 /** Free a RADIUS_PACKET
4904 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4906 RADIUS_PACKET *radius_packet;
4908 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4909 radius_packet = *radius_packet_ptr;
4911 VERIFY_PACKET(radius_packet);
4913 fr_pair_list_free(&radius_packet->vps);
4915 talloc_free(radius_packet);
4916 *radius_packet_ptr = NULL;
4919 /** Duplicate a RADIUS_PACKET
4921 * @param ctx the context in which the packet is allocated. May be NULL if
4922 * the packet is not associated with a REQUEST.
4923 * @param in The packet to copy
4924 * @return a new RADIUS_PACKET or NULL on error.
4926 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4930 out = rad_alloc(ctx, false);
4931 if (!out) return NULL;
4934 * Bootstrap by copying everything.
4936 memcpy(out, in, sizeof(*out));
4939 * Then reset necessary fields
4946 out->vps = fr_pair_list_copy(out, in->vps);