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 const *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("Unknown 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 for attribute %s", vp->da->name);
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 * Set up the authentication vector with zero, or with
1935 * the original vector, prior to signing.
1937 switch (packet->code) {
1938 case PW_CODE_ACCOUNTING_RESPONSE:
1939 if (original && original->code == PW_CODE_STATUS_SERVER) {
1943 case PW_CODE_ACCOUNTING_REQUEST:
1944 case PW_CODE_DISCONNECT_REQUEST:
1945 case PW_CODE_DISCONNECT_ACK:
1946 case PW_CODE_DISCONNECT_NAK:
1947 case PW_CODE_COA_REQUEST:
1948 case PW_CODE_COA_ACK:
1949 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1950 memset(packet->vector, 0, AUTH_VECTOR_LEN);
1954 case PW_CODE_ACCESS_ACCEPT:
1955 case PW_CODE_ACCESS_REJECT:
1956 case PW_CODE_ACCESS_CHALLENGE:
1958 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet");
1961 memcpy(hdr->vector, original->vector, AUTH_VECTOR_LEN);
1962 memcpy(packet->vector, original->vector, AUTH_VECTOR_LEN);
1965 default: /* others have vector already set to whatever */
1970 * If there's a Message-Authenticator, update it
1971 * now, using the zero / original authentication vector.
1973 if (packet->offset > 0) {
1974 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1977 * Set the authentication vector to zero,
1978 * calculate the HMAC, and put it
1979 * into the Message-Authenticator
1982 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
1983 (uint8_t const *) secret, strlen(secret));
1984 memcpy(packet->data + packet->offset + 2,
1985 calc_auth_vector, AUTH_VECTOR_LEN);
1988 * Copy the request vector back
1989 * to the raw packet.
1991 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1995 * Switch over the packet code, deciding how to
1998 switch (packet->code) {
2000 * Request packets are not signed, but
2001 * have a random authentication vector.
2003 case PW_CODE_ACCESS_REQUEST:
2004 case PW_CODE_STATUS_SERVER:
2008 * Reply packets are signed with the
2009 * authentication vector of the request.
2016 fr_md5_init(&context);
2017 fr_md5_update(&context, packet->data, packet->data_len);
2018 fr_md5_update(&context, (uint8_t const *) secret,
2020 fr_md5_final(digest, &context);
2022 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
2023 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
2026 }/* switch over packet codes */
2031 /** Reply to the request
2033 * Also attach reply attribute value pairs and any user message provided.
2035 int rad_send(RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2039 * Maybe it's a fake packet. Don't send it.
2041 if (!packet || (packet->sockfd < 0)) {
2046 * First time through, allocate room for the packet
2048 if (!packet->data) {
2050 * Encode the packet.
2052 if (rad_encode(packet, original, secret) < 0) {
2057 * Re-sign it, including updating the
2058 * Message-Authenticator.
2060 if (rad_sign(packet, original, secret) < 0) {
2065 * If packet->data points to data, then we print out
2066 * the VP list again only for debugging.
2071 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2076 * If the socket is TCP, call write(). Calling sendto()
2077 * is allowed on some platforms, but it's not nice. Even
2078 * worse, if UDPFROMTO is defined, we *can't* use it on
2079 * TCP sockets. So... just call write().
2081 if (packet->proto == IPPROTO_TCP) {
2084 rcode = write(packet->sockfd, packet->data, packet->data_len);
2085 if (rcode >= 0) return rcode;
2087 fr_strerror_printf("sendto failed: %s", fr_syserror(errno));
2093 * And send it on it's way.
2095 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
2096 &packet->src_ipaddr, packet->src_port,
2097 &packet->dst_ipaddr, packet->dst_port);
2100 /** Do a comparison of two authentication digests by comparing the FULL digest
2102 * Otherwise, the server can be subject to timing attacks that allow attackers
2103 * find a valid message authenticator.
2105 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
2107 int rad_digest_cmp(uint8_t const *a, uint8_t const *b, size_t length)
2112 for (i = 0; i < length; i++) {
2113 result |= a[i] ^ b[i];
2116 return result; /* 0 is OK, !0 is !OK, just like memcmp */
2120 /** Validates the requesting client NAS
2122 * Calculates the request Authenticator based on the clients private key.
2124 static int calc_acctdigest(RADIUS_PACKET *packet, char const *secret)
2126 uint8_t digest[AUTH_VECTOR_LEN];
2130 * Zero out the auth_vector in the received packet.
2131 * Then append the shared secret to the received packet,
2132 * and calculate the MD5 sum. This must be the same
2133 * as the original MD5 sum (packet->vector).
2135 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2138 * MD5(packet + secret);
2140 fr_md5_init(&context);
2141 fr_md5_update(&context, packet->data, packet->data_len);
2142 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2143 fr_md5_final(digest, &context);
2146 * Return 0 if OK, 2 if not OK.
2148 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
2153 /** Validates the requesting client NAS
2155 * Calculates the response Authenticator based on the clients
2158 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2161 uint8_t calc_digest[AUTH_VECTOR_LEN];
2167 if (original == NULL) {
2172 * Copy the original vector in place.
2174 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2177 * MD5(packet + secret);
2179 fr_md5_init(&context);
2180 fr_md5_update(&context, packet->data, packet->data_len);
2181 fr_md5_update(&context, (uint8_t const *) secret, strlen(secret));
2182 fr_md5_final(calc_digest, &context);
2185 * Copy the packet's vector back to the packet.
2187 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2190 * Return 0 if OK, 2 if not OK.
2192 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
2196 /** Check if a set of RADIUS formatted TLVs are OK
2199 int rad_tlv_ok(uint8_t const *data, size_t length,
2200 size_t dv_type, size_t dv_length)
2202 uint8_t const *end = data + length;
2204 VP_TRACE("checking TLV %u/%u\n", (unsigned int) dv_type, (unsigned int) dv_length);
2206 VP_HEXDUMP("tlv_ok", data, length);
2208 if ((dv_length > 2) || (dv_type == 0) || (dv_type > 4)) {
2209 fr_strerror_printf("rad_tlv_ok: Invalid arguments");
2213 while (data < end) {
2216 if ((data + dv_type + dv_length) > end) {
2217 fr_strerror_printf("Attribute header overflow");
2223 if ((data[0] == 0) && (data[1] == 0) &&
2224 (data[2] == 0) && (data[3] == 0)) {
2226 fr_strerror_printf("Invalid attribute 0");
2231 fr_strerror_printf("Invalid attribute > 2^24");
2237 if ((data[0] == 0) && (data[1] == 0)) goto zero;
2242 * Zero is allowed, because the Colubris
2243 * people are dumb and use it.
2248 fr_strerror_printf("Internal sanity check failed");
2252 switch (dv_length) {
2257 if (data[dv_type] != 0) {
2258 fr_strerror_printf("Attribute is longer than 256 octets");
2263 attrlen = data[dv_type + dv_length - 1];
2268 fr_strerror_printf("Internal sanity check failed");
2272 if (attrlen < (dv_type + dv_length)) {
2273 fr_strerror_printf("Attribute header has invalid length");
2277 if (attrlen > length) {
2278 fr_strerror_printf("Attribute overflows container");
2290 /** See if the data pointed to by PTR is a valid RADIUS packet.
2292 * Packet is not 'const * const' because we may update data_len, if there's more data
2293 * in the UDP packet than in the RADIUS packet.
2295 * @param packet to check
2296 * @param flags to control decoding
2297 * @param reason if not NULL, will have the failure reason written to where it points.
2298 * @return bool, true on success, false on failure.
2300 bool rad_packet_ok(RADIUS_PACKET *packet, int flags, decode_fail_t *reason)
2305 radius_packet_t *hdr;
2306 char host_ipaddr[128];
2307 bool require_ma = false;
2308 bool seen_ma = false;
2309 uint32_t num_attributes;
2310 decode_fail_t failure = DECODE_FAIL_NONE;
2313 * Check for packets smaller than the packet header.
2315 * RFC 2865, Section 3., subsection 'length' says:
2317 * "The minimum length is 20 ..."
2319 if (packet->data_len < RADIUS_HDR_LEN) {
2320 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (received %zu < minimum %d)",
2321 inet_ntop(packet->src_ipaddr.af,
2322 &packet->src_ipaddr.ipaddr,
2323 host_ipaddr, sizeof(host_ipaddr)),
2324 packet->data_len, RADIUS_HDR_LEN);
2325 failure = DECODE_FAIL_MIN_LENGTH_PACKET;
2331 * Check for packets with mismatched size.
2332 * i.e. We've received 128 bytes, and the packet header
2333 * says it's 256 bytes long.
2335 totallen = (packet->data[2] << 8) | packet->data[3];
2336 hdr = (radius_packet_t *)packet->data;
2339 * Code of 0 is not understood.
2340 * Code of 16 or greate is not understood.
2342 if ((hdr->code == 0) ||
2343 (hdr->code >= FR_MAX_PACKET_CODE)) {
2344 FR_DEBUG_STRERROR_PRINTF("Bad RADIUS packet from host %s: unknown packet code %d",
2345 inet_ntop(packet->src_ipaddr.af,
2346 &packet->src_ipaddr.ipaddr,
2347 host_ipaddr, sizeof(host_ipaddr)),
2349 failure = DECODE_FAIL_UNKNOWN_PACKET_CODE;
2354 * Message-Authenticator is required in Status-Server
2355 * packets, otherwise they can be trivially forged.
2357 if (hdr->code == PW_CODE_STATUS_SERVER) require_ma = true;
2360 * It's also required if the caller asks for it.
2362 if (flags) require_ma = true;
2365 * Repeat the length checks. This time, instead of
2366 * looking at the data we received, look at the value
2367 * of the 'length' field inside of the packet.
2369 * Check for packets smaller than the packet header.
2371 * RFC 2865, Section 3., subsection 'length' says:
2373 * "The minimum length is 20 ..."
2375 if (totallen < RADIUS_HDR_LEN) {
2376 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: too short (length %zu < minimum %d)",
2377 inet_ntop(packet->src_ipaddr.af,
2378 &packet->src_ipaddr.ipaddr,
2379 host_ipaddr, sizeof(host_ipaddr)),
2380 totallen, RADIUS_HDR_LEN);
2381 failure = DECODE_FAIL_MIN_LENGTH_FIELD;
2386 * And again, for the value of the 'length' field.
2388 * RFC 2865, Section 3., subsection 'length' says:
2390 * " ... and maximum length is 4096."
2392 * HOWEVER. This requirement is for the network layer.
2393 * If the code gets here, we assume that a well-formed
2394 * packet is an OK packet.
2396 * We allow both the UDP data length, and the RADIUS
2397 * "length" field to contain up to 64K of data.
2401 * RFC 2865, Section 3., subsection 'length' says:
2403 * "If the packet is shorter than the Length field
2404 * indicates, it MUST be silently discarded."
2406 * i.e. No response to the NAS.
2408 if (packet->data_len < totallen) {
2409 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: received %zu octets, packet length says %zu",
2410 inet_ntop(packet->src_ipaddr.af,
2411 &packet->src_ipaddr.ipaddr,
2412 host_ipaddr, sizeof(host_ipaddr)),
2413 packet->data_len, totallen);
2414 failure = DECODE_FAIL_MIN_LENGTH_MISMATCH;
2419 * RFC 2865, Section 3., subsection 'length' says:
2421 * "Octets outside the range of the Length field MUST be
2422 * treated as padding and ignored on reception."
2424 if (packet->data_len > totallen) {
2426 * We're shortening the packet below, but just
2427 * to be paranoid, zero out the extra data.
2429 memset(packet->data + totallen, 0, packet->data_len - totallen);
2430 packet->data_len = totallen;
2434 * Walk through the packet's attributes, ensuring that
2435 * they add up EXACTLY to the size of the packet.
2437 * If they don't, then the attributes either under-fill
2438 * or over-fill the packet. Any parsing of the packet
2439 * is impossible, and will result in unknown side effects.
2441 * This would ONLY happen with buggy RADIUS implementations,
2442 * or with an intentional attack. Either way, we do NOT want
2443 * to be vulnerable to this problem.
2446 count = totallen - RADIUS_HDR_LEN;
2451 * We need at least 2 bytes to check the
2455 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute header overflows the packet",
2456 inet_ntop(packet->src_ipaddr.af,
2457 &packet->src_ipaddr.ipaddr,
2458 host_ipaddr, sizeof(host_ipaddr)));
2459 failure = DECODE_FAIL_HEADER_OVERFLOW;
2464 * Attribute number zero is NOT defined.
2467 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Invalid attribute 0",
2468 inet_ntop(packet->src_ipaddr.af,
2469 &packet->src_ipaddr.ipaddr,
2470 host_ipaddr, sizeof(host_ipaddr)));
2471 failure = DECODE_FAIL_INVALID_ATTRIBUTE;
2476 * Attributes are at LEAST as long as the ID & length
2477 * fields. Anything shorter is an invalid attribute.
2480 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u too short",
2481 inet_ntop(packet->src_ipaddr.af,
2482 &packet->src_ipaddr.ipaddr,
2483 host_ipaddr, sizeof(host_ipaddr)),
2485 failure = DECODE_FAIL_ATTRIBUTE_TOO_SHORT;
2490 * If there are fewer bytes in the packet than in the
2491 * attribute, it's a bad packet.
2493 if (count < attr[1]) {
2494 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
2495 inet_ntop(packet->src_ipaddr.af,
2496 &packet->src_ipaddr.ipaddr,
2497 host_ipaddr, sizeof(host_ipaddr)),
2499 failure = DECODE_FAIL_ATTRIBUTE_OVERFLOW;
2504 * Sanity check the attributes for length.
2507 default: /* don't do anything by default */
2511 * If there's an EAP-Message, we require
2512 * a Message-Authenticator.
2514 case PW_EAP_MESSAGE:
2518 case PW_MESSAGE_AUTHENTICATOR:
2519 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
2520 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
2521 inet_ntop(packet->src_ipaddr.af,
2522 &packet->src_ipaddr.ipaddr,
2523 host_ipaddr, sizeof(host_ipaddr)),
2525 failure = DECODE_FAIL_MA_INVALID_LENGTH;
2533 * FIXME: Look up the base 255 attributes in the
2534 * dictionary, and switch over their type. For
2535 * integer/date/ip, the attribute length SHOULD
2538 count -= attr[1]; /* grab the attribute length */
2540 num_attributes++; /* seen one more attribute */
2544 * If the attributes add up to a packet, it's allowed.
2546 * If not, we complain, and throw the packet away.
2549 FR_DEBUG_STRERROR_PRINTF("Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
2550 inet_ntop(packet->src_ipaddr.af,
2551 &packet->src_ipaddr.ipaddr,
2552 host_ipaddr, sizeof(host_ipaddr)));
2553 failure = DECODE_FAIL_ATTRIBUTE_UNDERFLOW;
2558 * If we're configured to look for a maximum number of
2559 * attributes, and we've seen more than that maximum,
2560 * then throw the packet away, as a possible DoS.
2562 if ((fr_max_attributes > 0) &&
2563 (num_attributes > fr_max_attributes)) {
2564 FR_DEBUG_STRERROR_PRINTF("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2565 inet_ntop(packet->src_ipaddr.af,
2566 &packet->src_ipaddr.ipaddr,
2567 host_ipaddr, sizeof(host_ipaddr)),
2568 num_attributes, fr_max_attributes);
2569 failure = DECODE_FAIL_TOO_MANY_ATTRIBUTES;
2574 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
2576 * A packet with an EAP-Message attribute MUST also have
2577 * a Message-Authenticator attribute.
2579 * A Message-Authenticator all by itself is OK, though.
2581 * Similarly, Status-Server packets MUST contain
2582 * Message-Authenticator attributes.
2584 if (require_ma && !seen_ma) {
2585 FR_DEBUG_STRERROR_PRINTF("Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
2586 inet_ntop(packet->src_ipaddr.af,
2587 &packet->src_ipaddr.ipaddr,
2588 host_ipaddr, sizeof(host_ipaddr)));
2589 failure = DECODE_FAIL_MA_MISSING;
2594 * Fill RADIUS header fields
2596 packet->code = hdr->code;
2597 packet->id = hdr->id;
2598 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
2606 return (failure == DECODE_FAIL_NONE);
2610 /** Receive UDP client requests, and fill in the basics of a RADIUS_PACKET structure
2613 RADIUS_PACKET *rad_recv(TALLOC_CTX *ctx, int fd, int flags)
2617 RADIUS_PACKET *packet;
2620 * Allocate the new request data structure
2622 packet = rad_alloc(ctx, false);
2624 fr_strerror_printf("out of memory");
2629 sock_flags = MSG_PEEK;
2633 data_len = rad_recvfrom(fd, packet, sock_flags,
2634 &packet->src_ipaddr, &packet->src_port,
2635 &packet->dst_ipaddr, &packet->dst_port);
2638 * Check for socket errors.
2641 FR_DEBUG_STRERROR_PRINTF("Error receiving packet: %s", fr_syserror(errno));
2642 /* packet->data is NULL */
2646 packet->data_len = data_len; /* unsigned vs signed */
2649 * If the packet is too big, then rad_recvfrom did NOT
2650 * allocate memory. Instead, it just discarded the
2653 if (packet->data_len > MAX_PACKET_LEN) {
2654 FR_DEBUG_STRERROR_PRINTF("Discarding packet: Larger than RFC limitation of 4096 bytes");
2655 /* packet->data is NULL */
2661 * Read no data. Continue.
2662 * This check is AFTER the MAX_PACKET_LEN check above, because
2663 * if the packet is larger than MAX_PACKET_LEN, we also have
2664 * packet->data == NULL
2666 if ((packet->data_len == 0) || !packet->data) {
2667 FR_DEBUG_STRERROR_PRINTF("Empty packet: Socket is not ready");
2673 * See if it's a well-formed RADIUS packet.
2675 if (!rad_packet_ok(packet, flags, NULL)) {
2681 * Remember which socket we read the packet from.
2683 packet->sockfd = fd;
2686 * FIXME: Do even more filtering by only permitting
2687 * certain IP's. The problem is that we don't know
2688 * how to do this properly for all possible clients...
2692 * Explicitely set the VP list to empty.
2697 if ((fr_debug_lvl > 3) && fr_log_fp) rad_print_hex(packet);
2704 /** Verify the Request/Response Authenticator (and Message-Authenticator if present) of a packet
2707 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original, char const *secret)
2715 if (!packet || !packet->data) return -1;
2718 * Before we allocate memory for the attributes, do more
2721 ptr = packet->data + RADIUS_HDR_LEN;
2722 length = packet->data_len - RADIUS_HDR_LEN;
2723 while (length > 0) {
2724 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2725 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2730 default: /* don't do anything. */
2734 * Note that more than one Message-Authenticator
2735 * attribute is invalid.
2737 case PW_MESSAGE_AUTHENTICATOR:
2738 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2739 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2741 switch (packet->code) {
2745 case PW_CODE_ACCOUNTING_RESPONSE:
2747 (original->code == PW_CODE_STATUS_SERVER)) {
2751 case PW_CODE_ACCOUNTING_REQUEST:
2752 case PW_CODE_DISCONNECT_REQUEST:
2753 case PW_CODE_COA_REQUEST:
2754 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2758 case PW_CODE_ACCESS_ACCEPT:
2759 case PW_CODE_ACCESS_REJECT:
2760 case PW_CODE_ACCESS_CHALLENGE:
2761 case PW_CODE_DISCONNECT_ACK:
2762 case PW_CODE_DISCONNECT_NAK:
2763 case PW_CODE_COA_ACK:
2764 case PW_CODE_COA_NAK:
2766 fr_strerror_printf("Cannot validate Message-Authenticator in response "
2767 "packet without a request packet");
2770 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2774 fr_hmac_md5(calc_auth_vector, packet->data, packet->data_len,
2775 (uint8_t const *) secret, strlen(secret));
2776 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2777 sizeof(calc_auth_vector)) != 0) {
2778 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! "
2779 "(Shared secret is incorrect.)",
2780 inet_ntop(packet->src_ipaddr.af,
2781 &packet->src_ipaddr.ipaddr,
2782 buffer, sizeof(buffer)));
2783 /* Silently drop packet, according to RFC 3579 */
2785 } /* else the message authenticator was good */
2788 * Reinitialize Authenticators.
2790 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2791 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2793 } /* switch over the attributes */
2797 } /* loop over the packet, sanity checking the attributes */
2800 * It looks like a RADIUS packet, but we don't know what it is
2801 * so can't validate the authenticators.
2803 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2804 fr_strerror_printf("Received Unknown packet code %d "
2805 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2807 inet_ntop(packet->src_ipaddr.af,
2808 &packet->src_ipaddr.ipaddr,
2809 buffer, sizeof(buffer)),
2815 * Calculate and/or verify Request or Response Authenticator.
2817 switch (packet->code) {
2818 case PW_CODE_ACCESS_REQUEST:
2819 case PW_CODE_STATUS_SERVER:
2821 * The authentication vector is random
2822 * nonsense, invented by the client.
2826 case PW_CODE_COA_REQUEST:
2827 case PW_CODE_DISCONNECT_REQUEST:
2828 case PW_CODE_ACCOUNTING_REQUEST:
2829 if (calc_acctdigest(packet, secret) > 1) {
2830 fr_strerror_printf("Received %s packet "
2831 "from client %s with invalid Request Authenticator! "
2832 "(Shared secret is incorrect.)",
2833 fr_packet_codes[packet->code],
2834 inet_ntop(packet->src_ipaddr.af,
2835 &packet->src_ipaddr.ipaddr,
2836 buffer, sizeof(buffer)));
2841 /* Verify the reply digest */
2842 case PW_CODE_ACCESS_ACCEPT:
2843 case PW_CODE_ACCESS_REJECT:
2844 case PW_CODE_ACCESS_CHALLENGE:
2845 case PW_CODE_ACCOUNTING_RESPONSE:
2846 case PW_CODE_DISCONNECT_ACK:
2847 case PW_CODE_DISCONNECT_NAK:
2848 case PW_CODE_COA_ACK:
2849 case PW_CODE_COA_NAK:
2850 rcode = calc_replydigest(packet, original, secret);
2852 fr_strerror_printf("Received %s packet "
2853 "from home server %s port %d with invalid Response Authenticator! "
2854 "(Shared secret is incorrect.)",
2855 fr_packet_codes[packet->code],
2856 inet_ntop(packet->src_ipaddr.af,
2857 &packet->src_ipaddr.ipaddr,
2858 buffer, sizeof(buffer)),
2865 fr_strerror_printf("Received Unknown packet code %d "
2866 "from client %s port %d: Cannot validate Request/Response Authenticator",
2868 inet_ntop(packet->src_ipaddr.af,
2869 &packet->src_ipaddr.ipaddr,
2870 buffer, sizeof(buffer)),
2879 /** Convert a "concatenated" attribute to one long VP
2882 static ssize_t data2vp_concat(TALLOC_CTX *ctx,
2883 DICT_ATTR const *da, uint8_t const *start,
2884 size_t const packetlen, VALUE_PAIR **pvp)
2888 uint8_t const *ptr = start;
2889 uint8_t const *end = start + packetlen;
2897 * The packet has already been sanity checked, so we
2898 * don't care about walking off of the end of it.
2901 total += ptr[1] - 2;
2906 * Attributes MUST be consecutive.
2908 if (ptr[0] != attr) break;
2911 vp = fr_pair_afrom_da(ctx, da);
2914 vp->vp_length = total;
2915 vp->vp_octets = p = talloc_array(vp, uint8_t, vp->vp_length);
2917 fr_pair_list_free(&vp);
2923 while (total < vp->vp_length) {
2924 memcpy(p, ptr + 2, ptr[1] - 2);
2926 total += ptr[1] - 2;
2935 /** Convert TLVs to one or more VPs
2938 ssize_t rad_data2vp_tlvs(TALLOC_CTX *ctx,
2939 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
2940 char const *secret, DICT_ATTR const *da,
2941 uint8_t const *start, size_t length,
2944 uint8_t const *data = start;
2945 DICT_ATTR const *child;
2946 VALUE_PAIR *head, **tail;
2948 if (length < 3) return -1; /* type, length, value */
2950 VP_HEXDUMP("tlvs", data, length);
2952 if (rad_tlv_ok(data, length, 1, 1) < 0) return -1;
2957 while (data < (start + length)) {
2960 child = dict_attrbyparent(da, data[0], da->vendor);
2962 unsigned int my_attr, my_vendor;
2964 VP_TRACE("Failed to find child %u of TLV %s\n",
2968 * Get child attr/vendor so that
2969 * we can call unknown attr.
2972 my_vendor = da->vendor;
2974 if (!dict_attr_child(da, &my_attr, &my_vendor)) {
2975 fr_pair_list_free(&head);
2979 child = dict_unknown_afrom_fields(ctx, my_attr, my_vendor);
2981 fr_pair_list_free(&head);
2986 tlv_len = data2vp(ctx, packet, original, secret, child,
2987 data + 2, data[1] - 2, data[1] - 2, tail);
2989 fr_pair_list_free(&head);
2992 if (*tail) tail = &((*tail)->next);
3000 /** Convert a top-level VSA to a VP.
3002 * "length" can be LONGER than just this sub-vsa.
3004 static ssize_t data2vp_vsa(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3005 RADIUS_PACKET const *original,
3006 char const *secret, DICT_VENDOR *dv,
3007 uint8_t const *data, size_t length,
3010 unsigned int attribute;
3011 ssize_t attrlen, my_len;
3012 DICT_ATTR const *da;
3014 VP_TRACE("data2vp_vsa: length %u\n", (unsigned int) length);
3017 if (length <= (dv->type + dv->length)) {
3018 fr_strerror_printf("data2vp_vsa: Failure to call rad_tlv_ok");
3025 /* data[0] must be zero */
3026 attribute = data[1] << 16;
3027 attribute |= data[2] << 8;
3028 attribute |= data[3];
3032 attribute = data[0] << 8;
3033 attribute |= data[1];
3037 attribute = data[0];
3041 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3045 switch (dv->length) {
3047 /* data[dv->type] must be zero, from rad_tlv_ok() */
3048 attrlen = data[dv->type + 1];
3052 attrlen = data[dv->type];
3060 fr_strerror_printf("data2vp_vsa: Internal sanity check failed");
3065 * See if the VSA is known.
3067 da = dict_attrbyvalue(attribute, dv->vendorpec);
3068 if (!da) da = dict_unknown_afrom_fields(ctx, attribute, dv->vendorpec);
3071 my_len = data2vp(ctx, packet, original, secret, da,
3072 data + dv->type + dv->length,
3073 attrlen - (dv->type + dv->length),
3074 attrlen - (dv->type + dv->length),
3076 if (my_len < 0) return my_len;
3082 /** Convert a fragmented extended attr to a VP
3092 * But for the first fragment, we get passed a pointer to the "extended-attr"
3094 static ssize_t data2vp_extended(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3095 RADIUS_PACKET const *original,
3096 char const *secret, DICT_ATTR const *da,
3097 uint8_t const *data,
3098 size_t attrlen, size_t packetlen,
3103 uint8_t *head, *tail;
3104 uint8_t const *frag, *end;
3105 uint8_t const *attr;
3109 if (attrlen < 3) return -1;
3112 * Calculate the length of all of the fragments. For
3113 * now, they MUST be contiguous in the packet, and they
3114 * MUST be all of the same TYPE and EXTENDED-TYPE
3117 fraglen = attrlen - 2;
3118 frag = data + attrlen;
3119 end = data + packetlen;
3123 while (frag < end) {
3125 (frag[0] != attr[0]) ||
3126 (frag[1] < 4) || /* too short for long-extended */
3127 (frag[2] != attr[2]) ||
3128 ((frag + frag[1]) > end)) { /* overflow */
3133 last_frag = ((frag[3] & 0x80) == 0);
3135 fraglen += frag[1] - 4;
3140 head = tail = malloc(fraglen);
3141 if (!head) return -1;
3143 VP_TRACE("Fragments %d, total length %d\n", fragments, (int) fraglen);
3146 * And again, but faster and looser.
3148 * We copy the first fragment, followed by the rest of
3153 while (fragments > 0) {
3154 memcpy(tail, frag + 4, frag[1] - 4);
3155 tail += frag[1] - 4;
3160 VP_HEXDUMP("long-extended fragments", head, fraglen);
3162 rcode = data2vp(ctx, packet, original, secret, da,
3163 head, fraglen, fraglen, pvp);
3165 if (rcode < 0) return rcode;
3170 /** Convert a Vendor-Specific WIMAX to vps
3172 * @note Called ONLY for Vendor-Specific
3174 static ssize_t data2vp_wimax(TALLOC_CTX *ctx,
3175 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3176 char const *secret, uint32_t vendor,
3177 uint8_t const *data,
3178 size_t attrlen, size_t packetlen,
3184 uint8_t *head, *tail;
3185 uint8_t const *frag, *end;
3186 DICT_ATTR const *child;
3188 if (attrlen < 8) return -1;
3190 if (((size_t) (data[5] + 4)) != attrlen) return -1;
3192 child = dict_attrbyvalue(data[4], vendor);
3193 if (!child) return -1;
3195 if ((data[6] & 0x80) == 0) {
3196 rcode = data2vp(ctx, packet, original, secret, child,
3197 data + 7, data[5] - 3, data[5] - 3,
3199 if (rcode < 0) return -1;
3204 * Calculate the length of all of the fragments. For
3205 * now, they MUST be contiguous in the packet, and they
3206 * MUST be all of the same VSA, WiMAX, and WiMAX-attr.
3208 * The first fragment doesn't have a RADIUS attribute
3209 * header, so it needs to be treated a little special.
3211 fraglen = data[5] - 3;
3212 frag = data + attrlen;
3213 end = data + packetlen;
3216 while (frag < end) {
3218 (frag[0] != PW_VENDOR_SPECIFIC) ||
3219 (frag[1] < 9) || /* too short for wimax */
3220 ((frag + frag[1]) > end) || /* overflow */
3221 (memcmp(frag + 2, data, 4) != 0) || /* not wimax */
3222 (frag[6] != data[4]) || /* not the same wimax attr */
3223 ((frag[7] + 6) != frag[1])) { /* doesn't fill the attr */
3228 last_frag = ((frag[8] & 0x80) == 0);
3230 fraglen += frag[7] - 3;
3234 head = tail = malloc(fraglen);
3235 if (!head) return -1;
3238 * And again, but faster and looser.
3240 * We copy the first fragment, followed by the rest of
3245 memcpy(tail, frag + 4 + 3, frag[4 + 1] - 3);
3246 tail += frag[4 + 1] - 3;
3247 frag += attrlen; /* should be frag[1] - 7 */
3250 * frag now points to RADIUS attributes
3253 memcpy(tail, frag + 2 + 4 + 3, frag[2 + 4 + 1] - 3);
3254 tail += frag[2 + 4 + 1] - 3;
3256 } while (frag < end);
3258 VP_HEXDUMP("wimax fragments", head, fraglen);
3260 rcode = data2vp(ctx, packet, original, secret, child,
3261 head, fraglen, fraglen, pvp);
3263 if (rcode < 0) return rcode;
3269 /** Convert a top-level VSA to one or more VPs
3272 static ssize_t data2vp_vsas(TALLOC_CTX *ctx, RADIUS_PACKET *packet,
3273 RADIUS_PACKET const *original,
3274 char const *secret, uint8_t const *data,
3275 size_t attrlen, size_t packetlen,
3282 VALUE_PAIR *head, **tail;
3285 if (attrlen > packetlen) return -1;
3286 if (attrlen < 5) return -1; /* vid, value */
3287 if (data[0] != 0) return -1; /* we require 24-bit VIDs */
3289 VP_TRACE("data2vp_vsas\n");
3291 memcpy(&vendor, data, 4);
3292 vendor = ntohl(vendor);
3293 dv = dict_vendorbyvalue(vendor);
3296 * RFC format is 1 octet type, 1 octet length
3298 if (rad_tlv_ok(data + 4, attrlen - 4, 1, 1) < 0) {
3299 VP_TRACE("data2vp_vsas: unknown tlvs not OK: %s\n", fr_strerror());
3304 * It's a known unknown.
3306 memset(&my_dv, 0, sizeof(my_dv));
3310 * Fill in the fields. Note that the name is empty!
3312 dv->vendorpec = vendor;
3322 if ((vendor == VENDORPEC_WIMAX) && dv->flags) {
3323 rcode = data2vp_wimax(ctx, packet, original, secret, vendor,
3324 data, attrlen, packetlen, pvp);
3329 * VSAs should normally be in TLV format.
3331 if (rad_tlv_ok(data + 4, attrlen - 4,
3332 dv->type, dv->length) < 0) {
3333 VP_TRACE("data2vp_vsas: tlvs not OK: %s\n", fr_strerror());
3338 * There may be more than one VSA in the
3339 * Vendor-Specific. If so, loop over them all.
3349 while (attrlen > 0) {
3352 vsa_len = data2vp_vsa(ctx, packet, original, secret, dv,
3353 data, attrlen, tail);
3355 fr_pair_list_free(&head);
3356 fr_strerror_printf("Internal sanity check %d", __LINE__);
3361 * Vendors can send zero-length VSAs.
3363 if (*tail) tail = &((*tail)->next);
3367 packetlen -= vsa_len;
3375 /** Create any kind of VP from the attribute contents
3377 * "length" is AT LEAST the length of this attribute, as we
3378 * expect the caller to have verified the data with
3379 * rad_packet_ok(). "length" may be up to the length of the
3382 * @return -1 on error, or "length".
3384 ssize_t data2vp(TALLOC_CTX *ctx,
3385 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3387 DICT_ATTR const *da, uint8_t const *start,
3388 size_t const attrlen, size_t const packetlen,
3391 int8_t tag = TAG_NONE;
3395 DICT_ATTR const *child;
3397 uint8_t const *data = start;
3399 uint8_t buffer[256];
3402 * FIXME: Attrlen can be larger than 253 for extended attrs!
3404 if (!da || (attrlen > packetlen) ||
3405 ((attrlen > 253) && (attrlen != packetlen)) ||
3406 (attrlen > 128*1024)) {
3407 fr_strerror_printf("data2vp: invalid arguments");
3411 VP_HEXDUMP("data2vp", start, attrlen);
3413 VP_TRACE("parent %s len %zu ... %zu\n", da->name, attrlen, packetlen);
3418 * Hacks for CUI. The WiMAX spec says that it can be
3419 * zero length, even though this is forbidden by the
3420 * RADIUS specs. So... we make a special case for it.
3423 if (!((da->vendor == 0) &&
3424 (da->attr == PW_CHARGEABLE_USER_IDENTITY))) {
3431 * Hacks for Coverity. Editing the dictionary
3432 * will break assumptions about CUI. We know
3433 * this, but Coverity doesn't.
3435 if (da->type != PW_TYPE_OCTETS) return -1;
3440 goto alloc_cui; /* skip everything */
3444 * Hacks for tags. If the attribute is capable of
3445 * encoding a tag, and there's room for the tag, and
3446 * there is a tag, or it's encrypted with Tunnel-Password,
3447 * then decode the tag.
3449 if (da->flags.has_tag && (datalen > 1) &&
3450 ((data[0] < 0x20) ||
3451 (da->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
3453 * Only "short" attributes can be encrypted.
3455 if (datalen >= sizeof(buffer)) return -1;
3457 if (da->type == PW_TYPE_STRING) {
3458 memcpy(buffer, data + 1, datalen - 1);
3462 } else if (da->type == PW_TYPE_INTEGER) {
3463 memcpy(buffer, data, attrlen);
3468 return -1; /* only string and integer can have tags */
3475 * Decrypt the attribute.
3477 if (secret && packet && (da->flags.encrypt != FLAG_ENCRYPT_NONE)) {
3478 VP_TRACE("data2vp: decrypting type %u\n", da->flags.encrypt);
3480 * Encrypted attributes can only exist for the
3481 * old-style format. Extended attributes CANNOT
3484 if (attrlen > 253) {
3488 if (data == start) {
3489 memcpy(buffer, data, attrlen);
3493 switch (da->flags.encrypt) { /* can't be tagged */
3497 case FLAG_ENCRYPT_USER_PASSWORD:
3499 rad_pwdecode((char *) buffer,
3503 rad_pwdecode((char *) buffer,
3510 * MS-CHAP-MPPE-Keys are 24 octets, and
3511 * encrypted. Since it's binary, we can't
3512 * look for trailing zeros.
3514 if (da->flags.length) {
3515 if (datalen > da->flags.length) {
3516 datalen = da->flags.length;
3517 } /* else leave datalen alone */
3520 * Take off trailing zeros from the END.
3521 * This allows passwords to have zeros in
3522 * the middle of a field.
3524 * However, if the password has a zero at
3525 * the end, it will get mashed by this
3526 * code. There's really no way around
3529 while ((datalen > 0) && (buffer[datalen - 1] == '\0')) datalen--;
3534 * Tunnel-Password's may go ONLY in response
3535 * packets. They can have a tag, so datalen is
3536 * not the same as attrlen.
3538 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
3539 if (rad_tunnel_pwdecode(buffer, &datalen, secret,
3540 original ? original->vector : nullvector) < 0) {
3546 * Ascend-Send-Secret
3547 * Ascend-Receive-Secret
3549 case FLAG_ENCRYPT_ASCEND_SECRET:
3553 uint8_t my_digest[AUTH_VECTOR_LEN];
3554 make_secret(my_digest,
3557 memcpy(buffer, my_digest,
3559 buffer[AUTH_VECTOR_LEN] = '\0';
3560 datalen = strlen((char *) buffer);
3566 } /* switch over encryption flags */
3570 * Double-check the length after decrypting the
3573 VP_TRACE("data2vp: type %u\n", da->type);
3575 case PW_TYPE_STRING:
3576 case PW_TYPE_OCTETS:
3579 case PW_TYPE_ABINARY:
3580 if (datalen > sizeof(vp->vp_filter)) goto raw;
3583 case PW_TYPE_INTEGER:
3584 case PW_TYPE_IPV4_ADDR:
3586 case PW_TYPE_SIGNED:
3587 if (datalen != 4) goto raw;
3590 case PW_TYPE_INTEGER64:
3592 if (datalen != 8) goto raw;
3595 case PW_TYPE_IPV6_ADDR:
3596 if (datalen != 16) goto raw;
3599 case PW_TYPE_IPV6_PREFIX:
3600 if ((datalen < 2) || (datalen > 18)) goto raw;
3601 if (data[1] > 128) goto raw;
3605 if (datalen != 1) goto raw;
3609 if (datalen != 2) goto raw;
3612 case PW_TYPE_ETHERNET:
3613 if (datalen != 6) goto raw;
3616 case PW_TYPE_COMBO_IP_ADDR:
3618 child = dict_attrbytype(da->attr, da->vendor,
3620 } else if (datalen == 16) {
3621 child = dict_attrbytype(da->attr, da->vendor,
3626 if (!child) goto raw;
3627 da = child; /* re-write it */
3630 case PW_TYPE_IPV4_PREFIX:
3631 if (datalen != 6) goto raw;
3632 if ((data[1] & 0x3f) > 32) goto raw;
3636 * The rest of the data types can cause
3637 * recursion! Ask yourself, "is recursion OK?"
3640 case PW_TYPE_EXTENDED:
3641 if (datalen < 2) goto raw; /* etype, value */
3643 child = dict_attrbyparent(da, data[0], 0);
3644 if (!child) goto raw;
3647 * Recurse to decode the contents, which could be
3648 * a TLV, IPaddr, etc. Note that we decode only
3649 * the current attribute, and we ignore any extra
3652 rcode = data2vp(ctx, packet, original, secret, child,
3653 data + 1, attrlen - 1, attrlen - 1, pvp);
3654 if (rcode < 0) goto raw;
3657 case PW_TYPE_LONG_EXTENDED:
3658 if (datalen < 3) goto raw; /* etype, flags, value */
3660 child = dict_attrbyparent(da, data[0], 0);
3662 if ((data[0] != PW_VENDOR_SPECIFIC) ||
3663 (datalen < (3 + 4 + 1))) {
3664 /* da->attr < 255, da->vendor == 0 */
3665 child = dict_unknown_afrom_fields(ctx, data[0], da->attr * FR_MAX_VENDOR);
3668 * Try to find the VSA.
3670 memcpy(&vendor, data + 3, 4);
3671 vendor = ntohl(vendor);
3673 if (vendor == 0) goto raw;
3675 child = dict_unknown_afrom_fields(ctx, data[7], vendor | (da->attr * FR_MAX_VENDOR));
3679 fr_strerror_printf("Internal sanity check %d", __LINE__);
3685 * If there no more fragments, then the contents
3686 * have to be a well-known data type.
3689 if ((data[1] & 0x80) == 0) {
3690 rcode = data2vp(ctx, packet, original, secret, child,
3691 data + 2, attrlen - 2, attrlen - 2,
3693 if (rcode < 0) goto raw;
3698 * This requires a whole lot more work.
3700 return data2vp_extended(ctx, packet, original, secret, child,
3701 start, attrlen, packetlen, pvp);
3704 if (datalen < 6) goto raw; /* vid, vtype, value */
3706 if (data[0] != 0) goto raw; /* we require 24-bit VIDs */
3708 memcpy(&vendor, data, 4);
3709 vendor = ntohl(vendor);
3710 vendor |= da->vendor;
3712 child = dict_attrbyvalue(data[4], vendor);
3715 * Create a "raw" attribute from the
3716 * contents of the EVS VSA.
3718 da = dict_unknown_afrom_fields(ctx, data[4], vendor);
3724 rcode = data2vp(ctx, packet, original, secret, child,
3725 data + 5, attrlen - 5, attrlen - 5, pvp);
3726 if (rcode < 0) goto raw;
3731 * We presume that the TLVs all fit into one
3732 * attribute, OR they've already been grouped
3733 * into a contiguous memory buffer.
3735 rcode = rad_data2vp_tlvs(ctx, packet, original, secret, da,
3736 data, attrlen, pvp);
3737 if (rcode < 0) goto raw;
3742 * VSAs can be WiMAX, in which case they don't
3743 * fit into one attribute.
3745 rcode = data2vp_vsas(ctx, packet, original, secret,
3746 data, attrlen, packetlen, pvp);
3747 if (rcode < 0) goto raw;
3753 * Re-write the attribute to be "raw". It is
3754 * therefore of type "octets", and will be
3757 da = dict_unknown_afrom_fields(ctx, da->attr, da->vendor);
3759 fr_strerror_printf("Internal sanity check %d", __LINE__);
3767 if (da->type != PW_TYPE_OCTETS) {
3768 dict_attr_free(&da);
3776 * And now that we've verified the basic type
3777 * information, decode the actual data.
3780 vp = fr_pair_afrom_da(ctx, da);
3783 vp->vp_length = datalen;
3787 case PW_TYPE_STRING:
3788 p = talloc_array(vp, char, vp->vp_length + 1);
3789 memcpy(p, data, vp->vp_length);
3790 p[vp->vp_length] = '\0';
3791 vp->vp_strvalue = p;
3794 case PW_TYPE_OCTETS:
3795 fr_pair_value_memcpy(vp, data, vp->vp_length);
3798 case PW_TYPE_ABINARY:
3799 if (vp->vp_length > sizeof(vp->vp_filter)) {
3800 vp->vp_length = sizeof(vp->vp_filter);
3802 memcpy(vp->vp_filter, data, vp->vp_length);
3806 vp->vp_byte = data[0];
3810 vp->vp_short = (data[0] << 8) | data[1];
3813 case PW_TYPE_INTEGER:
3814 memcpy(&vp->vp_integer, data, 4);
3815 vp->vp_integer = ntohl(vp->vp_integer);
3818 case PW_TYPE_INTEGER64:
3819 memcpy(&vp->vp_integer64, data, 8);
3820 vp->vp_integer64 = ntohll(vp->vp_integer64);
3824 memcpy(&vp->vp_date, data, 4);
3825 vp->vp_date = ntohl(vp->vp_date);
3828 case PW_TYPE_ETHERNET:
3829 memcpy(vp->vp_ether, data, 6);
3832 case PW_TYPE_IPV4_ADDR:
3833 memcpy(&vp->vp_ipaddr, data, 4);
3837 memcpy(vp->vp_ifid, data, 8);
3840 case PW_TYPE_IPV6_ADDR:
3841 memcpy(&vp->vp_ipv6addr, data, 16);
3844 case PW_TYPE_IPV6_PREFIX:
3846 * FIXME: double-check that
3847 * (vp->vp_octets[1] >> 3) matches vp->vp_length + 2
3849 memcpy(vp->vp_ipv6prefix, data, vp->vp_length);
3850 if (vp->vp_length < 18) {
3851 memset(((uint8_t *)vp->vp_ipv6prefix) + vp->vp_length, 0,
3852 18 - vp->vp_length);
3856 case PW_TYPE_IPV4_PREFIX:
3857 /* FIXME: do the same double-check as for IPv6Prefix */
3858 memcpy(vp->vp_ipv4prefix, data, vp->vp_length);
3861 * /32 means "keep all bits". Otherwise, mask
3864 if ((data[1] & 0x3f) > 32) {
3865 uint32_t addr, mask;
3867 memcpy(&addr, vp->vp_octets + 2, sizeof(addr));
3869 mask <<= (32 - (data[1] & 0x3f));
3874 memcpy(vp->vp_ipv4prefix + 2, &addr, sizeof(addr));
3878 case PW_TYPE_SIGNED: /* overloaded with vp_integer */
3879 memcpy(&vp->vp_integer, buffer, 4);
3880 vp->vp_integer = ntohl(vp->vp_integer);
3884 fr_pair_list_free(&vp);
3885 fr_strerror_printf("Internal sanity check %d", __LINE__);
3895 /** Create a "normal" VALUE_PAIR from the given data
3898 ssize_t rad_attr2vp(TALLOC_CTX *ctx,
3899 RADIUS_PACKET *packet, RADIUS_PACKET const *original,
3901 uint8_t const *data, size_t length,
3906 DICT_ATTR const *da;
3908 if ((length < 2) || (data[1] < 2) || (data[1] > length)) {
3909 fr_strerror_printf("rad_attr2vp: Insufficient data");
3913 da = dict_attrbyvalue(data[0], 0);
3915 VP_TRACE("attr2vp: unknown attribute %u\n", data[0]);
3916 da = dict_unknown_afrom_fields(ctx, data[0], 0);
3921 * Pass the entire thing to the decoding function
3923 if (da->flags.concat) {
3924 VP_TRACE("attr2vp: concat attribute\n");
3925 return data2vp_concat(ctx, da, data, length, pvp);
3929 * Note that we pass the entire length, not just the
3930 * length of this attribute. The Extended or WiMAX
3931 * attributes may have the "continuation" bit set, and
3932 * will thus be more than one attribute in length.
3934 rcode = data2vp(ctx, packet, original, secret, da,
3935 data + 2, data[1] - 2, length - 2, pvp);
3936 if (rcode < 0) return rcode;
3941 fr_thread_local_setup(uint8_t *, rad_vp2data_buff)
3943 /** Converts vp_data to network byte order
3945 * Provide a pointer to a buffer which contains the value of the VALUE_PAIR
3946 * in an architecture independent format.
3948 * The pointer is only guaranteed to be valid between calls to rad_vp2data, and so long
3949 * as the source VALUE_PAIR is not freed.
3951 * @param out where to write the pointer to the value.
3952 * @param vp to get the value from.
3953 * @return -1 on error, or the length of the value
3955 ssize_t rad_vp2data(uint8_t const **out, VALUE_PAIR const *vp)
3963 buffer = fr_thread_local_init(rad_vp2data_buff, free);
3967 buffer = malloc(sizeof(uint8_t) * sizeof(value_data_t));
3969 fr_strerror_printf("Failed allocating memory for rad_vp2data buffer");
3973 ret = fr_thread_local_set(rad_vp2data_buff, buffer);
3975 fr_strerror_printf("Failed setting up TLS for rad_vp2data buffer: %s", strerror(errno));
3983 switch (vp->da->type) {
3984 case PW_TYPE_STRING:
3985 case PW_TYPE_OCTETS:
3986 memcpy(out, &vp->data.ptr, sizeof(*out));
3990 * All of these values are at the same location.
3993 case PW_TYPE_IPV4_ADDR:
3994 case PW_TYPE_IPV6_ADDR:
3995 case PW_TYPE_IPV6_PREFIX:
3996 case PW_TYPE_IPV4_PREFIX:
3997 case PW_TYPE_ABINARY:
3998 case PW_TYPE_ETHERNET:
3999 case PW_TYPE_COMBO_IP_ADDR:
4000 case PW_TYPE_COMBO_IP_PREFIX:
4002 void const *p = &vp->data;
4003 memcpy(out, &p, sizeof(*out));
4007 case PW_TYPE_BOOLEAN:
4008 buffer[0] = vp->vp_byte & 0x01;
4013 buffer[0] = vp->vp_byte & 0xff;
4018 buffer[0] = (vp->vp_short >> 8) & 0xff;
4019 buffer[1] = vp->vp_short & 0xff;
4023 case PW_TYPE_INTEGER:
4024 lvalue = htonl(vp->vp_integer);
4025 memcpy(buffer, &lvalue, sizeof(lvalue));
4029 case PW_TYPE_INTEGER64:
4030 lvalue64 = htonll(vp->vp_integer64);
4031 memcpy(buffer, &lvalue64, sizeof(lvalue64));
4036 lvalue = htonl(vp->vp_date);
4037 memcpy(buffer, &lvalue, sizeof(lvalue));
4041 case PW_TYPE_SIGNED:
4043 int32_t slvalue = htonl(vp->vp_signed);
4044 memcpy(buffer, &slvalue, sizeof(slvalue));
4049 case PW_TYPE_INVALID:
4050 case PW_TYPE_EXTENDED:
4051 case PW_TYPE_LONG_EXTENDED:
4055 case PW_TYPE_TIMEVAL:
4057 fr_strerror_printf("Cannot get data for VALUE_PAIR type %i", vp->da->type);
4060 /* Don't add default */
4063 return vp->vp_length;
4066 /** Calculate/check digest, and decode radius attributes
4068 * @return -1 on decoding error, 0 on success
4070 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
4074 uint32_t num_attributes;
4076 radius_packet_t *hdr;
4077 VALUE_PAIR *head, **tail, *vp;
4080 * Extract attribute-value pairs
4082 hdr = (radius_packet_t *)packet->data;
4084 packet_length = packet->data_len - RADIUS_HDR_LEN;
4091 * Loop over the attributes, decoding them into VPs.
4093 while (packet_length > 0) {
4097 * This may return many VPs
4099 my_len = rad_attr2vp(packet, packet, original, secret,
4100 ptr, packet_length, &vp);
4102 fr_pair_list_free(&head);
4114 * VSA's may not have been counted properly in
4115 * rad_packet_ok() above, as it is hard to count
4116 * then without using the dictionary. We
4117 * therefore enforce the limits here, too.
4119 if ((fr_max_attributes > 0) &&
4120 (num_attributes > fr_max_attributes)) {
4121 char host_ipaddr[128];
4123 fr_pair_list_free(&head);
4124 fr_strerror_printf("Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
4125 inet_ntop(packet->src_ipaddr.af,
4126 &packet->src_ipaddr.ipaddr,
4127 host_ipaddr, sizeof(host_ipaddr)),
4128 num_attributes, fr_max_attributes);
4133 packet_length -= my_len;
4137 * Merge information from the outside world into our
4140 fr_rand_seed(packet->data, RADIUS_HDR_LEN);
4143 * There may be VP's already in the packet. Don't
4144 * destroy them. Instead, add the decoded attributes to
4145 * the tail of the list.
4147 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
4158 * We assume that the passwd buffer passed is big enough.
4159 * RFC2138 says the password is max 128 chars, so the size
4160 * of the passwd buffer must be at least 129 characters.
4161 * Preferably it's just MAX_STRING_LEN.
4163 * int *pwlen is updated to the new length of the encrypted
4164 * password - a multiple of 16 bytes.
4166 int rad_pwencode(char *passwd, size_t *pwlen, char const *secret,
4167 uint8_t const *vector)
4169 FR_MD5_CTX context, old;
4170 uint8_t digest[AUTH_VECTOR_LEN];
4171 int i, n, secretlen;
4175 * RFC maximum is 128 bytes.
4177 * If length is zero, pad it out with zeros.
4179 * If the length isn't aligned to 16 bytes,
4180 * zero out the extra data.
4184 if (len > 128) len = 128;
4187 memset(passwd, 0, AUTH_PASS_LEN);
4188 len = AUTH_PASS_LEN;
4189 } else if ((len % AUTH_PASS_LEN) != 0) {
4190 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
4191 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
4196 * Use the secret to setup the decryption digest
4198 secretlen = strlen(secret);
4200 fr_md5_init(&context);
4201 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4202 old = context; /* save intermediate work */
4205 * Encrypt it in place. Don't bother checking
4206 * len, as we've ensured above that it's OK.
4208 for (n = 0; n < len; n += AUTH_PASS_LEN) {
4210 fr_md5_update(&context, vector, AUTH_PASS_LEN);
4211 fr_md5_final(digest, &context);
4214 fr_md5_update(&context,
4215 (uint8_t *) passwd + n - AUTH_PASS_LEN,
4217 fr_md5_final(digest, &context);
4220 for (i = 0; i < AUTH_PASS_LEN; i++) {
4221 passwd[i + n] ^= digest[i];
4231 int rad_pwdecode(char *passwd, size_t pwlen, char const *secret,
4232 uint8_t const *vector)
4234 FR_MD5_CTX context, old;
4235 uint8_t digest[AUTH_VECTOR_LEN];
4237 size_t n, secretlen;
4240 * The RFC's say that the maximum is 128.
4241 * The buffer we're putting it into above is 254, so
4242 * we don't need to do any length checking.
4244 if (pwlen > 128) pwlen = 128;
4249 if (pwlen == 0) goto done;
4252 * Use the secret to setup the decryption digest
4254 secretlen = strlen(secret);
4256 fr_md5_init(&context);
4257 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4258 old = context; /* save intermediate work */
4261 * The inverse of the code above.
4263 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
4265 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4266 fr_md5_final(digest, &context);
4269 if (pwlen > AUTH_PASS_LEN) {
4270 fr_md5_update(&context, (uint8_t *) passwd,
4274 fr_md5_final(digest, &context);
4277 if (pwlen > (n + AUTH_PASS_LEN)) {
4278 fr_md5_update(&context, (uint8_t *) passwd + n,
4283 for (i = 0; i < AUTH_PASS_LEN; i++) {
4284 passwd[i + n] ^= digest[i];
4289 passwd[pwlen] = '\0';
4290 return strlen(passwd);
4294 /** Encode Tunnel-Password attributes when sending them out on the wire
4296 * int *pwlen is updated to the new length of the encrypted
4297 * password - a multiple of 16 bytes.
4299 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
4302 ssize_t rad_tunnel_pwencode(char *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4304 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
4305 unsigned char digest[AUTH_VECTOR_LEN];
4307 int i, n, secretlen;
4312 if (len > 127) len = 127;
4315 * Shift the password 3 positions right to place a salt and original
4316 * length, tag will be added automatically on packet send.
4318 for (n = len ; n >= 0 ; n--) passwd[n + 3] = passwd[n];
4323 * save original password length as first password character;
4330 * Generate salt. The RFC's say:
4332 * The high bit of salt[0] must be set, each salt in a
4333 * packet should be unique, and they should be random
4335 * So, we set the high bit, add in a counter, and then
4336 * add in some CSPRNG data. should be OK..
4338 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
4339 (fr_rand() & 0x07));
4340 salt[1] = fr_rand();
4343 * Padd password to multiple of AUTH_PASS_LEN bytes.
4345 n = len % AUTH_PASS_LEN;
4347 n = AUTH_PASS_LEN - n;
4348 for (; n > 0; n--, len++)
4351 /* set new password length */
4355 * Use the secret to setup the decryption digest
4357 secretlen = strlen(secret);
4358 memcpy(buffer, secret, secretlen);
4360 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
4362 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
4363 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
4364 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
4366 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
4367 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
4370 for (i = 0; i < AUTH_PASS_LEN; i++) {
4371 passwd[i + n2] ^= digest[i];
4378 /** Decode Tunnel-Password encrypted attributes
4380 * Defined in RFC-2868, this uses a two char SALT along with the
4381 * initial intermediate value, to differentiate it from the
4384 ssize_t rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, char const *secret, uint8_t const *vector)
4386 FR_MD5_CTX context, old;
4387 uint8_t digest[AUTH_VECTOR_LEN];
4389 size_t i, n, encrypted_len, reallen;
4391 encrypted_len = *pwlen;
4394 * We need at least a salt.
4396 if (encrypted_len < 2) {
4397 fr_strerror_printf("tunnel password is too short");
4402 * There's a salt, but no password. Or, there's a salt
4403 * and a 'data_len' octet. It's wrong, but at least we
4404 * can figure out what it means: the password is empty.
4406 * Note that this means we ignore the 'data_len' field,
4407 * if the attribute length tells us that there's no
4408 * more data. So the 'data_len' field may be wrong,
4411 if (encrypted_len <= 3) {
4417 encrypted_len -= 2; /* discount the salt */
4420 * Use the secret to setup the decryption digest
4422 secretlen = strlen(secret);
4424 fr_md5_init(&context);
4425 fr_md5_update(&context, (uint8_t const *) secret, secretlen);
4426 old = context; /* save intermediate work */
4429 * Set up the initial key:
4431 * b(1) = MD5(secret + vector + salt)
4433 fr_md5_update(&context, vector, AUTH_VECTOR_LEN);
4434 fr_md5_update(&context, passwd, 2);
4437 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
4439 size_t block_len = AUTH_PASS_LEN;
4442 * Ensure we don't overflow the input on MD5
4444 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
4445 block_len = *pwlen - n - 2;
4451 fr_md5_final(digest, &context);
4456 * A quick check: decrypt the first octet
4457 * of the password, which is the
4458 * 'data_len' field. Ensure it's sane.
4460 reallen = passwd[2] ^ digest[0];
4461 if (reallen > encrypted_len) {
4462 fr_strerror_printf("tunnel password is too long for the attribute");
4466 fr_md5_update(&context, passwd + 2, block_len);
4471 fr_md5_final(digest, &context);
4474 fr_md5_update(&context, passwd + n + 2, block_len);
4477 for (i = base; i < block_len; i++) {
4478 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
4483 passwd[reallen] = 0;
4488 /** Encode a CHAP password
4490 * @bug FIXME: might not work with Ascend because
4491 * we use vp->vp_length, and Ascend gear likes
4492 * to send an extra '\0' in the string!
4494 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
4495 VALUE_PAIR *password)
4499 uint8_t string[MAX_STRING_LEN * 2 + 1];
4500 VALUE_PAIR *challenge;
4503 * Sanity check the input parameters
4505 if ((packet == NULL) || (password == NULL)) {
4510 * Note that the password VP can be EITHER
4511 * a User-Password attribute (from a check-item list),
4512 * or a CHAP-Password attribute (the client asking
4513 * the library to encode it).
4521 memcpy(ptr, password->vp_strvalue, password->vp_length);
4522 ptr += password->vp_length;
4523 i += password->vp_length;
4526 * Use Chap-Challenge pair if present,
4527 * Request Authenticator otherwise.
4529 challenge = fr_pair_find_by_num(packet->vps, PW_CHAP_CHALLENGE, 0, TAG_ANY);
4531 memcpy(ptr, challenge->vp_strvalue, challenge->vp_length);
4532 i += challenge->vp_length;
4534 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
4535 i += AUTH_VECTOR_LEN;
4539 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
4545 /** Seed the random number generator
4547 * May be called any number of times.
4549 void fr_rand_seed(void const *data, size_t size)
4554 * Ensure that the pool is initialized.
4556 if (!fr_rand_initialized) {
4559 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
4561 fd = open("/dev/urandom", O_RDONLY);
4567 while (total < sizeof(fr_rand_pool.randrsl)) {
4568 this = read(fd, fr_rand_pool.randrsl,
4569 sizeof(fr_rand_pool.randrsl) - total);
4570 if ((this < 0) && (errno != EINTR)) break;
4571 if (this > 0) total += this;
4575 fr_rand_pool.randrsl[0] = fd;
4576 fr_rand_pool.randrsl[1] = time(NULL);
4577 fr_rand_pool.randrsl[2] = errno;
4580 fr_randinit(&fr_rand_pool, 1);
4581 fr_rand_pool.randcnt = 0;
4582 fr_rand_initialized = 1;
4588 * Hash the user data
4591 if (!hash) hash = fr_rand();
4592 hash = fr_hash_update(data, size, hash);
4594 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
4598 /** Return a 32-bit random number
4601 uint32_t fr_rand(void)
4606 * Ensure that the pool is initialized.
4608 if (!fr_rand_initialized) {
4609 fr_rand_seed(NULL, 0);
4612 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
4613 if (fr_rand_pool.randcnt >= 256) {
4614 fr_rand_pool.randcnt = 0;
4615 fr_isaac(&fr_rand_pool);
4622 /** Allocate a new RADIUS_PACKET
4624 * @param ctx the context in which the packet is allocated. May be NULL if
4625 * the packet is not associated with a REQUEST.
4626 * @param new_vector if true a new request authenticator will be generated.
4627 * @return a new RADIUS_PACKET or NULL on error.
4629 RADIUS_PACKET *rad_alloc(TALLOC_CTX *ctx, bool new_vector)
4633 rp = talloc_zero(ctx, RADIUS_PACKET);
4635 fr_strerror_printf("out of memory");
4643 uint32_t hash, base;
4646 * Don't expose the actual contents of the random
4650 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
4651 hash = fr_rand() ^ base;
4652 memcpy(rp->vector + i, &hash, sizeof(hash));
4655 fr_rand(); /* stir the pool again */
4660 /** Allocate a new RADIUS_PACKET response
4662 * @param ctx the context in which the packet is allocated. May be NULL if
4663 * the packet is not associated with a REQUEST.
4664 * @param packet The request packet.
4665 * @return a new RADIUS_PACKET or NULL on error.
4667 RADIUS_PACKET *rad_alloc_reply(TALLOC_CTX *ctx, RADIUS_PACKET *packet)
4669 RADIUS_PACKET *reply;
4671 if (!packet) return NULL;
4673 reply = rad_alloc(ctx, false);
4674 if (!reply) return NULL;
4677 * Initialize the fields from the request.
4679 reply->sockfd = packet->sockfd;
4680 reply->dst_ipaddr = packet->src_ipaddr;
4681 reply->src_ipaddr = packet->dst_ipaddr;
4682 reply->dst_port = packet->src_port;
4683 reply->src_port = packet->dst_port;
4684 reply->id = packet->id;
4685 reply->code = 0; /* UNKNOWN code */
4686 memcpy(reply->vector, packet->vector,
4687 sizeof(reply->vector));
4690 reply->data_len = 0;
4693 reply->proto = packet->proto;
4699 /** Free a RADIUS_PACKET
4702 void rad_free(RADIUS_PACKET **radius_packet_ptr)
4704 RADIUS_PACKET *radius_packet;
4706 if (!radius_packet_ptr || !*radius_packet_ptr) return;
4707 radius_packet = *radius_packet_ptr;
4709 VERIFY_PACKET(radius_packet);
4711 fr_pair_list_free(&radius_packet->vps);
4713 talloc_free(radius_packet);
4714 *radius_packet_ptr = NULL;
4717 /** Duplicate a RADIUS_PACKET
4719 * @param ctx the context in which the packet is allocated. May be NULL if
4720 * the packet is not associated with a REQUEST.
4721 * @param in The packet to copy
4722 * @return a new RADIUS_PACKET or NULL on error.
4724 RADIUS_PACKET *rad_copy_packet(TALLOC_CTX *ctx, RADIUS_PACKET const *in)
4728 out = rad_alloc(ctx, false);
4729 if (!out) return NULL;
4732 * Bootstrap by copying everything.
4734 memcpy(out, in, sizeof(*out));
4737 * Then reset necessary fields
4744 out->vps = fr_pair_list_copy(out, in->vps);