2 * This library is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU Lesser General Public
4 * License as published by the Free Software Foundation; either
5 * version 2.1 of the License, or (at your option) any later version.
7 * This library is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * Lesser General Public License for more details.
12 * You should have received a copy of the GNU Lesser General Public
13 * License along with this library; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * @brief Functions to send/receive radius packets.
23 * @copyright 2000-2003,2006 The FreeRADIUS server project
28 #include <freeradius-devel/libradius.h>
30 #include <freeradius-devel/md5.h>
36 #include <freeradius-devel/udpfromto.h>
40 * Some messages get printed out only in debugging mode.
42 #define FR_DEBUG_STRERROR_PRINTF if (fr_debug_lvl) fr_strerror_printf
45 #define VP_TRACE printf
47 static void VP_HEXDUMP(char const *msg, uint8_t const *data, size_t len)
51 printf("--- %s ---\n", msg);
52 for (i = 0; i < len; i++) {
53 if ((i & 0x0f) == 0) printf("%04x: ", (unsigned int) i);
54 printf("%02x ", data[i]);
55 if ((i & 0x0f) == 0x0f) printf("\n");
57 if ((len == 0x0f) || ((len & 0x0f) != 0x0f)) printf("\n");
62 #define VP_TRACE(_x, ...)
63 #define VP_HEXDUMP(_x, _y, _z)
68 * The RFC says 4096 octets max, and most packets are less than 256.
70 #define MAX_PACKET_LEN 4096
73 * The maximum number of attributes which we allow in an incoming
74 * request. If there are more attributes than this, the request
77 * This helps to minimize the potential for a DoS, when an
78 * attacker spoofs Access-Request packets, which don't have a
79 * Message-Authenticator attribute. This means that the packet
80 * is unsigned, and the attacker can use resources on the server,
81 * even if the end request is rejected.
83 uint32_t fr_max_attributes = 0;
84 FILE *fr_log_fp = NULL;
86 typedef struct radius_packet_t {
90 uint8_t vector[AUTH_VECTOR_LEN];
94 static fr_randctx fr_rand_pool; /* across multiple calls */
95 static int fr_rand_initialized = 0;
96 static unsigned int salt_offset = 0;
97 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
99 char const *fr_packet_codes[FR_MAX_PACKET_CODE] = {
104 "Accounting-Request",
105 "Accounting-Response",
110 "Accounting-Message", //!< 10
121 "Resource-Free-Request",
122 "Resource-Free-Response",
123 "Resource-Query-Request",
124 "Resource-Query-Response",
125 "Alternate-Resource-Reclaim-Request",
126 "NAS-Reboot-Request",
127 "NAS-Reboot-Response",
140 "Disconnect-Request", //!< 40
150 "IP-Address-Allocate",
151 "IP-Address-Release", //!< 50
155 void fr_printf_log(char const *fmt, ...)
160 if ((fr_debug_lvl == 0) || !fr_log_fp) {
165 vfprintf(fr_log_fp, fmt, ap);
171 static char const tabs[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
173 static void print_hex_data(uint8_t const *ptr, int attrlen, int depth)
177 for (i = 0; i < attrlen; i++) {
178 if ((i > 0) && ((i & 0x0f) == 0x00))
179 fprintf(fr_log_fp, "%.*s", depth, tabs);
180 fprintf(fr_log_fp, "%02x ", ptr[i]);
181 if ((i & 0x0f) == 0x0f) fprintf(fr_log_fp, "\n");
183 if ((i & 0x0f) != 0) fprintf(fr_log_fp, "\n");
187 void rad_print_hex(RADIUS_PACKET *packet)
191 if (!packet->data || !fr_log_fp) return;
193 fprintf(fr_log_fp, " Socket:\t%d\n", packet->sockfd);
195 fprintf(fr_log_fp, " Proto:\t%d\n", packet->proto);
198 if (packet->src_ipaddr.af == AF_INET) {
201 fprintf(fr_log_fp, " Src IP:\t%s\n",
202 inet_ntop(packet->src_ipaddr.af,
203 &packet->src_ipaddr.ipaddr,
204 buffer, sizeof(buffer)));
205 fprintf(fr_log_fp, " port:\t%u\n", packet->src_port);
207 fprintf(fr_log_fp, " Dst IP:\t%s\n",
208 inet_ntop(packet->dst_ipaddr.af,
209 &packet->dst_ipaddr.ipaddr,
210 buffer, sizeof(buffer)));
211 fprintf(fr_log_fp, " port:\t%u\n", packet->dst_port);
214 if (packet->data[0] < FR_MAX_PACKET_CODE) {
215 fprintf(fr_log_fp, " Code:\t\t(%d) %s\n", packet->data[0], fr_packet_codes[packet->data[0]]);
217 fprintf(fr_log_fp, " Code:\t\t%u\n", packet->data[0]);
219 fprintf(fr_log_fp, " Id:\t\t%u\n", packet->data[1]);
220 fprintf(fr_log_fp, " Length:\t%u\n", ((packet->data[2] << 8) |
222 fprintf(fr_log_fp, " Vector:\t");
223 for (i = 4; i < 20; i++) {
224 fprintf(fr_log_fp, "%02x", packet->data[i]);
226 fprintf(fr_log_fp, "\n");
228 if (packet->data_len > 20) {
231 fprintf(fr_log_fp, " Data:");
233 total = packet->data_len - 20;
234 ptr = packet->data + 20;
238 unsigned int vendor = 0;
240 fprintf(fr_log_fp, "\t\t");
241 if (total < 2) { /* too short */
242 fprintf(fr_log_fp, "%02x\n", *ptr);
246 if (ptr[1] > total) { /* too long */
247 for (i = 0; i < total; i++) {
248 fprintf(fr_log_fp, "%02x ", ptr[i]);
253 fprintf(fr_log_fp, "%02x %02x ", ptr[0], ptr[1]);
254 attrlen = ptr[1] - 2;
256 if ((ptr[0] == PW_VENDOR_SPECIFIC) &&
258 vendor = (ptr[3] << 16) | (ptr[4] << 8) | ptr[5];
259 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) ",
260 ptr[2], ptr[3], ptr[4], ptr[5], vendor);
270 print_hex_data(ptr, attrlen, 3);
279 /** Wrapper for sendto which handles sendfromto, IPv6, and all possible combinations
282 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
283 #ifdef WITH_UDPFROMTO
284 fr_ipaddr_t *src_ipaddr, uint16_t src_port,
286 UNUSED fr_ipaddr_t *src_ipaddr, UNUSED uint16_t src_port,
288 fr_ipaddr_t *dst_ipaddr, uint16_t dst_port)
291 struct sockaddr_storage dst;
292 socklen_t sizeof_dst;
294 #ifdef WITH_UDPFROMTO
295 struct sockaddr_storage src;
296 socklen_t sizeof_src;
298 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
301 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
305 #ifdef WITH_UDPFROMTO
307 * And if they don't specify a source IP address, don't
310 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
311 (src_ipaddr->af != AF_UNSPEC) &&
312 !fr_inaddr_any(src_ipaddr)) {
313 rcode = sendfromto(sockfd, data, data_len, flags,
314 (struct sockaddr *)&src, sizeof_src,
315 (struct sockaddr *)&dst, sizeof_dst);
321 * No udpfromto, fail gracefully.
323 rcode = sendto(sockfd, data, data_len, flags,
324 (struct sockaddr *) &dst, sizeof_dst);
325 #ifdef WITH_UDPFROMTO
329 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
336 void rad_recv_discard(int sockfd)
339 struct sockaddr_storage src;
340 socklen_t sizeof_src = sizeof(src);
342 (void) recvfrom(sockfd, header, sizeof(header), 0,
343 (struct sockaddr *)&src, &sizeof_src);
346 /** Basic validation of RADIUS packet header
348 * @note fr_strerror errors are only available if fr_debug_lvl > 0. This is to reduce CPU time
349 * consumed when discarding malformed packet.
351 * @param[in] sockfd we're reading from.
352 * @param[out] src_ipaddr of the packet.
353 * @param[out] src_port of the packet.
354 * @param[out] code Pointer to where to write the packet code.
357 * - 1 on decode error.
358 * - >= RADIUS_HDR_LEN on success. This is the packet length as specified in the header.
360 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, uint16_t *src_port, int *code)
362 ssize_t data_len, packet_len;
364 struct sockaddr_storage src;
365 socklen_t sizeof_src = sizeof(src);
367 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK, (struct sockaddr *)&src, &sizeof_src);
369 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
374 * Convert AF. If unknown, discard packet.
376 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
377 FR_DEBUG_STRERROR_PRINTF("Unkown address family");
378 rad_recv_discard(sockfd);
384 * Too little data is available, discard the packet.
387 FR_DEBUG_STRERROR_PRINTF("Expected at least 4 bytes of header data, got %zu bytes", data_len);
389 FR_DEBUG_STRERROR_PRINTF("Invalid data from %s: %s",
390 fr_inet_ntop(src_ipaddr->af, &src_ipaddr->ipaddr),
392 rad_recv_discard(sockfd);
398 * See how long the packet says it is.
400 packet_len = (header[2] * 256) + header[3];
403 * The length in the packet says it's less than
404 * a RADIUS header length: discard it.
406 if (packet_len < RADIUS_HDR_LEN) {
407 FR_DEBUG_STRERROR_PRINTF("Expected at least " STRINGIFY(RADIUS_HDR_LEN) " bytes of packet "
408 "data, got %zu bytes", packet_len);
413 * Enforce RFC requirements, for sanity.
414 * Anything after 4k will be discarded.
416 if (packet_len > MAX_PACKET_LEN) {
417 FR_DEBUG_STRERROR_PRINTF("Length field value too large, expected maximum of "
418 STRINGIFY(MAX_PACKET_LEN) " bytes, got %zu bytes", packet_len);
425 * The packet says it's this long, but the actual UDP
426 * size could still be smaller.
432 /** Wrapper for recvfrom, which handles recvfromto, IPv6, and all possible combinations
435 static ssize_t rad_recvfrom(int sockfd, RADIUS_PACKET *packet, int flags,
436 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
437 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
439 struct sockaddr_storage src;
440 struct sockaddr_storage dst;
441 socklen_t sizeof_src = sizeof(src);
442 socklen_t sizeof_dst = sizeof(dst);
448 memset(&src, 0, sizeof_src);
449 memset(&dst, 0, sizeof_dst);
452 * Read the length of the packet, from the packet.
453 * This lets us allocate the buffer to use for
454 * reading the rest of the packet.
456 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
457 (struct sockaddr *)&src, &sizeof_src);
459 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
464 * Too little data is available, discard the packet.
467 rad_recv_discard(sockfd);
471 } else { /* we got 4 bytes of data. */
473 * See how long the packet says it is.
475 len = (header[2] * 256) + header[3];
478 * The length in the packet says it's less than
479 * a RADIUS header length: discard it.
481 if (len < RADIUS_HDR_LEN) {
482 recvfrom(sockfd, header, sizeof(header), flags,
483 (struct sockaddr *)&src, &sizeof_src);
487 * Enforce RFC requirements, for sanity.
488 * Anything after 4k will be discarded.
490 } else if (len > MAX_PACKET_LEN) {
491 recvfrom(sockfd, header, sizeof(header), flags,
492 (struct sockaddr *)&src, &sizeof_src);
497 packet->data = talloc_array(packet, uint8_t, len);
498 if (!packet->data) return -1;
501 * Receive the packet. The OS will discard any data in the
502 * packet after "len" bytes.
504 #ifdef WITH_UDPFROMTO
505 data_len = recvfromto(sockfd, packet->data, len, flags,
506 (struct sockaddr *)&src, &sizeof_src,
507 (struct sockaddr *)&dst, &sizeof_dst);
509 data_len = recvfrom(sockfd, packet->data, len, flags,
510 (struct sockaddr *)&src, &sizeof_src);
513 * Get the destination address, too.
515 if (getsockname(sockfd, (struct sockaddr *)&dst,
516 &sizeof_dst) < 0) return -1;
522 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
523 return -1; /* Unknown address family, Die Die Die! */
527 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
531 * Different address families should never happen.
533 if (src.ss_family != dst.ss_family) {
541 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
542 /** Build an encrypted secret value to return in a reply packet
544 * The secret is hidden by xoring with a MD5 digest created from
545 * the shared secret and the authentication vector.
546 * We put them into MD5 in the reverse order from that used when
547 * encrypting passwords to RADIUS.
549 static void make_secret(uint8_t *digest, uint8_t const *vector,
550 char const *secret, uint8_t const *value)
555 fr_md5_init(&context);
556 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
557 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
558 fr_md5_final(digest, &context);
560 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
561 digest[i] ^= value[i];
565 #define MAX_PASS_LEN (128)
566 static void make_passwd(uint8_t *output, ssize_t *outlen,
567 uint8_t const *input, size_t inlen,
568 char const *secret, uint8_t const *vector)
570 FR_MD5_CTX context, old;
571 uint8_t digest[AUTH_VECTOR_LEN];
572 uint8_t passwd[MAX_PASS_LEN];
577 * If the length is zero, round it up.
581 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
583 memcpy(passwd, input, len);
584 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
590 else if ((len & 0x0f) != 0) {
596 fr_md5_init(&context);
597 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
603 fr_md5_update(&context, vector, AUTH_PASS_LEN);
605 for (n = 0; n < len; n += AUTH_PASS_LEN) {
608 fr_md5_update(&context,
609 passwd + n - AUTH_PASS_LEN,
613 fr_md5_final(digest, &context);
614 for (i = 0; i < AUTH_PASS_LEN; i++) {
615 passwd[i + n] ^= digest[i];
619 memcpy(output, passwd, len);
623 static void make_tunnel_passwd(uint8_t *output, ssize_t *outlen,
624 uint8_t const *input, size_t inlen, size_t room,
625 char const *secret, uint8_t const *vector)
627 FR_MD5_CTX context, old;
628 uint8_t digest[AUTH_VECTOR_LEN];
630 size_t encrypted_len;
633 * The password gets encoded with a 1-byte "length"
634 * field. Ensure that it doesn't overflow.
636 if (room > 253) room = 253;
639 * Limit the maximum size of the input password. 2 bytes
640 * are taken up by the salt, and one by the encoded
641 * "length" field. Note that if we have a tag, the
642 * "room" will be 252 octets, not 253 octets.
644 if (inlen > (room - 3)) inlen = room - 3;
647 * Length of the encrypted data is the clear-text
648 * password length plus one byte which encodes the length
649 * of the password. We round up to the nearest encoding
650 * block. Note that this can result in the encoding
651 * length being more than 253 octets.
653 encrypted_len = inlen + 1;
654 if ((encrypted_len & 0x0f) != 0) {
655 encrypted_len += 0x0f;
656 encrypted_len &= ~0x0f;
660 * We need 2 octets for the salt, followed by the actual
663 if (encrypted_len > (room - 2)) encrypted_len = room - 2;
665 *outlen = encrypted_len + 2; /* account for the salt */
668 * Copy the password over, and zero-fill the remainder.
670 memcpy(output + 3, input, inlen);
671 memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
674 * Generate salt. The RFCs say:
676 * The high bit of salt[0] must be set, each salt in a
677 * packet should be unique, and they should be random
679 * So, we set the high bit, add in a counter, and then
680 * add in some CSPRNG data. should be OK..
682 output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
684 output[1] = fr_rand();
685 output[2] = inlen; /* length of the password string */
687 fr_md5_init(&context);
688 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
691 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
692 fr_md5_update(&context, &output[0], 2);
694 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
699 fr_md5_update(&context,
700 output + 2 + n - AUTH_PASS_LEN,
704 fr_md5_final(digest, &context);
706 if ((2 + n + AUTH_PASS_LEN) < room) {
707 block_len = AUTH_PASS_LEN;
709 block_len = room - 2 - n;
712 for (i = 0; i < block_len; i++) {
713 output[i + 2 + n] ^= digest[i];
718 static int do_next_tlv(VALUE_PAIR const *vp, VALUE_PAIR const *next, int nest)
720 unsigned int tlv1, tlv2;
722 if (nest > fr_attr_max_tlv) return 0;
727 * Keep encoding TLVs which have the same scope.
728 * e.g. two attributes of:
729 * ATTR.TLV1.TLV2.TLV3 = data1
730 * ATTR.TLV1.TLV2.TLV4 = data2
731 * both get put into a container of "ATTR.TLV1.TLV2"
735 * Nothing to follow, we're done.
740 * Not from the same vendor, skip it.
742 if (vp->da->vendor != next->da->vendor) return 0;
745 * In a different TLV space, skip it.
748 tlv2 = next->da->attr;
750 tlv1 &= ((1 << fr_attr_shift[nest]) - 1);
751 tlv2 &= ((1 << fr_attr_shift[nest]) - 1);
753 if (tlv1 != tlv2) return 0;
759 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
760 RADIUS_PACKET const *original,
761 char const *secret, int nest,
762 VALUE_PAIR const **pvp,
763 uint8_t *start, size_t room);
765 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
766 RADIUS_PACKET const *original,
767 char const *secret, VALUE_PAIR const **pvp,
768 unsigned int attribute, uint8_t *ptr, size_t room);
770 /** Encode the *data* portion of the TLV
772 * This is really a sub-function of vp2data_any(). It encodes the *data* portion
773 * of the TLV, and assumes that the encapsulating attribute has already been encoded.
775 static ssize_t vp2data_tlvs(RADIUS_PACKET const *packet,
776 RADIUS_PACKET const *original,
777 char const *secret, int nest,
778 VALUE_PAIR const **pvp,
779 uint8_t *start, size_t room)
783 uint8_t *ptr = start;
784 VALUE_PAIR const *vp = *pvp;
785 VALUE_PAIR const *svp = vp;
790 if (nest > fr_attr_max_tlv) {
791 fr_strerror_printf("vp2data_tlvs: attribute nesting overflow");
799 if (room <= 2) return ptr - start;
801 ptr[0] = (vp->da->attr >> fr_attr_shift[nest]) & fr_attr_mask[nest];
805 if (room > 255) my_room = 255;
807 len = vp2data_any(packet, original, secret, nest,
808 &vp, ptr + 2, my_room - 2);
809 if (len < 0) return len;
810 if (len == 0) return ptr - start;
811 /* len can NEVER be more than 253 */
816 if ((fr_debug_lvl > 3) && fr_log_fp) {
817 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
818 print_hex_data(ptr + 2, len, 3);
826 if (!do_next_tlv(svp, vp, nest)) break;
830 if ((fr_debug_lvl > 3) && fr_log_fp) {
833 da = dict_attrbyvalue(svp->da->attr & ((1 << fr_attr_shift[nest ]) - 1), svp->da->vendor);
834 if (da) fprintf(fr_log_fp, "\t%s = ...\n", da->name);
841 /** Encodes the data portion of an attribute
843 * @return -1 on error, or the length of the data portion.
845 static ssize_t vp2data_any(RADIUS_PACKET const *packet,
846 RADIUS_PACKET const *original,
847 char const *secret, int nest,
848 VALUE_PAIR const **pvp,
849 uint8_t *start, size_t room)
854 uint8_t *ptr = start;
857 VALUE_PAIR const *vp = *pvp;
862 * See if we need to encode a TLV. The low portion of
863 * the attribute has already been placed into the packer.
864 * If there are still attribute bytes left, then go
865 * encode them as TLVs.
867 * If we cared about the stack, we could unroll the loop.
869 if (vp->da->flags.is_tlv && (nest < fr_attr_max_tlv) &&
870 ((vp->da->attr >> fr_attr_shift[nest + 1]) != 0)) {
871 return vp2data_tlvs(packet, original, secret, nest + 1, pvp,
876 * Set up the default sources for the data.
880 switch (vp->da->type) {
885 fr_strerror_printf("ERROR: Cannot encode NULL data");
891 case PW_TYPE_IPV4_ADDR:
892 case PW_TYPE_IPV6_ADDR:
893 case PW_TYPE_IPV6_PREFIX:
894 case PW_TYPE_IPV4_PREFIX:
895 case PW_TYPE_ABINARY:
896 case PW_TYPE_ETHERNET: /* just in case */
897 data = (uint8_t const *) &vp->data;
901 len = 1; /* just in case */
902 array[0] = vp->vp_byte;
907 len = 2; /* just in case */
908 array[0] = (vp->vp_short >> 8) & 0xff;
909 array[1] = vp->vp_short & 0xff;
913 case PW_TYPE_INTEGER:
914 len = 4; /* just in case */
915 lvalue = htonl(vp->vp_integer);
916 memcpy(array, &lvalue, sizeof(lvalue));
920 case PW_TYPE_INTEGER64:
921 len = 8; /* just in case */
922 lvalue64 = htonll(vp->vp_integer64);
923 data = (uint8_t *) &lvalue64;
927 * There are no tagged date attributes.
930 lvalue = htonl(vp->vp_date);
931 data = (uint8_t const *) &lvalue;
932 len = 4; /* just in case */
939 len = 4; /* just in case */
940 slvalue = htonl(vp->vp_signed);
941 memcpy(array, &slvalue, sizeof(slvalue));
946 default: /* unknown type: ignore it */
947 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->da->type);
960 * Bound the data to the calling size
962 if (len > (ssize_t) room) len = room;
965 * Encrypt the various password styles
967 * Attributes with encrypted values MUST be less than
970 switch (vp->da->flags.encrypt) {
971 case FLAG_ENCRYPT_USER_PASSWORD:
972 make_passwd(ptr, &len, data, len,
973 secret, packet->vector);
976 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
978 if (vp->da->flags.has_tag) lvalue = 1;
981 * Check if there's enough room. If there isn't,
982 * we discard the attribute.
984 * This is ONLY a problem if we have multiple VSA's
985 * in one Vendor-Specific, though.
987 if (room < (18 + lvalue)) return 0;
989 switch (packet->code) {
990 case PW_CODE_ACCESS_ACCEPT:
991 case PW_CODE_ACCESS_REJECT:
992 case PW_CODE_ACCESS_CHALLENGE:
995 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->da->name);
999 if (lvalue) ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1000 make_tunnel_passwd(ptr + lvalue, &len, data, len,
1002 secret, original->vector);
1005 case PW_CODE_ACCOUNTING_REQUEST:
1006 case PW_CODE_DISCONNECT_REQUEST:
1007 case PW_CODE_COA_REQUEST:
1008 ptr[0] = TAG_VALID(vp->tag) ? vp->tag : TAG_NONE;
1009 make_tunnel_passwd(ptr + 1, &len, data, len, room - 1,
1010 secret, packet->vector);
1017 * The code above ensures that this attribute
1020 case FLAG_ENCRYPT_ASCEND_SECRET:
1021 if (len != 16) return 0;
1022 make_secret(ptr, packet->vector, secret, data);
1023 len = AUTH_VECTOR_LEN;
1028 if (vp->da->flags.has_tag && TAG_VALID(vp->tag)) {
1029 if (vp->da->type == PW_TYPE_STRING) {
1030 if (len > ((ssize_t) (room - 1))) len = room - 1;
1033 } else if (vp->da->type == PW_TYPE_INTEGER) {
1035 } /* else it can't be any other type */
1037 memcpy(ptr, data, len);
1039 } /* switch over encryption flags */
1042 return len + (ptr - start);
1045 static ssize_t attr_shift(uint8_t const *start, uint8_t const *end,
1046 uint8_t *ptr, int hdr_len, ssize_t len,
1047 int flag_offset, int vsa_offset)
1049 int check_len = len - ptr[1];
1050 int total = len + hdr_len;
1053 * Pass 1: Check if the addition of the headers
1054 * overflows the available room. If so, return
1055 * what we were capable of encoding.
1058 while (check_len > (255 - hdr_len)) {
1060 check_len -= (255 - hdr_len);
1064 * Note that this results in a number of attributes maybe
1065 * being marked as "encoded", but which aren't in the
1066 * packet. Oh well. The solution is to fix the
1067 * "vp2data_any" function to take into account the header
1070 if ((ptr + ptr[1] + total) > end) {
1071 return (ptr + ptr[1]) - start;
1075 * Pass 2: Now that we know there's enough room,
1076 * re-arrange the data to form a set of valid
1077 * RADIUS attributes.
1080 int sublen = 255 - ptr[1];
1082 if (len <= sublen) {
1087 memmove(ptr + 255 + hdr_len, ptr + 255, sublen);
1088 memmove(ptr + 255, ptr, hdr_len);
1090 if (vsa_offset) ptr[vsa_offset] += sublen;
1091 ptr[flag_offset] |= 0x80;
1095 if (vsa_offset) ptr[vsa_offset] = 3;
1099 if (vsa_offset) ptr[vsa_offset] += len;
1101 return (ptr + ptr[1]) - start;
1105 /** Encode an "extended" attribute
1107 int rad_vp2extended(RADIUS_PACKET const *packet,
1108 RADIUS_PACKET const *original,
1109 char const *secret, VALUE_PAIR const **pvp,
1110 uint8_t *ptr, size_t room)
1114 uint8_t *start = ptr;
1115 VALUE_PAIR const *vp = *pvp;
1119 if (!vp->da->flags.extended) {
1120 fr_strerror_printf("rad_vp2extended called for non-extended attribute");
1125 * The attribute number is encoded into the upper 8 bits
1128 ptr[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1130 if (!vp->da->flags.long_extended) {
1131 if (room < 3) return 0;
1134 ptr[2] = vp->da->attr & fr_attr_mask[0];
1137 if (room < 4) return 0;
1140 ptr[2] = vp->da->attr & fr_attr_mask[0];
1145 * Only "flagged" attributes can be longer than one
1148 if (!vp->da->flags.long_extended && (room > 255)) {
1155 if (vp->da->flags.evs) {
1156 uint8_t *evs = ptr + ptr[1];
1158 if (room < (size_t) (ptr[1] + 5)) return 0;
1162 evs[0] = 0; /* always zero */
1163 evs[1] = (vp->da->vendor >> 16) & 0xff;
1164 evs[2] = (vp->da->vendor >> 8) & 0xff;
1165 evs[3] = vp->da->vendor & 0xff;
1166 evs[4] = vp->da->attr & fr_attr_mask[0];
1172 len = vp2data_any(packet, original, secret, 0,
1173 pvp, ptr + ptr[1], room - hdr_len);
1174 if (len <= 0) return len;
1177 * There may be more than 252 octets of data encoded in
1178 * the attribute. If so, move the data up in the packet,
1179 * and copy the existing header over. Set the "M" flag ONLY
1180 * after copying the rest of the data.
1182 if (vp->da->flags.long_extended && (len > (255 - ptr[1]))) {
1183 return attr_shift(start, start + room, ptr, 4, len, 3, 0);
1189 if ((fr_debug_lvl > 3) && fr_log_fp) {
1192 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1193 if (!vp->da->flags.long_extended) {
1194 fprintf(fr_log_fp, "%02x ", ptr[2]);
1197 fprintf(fr_log_fp, "%02x %02x ", ptr[2], ptr[3]);
1201 if (vp->da->flags.evs) {
1202 fprintf(fr_log_fp, "%02x%02x%02x%02x (%u) %02x ",
1203 ptr[jump], ptr[jump + 1],
1204 ptr[jump + 2], ptr[jump + 3],
1205 ((ptr[jump + 1] << 16) |
1206 (ptr[jump + 2] << 8) |
1212 print_hex_data(ptr + jump, len, 3);
1216 return (ptr + ptr[1]) - start;
1220 /** Encode a WiMAX attribute
1223 int rad_vp2wimax(RADIUS_PACKET const *packet,
1224 RADIUS_PACKET const *original,
1225 char const *secret, VALUE_PAIR const **pvp,
1226 uint8_t *ptr, size_t room)
1231 uint8_t *start = ptr;
1232 VALUE_PAIR const *vp = *pvp;
1237 * Double-check for WiMAX format.
1239 if (!vp->da->flags.wimax) {
1240 fr_strerror_printf("rad_vp2wimax called for non-WIMAX VSA");
1245 * Not enough room for:
1246 * attr, len, vendor-id, vsa, vsalen, continuation
1248 if (room < 9) return 0;
1251 * Build the Vendor-Specific header
1254 ptr[0] = PW_VENDOR_SPECIFIC;
1256 lvalue = htonl(vp->da->vendor);
1257 memcpy(ptr + 2, &lvalue, 4);
1258 ptr[6] = (vp->da->attr & fr_attr_mask[1]);
1260 ptr[8] = 0; /* continuation byte */
1264 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1],
1266 if (len <= 0) return len;
1269 * There may be more than 252 octets of data encoded in
1270 * the attribute. If so, move the data up in the packet,
1271 * and copy the existing header over. Set the "C" flag
1272 * ONLY after copying the rest of the data.
1274 if (len > (255 - ptr[1])) {
1275 return attr_shift(start, start + room, ptr, hdr_len, len, 8, 7);
1282 if ((fr_debug_lvl > 3) && fr_log_fp) {
1283 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) %02x %02x %02x ",
1285 ptr[2], ptr[3], ptr[4], ptr[5],
1286 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5],
1287 ptr[6], ptr[7], ptr[8]);
1288 print_hex_data(ptr + 9, len, 3);
1292 return (ptr + ptr[1]) - start;
1295 /** Encode an RFC format attribute, with the "concat" flag set
1297 * If there isn't enough room in the packet, the data is
1300 static ssize_t vp2attr_concat(UNUSED RADIUS_PACKET const *packet,
1301 UNUSED RADIUS_PACKET const *original,
1302 UNUSED char const *secret, VALUE_PAIR const **pvp,
1303 unsigned int attribute, uint8_t *start, size_t room)
1305 uint8_t *ptr = start;
1308 VALUE_PAIR const *vp = *pvp;
1313 len = vp->vp_length;
1316 if (room <= 2) break;
1323 /* no more than 253 octets */
1324 if (left > 253) left = 253;
1326 /* no more than "room" octets */
1327 if (room < (left + 2)) left = room - 2;
1329 memcpy(ptr + 2, p, left);
1332 if ((fr_debug_lvl > 3) && fr_log_fp) {
1333 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1334 print_hex_data(ptr + 2, len, 3);
1348 /** Encode an RFC format TLV.
1350 * This could be a standard attribute, or a TLV data type.
1351 * If it's a standard attribute, then vp->da->attr == attribute.
1352 * Otherwise, attribute may be something else.
1354 static ssize_t vp2attr_rfc(RADIUS_PACKET const *packet,
1355 RADIUS_PACKET const *original,
1356 char const *secret, VALUE_PAIR const **pvp,
1357 unsigned int attribute, uint8_t *ptr, size_t room)
1361 if (room <= 2) return 0;
1363 ptr[0] = attribute & 0xff;
1366 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1368 len = vp2data_any(packet, original, secret, 0, pvp, ptr + ptr[1], room);
1369 if (len <= 0) return len;
1374 if ((fr_debug_lvl > 3) && fr_log_fp) {
1375 fprintf(fr_log_fp, "\t\t%02x %02x ", ptr[0], ptr[1]);
1376 print_hex_data(ptr + 2, len, 3);
1384 /** Encode a VSA which is a TLV
1386 * If it's in the RFC format, call vp2attr_rfc. Otherwise, encode it here.
1388 static ssize_t vp2attr_vsa(RADIUS_PACKET const *packet,
1389 RADIUS_PACKET const *original,
1390 char const *secret, VALUE_PAIR const **pvp,
1391 unsigned int attribute, unsigned int vendor,
1392 uint8_t *ptr, size_t room)
1396 VALUE_PAIR const *vp = *pvp;
1400 * Unknown vendor: RFC format.
1401 * Known vendor and RFC format: go do that.
1403 dv = dict_vendorbyvalue(vendor);
1405 (!vp->da->flags.is_tlv && (dv->type == 1) && (dv->length == 1))) {
1406 return vp2attr_rfc(packet, original, secret, pvp,
1407 attribute, ptr, room);
1412 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1413 " type %u", (unsigned) dv->type);
1417 ptr[0] = 0; /* attr must be 24-bit */
1418 ptr[1] = (attribute >> 16) & 0xff;
1419 ptr[2] = (attribute >> 8) & 0xff;
1420 ptr[3] = attribute & 0xff;
1424 ptr[0] = (attribute >> 8) & 0xff;
1425 ptr[1] = attribute & 0xff;
1429 ptr[0] = attribute & 0xff;
1433 switch (dv->length) {
1435 fr_strerror_printf("vp2attr_vsa: Internal sanity check failed,"
1436 " length %u", (unsigned) dv->length);
1444 ptr[dv->type + 1] = dv->type + 2;
1448 ptr[dv->type] = dv->type + 1;
1453 if (room > ((unsigned) 255 - (dv->type + dv->length))) {
1454 room = 255 - (dv->type + dv->length);
1457 len = vp2data_any(packet, original, secret, 0, pvp,
1458 ptr + dv->type + dv->length, room);
1459 if (len <= 0) return len;
1461 if (dv->length) ptr[dv->type + dv->length - 1] += len;
1464 if ((fr_debug_lvl > 3) && fr_log_fp) {
1470 if ((fr_debug_lvl > 3) && fr_log_fp)
1471 fprintf(fr_log_fp, "\t\t%02x%02x%02x%02x ",
1472 ptr[0], ptr[1], ptr[2], ptr[3]);
1476 if ((fr_debug_lvl > 3) && fr_log_fp)
1477 fprintf(fr_log_fp, "\t\t%02x%02x ",
1482 if ((fr_debug_lvl > 3) && fr_log_fp)
1483 fprintf(fr_log_fp, "\t\t%02x ", ptr[0]);
1487 switch (dv->length) {
1492 fprintf(fr_log_fp, " ");
1496 fprintf(fr_log_fp, "%02x ",
1501 fprintf(fr_log_fp, "%02x%02x ",
1502 ptr[dv->type], ptr[dv->type] + 1);
1506 print_hex_data(ptr + dv->type + dv->length, len, 3);
1510 return dv->type + dv->length + len;
1514 /** Encode a Vendor-Specific attribute
1517 int rad_vp2vsa(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1518 char const *secret, VALUE_PAIR const **pvp, uint8_t *ptr,
1523 VALUE_PAIR const *vp = *pvp;
1527 if (vp->da->vendor == 0) {
1528 fr_strerror_printf("rad_vp2vsa called with rfc attribute");
1533 * Double-check for WiMAX format.
1535 if (vp->da->flags.wimax) {
1536 return rad_vp2wimax(packet, original, secret, pvp, ptr, room);
1539 if (vp->da->vendor > FR_MAX_VENDOR) {
1540 fr_strerror_printf("rad_vp2vsa: Invalid arguments");
1545 * Not enough room for:
1546 * attr, len, vendor-id
1548 if (room < 6) return 0;
1551 * Build the Vendor-Specific header
1553 ptr[0] = PW_VENDOR_SPECIFIC;
1555 lvalue = htonl(vp->da->vendor);
1556 memcpy(ptr + 2, &lvalue, 4);
1558 if (room > ((unsigned) 255 - ptr[1])) room = 255 - ptr[1];
1560 len = vp2attr_vsa(packet, original, secret, pvp,
1561 vp->da->attr, vp->da->vendor,
1562 ptr + ptr[1], room);
1563 if (len < 0) return len;
1566 if ((fr_debug_lvl > 3) && fr_log_fp) {
1567 fprintf(fr_log_fp, "\t\t%02x %02x %02x%02x%02x%02x (%u) ",
1569 ptr[2], ptr[3], ptr[4], ptr[5],
1570 (ptr[3] << 16) | (ptr[4] << 8) | ptr[5]);
1571 print_hex_data(ptr + 6, len, 3);
1581 /** Encode an RFC standard attribute 1..255
1584 int rad_vp2rfc(RADIUS_PACKET const *packet,
1585 RADIUS_PACKET const *original,
1586 char const *secret, VALUE_PAIR const **pvp,
1587 uint8_t *ptr, size_t room)
1589 VALUE_PAIR const *vp = *pvp;
1593 if (vp->da->vendor != 0) {
1594 fr_strerror_printf("rad_vp2rfc called with VSA");
1598 if ((vp->da->attr == 0) || (vp->da->attr > 255)) {
1599 fr_strerror_printf("rad_vp2rfc called with non-standard attribute %u", vp->da->attr);
1604 * Only CUI is allowed to have zero length.
1607 if ((vp->vp_length == 0) &&
1608 (vp->da->attr == PW_CHARGEABLE_USER_IDENTITY)) {
1609 ptr[0] = PW_CHARGEABLE_USER_IDENTITY;
1617 * Message-Authenticator is hard-coded.
1619 if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1620 if (room < 18) return -1;
1622 ptr[0] = PW_MESSAGE_AUTHENTICATOR;
1624 memset(ptr + 2, 0, 16);
1626 if ((fr_debug_lvl > 3) && fr_log_fp) {
1627 fprintf(fr_log_fp, "\t\t50 12 ...\n");
1631 *pvp = (*pvp)->next;
1636 * EAP-Message is special.
1638 if (vp->da->flags.concat && (vp->vp_length > 253)) {
1639 return vp2attr_concat(packet, original, secret, pvp, vp->da->attr,
1643 return vp2attr_rfc(packet, original, secret, pvp, vp->da->attr,
1647 static ssize_t rad_vp2rfctlv(RADIUS_PACKET const *packet,
1648 RADIUS_PACKET const *original,
1649 char const *secret, VALUE_PAIR const **pvp,
1650 uint8_t *start, size_t room)
1653 VALUE_PAIR const *vp = *pvp;
1657 if (!vp->da->flags.is_tlv) {
1658 fr_strerror_printf("rad_vp2rfctlv: attr is not a TLV");
1662 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) != 0) {
1663 fr_strerror_printf("rad_vp2rfctlv: attr is not an RFC TLV");
1667 if (room < 5) return 0;
1670 * Encode the first level of TLVs
1672 start[0] = (vp->da->vendor / FR_MAX_VENDOR) & 0xff;
1674 start[2] = vp->da->attr & fr_attr_mask[0];
1677 len = vp2data_any(packet, original, secret, 0, pvp,
1678 start + 4, room - 4);
1679 if (len <= 0) return len;
1691 /** Parse a data structure into a RADIUS attribute
1694 int rad_vp2attr(RADIUS_PACKET const *packet, RADIUS_PACKET const *original,
1695 char const *secret, VALUE_PAIR const **pvp, uint8_t *start,
1698 VALUE_PAIR const *vp;
1700 if (!pvp || !*pvp || !start || (room <= 2)) return -1;
1707 * RFC format attributes take the fast path.
1709 if (!vp->da->vendor) {
1710 if (vp->da->attr > 255) return 0;
1712 return rad_vp2rfc(packet, original, secret, pvp,
1716 if (vp->da->flags.extended) {
1717 return rad_vp2extended(packet, original, secret, pvp,
1722 * The upper 8 bits of the vendor number are the standard
1723 * space attribute which is a TLV.
1725 if ((vp->da->vendor & (FR_MAX_VENDOR - 1)) == 0) {
1726 return rad_vp2rfctlv(packet, original, secret, pvp,
1730 if (vp->da->flags.wimax) {
1731 return rad_vp2wimax(packet, original, secret, pvp,
1735 return rad_vp2vsa(packet, original, secret, pvp, start, room);
1742 int rad_encode(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1745 radius_packet_t *hdr;
1747 uint16_t total_length;
1749 VALUE_PAIR const *reply;
1752 * A 4K packet, aligned on 64-bits.
1754 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1757 * Double-check some things based on packet code.
1759 switch (packet->code) {
1760 case PW_CODE_ACCESS_ACCEPT:
1761 case PW_CODE_ACCESS_REJECT:
1762 case PW_CODE_ACCESS_CHALLENGE:
1764 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1770 * These packet vectors start off as all zero.
1772 case PW_CODE_ACCOUNTING_REQUEST:
1773 case PW_CODE_DISCONNECT_REQUEST:
1774 case PW_CODE_COA_REQUEST:
1775 memset(packet->vector, 0, sizeof(packet->vector));
1783 * Use memory on the stack, until we know how
1784 * large the packet will be.
1786 hdr = (radius_packet_t *) data;
1789 * Build standard header
1791 hdr->code = packet->code;
1792 hdr->id = packet->id;
1794 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1796 total_length = RADIUS_HDR_LEN;
1799 * Load up the configuration values for the user
1805 * FIXME: Loop twice over the reply list. The first time,
1806 * calculate the total length of data. The second time,
1807 * allocate the memory, and fill in the VP's.
1809 * Hmm... this may be slower than just doing a small
1814 * Loop over the reply attributes for the packet.
1816 reply = packet->vps;
1819 char const *last_name = NULL;
1824 * Ignore non-wire attributes, but allow extended
1827 if ((reply->da->vendor == 0) &&
1828 ((reply->da->attr & 0xFFFF) >= 256) &&
1829 !reply->da->flags.extended && !reply->da->flags.long_extended) {
1832 * Permit the admin to send BADLY formatted
1833 * attributes with a debug build.
1835 if (reply->da->attr == PW_RAW_ATTRIBUTE) {
1836 memcpy(ptr, reply->vp_octets, reply->vp_length);
1837 len = reply->vp_length;
1838 reply = reply->next;
1842 reply = reply->next;
1847 * Set the Message-Authenticator to the correct
1848 * length and initial value.
1850 if (!reply->da->vendor && (reply->da->attr == PW_MESSAGE_AUTHENTICATOR)) {
1852 * Cache the offset to the
1853 * Message-Authenticator
1855 packet->offset = total_length;
1858 last_len = reply->vp_length;
1860 last_name = reply->da->name;
1862 len = rad_vp2attr(packet, original, secret, &reply, ptr,
1863 ((uint8_t *) data) + sizeof(data) - ptr);
1864 if (len < 0) return -1;
1867 * Failed to encode the attribute, likely because
1868 * the packet is full.
1871 if (last_len != 0) {
1872 fr_strerror_printf("WARNING: Failed encoding attribute %s\n", last_name);
1875 fr_strerror_printf("WARNING: Skipping zero-length attribute %s\n", last_name);
1880 next: /* Used only for Raw-Attribute */
1883 total_length += len;
1884 } /* done looping over all attributes */
1887 * Fill in the rest of the fields, and copy the data over
1888 * from the local stack to the newly allocated memory.
1890 * Yes, all this 'memcpy' is slow, but it means
1891 * that we only allocate the minimum amount of
1892 * memory for a request.
1894 packet->data_len = total_length;
1895 packet->data = talloc_array(packet, uint8_t, packet->data_len);
1896 if (!packet->data) {
1897 fr_strerror_printf("Out of memory");
1901 memcpy(packet->data, hdr, packet->data_len);
1902 hdr = (radius_packet_t *) packet->data;
1904 total_length = htons(total_length);
1905 memcpy(hdr->length, &total_length, sizeof(total_length));
1911 /** Sign a previously encoded packet
1914 int rad_sign(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
1917 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1920 * It wasn't assigned an Id, this is bad!
1922 if (packet->id < 0) {
1923 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id");
1927 if (!packet->data || (packet->data_len < RADIUS_HDR_LEN) ||
1928 (packet->offset < 0)) {
1929 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1934 * If there's a Message-Authenticator, update it
1935 * now, BEFORE updating the authentication vector.
1937 if (packet->offset > 0) {
1938 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1940 switch (packet->code) {
1941 case PW_CODE_ACCOUNTING_RESPONSE:
1942 if (original && original->code == PW_CODE_STATUS_SERVER) {
1946 case PW_CODE_ACCOUNTING_REQUEST:
1947 case PW_CODE_DISCONNECT_REQUEST:
1948 case PW_CODE_DISCONNECT_ACK:
1949 case PW_CODE_DISCONNECT_NAK:
1950 case PW_CODE_COA_REQUEST:
1951 case PW_CODE_COA_ACK:
1952 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1956 case PW_CODE_ACCESS_ACCEPT:
1957 case PW_CODE_ACCESS_REJECT:
1958 case PW_CODE_ACCESS_CHALLENGE:
1960 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1963 memcpy(hdr->vector, original->vector,
1967 default: /* others have vector already set to zero */
1973 * Set the authentication vector to zero,
1974 * calculate the HMAC, and put it
1975 * into the Message-Authenticator
1978 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1979 (uint8_t const *) secret, strlen(secret));
1980 memcpy(packet->data + packet->offset + 2,
1981 calc_auth_vector, AUTH_VECTOR_LEN);
1984 * Copy the original request vector back
1985 * to the raw packet.
1987 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1991 * Switch over the packet code, deciding how to
1994 switch (packet->code) {
1996 * Request packets are not signed, bur
1997 * have a random authentication vector.
1999 case PW_CODE_ACCESS_REQUEST:
2000 case PW_CODE_STATUS_SERVER:
2004 * Reply packets are signed with the
2005 * authentication vector of the request.
2012 fr_md5_init(&context);
2013 fr_md5_update(&context, packet->data, packet->data_len);
2014 fr_md5_update(&context, (uint8_t const *) secret,
2016 fr_md5_final(digest, &context);
2018 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2019 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2022 }/* switch over packet codes */
2027 /** Reply to the request
2029 * Also attach reply attribute value pairs and any user message provided.
2031 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2035 * Maybe it's a fake packet. Don't send it.
2037 if (!packet || (packet->sockfd < 0)) {
2042 * First time through, allocate room for the packet
2044 if (!packet->data) {
2046 * Encode the packet.
2048 if (rad_encode(packet, original, secret) < 0) {
2053 * Re-sign it, including updating the
2054 * Message-Authenticator.
2056 if (rad_sign(packet, original, secret) < 0) {
2061 * If packet->data points to data, then we print out
2062 * the VP list again only for debugging.
2067 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2072 * If the socket is TCP, call write(). Calling sendto()
2073 * is allowed on some platforms, but it's not nice. Even
2074 * worse, if UDPFROMTO is defined, we *can't* use it on
2075 * TCP sockets. So... just call write().
2077 if (packet->proto == IPPROTO_TCP) {
2080 rcode = write(packet->sockfd, packet->data, packet->data_len);
2081 if (rcode >= 0) return rcode;
2083 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2089 * And send it on it's way.
2091 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2092 &packet->src_ipaddr, packet->src_port,
2093 &packet->dst_ipaddr, packet->dst_port);
2096 /** Do a comparison of two authentication digests by comparing the FULL digest
2098 * Otherwise, the server can be subject to timing attacks that allow attackers
2099 * find a valid message authenticator.
2101 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2103 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2108 for (i = 0; i < length; i++) {
2109 result |= a[i] ^ b[i];
2112 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2116 /** Validates the requesting client NAS
2118 * Calculates the request Authenticator based on the clients private key.
2120 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2122 uint8_t digest[AUTH_VECTOR_LEN];
2126 * Zero out the auth_vector in the received packet.
2127 * Then append the shared secret to the received packet,
2128 * and calculate the MD5 sum. This must be the same
2129 * as the original MD5 sum (packet->vector).
2131 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2134 * MD5(packet + secret);
2136 fr_md5_init(&context);
2137 fr_md5_update(&context, packet->data, packet->data_len);
2138 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2139 fr_md5_final(digest, &context);
2142 * Return 0 if OK, 2 if not OK.
2144 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2149 /** Validates the requesting client NAS
2151 * Calculates the response Authenticator based on the clients
2154 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2157 uint8_t calc_digest[AUTH_VECTOR_LEN];
2163 if (original == NULL) {
2168 * Copy the original vector in place.
2170 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2173 * MD5(packet + secret);
2175 fr_md5_init(&context);
2176 fr_md5_update(&context, packet->data, packet->data_len);
2177 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2178 fr_md5_final(calc_digest, &context);
2181 * Copy the packet's vector back to the packet.
2183 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2186 * Return 0 if OK, 2 if not OK.
2188 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2192 /** Check if a set of RADIUS formatted TLVs are OK
2195 int rad_tlv_ok(uint8_t const *data, size_t length,
2196 size_t dv_type, size_t dv_length)
2198 uint8_t const *end = data + length;
2200 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2202 VP_HEXDUMP("tlv_ok", data, length);
2204 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2205 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2209 while (data < end) {
2212 if ((data + dv_type + dv_length) > end) {
2213 fr_strerror_printf("Attribute header overflow");
2219 if ((data[0] == 0) && (data[1] == 0) &&
2220 (data[2] == 0) && (data[3] == 0)) {
2222 fr_strerror_printf("Invalid attribute 0");
2227 fr_strerror_printf("Invalid attribute > 2^24");
2233 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2238 * Zero is allowed, because the Colubris
2239 * people are dumb and use it.
2244 fr_strerror_printf("Internal sanity check failed");
2248 switch (dv_length) {
2253 if (data[dv_type] != 0) {
2254 fr_strerror_printf("Attribute is longer than 256 octets");
2259 attrlen = data[dv_type + dv_length - 1];
2264 fr_strerror_printf("Internal sanity check failed");
2268 if (attrlen < (dv_type + dv_length)) {
2269 fr_strerror_printf("Attribute header has invalid length");
2273 if (attrlen > length) {
2274 fr_strerror_printf("Attribute overflows container");
2286 /** See if the data pointed to by PTR is a valid RADIUS packet.
2288 * Packet is not 'const * const' because we may update data_len, if there's more data
2289 * in the UDP packet than in the RADIUS packet.
2291 * @param packet to check
2292 * @param flags to control decoding
2293 * @param reason if not NULL, will have the failure reason written to where it points.
2294 * @return bool, true on success, false on failure.
2296 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2301 radius_packet_t *hdr;
2302 char host_ipaddr[128];
2303 bool require_ma = false;
2304 bool seen_ma = false;
2305 uint32_t num_attributes;
2306 decode_fail_t failure = DECODE_FAIL_NONE;
2309 * Check for packets smaller than the packet header.
2311 * RFC 2865, Section 3., subsection 'length' says:
2313 * "The minimum length is 20 ..."
2315 if (packet->data_len < RADIUS_HDR_LEN) {
2316 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2317 inet_ntop(packet->src_ipaddr.af,
2318 &packet->src_ipaddr.ipaddr,
2319 host_ipaddr, sizeof(host_ipaddr)),
2320 packet->data_len, RADIUS_HDR_LEN);
2321 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2327 * Check for packets with mismatched size.
2328 * i.e. We've received 128 bytes, and the packet header
2329 * says it's 256 bytes long.
2331 totallen = (packet->data[2] << 8) | packet->data[3];
2332 hdr = (radius_packet_t *)packet->data;
2335 * Code of 0 is not understood.
2336 * Code of 16 or greate is not understood.
2338 if ((hdr->code == 0) ||
2339 (hdr->code >= FR_MAX_PACKET_CODE)) {
2340 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2341 inet_ntop(packet->src_ipaddr.af,
2342 &packet->src_ipaddr.ipaddr,
2343 host_ipaddr, sizeof(host_ipaddr)),
2345 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2350 * Message-Authenticator is required in Status-Server
2351 * packets, otherwise they can be trivially forged.
2353 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2356 * It's also required if the caller asks for it.
2358 if (flags) require_ma = true;
2361 * Repeat the length checks. This time, instead of
2362 * looking at the data we received, look at the value
2363 * of the 'length' field inside of the packet.
2365 * Check for packets smaller than the packet header.
2367 * RFC 2865, Section 3., subsection 'length' says:
2369 * "The minimum length is 20 ..."
2371 if (totallen < RADIUS_HDR_LEN) {
2372 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2373 inet_ntop(packet->src_ipaddr.af,
2374 &packet->src_ipaddr.ipaddr,
2375 host_ipaddr, sizeof(host_ipaddr)),
2376 totallen, RADIUS_HDR_LEN);
2377 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2382 * And again, for the value of the 'length' field.
2384 * RFC 2865, Section 3., subsection 'length' says:
2386 * " ... and maximum length is 4096."
2388 * HOWEVER. This requirement is for the network layer.
2389 * If the code gets here, we assume that a well-formed
2390 * packet is an OK packet.
2392 * We allow both the UDP data length, and the RADIUS
2393 * "length" field to contain up to 64K of data.
2397 * RFC 2865, Section 3., subsection 'length' says:
2399 * "If the packet is shorter than the Length field
2400 * indicates, it MUST be silently discarded."
2402 * i.e. No response to the NAS.
2404 if (packet->data_len < totallen) {
2405 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2406 inet_ntop(packet->src_ipaddr.af,
2407 &packet->src_ipaddr.ipaddr,
2408 host_ipaddr, sizeof(host_ipaddr)),
2409 packet->data_len, totallen);
2410 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2415 * RFC 2865, Section 3., subsection 'length' says:
2417 * "Octets outside the range of the Length field MUST be
2418 * treated as padding and ignored on reception."
2420 if (packet->data_len > totallen) {
2422 * We're shortening the packet below, but just
2423 * to be paranoid, zero out the extra data.
2425 memset(packet->data + totallen, 0, packet->data_len - totallen);
2426 packet->data_len = totallen;
2430 * Walk through the packet's attributes, ensuring that
2431 * they add up EXACTLY to the size of the packet.
2433 * If they don't, then the attributes either under-fill
2434 * or over-fill the packet. Any parsing of the packet
2435 * is impossible, and will result in unknown side effects.
2437 * This would ONLY happen with buggy RADIUS implementations,
2438 * or with an intentional attack. Either way, we do NOT want
2439 * to be vulnerable to this problem.
2442 count = totallen - RADIUS_HDR_LEN;
2447 * We need at least 2 bytes to check the
2451 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2452 inet_ntop(packet->src_ipaddr.af,
2453 &packet->src_ipaddr.ipaddr,
2454 host_ipaddr, sizeof(host_ipaddr)));
2455 failure = DECODE_FAIL_HEADER_OVERFLOW;
2460 * Attribute number zero is NOT defined.
2463 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2464 inet_ntop(packet->src_ipaddr.af,
2465 &packet->src_ipaddr.ipaddr,
2466 host_ipaddr, sizeof(host_ipaddr)));
2467 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2472 * Attributes are at LEAST as long as the ID & length
2473 * fields. Anything shorter is an invalid attribute.
2476 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2477 inet_ntop(packet->src_ipaddr.af,
2478 &packet->src_ipaddr.ipaddr,
2479 host_ipaddr, sizeof(host_ipaddr)),
2481 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2486 * If there are fewer bytes in the packet than in the
2487 * attribute, it's a bad packet.
2489 if (count < attr[1]) {
2490 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2491 inet_ntop(packet->src_ipaddr.af,
2492 &packet->src_ipaddr.ipaddr,
2493 host_ipaddr, sizeof(host_ipaddr)),
2495 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2500 * Sanity check the attributes for length.
2503 default: /* don't do anything by default */
2507 * If there's an EAP-Message, we require
2508 * a Message-Authenticator.
2510 case PW_EAP_MESSAGE:
2514 case PW_MESSAGE_AUTHENTICATOR:
2515 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2516 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2517 inet_ntop(packet->src_ipaddr.af,
2518 &packet->src_ipaddr.ipaddr,
2519 host_ipaddr, sizeof(host_ipaddr)),
2521 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2529 * FIXME: Look up the base 255 attributes in the
2530 * dictionary, and switch over their type. For
2531 * integer/date/ip, the attribute length SHOULD
2534 count -= attr[1]; /* grab the attribute length */
2536 num_attributes++; /* seen one more attribute */
2540 * If the attributes add up to a packet, it's allowed.
2542 * If not, we complain, and throw the packet away.
2545 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2546 inet_ntop(packet->src_ipaddr.af,
2547 &packet->src_ipaddr.ipaddr,
2548 host_ipaddr, sizeof(host_ipaddr)));
2549 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2554 * If we're configured to look for a maximum number of
2555 * attributes, and we've seen more than that maximum,
2556 * then throw the packet away, as a possible DoS.
2558 if ((fr_max_attributes > 0) &&
2559 (num_attributes > fr_max_attributes)) {
2560 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2561 inet_ntop(packet->src_ipaddr.af,
2562 &packet->src_ipaddr.ipaddr,
2563 host_ipaddr, sizeof(host_ipaddr)),
2564 num_attributes, fr_max_attributes);
2565 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2570 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2572 * A packet with an EAP-Message attribute MUST also have
2573 * a Message-Authenticator attribute.
2575 * A Message-Authenticator all by itself is OK, though.
2577 * Similarly, Status-Server packets MUST contain
2578 * Message-Authenticator attributes.
2580 if (require_ma && !seen_ma) {
2581 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2582 inet_ntop(packet->src_ipaddr.af,
2583 &packet->src_ipaddr.ipaddr,
2584 host_ipaddr, sizeof(host_ipaddr)));
2585 failure = DECODE_FAIL_MA_MISSING;
2590 * Fill RADIUS header fields
2592 packet->code = hdr->code;
2593 packet->id = hdr->id;
2594 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2602 return (failure == DECODE_FAIL_NONE);
2606 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2609 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2613 RADIUS_PACKET *packet;
2616 * Allocate the new request data structure
2618 packet = rad_alloc(ctx, false);
2620 fr_strerror_printf("out of memory");
2625 sock_flags = MSG_PEEK;
2629 data_len = rad_recvfrom(fd, packet, sock_flags,
2630 &packet->src_ipaddr, &packet->src_port,
2631 &packet->dst_ipaddr, &packet->dst_port);
2634 * Check for socket errors.
2637 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2638 /* packet->data is NULL */
2642 packet->data_len = data_len; /* unsigned vs signed */
2645 * If the packet is too big, then rad_recvfrom did NOT
2646 * allocate memory. Instead, it just discarded the
2649 if (packet->data_len > MAX_PACKET_LEN) {
2650 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2651 /* packet->data is NULL */
2657 * Read no data. Continue.
2658 * This check is AFTER the MAX_PACKET_LEN check above, because
2659 * if the packet is larger than MAX_PACKET_LEN, we also have
2660 * packet->data == NULL
2662 if ((packet->data_len == 0) || !packet->data) {
2663 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2669 * See if it's a well-formed RADIUS packet.
2671 if (!rad_packet_ok(packet, flags, NULL)) {
2677 * Remember which socket we read the packet from.
2679 packet->sockfd = fd;
2682 * FIXME: Do even more filtering by only permitting
2683 * certain IP's. The problem is that we don't know
2684 * how to do this properly for all possible clients...
2688 * Explicitely set the VP list to empty.
2693 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2700 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2703 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2711 if (!packet || !packet->data) return -1;
2714 * Before we allocate memory for the attributes, do more
2717 ptr = packet->data + RADIUS_HDR_LEN;
2718 length = packet->data_len - RADIUS_HDR_LEN;
2719 while (length > 0) {
2720 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2721 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2726 default: /* don't do anything. */
2730 * Note that more than one Message-Authenticator
2731 * attribute is invalid.
2733 case PW_MESSAGE_AUTHENTICATOR:
2734 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2735 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2737 switch (packet->code) {
2741 case PW_CODE_ACCOUNTING_RESPONSE:
2743 (original->code == PW_CODE_STATUS_SERVER)) {
2747 case PW_CODE_ACCOUNTING_REQUEST:
2748 case PW_CODE_DISCONNECT_REQUEST:
2749 case PW_CODE_COA_REQUEST:
2750 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2754 case PW_CODE_ACCESS_ACCEPT:
2755 case PW_CODE_ACCESS_REJECT:
2756 case PW_CODE_ACCESS_CHALLENGE:
2757 case PW_CODE_DISCONNECT_ACK:
2758 case PW_CODE_DISCONNECT_NAK:
2759 case PW_CODE_COA_ACK:
2760 case PW_CODE_COA_NAK:
2762 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2763 "packet without a request packet");
2766 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2770 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2771 (uint8_t const *) secret, strlen(secret));
2772 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2773 sizeof(calc_auth_vector)) != 0) {
2774 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2775 "(Shared secret is incorrect.)",
2776 inet_ntop(packet->src_ipaddr.af,
2777 &packet->src_ipaddr.ipaddr,
2778 buffer, sizeof(buffer)));
2779 /* Silently drop packet, according to RFC 3579 */
2781 } /* else the message authenticator was good */
2784 * Reinitialize Authenticators.
2786 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2787 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2789 } /* switch over the attributes */
2793 } /* loop over the packet, sanity checking the attributes */
2796 * It looks like a RADIUS packet, but we don't know what it is
2797 * so can't validate the authenticators.
2799 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2800 fr_strerror_printf("Received Unknown packet code %d "
2801 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2803 inet_ntop(packet->src_ipaddr.af,
2804 &packet->src_ipaddr.ipaddr,
2805 buffer, sizeof(buffer)),
2811 * Calculate and/or verify Request or Response Authenticator.
2813 switch (packet->code) {
2814 case PW_CODE_ACCESS_REQUEST:
2815 case PW_CODE_STATUS_SERVER:
2817 * The authentication vector is random
2818 * nonsense, invented by the client.
2822 case PW_CODE_COA_REQUEST:
2823 case PW_CODE_DISCONNECT_REQUEST:
2824 case PW_CODE_ACCOUNTING_REQUEST:
2825 if (calc_acctdigest(packet, secret) > 1) {
2826 fr_strerror_printf("Received %s packet "
2827 "from client %s with invalid Request Authenticator! "
2828 "(Shared secret is incorrect.)",
2829 fr_packet_codes[packet->code],
2830 inet_ntop(packet->src_ipaddr.af,
2831 &packet->src_ipaddr.ipaddr,
2832 buffer, sizeof(buffer)));
2837 /* Verify the reply digest */
2838 case PW_CODE_ACCESS_ACCEPT:
2839 case PW_CODE_ACCESS_REJECT:
2840 case PW_CODE_ACCESS_CHALLENGE:
2841 case PW_CODE_ACCOUNTING_RESPONSE:
2842 case PW_CODE_DISCONNECT_ACK:
2843 case PW_CODE_DISCONNECT_NAK:
2844 case PW_CODE_COA_ACK:
2845 case PW_CODE_COA_NAK:
2846 rcode = calc_replydigest(packet, original, secret);
2848 fr_strerror_printf("Received %s packet "
2849 "from home server %s port %d with invalid Response Authenticator! "
2850 "(Shared secret is incorrect.)",
2851 fr_packet_codes[packet->code],
2852 inet_ntop(packet->src_ipaddr.af,
2853 &packet->src_ipaddr.ipaddr,
2854 buffer, sizeof(buffer)),
2861 fr_strerror_printf("Received Unknown packet code %d "
2862 "from client %s port %d: Cannot validate Request/Response Authenticator",
2864 inet_ntop(packet->src_ipaddr.af,
2865 &packet->src_ipaddr.ipaddr,
2866 buffer, sizeof(buffer)),
2875 /** Convert a "concatenated" attribute to one long VP
2878 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2879 DICT_ATTR const *da, uint8_t const *start,
2880 size_t const packetlen, VALUE_PAIR **pvp)
2884 uint8_t const *ptr = start;
2885 uint8_t const *end = start + packetlen;
2893 * The packet has already been sanity checked, so we
2894 * don't care about walking off of the end of it.
2897 total += ptr[1] - 2;
2902 * Attributes MUST be consecutive.
2904 if (ptr[0] != attr) break;
2907 vp = fr_pair_afrom_da(ctx, da);
2910 vp->vp_length = total;
2911 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2913 fr_pair_list_free(&vp);
2919 while (total < vp->vp_length) {
2920 memcpy(p, ptr + 2, ptr[1] - 2);
2922 total += ptr[1] - 2;
2931 /** Convert TLVs to one or more VPs
2934 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2935 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2936 char const *secret, DICT_ATTR const *da,
2937 uint8_t const *start, size_t length,
2940 uint8_t const *data = start;
2941 DICT_ATTR const *child;
2942 VALUE_PAIR *head, **tail;
2944 if (length < 3) return -1; /* type, length, value */
2946 VP_HEXDUMP("tlvs", data, length);
2948 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2953 while (data < (start + length)) {
2956 child = dict_attrbyparent(da, data[0], da->vendor);
2958 unsigned int my_attr, my_vendor;
2960 VP_TRACE("Failed to find child %u of TLV %s\n",
2964 * Get child attr/vendor so that
2965 * we can call unknown attr.
2968 my_vendor = da->vendor;
2970 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2971 fr_pair_list_free(&head);
2975 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2977 fr_pair_list_free(&head);
2982 tlv_len = data2vp(ctx, packet, original, secret, child,
2983 data + 2, data[1] - 2, data[1] - 2, tail);
2985 fr_pair_list_free(&head);
2988 if (*tail) tail = &((*tail)->next);
2996 /** Convert a top-level VSA to a VP.
2998 * "length" can be LONGER than just this sub-vsa.
3000 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3001 RADIUS_PACKET const *original,
3002 char const *secret, DICT_VENDOR *dv,
3003 uint8_t const *data, size_t length,
3006 unsigned int attribute;
3007 ssize_t attrlen, my_len;
3008 DICT_ATTR const *da;
3010 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3013 if (length <= (dv->type + dv->length)) {
3014 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3021 /* data[0] must be zero */
3022 attribute = data[1] << 16;
3023 attribute |= data[2] << 8;
3024 attribute |= data[3];
3028 attribute = data[0] << 8;
3029 attribute |= data[1];
3033 attribute = data[0];
3037 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3041 switch (dv->length) {
3043 /* data[dv->type] must be zero, from rad_tlv_ok() */
3044 attrlen = data[dv->type + 1];
3048 attrlen = data[dv->type];
3056 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3061 * See if the VSA is known.
3063 da = dict_attrbyvalue(attribute, dv->vendorpec);
3064 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3067 my_len = data2vp(ctx, packet, original, secret, da,
3068 data + dv->type + dv->length,
3069 attrlen - (dv->type + dv->length),
3070 attrlen - (dv->type + dv->length),
3072 if (my_len < 0) return my_len;
3078 /** Convert a fragmented extended attr to a VP
3088 * But for the first fragment, we get passed a pointer to the "extended-attr"
3090 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3091 RADIUS_PACKET const *original,
3092 char const *secret, DICT_ATTR const *da,
3093 uint8_t const *data,
3094 size_t attrlen, size_t packetlen,
3099 uint8_t *head, *tail;
3100 uint8_t const *frag, *end;
3101 uint8_t const *attr;
3105 if (attrlen < 3) return -1;
3108 * Calculate the length of all of the fragments. For
3109 * now, they MUST be contiguous in the packet, and they
3110 * MUST be all of the same TYPE and EXTENDED-TYPE
3113 fraglen = attrlen - 2;
3114 frag = data + attrlen;
3115 end = data + packetlen;
3119 while (frag < end) {
3121 (frag[0] != attr[0]) ||
3122 (frag[1] < 4) || /* too short for long-extended */
3123 (frag[2] != attr[2]) ||
3124 ((frag + frag[1]) > end)) { /* overflow */
3129 last_frag = ((frag[3] & 0x80) == 0);
3131 fraglen += frag[1] - 4;
3136 head = tail = malloc(fraglen);
3137 if (!head) return -1;
3139 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3142 * And again, but faster and looser.
3144 * We copy the first fragment, followed by the rest of
3149 while (fragments > 0) {
3150 memcpy(tail, frag + 4, frag[1] - 4);
3151 tail += frag[1] - 4;
3156 VP_HEXDUMP("long-extended fragments", head, fraglen);
3158 rcode = data2vp(ctx, packet, original, secret, da,
3159 head, fraglen, fraglen, pvp);
3161 if (rcode < 0) return rcode;
3166 /** Convert a Vendor-Specific WIMAX to vps
3168 * @note Called ONLY for Vendor-Specific
3170 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3171 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3172 char const *secret, uint32_t vendor,
3173 uint8_t const *data,
3174 size_t attrlen, size_t packetlen,
3180 uint8_t *head, *tail;
3181 uint8_t const *frag, *end;
3182 DICT_ATTR const *child;
3184 if (attrlen < 8) return -1;
3186 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3188 child = dict_attrbyvalue(data[4], vendor);
3189 if (!child) return -1;
3191 if ((data[6] & 0x80) == 0) {
3192 rcode = data2vp(ctx, packet, original, secret, child,
3193 data + 7, data[5] - 3, data[5] - 3,
3195 if (rcode < 0) return -1;
3200 * Calculate the length of all of the fragments. For
3201 * now, they MUST be contiguous in the packet, and they
3202 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3204 * The first fragment doesn't have a RADIUS attribute
3205 * header, so it needs to be treated a little special.
3207 fraglen = data[5] - 3;
3208 frag = data + attrlen;
3209 end = data + packetlen;
3212 while (frag < end) {
3214 (frag[0] != PW_VENDOR_SPECIFIC) ||
3215 (frag[1] < 9) || /* too short for wimax */
3216 ((frag + frag[1]) > end) || /* overflow */
3217 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3218 (frag[6] != data[4]) || /* not the same wimax attr */
3219 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3224 last_frag = ((frag[8] & 0x80) == 0);
3226 fraglen += frag[7] - 3;
3230 head = tail = malloc(fraglen);
3231 if (!head) return -1;
3234 * And again, but faster and looser.
3236 * We copy the first fragment, followed by the rest of
3241 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3242 tail += frag[4 + 1] - 3;
3243 frag += attrlen; /* should be frag[1] - 7 */
3246 * frag now points to RADIUS attributes
3249 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3250 tail += frag[2 + 4 + 1] - 3;
3252 } while (frag < end);
3254 VP_HEXDUMP("wimax fragments", head, fraglen);
3256 rcode = data2vp(ctx, packet, original, secret, child,
3257 head, fraglen, fraglen, pvp);
3259 if (rcode < 0) return rcode;
3265 /** Convert a top-level VSA to one or more VPs
3268 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3269 RADIUS_PACKET const *original,
3270 char const *secret, uint8_t const *data,
3271 size_t attrlen, size_t packetlen,
3278 VALUE_PAIR *head, **tail;
3281 if (attrlen > packetlen) return -1;
3282 if (attrlen < 5) return -1; /* vid, value */
3283 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3285 VP_TRACE("data2vp_vsas\n");
3287 memcpy(&vendor, data, 4);
3288 vendor = ntohl(vendor);
3289 dv = dict_vendorbyvalue(vendor);
3292 * RFC format is 1 octet type, 1 octet length
3294 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3295 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3300 * It's a known unknown.
3302 memset(&my_dv, 0, sizeof(my_dv));
3306 * Fill in the fields. Note that the name is empty!
3308 dv->vendorpec = vendor;
3318 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3319 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3320 data, attrlen, packetlen, pvp);
3325 * VSAs should normally be in TLV format.
3327 if (rad_tlv_ok(data + 4, attrlen - 4,
3328 dv->type, dv->length) < 0) {
3329 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3334 * There may be more than one VSA in the
3335 * Vendor-Specific. If so, loop over them all.
3345 while (attrlen > 0) {
3348 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3349 data, attrlen, tail);
3351 fr_pair_list_free(&head);
3352 fr_strerror_printf("Internal sanity check %d", __LINE__);
3357 * Vendors can send zero-length VSAs.
3359 if (*tail) tail = &((*tail)->next);
3363 packetlen -= vsa_len;
3371 /** Create any kind of VP from the attribute contents
3373 * "length" is AT LEAST the length of this attribute, as we
3374 * expect the caller to have verified the data with
3375 * rad_packet_ok(). "length" may be up to the length of the
3378 * @return -1 on error, or "length".
3380 ssize_t data2vp(TALLOC_CTX *ctx,
3381 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3383 DICT_ATTR const *da, uint8_t const *start,
3384 size_t const attrlen, size_t const packetlen,
3387 int8_t tag = TAG_NONE;
3391 DICT_ATTR const *child;
3393 uint8_t const *data = start;
3395 uint8_t buffer[256];
3398 * FIXME: Attrlen can be larger than 253 for extended attrs!
3400 if (!da || (attrlen > packetlen) ||
3401 ((attrlen > 253) && (attrlen != packetlen)) ||
3402 (attrlen > 128*1024)) {
3403 fr_strerror_printf("data2vp: invalid arguments");
3407 VP_HEXDUMP("data2vp", start, attrlen);
3409 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3414 * Hacks for CUI. The WiMAX spec says that it can be
3415 * zero length, even though this is forbidden by the
3416 * RADIUS specs. So... we make a special case for it.
3419 if (!((da->vendor == 0) &&
3420 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3427 * Hacks for Coverity. Editing the dictionary
3428 * will break assumptions about CUI. We know
3429 * this, but Coverity doesn't.
3431 if (da->type != PW_TYPE_OCTETS) return -1;
3436 goto alloc_cui; /* skip everything */
3440 * Hacks for tags. If the attribute is capable of
3441 * encoding a tag, and there's room for the tag, and
3442 * there is a tag, or it's encrypted with Tunnel-Password,
3443 * then decode the tag.
3445 if (da->flags.has_tag && (datalen > 1) &&
3446 ((data[0] < 0x20) ||
3447 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3449 * Only "short" attributes can be encrypted.
3451 if (datalen >= sizeof(buffer)) return -1;
3453 if (da->type == PW_TYPE_STRING) {
3454 memcpy(buffer, data + 1, datalen - 1);
3458 } else if (da->type == PW_TYPE_INTEGER) {
3459 memcpy(buffer, data, attrlen);
3464 return -1; /* only string and integer can have tags */
3471 * Decrypt the attribute.
3473 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3474 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3476 * Encrypted attributes can only exist for the
3477 * old-style format. Extended attributes CANNOT
3480 if (attrlen > 253) {
3484 if (data == start) {
3485 memcpy(buffer, data, attrlen);
3489 switch (da->flags.encrypt) { /* can't be tagged */
3493 case FLAG_ENCRYPT_USER_PASSWORD:
3495 rad_pwdecode((char *) buffer,
3499 rad_pwdecode((char *) buffer,
3506 * MS-CHAP-MPPE-Keys are 24 octets, and
3507 * encrypted. Since it's binary, we can't
3508 * look for trailing zeros.
3510 if (da->flags.length) {
3511 if (datalen > da->flags.length) {
3512 datalen = da->flags.length;
3513 } /* else leave datalen alone */
3516 * Take off trailing zeros from the END.
3517 * This allows passwords to have zeros in
3518 * the middle of a field.
3520 * However, if the password has a zero at
3521 * the end, it will get mashed by this
3522 * code. There's really no way around
3525 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3530 * Tunnel-Password's may go ONLY in response
3531 * packets. They can have a tag, so datalen is
3532 * not the same as attrlen.
3534 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3535 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3536 original ? original->vector : nullvector) < 0) {
3542 * Ascend-Send-Secret
3543 * Ascend-Receive-Secret
3545 case FLAG_ENCRYPT_ASCEND_SECRET:
3549 uint8_t my_digest[AUTH_VECTOR_LEN];
3550 make_secret(my_digest,
3553 memcpy(buffer, my_digest,
3555 buffer[AUTH_VECTOR_LEN] = '\0';
3556 datalen = strlen((char *) buffer);
3562 } /* switch over encryption flags */
3566 * Double-check the length after decrypting the
3569 VP_TRACE("data2vp: type %u\n", da->type);
3571 case PW_TYPE_STRING:
3572 case PW_TYPE_OCTETS:
3575 case PW_TYPE_ABINARY:
3576 if (datalen > sizeof(vp->vp_filter)) goto raw;
3579 case PW_TYPE_INTEGER:
3580 case PW_TYPE_IPV4_ADDR:
3582 case PW_TYPE_SIGNED:
3583 if (datalen != 4) goto raw;
3586 case PW_TYPE_INTEGER64:
3588 if (datalen != 8) goto raw;
3591 case PW_TYPE_IPV6_ADDR:
3592 if (datalen != 16) goto raw;
3595 case PW_TYPE_IPV6_PREFIX:
3596 if ((datalen < 2) || (datalen > 18)) goto raw;
3597 if (data[1] > 128) goto raw;
3601 if (datalen != 1) goto raw;
3605 if (datalen != 2) goto raw;
3608 case PW_TYPE_ETHERNET:
3609 if (datalen != 6) goto raw;
3612 case PW_TYPE_COMBO_IP_ADDR:
3614 child = dict_attrbytype(da->attr, da->vendor,
3616 } else if (datalen == 16) {
3617 child = dict_attrbytype(da->attr, da->vendor,
3622 if (!child) goto raw;
3623 da = child; /* re-write it */
3626 case PW_TYPE_IPV4_PREFIX:
3627 if (datalen != 6) goto raw;
3628 if ((data[1] & 0x3f) > 32) goto raw;
3632 * The rest of the data types can cause
3633 * recursion! Ask yourself, "is recursion OK?"
3636 case PW_TYPE_EXTENDED:
3637 if (datalen < 2) goto raw; /* etype, value */
3639 child = dict_attrbyparent(da, data[0], 0);
3640 if (!child) goto raw;
3643 * Recurse to decode the contents, which could be
3644 * a TLV, IPaddr, etc. Note that we decode only
3645 * the current attribute, and we ignore any extra
3648 rcode = data2vp(ctx, packet, original, secret, child,
3649 data + 1, attrlen - 1, attrlen - 1, pvp);
3650 if (rcode < 0) goto raw;
3653 case PW_TYPE_LONG_EXTENDED:
3654 if (datalen < 3) goto raw; /* etype, flags, value */
3656 child = dict_attrbyparent(da, data[0], 0);
3658 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3659 (datalen < (3 + 4 + 1))) {
3660 /* da->attr < 255, da->vendor == 0 */
3661 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3664 * Try to find the VSA.
3666 memcpy(&vendor, data + 3, 4);
3667 vendor = ntohl(vendor);
3669 if (vendor == 0) goto raw;
3671 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3675 fr_strerror_printf("Internal sanity check %d", __LINE__);
3681 * If there no more fragments, then the contents
3682 * have to be a well-known data type.
3685 if ((data[1] & 0x80) == 0) {
3686 rcode = data2vp(ctx, packet, original, secret, child,
3687 data + 2, attrlen - 2, attrlen - 2,
3689 if (rcode < 0) goto raw;
3694 * This requires a whole lot more work.
3696 return data2vp_extended(ctx, packet, original, secret, child,
3697 start, attrlen, packetlen, pvp);
3700 if (datalen < 6) goto raw; /* vid, vtype, value */
3702 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3704 memcpy(&vendor, data, 4);
3705 vendor = ntohl(vendor);
3706 vendor |= da->vendor;
3708 child = dict_attrbyvalue(data[4], vendor);
3711 * Create a "raw" attribute from the
3712 * contents of the EVS VSA.
3714 da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3720 rcode = data2vp(ctx, packet, original, secret, child,
3721 data + 5, attrlen - 5, attrlen - 5, pvp);
3722 if (rcode < 0) goto raw;
3727 * We presume that the TLVs all fit into one
3728 * attribute, OR they've already been grouped
3729 * into a contiguous memory buffer.
3731 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3732 data, attrlen, pvp);
3733 if (rcode < 0) goto raw;
3738 * VSAs can be WiMAX, in which case they don't
3739 * fit into one attribute.
3741 rcode = data2vp_vsas(ctx, packet, original, secret,
3742 data, attrlen, packetlen, pvp);
3743 if (rcode < 0) goto raw;
3749 * Re-write the attribute to be "raw". It is
3750 * therefore of type "octets", and will be
3753 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3755 fr_strerror_printf("Internal sanity check %d", __LINE__);
3763 if (da->type != PW_TYPE_OCTETS) {
3764 dict_attr_free(&da);
3772 * And now that we've verified the basic type
3773 * information, decode the actual data.
3776 vp = fr_pair_afrom_da(ctx, da);
3779 vp->vp_length = datalen;
3783 case PW_TYPE_STRING:
3784 p = talloc_array(vp, char, vp->vp_length + 1);
3785 memcpy(p, data, vp->vp_length);
3786 p[vp->vp_length] = '\0';
3787 vp->vp_strvalue = p;
3790 case PW_TYPE_OCTETS:
3791 fr_pair_value_memcpy(vp, data, vp->vp_length);
3794 case PW_TYPE_ABINARY:
3795 if (vp->vp_length > sizeof(vp->vp_filter)) {
3796 vp->vp_length = sizeof(vp->vp_filter);
3798 memcpy(vp->vp_filter, data, vp->vp_length);
3802 vp->vp_byte = data[0];
3806 vp->vp_short = (data[0] << 8) | data[1];
3809 case PW_TYPE_INTEGER:
3810 memcpy(&vp->vp_integer, data, 4);
3811 vp->vp_integer = ntohl(vp->vp_integer);
3814 case PW_TYPE_INTEGER64:
3815 memcpy(&vp->vp_integer64, data, 8);
3816 vp->vp_integer64 = ntohll(vp->vp_integer64);
3820 memcpy(&vp->vp_date, data, 4);
3821 vp->vp_date = ntohl(vp->vp_date);
3824 case PW_TYPE_ETHERNET:
3825 memcpy(vp->vp_ether, data, 6);
3828 case PW_TYPE_IPV4_ADDR:
3829 memcpy(&vp->vp_ipaddr, data, 4);
3833 memcpy(vp->vp_ifid, data, 8);
3836 case PW_TYPE_IPV6_ADDR:
3837 memcpy(&vp->vp_ipv6addr, data, 16);
3840 case PW_TYPE_IPV6_PREFIX:
3842 * FIXME: double-check that
3843 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3845 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3846 if (vp->vp_length < 18) {
3847 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3848 18 - vp->vp_length);
3852 case PW_TYPE_IPV4_PREFIX:
3853 /* FIXME: do the same double-check as for IPv6Prefix */
3854 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3857 * /32 means "keep all bits". Otherwise, mask
3860 if ((data[1] & 0x3f) > 32) {
3861 uint32_t addr, mask;
3863 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3865 mask <<= (32 - (data[1] & 0x3f));
3870 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3874 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3875 memcpy(&vp->vp_integer, buffer, 4);
3876 vp->vp_integer = ntohl(vp->vp_integer);
3880 fr_pair_list_free(&vp);
3881 fr_strerror_printf("Internal sanity check %d", __LINE__);
3891 /** Create a "normal" VALUE_PAIR from the given data
3894 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3895 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3897 uint8_t const *data, size_t length,
3902 DICT_ATTR const *da;
3904 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3905 fr_strerror_printf("rad_attr2vp: Insufficient data");
3909 da = dict_attrbyvalue(data[0], 0);
3911 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3912 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3917 * Pass the entire thing to the decoding function
3919 if (da->flags.concat) {
3920 VP_TRACE("attr2vp: concat attribute\n");
3921 return data2vp_concat(ctx, da, data, length, pvp);
3925 * Note that we pass the entire length, not just the
3926 * length of this attribute. The Extended or WiMAX
3927 * attributes may have the "continuation" bit set, and
3928 * will thus be more than one attribute in length.
3930 rcode = data2vp(ctx, packet, original, secret, da,
3931 data + 2, data[1] - 2, length - 2, pvp);
3932 if (rcode < 0) return rcode;
3937 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3939 /** Converts vp_data to network byte order
3941 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3942 * in an architecture independent format.
3944 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3945 * as the source VALUE_PAIR is not freed.
3947 * @param out where to write the pointer to the value.
3948 * @param vp to get the value from.
3949 * @return -1 on error, or the length of the value
3951 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3959 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3963 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3965 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3969 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3971 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3979 switch (vp->da->type) {
3980 case PW_TYPE_STRING:
3981 case PW_TYPE_OCTETS:
3982 memcpy(out, &vp->data.ptr, sizeof(*out));
3986 * All of these values are at the same location.
3989 case PW_TYPE_IPV4_ADDR:
3990 case PW_TYPE_IPV6_ADDR:
3991 case PW_TYPE_IPV6_PREFIX:
3992 case PW_TYPE_IPV4_PREFIX:
3993 case PW_TYPE_ABINARY:
3994 case PW_TYPE_ETHERNET:
3995 case PW_TYPE_COMBO_IP_ADDR:
3996 case PW_TYPE_COMBO_IP_PREFIX:
3998 void const *p = &vp->data;
3999 memcpy(out, &p, sizeof(*out));
4003 case PW_TYPE_BOOLEAN:
4004 buffer[0] = vp->vp_byte & 0x01;
4009 buffer[0] = vp->vp_byte & 0xff;
4014 buffer[0] = (vp->vp_short >> 8) & 0xff;
4015 buffer[1] = vp->vp_short & 0xff;
4019 case PW_TYPE_INTEGER:
4020 lvalue = htonl(vp->vp_integer);
4021 memcpy(buffer, &lvalue, sizeof(lvalue));
4025 case PW_TYPE_INTEGER64:
4026 lvalue64 = htonll(vp->vp_integer64);
4027 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4032 lvalue = htonl(vp->vp_date);
4033 memcpy(buffer, &lvalue, sizeof(lvalue));
4037 case PW_TYPE_SIGNED:
4039 int32_t slvalue = htonl(vp->vp_signed);
4040 memcpy(buffer, &slvalue, sizeof(slvalue));
4045 case PW_TYPE_INVALID:
4046 case PW_TYPE_EXTENDED:
4047 case PW_TYPE_LONG_EXTENDED:
4051 case PW_TYPE_TIMEVAL:
4053 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4056 /* Don't add default */
4059 return vp->vp_length;
4062 /** Calculate/check digest, and decode radius attributes
4064 * @return -1 on decoding error, 0 on success
4066 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4070 uint32_t num_attributes;
4072 radius_packet_t *hdr;
4073 VALUE_PAIR *head, **tail, *vp;
4076 * Extract attribute-value pairs
4078 hdr = (radius_packet_t *)packet->data;
4080 packet_length = packet->data_len - RADIUS_HDR_LEN;
4087 * Loop over the attributes, decoding them into VPs.
4089 while (packet_length > 0) {
4093 * This may return many VPs
4095 my_len = rad_attr2vp(packet, packet, original, secret,
4096 ptr, packet_length, &vp);
4098 fr_pair_list_free(&head);
4110 * VSA's may not have been counted properly in
4111 * rad_packet_ok() above, as it is hard to count
4112 * then without using the dictionary. We
4113 * therefore enforce the limits here, too.
4115 if ((fr_max_attributes > 0) &&
4116 (num_attributes > fr_max_attributes)) {
4117 char host_ipaddr[128];
4119 fr_pair_list_free(&head);
4120 fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4121 inet_ntop(packet->src_ipaddr.af,
4122 &packet->src_ipaddr.ipaddr,
4123 host_ipaddr, sizeof(host_ipaddr)),
4124 num_attributes, fr_max_attributes);
4129 packet_length -= my_len;
4133 * Merge information from the outside world into our
4136 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4139 * There may be VP's already in the packet. Don't
4140 * destroy them. Instead, add the decoded attributes to
4141 * the tail of the list.
4143 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4154 * We assume that the passwd buffer passed is big enough.
4155 * RFC2138 says the password is max 128 chars, so the size
4156 * of the passwd buffer must be at least 129 characters.
4157 * Preferably it's just MAX_STRING_LEN.
4159 * int *pwlen is updated to the new length of the encrypted
4160 * password - a multiple of 16 bytes.
4162 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4163 uint8_t const *vector)
4165 FR_MD5_CTX context, old;
4166 uint8_t digest[AUTH_VECTOR_LEN];
4167 int i, n, secretlen;
4171 * RFC maximum is 128 bytes.
4173 * If length is zero, pad it out with zeros.
4175 * If the length isn't aligned to 16 bytes,
4176 * zero out the extra data.
4180 if (len > 128) len = 128;
4183 memset(passwd, 0, AUTH_PASS_LEN);
4184 len = AUTH_PASS_LEN;
4185 } else if ((len % AUTH_PASS_LEN) != 0) {
4186 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4187 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4192 * Use the secret to setup the decryption digest
4194 secretlen = strlen(secret);
4196 fr_md5_init(&context);
4197 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4198 old = context; /* save intermediate work */
4201 * Encrypt it in place. Don't bother checking
4202 * len, as we've ensured above that it's OK.
4204 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4206 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4207 fr_md5_final(digest, &context);
4210 fr_md5_update(&context,
4211 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4213 fr_md5_final(digest, &context);
4216 for (i = 0; i < AUTH_PASS_LEN; i++) {
4217 passwd[i + n] ^= digest[i];
4227 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4228 uint8_t const *vector)
4230 FR_MD5_CTX context, old;
4231 uint8_t digest[AUTH_VECTOR_LEN];
4233 size_t n, secretlen;
4236 * The RFC's say that the maximum is 128.
4237 * The buffer we're putting it into above is 254, so
4238 * we don't need to do any length checking.
4240 if (pwlen > 128) pwlen = 128;
4245 if (pwlen == 0) goto done;
4248 * Use the secret to setup the decryption digest
4250 secretlen = strlen(secret);
4252 fr_md5_init(&context);
4253 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4254 old = context; /* save intermediate work */
4257 * The inverse of the code above.
4259 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4261 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4262 fr_md5_final(digest, &context);
4265 if (pwlen > AUTH_PASS_LEN) {
4266 fr_md5_update(&context, (uint8_t *) passwd,
4270 fr_md5_final(digest, &context);
4273 if (pwlen > (n + AUTH_PASS_LEN)) {
4274 fr_md5_update(&context, (uint8_t *) passwd + n,
4279 for (i = 0; i < AUTH_PASS_LEN; i++) {
4280 passwd[i + n] ^= digest[i];
4285 passwd[pwlen] = '\0';
4286 return strlen(passwd);
4290 /** Encode Tunnel-Password attributes when sending them out on the wire
4292 * int *pwlen is updated to the new length of the encrypted
4293 * password - a multiple of 16 bytes.
4295 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4298 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret,
4299 uint8_t const *vector)
4301 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4302 unsigned char digest[AUTH_VECTOR_LEN];
4304 int i, n, secretlen;
4309 if (len > 127) len = 127;
4312 * Shift the password 3 positions right to place a salt and original
4313 * length, tag will be added automatically on packet send.
4315 for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4320 * save original password length as first password character;
4327 * Generate salt. The RFC's say:
4329 * The high bit of salt[0] must be set, each salt in a
4330 * packet should be unique, and they should be random
4332 * So, we set the high bit, add in a counter, and then
4333 * add in some CSPRNG data. should be OK..
4335 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4336 (fr_rand() & 0x07));
4337 salt[1] = fr_rand();
4340 * Padd password to multiple of AUTH_PASS_LEN bytes.
4342 n = len % AUTH_PASS_LEN;
4344 n = AUTH_PASS_LEN - n;
4345 for (; n > 0; n--, len++)
4348 /* set new password length */
4352 * Use the secret to setup the decryption digest
4354 secretlen = strlen(secret);
4355 memcpy(buffer, secret, secretlen);
4357 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4359 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4360 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4361 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4363 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4364 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4367 for (i = 0; i < AUTH_PASS_LEN; i++) {
4368 passwd[i + n2] ^= digest[i];
4375 /** Decode Tunnel-Password encrypted attributes
4377 * Defined in RFC-2868, this uses a two char SALT along with the
4378 * initial intermediate value, to differentiate it from the
4381 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret,
4382 uint8_t const *vector)
4384 FR_MD5_CTX context, old;
4385 uint8_t digest[AUTH_VECTOR_LEN];
4387 size_t i, n, encrypted_len, reallen;
4389 encrypted_len = *pwlen;
4392 * We need at least a salt.
4394 if (encrypted_len < 2) {
4395 fr_strerror_printf("tunnel password is too short");
4400 * There's a salt, but no password. Or, there's a salt
4401 * and a 'data_len' octet. It's wrong, but at least we
4402 * can figure out what it means: the password is empty.
4404 * Note that this means we ignore the 'data_len' field,
4405 * if the attribute length tells us that there's no
4406 * more data. So the 'data_len' field may be wrong,
4409 if (encrypted_len <= 3) {
4415 encrypted_len -= 2; /* discount the salt */
4418 * Use the secret to setup the decryption digest
4420 secretlen = strlen(secret);
4422 fr_md5_init(&context);
4423 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4424 old = context; /* save intermediate work */
4427 * Set up the initial key:
4429 * b(1) = MD5(secret + vector + salt)
4431 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4432 fr_md5_update(&context, passwd, 2);
4435 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4437 size_t block_len = AUTH_PASS_LEN;
4440 * Ensure we don't overflow the input on MD5
4442 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4443 block_len = *pwlen - n - 2;
4449 fr_md5_final(digest, &context);
4454 * A quick check: decrypt the first octet
4455 * of the password, which is the
4456 * 'data_len' field. Ensure it's sane.
4458 reallen = passwd[2] ^ digest[0];
4459 if (reallen > encrypted_len) {
4460 fr_strerror_printf("tunnel password is too long for the attribute");
4464 fr_md5_update(&context, passwd + 2, block_len);
4469 fr_md5_final(digest, &context);
4472 fr_md5_update(&context, passwd + n + 2, block_len);
4475 for (i = base; i < block_len; i++) {
4476 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4481 passwd[reallen] = 0;
4486 /** Encode a CHAP password
4488 * @bug FIXME: might not work with Ascend because
4489 * we use vp->vp_length, and Ascend gear likes
4490 * to send an extra '\0' in the string!
4492 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4493 VALUE_PAIR *password)
4497 uint8_t string[MAX_STRING_LEN * 2 + 1];
4498 VALUE_PAIR *challenge;
4501 * Sanity check the input parameters
4503 if ((packet == NULL) || (password == NULL)) {
4508 * Note that the password VP can be EITHER
4509 * a User-Password attribute (from a check-item list),
4510 * or a CHAP-Password attribute (the client asking
4511 * the library to encode it).
4519 memcpy(ptr, password->vp_strvalue, password->vp_length);
4520 ptr += password->vp_length;
4521 i += password->vp_length;
4524 * Use Chap-Challenge pair if present,
4525 * Request Authenticator otherwise.
4527 challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4529 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4530 i += challenge->vp_length;
4532 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4533 i += AUTH_VECTOR_LEN;
4537 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4543 /** Seed the random number generator
4545 * May be called any number of times.
4547 void fr_rand_seed(void const *data, size_t size)
4552 * Ensure that the pool is initialized.
4554 if (!fr_rand_initialized) {
4557 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4559 fd = open("/dev/urandom", O_RDONLY);
4565 while (total < sizeof(fr_rand_pool.randrsl)) {
4566 this = read(fd, fr_rand_pool.randrsl,
4567 sizeof(fr_rand_pool.randrsl) - total);
4568 if ((this < 0) && (errno != EINTR)) break;
4569 if (this > 0) total += this;
4573 fr_rand_pool.randrsl[0] = fd;
4574 fr_rand_pool.randrsl[1] = time(NULL);
4575 fr_rand_pool.randrsl[2] = errno;
4578 fr_randinit(&fr_rand_pool, 1);
4579 fr_rand_pool.randcnt = 0;
4580 fr_rand_initialized = 1;
4586 * Hash the user data
4589 if (!hash) hash = fr_rand();
4590 hash = fr_hash_update(data, size, hash);
4592 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4596 /** Return a 32-bit random number
4599 uint32_t fr_rand(void)
4604 * Ensure that the pool is initialized.
4606 if (!fr_rand_initialized) {
4607 fr_rand_seed(NULL, 0);
4610 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4611 if (fr_rand_pool.randcnt >= 256) {
4612 fr_rand_pool.randcnt = 0;
4613 fr_isaac(&fr_rand_pool);
4620 /** Allocate a new RADIUS_PACKET
4622 * @param ctx the context in which the packet is allocated. May be NULL if
4623 * the packet is not associated with a REQUEST.
4624 * @param new_vector if true a new request authenticator will be generated.
4625 * @return a new RADIUS_PACKET or NULL on error.
4627 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4631 rp = talloc_zero(ctx, RADIUS_PACKET);
4633 fr_strerror_printf("out of memory");
4641 uint32_t hash, base;
4644 * Don't expose the actual contents of the random
4648 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4649 hash = fr_rand() ^ base;
4650 memcpy(rp->vector + i, &hash, sizeof(hash));
4653 fr_rand(); /* stir the pool again */
4658 /** Allocate a new RADIUS_PACKET response
4660 * @param ctx the context in which the packet is allocated. May be NULL if
4661 * the packet is not associated with a REQUEST.
4662 * @param packet The request packet.
4663 * @return a new RADIUS_PACKET or NULL on error.
4665 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4667 RADIUS_PACKET *reply;
4669 if (!packet) return NULL;
4671 reply = rad_alloc(ctx, false);
4672 if (!reply) return NULL;
4675 * Initialize the fields from the request.
4677 reply->sockfd = packet->sockfd;
4678 reply->dst_ipaddr = packet->src_ipaddr;
4679 reply->src_ipaddr = packet->dst_ipaddr;
4680 reply->dst_port = packet->src_port;
4681 reply->src_port = packet->dst_port;
4682 reply->id = packet->id;
4683 reply->code = 0; /* UNKNOWN code */
4684 memcpy(reply->vector, packet->vector,
4685 sizeof(reply->vector));
4688 reply->data_len = 0;
4691 reply->proto = packet->proto;
4697 /** Free a RADIUS_PACKET
4700 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4702 RADIUS_PACKET *radius_packet;
4704 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4705 radius_packet = *radius_packet_ptr;
4707 VERIFY_PACKET(radius_packet);
4709 fr_pair_list_free(&radius_packet->vps);
4711 talloc_free(radius_packet);
4712 *radius_packet_ptr = NULL;
4715 /** Duplicate a RADIUS_PACKET
4717 * @param ctx the context in which the packet is allocated. May be NULL if
4718 * the packet is not associated with a REQUEST.
4719 * @param in The packet to copy
4720 * @return a new RADIUS_PACKET or NULL on error.
4722 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4726 out = rad_alloc(ctx, false);
4727 if (!out) return NULL;
4730 * Bootstrap by copying everything.
4732 memcpy(out, in, sizeof(*out));
4735 * Then reset necessary fields
4742 out->vps = fr_pair_list_copy(out, in->vps);