2 * radius.c Functions to send/receive radius packets.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000-2003,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/libradius.h>
27 #include <freeradius-devel/md5.h>
33 #include <freeradius-devel/udpfromto.h>
41 * The RFC says 4096 octets max, and most packets are less than 256.
43 #define MAX_PACKET_LEN 4096
46 * The maximum number of attributes which we allow in an incoming
47 * request. If there are more attributes than this, the request
50 * This helps to minimize the potential for a DoS, when an
51 * attacker spoofs Access-Request packets, which don't have a
52 * Message-Authenticator attribute. This means that the packet
53 * is unsigned, and the attacker can use resources on the server,
54 * even if the end request is rejected.
56 int fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
59 typedef struct radius_packet_t {
63 uint8_t vector[AUTH_VECTOR_LEN];
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
77 "Accounting-Response",
93 "Resource-Free-Request",
94 "Resource-Free-Response",
95 "Resource-Query-Request",
96 "Resource-Query-Response",
97 "Alternate-Resource-Reclaim-Request",
99 "NAS-Reboot-Response",
112 "Disconnect-Request",
122 "IP-Address-Allocate",
127 void fr_printf_log(const char *fmt, ...)
132 if ((fr_debug_flag == 0) || !fr_log_fp) {
137 vfprintf(fr_log_fp, fmt, ap);
144 * Wrapper for sendto which handles sendfromto, IPv6, and all
145 * possible combinations.
147 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
148 fr_ipaddr_t *src_ipaddr, int src_port,
149 fr_ipaddr_t *dst_ipaddr, int dst_port)
151 struct sockaddr_storage dst;
152 socklen_t sizeof_dst;
154 #ifdef WITH_UDPFROMTO
155 struct sockaddr_storage src;
156 socklen_t sizeof_src;
158 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
160 src_port = src_port; /* -Wunused */
163 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
167 #ifdef WITH_UDPFROMTO
169 * Only IPv4 is supported for udpfromto.
171 * And if they don't specify a source IP address, don't
174 if ((dst_ipaddr->af == AF_INET) ||
175 (src_ipaddr->af != AF_UNSPEC)) {
176 return sendfromto(sockfd, data, data_len, flags,
177 (struct sockaddr *)&src, sizeof_src,
178 (struct sockaddr *)&dst, sizeof_dst);
181 src_ipaddr = src_ipaddr; /* -Wunused */
185 * No udpfromto, OR an IPv6 socket, fail gracefully.
187 return sendto(sockfd, data, data_len, flags,
188 (struct sockaddr *) &dst, sizeof_dst);
192 void rad_recv_discard(int sockfd)
195 struct sockaddr_storage src;
196 socklen_t sizeof_src = sizeof(src);
198 recvfrom(sockfd, header, sizeof(header), 0,
199 (struct sockaddr *)&src, &sizeof_src);
203 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
206 ssize_t data_len, packet_len;
208 struct sockaddr_storage src;
209 socklen_t sizeof_src = sizeof(src);
211 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
212 (struct sockaddr *)&src, &sizeof_src);
214 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
219 * Too little data is available, discard the packet.
222 recvfrom(sockfd, header, sizeof(header), 0,
223 (struct sockaddr *)&src, &sizeof_src);
226 } else { /* we got 4 bytes of data. */
228 * See how long the packet says it is.
230 packet_len = (header[2] * 256) + header[3];
233 * The length in the packet says it's less than
234 * a RADIUS header length: discard it.
236 if (packet_len < AUTH_HDR_LEN) {
237 recvfrom(sockfd, header, sizeof(header), 0,
238 (struct sockaddr *)&src, &sizeof_src);
242 * Enforce RFC requirements, for sanity.
243 * Anything after 4k will be discarded.
245 } else if (packet_len > MAX_PACKET_LEN) {
246 recvfrom(sockfd, header, sizeof(header), 0,
247 (struct sockaddr *)&src, &sizeof_src);
253 * Convert AF. If unknown, discard packet.
255 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
256 recvfrom(sockfd, header, sizeof(header), 0,
257 (struct sockaddr *)&src, &sizeof_src);
264 * The packet says it's this long, but the actual UDP
265 * size could still be smaller.
272 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
273 * possible combinations.
275 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
276 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
277 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
279 struct sockaddr_storage src;
280 struct sockaddr_storage dst;
281 socklen_t sizeof_src = sizeof(src);
282 socklen_t sizeof_dst = sizeof(dst);
289 memset(&src, 0, sizeof_src);
290 memset(&dst, 0, sizeof_dst);
293 * Get address family, etc. first, so we know if we
294 * need to do udpfromto.
296 * FIXME: udpfromto also does this, but it's not
297 * a critical problem.
299 if (getsockname(sockfd, (struct sockaddr *)&dst,
300 &sizeof_dst) < 0) return -1;
303 * Read the length of the packet, from the packet.
304 * This lets us allocate the buffer to use for
305 * reading the rest of the packet.
307 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
308 (struct sockaddr *)&src, &sizeof_src);
310 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
315 * Too little data is available, discard the packet.
318 recvfrom(sockfd, header, sizeof(header), flags,
319 (struct sockaddr *)&src, &sizeof_src);
322 } else { /* we got 4 bytes of data. */
324 * See how long the packet says it is.
326 len = (header[2] * 256) + header[3];
329 * The length in the packet says it's less than
330 * a RADIUS header length: discard it.
332 if (len < AUTH_HDR_LEN) {
333 recvfrom(sockfd, header, sizeof(header), flags,
334 (struct sockaddr *)&src, &sizeof_src);
338 * Enforce RFC requirements, for sanity.
339 * Anything after 4k will be discarded.
341 } else if (len > MAX_PACKET_LEN) {
342 recvfrom(sockfd, header, sizeof(header), flags,
343 (struct sockaddr *)&src, &sizeof_src);
352 * Receive the packet. The OS will discard any data in the
353 * packet after "len" bytes.
355 #ifdef WITH_UDPFROMTO
356 if (dst.ss_family == AF_INET) {
357 data_len = recvfromto(sockfd, buf, len, flags,
358 (struct sockaddr *)&src, &sizeof_src,
359 (struct sockaddr *)&dst, &sizeof_dst);
363 * No udpfromto, OR an IPv6 socket. Fail gracefully.
365 data_len = recvfrom(sockfd, buf, len, flags,
366 (struct sockaddr *)&src, &sizeof_src);
372 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
374 return -1; /* Unknown address family, Die Die Die! */
378 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
382 * Different address families should never happen.
384 if (src.ss_family != dst.ss_family) {
390 * Tell the caller about the data
398 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
399 /*************************************************************************
401 * Function: make_secret
403 * Purpose: Build an encrypted secret value to return in a reply
404 * packet. The secret is hidden by xoring with a MD5 digest
405 * created from the shared secret and the authentication
406 * vector. We put them into MD5 in the reverse order from
407 * that used when encrypting passwords to RADIUS.
409 *************************************************************************/
410 static void make_secret(uint8_t *digest, const uint8_t *vector,
411 const char *secret, const uint8_t *value)
416 fr_MD5Init(&context);
417 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
418 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
419 fr_MD5Final(digest, &context);
421 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
422 digest[i] ^= value[i];
426 #define MAX_PASS_LEN (128)
427 static void make_passwd(uint8_t *output, int *outlen,
428 const uint8_t *input, int inlen,
429 const char *secret, const uint8_t *vector)
431 FR_MD5_CTX context, old;
432 uint8_t digest[AUTH_VECTOR_LEN];
433 uint8_t passwd[MAX_PASS_LEN];
438 * If the length is zero, round it up.
444 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
446 else if ((len & 0x0f) != 0) {
452 memcpy(passwd, input, len);
453 memset(passwd + len, 0, sizeof(passwd) - len);
455 fr_MD5Init(&context);
456 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
462 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
464 for (n = 0; n < len; n += AUTH_PASS_LEN) {
467 fr_MD5Update(&context,
468 passwd + n - AUTH_PASS_LEN,
472 fr_MD5Final(digest, &context);
473 for (i = 0; i < AUTH_PASS_LEN; i++) {
474 passwd[i + n] ^= digest[i];
478 memcpy(output, passwd, len);
481 static void make_tunnel_passwd(uint8_t *output, int *outlen,
482 const uint8_t *input, int inlen, int room,
483 const char *secret, const uint8_t *vector)
485 FR_MD5_CTX context, old;
486 uint8_t digest[AUTH_VECTOR_LEN];
487 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
494 if (room > 253) room = 253;
497 * Account for 2 bytes of the salt, and round the room
498 * available down to the nearest multiple of 16. Then,
499 * subtract one from that to account for the length byte,
500 * and the resulting number is the upper bound on the data
503 * We could short-cut this calculation just be forcing
504 * inlen to be no more than 239. It would work for all
505 * VSA's, as we don't pack multiple VSA's into one
508 * However, this calculation is more general, if a little
509 * complex. And it will work in the future for all possible
510 * kinds of weird attribute packing.
513 room -= (room & 0x0f);
516 if (inlen > room) inlen = room;
519 * Length of the encrypted data is password length plus
520 * one byte for the length of the password.
523 if ((len & 0x0f) != 0) {
527 *outlen = len + 2; /* account for the salt */
530 * Copy the password over.
532 memcpy(passwd + 3, input, inlen);
533 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
536 * Generate salt. The RFC's say:
538 * The high bit of salt[0] must be set, each salt in a
539 * packet should be unique, and they should be random
541 * So, we set the high bit, add in a counter, and then
542 * add in some CSPRNG data. should be OK..
544 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
546 passwd[1] = fr_rand();
547 passwd[2] = inlen; /* length of the password string */
549 fr_MD5Init(&context);
550 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
553 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
554 fr_MD5Update(&context, &passwd[0], 2);
556 for (n = 0; n < len; n += AUTH_PASS_LEN) {
559 fr_MD5Update(&context,
560 passwd + 2 + n - AUTH_PASS_LEN,
564 fr_MD5Final(digest, &context);
565 for (i = 0; i < AUTH_PASS_LEN; i++) {
566 passwd[i + 2 + n] ^= digest[i];
569 memcpy(output, passwd, len + 2);
572 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
573 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
574 int offset, int room)
582 * Set up the default sources for the data.
584 data = vp->vp_octets;
591 case PW_TYPE_IPV6ADDR:
592 case PW_TYPE_IPV6PREFIX:
593 case PW_TYPE_ABINARY:
594 /* nothing more to do */
598 len = 1; /* just in case */
599 array[0] = vp->vp_integer & 0xff;
605 len = 2; /* just in case */
606 array[0] = (vp->vp_integer >> 8) & 0xff;
607 array[1] = vp->vp_integer & 0xff;
612 case PW_TYPE_INTEGER:
613 len = 4; /* just in case */
614 lvalue = htonl(vp->vp_integer);
615 memcpy(array, &lvalue, sizeof(lvalue));
618 * Perhaps discard the first octet.
620 data = &array[offset];
625 data = (const uint8_t *) &vp->vp_ipaddr;
626 len = 4; /* just in case */
630 * There are no tagged date attributes.
633 lvalue = htonl(vp->vp_date);
634 data = (const uint8_t *) &lvalue;
635 len = 4; /* just in case */
642 len = 4; /* just in case */
643 slvalue = htonl(vp->vp_signed);
644 memcpy(array, &slvalue, sizeof(slvalue));
651 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
656 default: /* unknown type: ignore it */
657 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
662 * Bound the data to 255 bytes.
664 if (len + offset > room) {
669 * Encrypt the various password styles
671 * Attributes with encrypted values MUST be less than
674 switch (vp->flags.encrypt) {
675 case FLAG_ENCRYPT_USER_PASSWORD:
676 make_passwd(ptr + offset, &len,
678 secret, packet->vector);
681 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
683 * Check if 255 - offset - total_length is less
684 * than 18. If so, we can't fit the data into
685 * the available space, and we discard the
688 * This is ONLY a problem if we have multiple VSA's
689 * in one Vendor-Specific, though.
691 if ((room - offset) < 18) return 0;
693 switch (packet->code) {
694 case PW_AUTHENTICATION_ACK:
695 case PW_AUTHENTICATION_REJECT:
696 case PW_ACCESS_CHALLENGE:
699 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
702 make_tunnel_passwd(ptr + offset, &len,
703 data, len, room - offset,
704 secret, original->vector);
706 case PW_ACCOUNTING_REQUEST:
707 case PW_DISCONNECT_REQUEST:
709 make_tunnel_passwd(ptr + offset, &len,
710 data, len, room - offset,
711 secret, packet->vector);
717 * The code above ensures that this attribute
720 case FLAG_ENCRYPT_ASCEND_SECRET:
721 make_secret(ptr + offset, packet->vector,
723 len = AUTH_VECTOR_LEN;
729 * Just copy the data over
731 memcpy(ptr + offset, data, len);
733 } /* switch over encryption flags */
739 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
742 int length, attribute;
744 VALUE_PAIR *vp, *tlv;
746 attribute = vps->attribute & 0xffff00ff;
747 maxattr = vps->attribute & 0x0ff;
749 tlv = paircreate(attribute, PW_TYPE_TLV);
750 if (!tlv) return NULL;
753 for (vp = vps; vp != NULL; vp = vp->next) {
755 * Group the attributes ONLY until we see a
758 if (!vp->flags.is_tlv ||
760 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
761 ((vp->attribute & 0xffff00ff) != attribute) ||
762 ((vp->attribute & 0x0000ff00) <= maxattr)) {
766 maxattr = vp->attribute & 0xff00;
767 tlv->length += vp->length + 2;
775 tlv->vp_tlv = malloc(tlv->length);
782 maxattr = vps->attribute & 0x0ff;
783 for (vp = vps; vp != NULL; vp = vp->next) {
784 if (!vp->flags.is_tlv ||
786 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
787 ((vp->attribute & 0xffff00ff) != attribute) ||
788 ((vp->attribute & 0x0000ff00) <= maxattr)) {
792 maxattr = vp->attribute & 0xff00;
793 length = vp2data(NULL, NULL, NULL, vp, ptr + 2, 0,
794 tlv->vp_tlv + tlv->length - ptr);
796 vp->length = ptr - vp->vp_tlv;
797 return tlv; /* should be a more serious error... */
801 * Pack the attribute.
803 ptr[0] = (vp->attribute & 0xff00) >> 8;
804 ptr[1] = (length & 0xff) + 2;
806 ptr += vp->length + 2;
807 vp->flags.encoded = 1;
814 * Pack data without any encryption.
815 * start == start of RADIUS attribute
816 * ptr == continuation byte (i.e. one after length)
818 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
822 size_t hsize = (ptr - start);
823 uint8_t *this = start;
828 * If it's too long and marked as encrypted, ignore it.
830 if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
834 memcpy(header, start, hsize);
845 data = vp->vp_octets;
856 memcpy(this, header, hsize);
863 if (left > (254 - hsize)) {
871 memcpy(ptr, data, piece);
872 this[1] = hsize + piece + 1;
877 this[hsize - 1] = hsize - 6 + 1 + piece;
884 return (ptr - start);
889 * Parse a data structure into a RADIUS attribute.
891 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
892 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
895 int offset, len, total_length;
897 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
900 vendorcode = total_length = 0;
901 length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
904 * For interoperability, always put vendor attributes
905 * into their own VSA.
907 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
908 *(ptr++) = vp->attribute & 0xFF;
917 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
920 * This must be an RFC-format attribute. If it
921 * wasn't, then the "decode" function would have
922 * made a Vendor-Specific attribute (i.e. type
923 * 26), and we would have "vendorcode == 0" here.
927 vsa_llen = dv->length;
928 if (dv->flags) vsa_offset = 1;
932 * Build a VSA header.
934 *ptr++ = PW_VENDOR_SPECIFIC;
935 vsa_length_ptr = ptr;
937 lvalue = htonl(vendorcode);
938 memcpy(ptr, &lvalue, 4);
944 ptr[0] = (vp->attribute & 0xFF);
948 ptr[0] = ((vp->attribute >> 8) & 0xFF);
949 ptr[1] = (vp->attribute & 0xFF);
955 ptr[2] = ((vp->attribute >> 8) & 0xFF);
956 ptr[3] = (vp->attribute & 0xFF);
960 return 0; /* silently discard it */
966 length_ptr = vsa_length_ptr;
967 vsa_length_ptr = NULL;
976 length_ptr = ptr + 1;
980 return 0; /* silently discard it */
985 * Allow for some continuation.
989 * Allow TLV's to be encoded, if someone
990 * manages to somehow encode the sub-tlv's.
992 * FIXME: Keep track of room in the packet!
994 if (vp->length > (254 - (ptr - start))) {
995 return rad_vp2continuation(vp, start, ptr);
1002 * sub-TLV's can only be in one format.
1004 if (vp->flags.is_tlv) {
1005 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1006 tlv_length_ptr = ptr;
1012 total_length += vsa_tlen + vsa_llen + vsa_offset;
1013 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1014 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1018 if (vp->flags.has_tag) {
1019 if (TAG_VALID(vp->flags.tag)) {
1020 ptr[0] = vp->flags.tag & 0xff;
1023 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
1025 * Tunnel passwords REQUIRE a tag, even
1026 * if don't have a valid tag.
1030 } /* else don't write a tag */
1031 } /* else the attribute doesn't have a tag */
1033 len = vp2data(packet, original, secret, vp, ptr, offset,
1034 255 - total_length);
1035 if (len < 0) return -1;
1038 * Account for the tag (if any).
1043 * RFC 2865 section 5 says that zero-length attributes
1046 * ... and the WiMAX forum ignores this... because of
1047 * one vendor. Don't they have anything better to do
1051 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1054 * Update the various lengths.
1057 if (vsa_length_ptr) *vsa_length_ptr += len;
1058 if (tlv_length_ptr) *tlv_length_ptr += len;
1060 total_length += len;
1062 return total_length; /* of attribute */
1069 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1072 radius_packet_t *hdr;
1074 uint16_t total_length;
1078 char ip_buffer[128];
1081 * For simplicity in the following logic, we allow
1082 * the attributes to "overflow" the 4k maximum
1083 * RADIUS packet size, by one attribute.
1085 * It's uint32_t, for alignment purposes.
1087 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
1089 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1090 what = fr_packet_codes[packet->code];
1095 DEBUG("Sending %s of id %d to %s port %d\n",
1097 inet_ntop(packet->dst_ipaddr.af,
1098 &packet->dst_ipaddr.ipaddr,
1099 ip_buffer, sizeof(ip_buffer)),
1103 * Double-check some things based on packet code.
1105 switch (packet->code) {
1106 case PW_AUTHENTICATION_ACK:
1107 case PW_AUTHENTICATION_REJECT:
1108 case PW_ACCESS_CHALLENGE:
1110 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1116 * These packet vectors start off as all zero.
1118 case PW_ACCOUNTING_REQUEST:
1119 case PW_DISCONNECT_REQUEST:
1120 case PW_COA_REQUEST:
1121 memset(packet->vector, 0, sizeof(packet->vector));
1129 * Use memory on the stack, until we know how
1130 * large the packet will be.
1132 hdr = (radius_packet_t *) data;
1135 * Build standard header
1137 hdr->code = packet->code;
1138 hdr->id = packet->id;
1140 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1142 total_length = AUTH_HDR_LEN;
1145 * Load up the configuration values for the user
1151 * FIXME: Loop twice over the reply list. The first time,
1152 * calculate the total length of data. The second time,
1153 * allocate the memory, and fill in the VP's.
1155 * Hmm... this may be slower than just doing a small
1160 * Loop over the reply attributes for the packet.
1162 for (reply = packet->vps; reply; reply = reply->next) {
1164 * Ignore non-wire attributes
1166 if ((VENDOR(reply->attribute) == 0) &&
1167 ((reply->attribute & 0xFFFF) > 0xff)) {
1170 * Permit the admin to send BADLY formatted
1171 * attributes with a debug build.
1173 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1174 memcpy(ptr, reply->vp_octets, reply->length);
1175 len = reply->length;
1183 * Set the Message-Authenticator to the correct
1184 * length and initial value.
1186 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1187 reply->length = AUTH_VECTOR_LEN;
1188 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1191 * Cache the offset to the
1192 * Message-Authenticator
1194 packet->offset = total_length;
1198 * Print out ONLY the attributes which
1199 * we're sending over the wire, and print
1200 * them out BEFORE they're encrypted.
1205 * Print them in order, even if they were encoded
1209 if (reply->flags.encoded) goto next;
1211 if (reply->flags.is_tlv) {
1212 VALUE_PAIR *tlv = rad_vp2tlv(reply);
1214 tlv->next = reply->next;
1219 * The encoded flag MUST be set in reply!
1221 reply = reply->next;
1224 len = rad_vp2attr(packet, original, secret, reply, ptr);
1226 if (len < 0) return -1;
1229 * Check that the packet is no more than 4k in
1230 * size, AFTER writing the attribute past the 4k
1231 * boundary, but BEFORE deciding to increase the
1232 * size of the packet. Note that the 'data'
1233 * buffer, above, is one attribute longer than
1234 * necessary, in order to permit this overflow.
1236 if ((total_length + len) > MAX_PACKET_LEN) {
1242 total_length += len;
1243 } /* done looping over all attributes */
1246 * Fill in the rest of the fields, and copy the data over
1247 * from the local stack to the newly allocated memory.
1249 * Yes, all this 'memcpy' is slow, but it means
1250 * that we only allocate the minimum amount of
1251 * memory for a request.
1253 packet->data_len = total_length;
1254 packet->data = (uint8_t *) malloc(packet->data_len);
1255 if (!packet->data) {
1256 fr_strerror_printf("Out of memory");
1260 memcpy(packet->data, hdr, packet->data_len);
1261 hdr = (radius_packet_t *) packet->data;
1263 total_length = htons(total_length);
1264 memcpy(hdr->length, &total_length, sizeof(total_length));
1271 * Sign a previously encoded packet.
1273 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1276 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1279 * It wasn't assigned an Id, this is bad!
1281 if (packet->id < 0) {
1282 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1286 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1287 (packet->offset < 0)) {
1288 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1293 * If there's a Message-Authenticator, update it
1294 * now, BEFORE updating the authentication vector.
1296 if (packet->offset > 0) {
1297 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1299 switch (packet->code) {
1300 case PW_ACCOUNTING_REQUEST:
1301 case PW_ACCOUNTING_RESPONSE:
1302 case PW_DISCONNECT_REQUEST:
1303 case PW_DISCONNECT_ACK:
1304 case PW_DISCONNECT_NAK:
1305 case PW_COA_REQUEST:
1308 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1311 case PW_AUTHENTICATION_ACK:
1312 case PW_AUTHENTICATION_REJECT:
1313 case PW_ACCESS_CHALLENGE:
1315 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1318 memcpy(hdr->vector, original->vector,
1322 default: /* others have vector already set to zero */
1328 * Set the authentication vector to zero,
1329 * calculate the signature, and put it
1330 * into the Message-Authenticator
1333 fr_hmac_md5(packet->data, packet->data_len,
1334 (const uint8_t *) secret, strlen(secret),
1336 memcpy(packet->data + packet->offset + 2,
1337 calc_auth_vector, AUTH_VECTOR_LEN);
1340 * Copy the original request vector back
1341 * to the raw packet.
1343 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1347 * Switch over the packet code, deciding how to
1350 switch (packet->code) {
1352 * Request packets are not signed, bur
1353 * have a random authentication vector.
1355 case PW_AUTHENTICATION_REQUEST:
1356 case PW_STATUS_SERVER:
1360 * Reply packets are signed with the
1361 * authentication vector of the request.
1368 fr_MD5Init(&context);
1369 fr_MD5Update(&context, packet->data, packet->data_len);
1370 fr_MD5Update(&context, (const uint8_t *) secret,
1372 fr_MD5Final(digest, &context);
1374 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1375 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1378 }/* switch over packet codes */
1384 * Reply to the request. Also attach
1385 * reply attribute value pairs and any user message provided.
1387 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1392 char ip_buffer[128];
1395 * Maybe it's a fake packet. Don't send it.
1397 if (!packet || (packet->sockfd < 0)) {
1401 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1402 what = fr_packet_codes[packet->code];
1408 * First time through, allocate room for the packet
1410 if (!packet->data) {
1412 * Encode the packet.
1414 if (rad_encode(packet, original, secret) < 0) {
1419 * Re-sign it, including updating the
1420 * Message-Authenticator.
1422 if (rad_sign(packet, original, secret) < 0) {
1427 * If packet->data points to data, then we print out
1428 * the VP list again only for debugging.
1430 } else if (fr_debug_flag) {
1431 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1432 inet_ntop(packet->dst_ipaddr.af,
1433 &packet->dst_ipaddr.ipaddr,
1434 ip_buffer, sizeof(ip_buffer)),
1437 for (reply = packet->vps; reply; reply = reply->next) {
1438 if ((VENDOR(reply->attribute) == 0) &&
1439 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1445 * And send it on it's way.
1447 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1448 &packet->src_ipaddr, packet->src_port,
1449 &packet->dst_ipaddr, packet->dst_port);
1454 * Validates the requesting client NAS. Calculates the
1455 * signature based on the clients private key.
1457 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1459 uint8_t digest[AUTH_VECTOR_LEN];
1463 * Zero out the auth_vector in the received packet.
1464 * Then append the shared secret to the received packet,
1465 * and calculate the MD5 sum. This must be the same
1466 * as the original MD5 sum (packet->vector).
1468 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1471 * MD5(packet + secret);
1473 fr_MD5Init(&context);
1474 fr_MD5Update(&context, packet->data, packet->data_len);
1475 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1476 fr_MD5Final(digest, &context);
1479 * Return 0 if OK, 2 if not OK.
1481 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1487 * Validates the requesting client NAS. Calculates the
1488 * signature based on the clients private key.
1490 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1493 uint8_t calc_digest[AUTH_VECTOR_LEN];
1499 if (original == NULL) {
1504 * Copy the original vector in place.
1506 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1509 * MD5(packet + secret);
1511 fr_MD5Init(&context);
1512 fr_MD5Update(&context, packet->data, packet->data_len);
1513 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1514 fr_MD5Final(calc_digest, &context);
1517 * Copy the packet's vector back to the packet.
1519 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1522 * Return 0 if OK, 2 if not OK.
1524 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1530 * See if the data pointed to by PTR is a valid RADIUS packet.
1532 * packet is not 'const * const' because we may update data_len,
1533 * if there's more data in the UDP packet than in the RADIUS packet.
1535 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1540 radius_packet_t *hdr;
1541 char host_ipaddr[128];
1547 * Check for packets smaller than the packet header.
1549 * RFC 2865, Section 3., subsection 'length' says:
1551 * "The minimum length is 20 ..."
1553 if (packet->data_len < AUTH_HDR_LEN) {
1554 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1555 inet_ntop(packet->src_ipaddr.af,
1556 &packet->src_ipaddr.ipaddr,
1557 host_ipaddr, sizeof(host_ipaddr)),
1558 packet->data_len, AUTH_HDR_LEN);
1563 * RFC 2865, Section 3., subsection 'length' says:
1565 * " ... and maximum length is 4096."
1567 if (packet->data_len > MAX_PACKET_LEN) {
1568 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1569 inet_ntop(packet->src_ipaddr.af,
1570 &packet->src_ipaddr.ipaddr,
1571 host_ipaddr, sizeof(host_ipaddr)),
1572 packet->data_len, MAX_PACKET_LEN);
1577 * Check for packets with mismatched size.
1578 * i.e. We've received 128 bytes, and the packet header
1579 * says it's 256 bytes long.
1581 totallen = (packet->data[2] << 8) | packet->data[3];
1582 hdr = (radius_packet_t *)packet->data;
1585 * Code of 0 is not understood.
1586 * Code of 16 or greate is not understood.
1588 if ((hdr->code == 0) ||
1589 (hdr->code >= FR_MAX_PACKET_CODE)) {
1590 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1591 inet_ntop(packet->src_ipaddr.af,
1592 &packet->src_ipaddr.ipaddr,
1593 host_ipaddr, sizeof(host_ipaddr)),
1599 * Message-Authenticator is required in Status-Server
1600 * packets, otherwise they can be trivially forged.
1602 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1605 * It's also required if the caller asks for it.
1607 if (flags) require_ma = 1;
1610 * Repeat the length checks. This time, instead of
1611 * looking at the data we received, look at the value
1612 * of the 'length' field inside of the packet.
1614 * Check for packets smaller than the packet header.
1616 * RFC 2865, Section 3., subsection 'length' says:
1618 * "The minimum length is 20 ..."
1620 if (totallen < AUTH_HDR_LEN) {
1621 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1622 inet_ntop(packet->src_ipaddr.af,
1623 &packet->src_ipaddr.ipaddr,
1624 host_ipaddr, sizeof(host_ipaddr)),
1625 totallen, AUTH_HDR_LEN);
1630 * And again, for the value of the 'length' field.
1632 * RFC 2865, Section 3., subsection 'length' says:
1634 * " ... and maximum length is 4096."
1636 if (totallen > MAX_PACKET_LEN) {
1637 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1638 inet_ntop(packet->src_ipaddr.af,
1639 &packet->src_ipaddr.ipaddr,
1640 host_ipaddr, sizeof(host_ipaddr)),
1641 totallen, MAX_PACKET_LEN);
1646 * RFC 2865, Section 3., subsection 'length' says:
1648 * "If the packet is shorter than the Length field
1649 * indicates, it MUST be silently discarded."
1651 * i.e. No response to the NAS.
1653 if (packet->data_len < totallen) {
1654 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1655 inet_ntop(packet->src_ipaddr.af,
1656 &packet->src_ipaddr.ipaddr,
1657 host_ipaddr, sizeof(host_ipaddr)),
1658 packet->data_len, totallen);
1663 * RFC 2865, Section 3., subsection 'length' says:
1665 * "Octets outside the range of the Length field MUST be
1666 * treated as padding and ignored on reception."
1668 if (packet->data_len > totallen) {
1670 * We're shortening the packet below, but just
1671 * to be paranoid, zero out the extra data.
1673 memset(packet->data + totallen, 0, packet->data_len - totallen);
1674 packet->data_len = totallen;
1678 * Walk through the packet's attributes, ensuring that
1679 * they add up EXACTLY to the size of the packet.
1681 * If they don't, then the attributes either under-fill
1682 * or over-fill the packet. Any parsing of the packet
1683 * is impossible, and will result in unknown side effects.
1685 * This would ONLY happen with buggy RADIUS implementations,
1686 * or with an intentional attack. Either way, we do NOT want
1687 * to be vulnerable to this problem.
1690 count = totallen - AUTH_HDR_LEN;
1695 * Attribute number zero is NOT defined.
1698 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1699 inet_ntop(packet->src_ipaddr.af,
1700 &packet->src_ipaddr.ipaddr,
1701 host_ipaddr, sizeof(host_ipaddr)));
1706 * Attributes are at LEAST as long as the ID & length
1707 * fields. Anything shorter is an invalid attribute.
1710 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1711 inet_ntop(packet->src_ipaddr.af,
1712 &packet->src_ipaddr.ipaddr,
1713 host_ipaddr, sizeof(host_ipaddr)),
1719 * Sanity check the attributes for length.
1722 default: /* don't do anything by default */
1726 * If there's an EAP-Message, we require
1727 * a Message-Authenticator.
1729 case PW_EAP_MESSAGE:
1733 case PW_MESSAGE_AUTHENTICATOR:
1734 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1735 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1736 inet_ntop(packet->src_ipaddr.af,
1737 &packet->src_ipaddr.ipaddr,
1738 host_ipaddr, sizeof(host_ipaddr)),
1747 * FIXME: Look up the base 255 attributes in the
1748 * dictionary, and switch over their type. For
1749 * integer/date/ip, the attribute length SHOULD
1752 count -= attr[1]; /* grab the attribute length */
1754 num_attributes++; /* seen one more attribute */
1758 * If the attributes add up to a packet, it's allowed.
1760 * If not, we complain, and throw the packet away.
1763 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1764 inet_ntop(packet->src_ipaddr.af,
1765 &packet->src_ipaddr.ipaddr,
1766 host_ipaddr, sizeof(host_ipaddr)));
1771 * If we're configured to look for a maximum number of
1772 * attributes, and we've seen more than that maximum,
1773 * then throw the packet away, as a possible DoS.
1775 if ((fr_max_attributes > 0) &&
1776 (num_attributes > fr_max_attributes)) {
1777 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1778 inet_ntop(packet->src_ipaddr.af,
1779 &packet->src_ipaddr.ipaddr,
1780 host_ipaddr, sizeof(host_ipaddr)),
1781 num_attributes, fr_max_attributes);
1786 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1788 * A packet with an EAP-Message attribute MUST also have
1789 * a Message-Authenticator attribute.
1791 * A Message-Authenticator all by itself is OK, though.
1793 * Similarly, Status-Server packets MUST contain
1794 * Message-Authenticator attributes.
1796 if (require_ma && ! seen_ma) {
1797 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1798 inet_ntop(packet->src_ipaddr.af,
1799 &packet->src_ipaddr.ipaddr,
1800 host_ipaddr, sizeof(host_ipaddr)));
1805 * Fill RADIUS header fields
1807 packet->code = hdr->code;
1808 packet->id = hdr->id;
1809 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1816 * Receive UDP client requests, and fill in
1817 * the basics of a RADIUS_PACKET structure.
1819 RADIUS_PACKET *rad_recv(int fd, int flags)
1821 RADIUS_PACKET *packet;
1824 * Allocate the new request data structure
1826 if ((packet = malloc(sizeof(*packet))) == NULL) {
1827 fr_strerror_printf("out of memory");
1830 memset(packet, 0, sizeof(*packet));
1832 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1833 &packet->src_ipaddr, &packet->src_port,
1834 &packet->dst_ipaddr, &packet->dst_port);
1837 * Check for socket errors.
1839 if (packet->data_len < 0) {
1840 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1841 /* packet->data is NULL */
1847 * If the packet is too big, then rad_recvfrom did NOT
1848 * allocate memory. Instead, it just discarded the
1851 if (packet->data_len > MAX_PACKET_LEN) {
1852 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1853 /* packet->data is NULL */
1859 * Read no data. Continue.
1860 * This check is AFTER the MAX_PACKET_LEN check above, because
1861 * if the packet is larger than MAX_PACKET_LEN, we also have
1862 * packet->data == NULL
1864 if ((packet->data_len == 0) || !packet->data) {
1865 fr_strerror_printf("Empty packet: Socket is not ready.");
1871 * See if it's a well-formed RADIUS packet.
1873 if (!rad_packet_ok(packet, flags)) {
1879 * Remember which socket we read the packet from.
1881 packet->sockfd = fd;
1884 * FIXME: Do even more filtering by only permitting
1885 * certain IP's. The problem is that we don't know
1886 * how to do this properly for all possible clients...
1890 * Explicitely set the VP list to empty.
1894 if (fr_debug_flag) {
1895 char host_ipaddr[128];
1897 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1898 DEBUG("rad_recv: %s packet from host %s port %d",
1899 fr_packet_codes[packet->code],
1900 inet_ntop(packet->src_ipaddr.af,
1901 &packet->src_ipaddr.ipaddr,
1902 host_ipaddr, sizeof(host_ipaddr)),
1905 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1906 inet_ntop(packet->src_ipaddr.af,
1907 &packet->src_ipaddr.ipaddr,
1908 host_ipaddr, sizeof(host_ipaddr)),
1912 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1920 * Verify the signature of a packet.
1922 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1929 if (!packet || !packet->data) return -1;
1932 * Before we allocate memory for the attributes, do more
1935 ptr = packet->data + AUTH_HDR_LEN;
1936 length = packet->data_len - AUTH_HDR_LEN;
1937 while (length > 0) {
1938 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1939 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1944 default: /* don't do anything. */
1948 * Note that more than one Message-Authenticator
1949 * attribute is invalid.
1951 case PW_MESSAGE_AUTHENTICATOR:
1952 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1953 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1955 switch (packet->code) {
1959 case PW_ACCOUNTING_REQUEST:
1960 case PW_ACCOUNTING_RESPONSE:
1961 case PW_DISCONNECT_REQUEST:
1962 case PW_DISCONNECT_ACK:
1963 case PW_DISCONNECT_NAK:
1964 case PW_COA_REQUEST:
1967 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1970 case PW_AUTHENTICATION_ACK:
1971 case PW_AUTHENTICATION_REJECT:
1972 case PW_ACCESS_CHALLENGE:
1974 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1977 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1981 fr_hmac_md5(packet->data, packet->data_len,
1982 (const uint8_t *) secret, strlen(secret),
1984 if (memcmp(calc_auth_vector, msg_auth_vector,
1985 sizeof(calc_auth_vector)) != 0) {
1987 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1988 inet_ntop(packet->src_ipaddr.af,
1989 &packet->src_ipaddr.ipaddr,
1990 buffer, sizeof(buffer)));
1991 /* Silently drop packet, according to RFC 3579 */
1993 } /* else the message authenticator was good */
1996 * Reinitialize Authenticators.
1998 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1999 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2001 } /* switch over the attributes */
2005 } /* loop over the packet, sanity checking the attributes */
2008 * It looks like a RADIUS packet, but we can't validate
2011 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2013 fr_strerror_printf("Received Unknown packet code %d "
2014 "from client %s port %d: Cannot validate signature.",
2016 inet_ntop(packet->src_ipaddr.af,
2017 &packet->src_ipaddr.ipaddr,
2018 buffer, sizeof(buffer)),
2024 * Calculate and/or verify digest.
2026 switch(packet->code) {
2030 case PW_AUTHENTICATION_REQUEST:
2031 case PW_STATUS_SERVER:
2033 * The authentication vector is random
2034 * nonsense, invented by the client.
2038 case PW_COA_REQUEST:
2039 case PW_DISCONNECT_REQUEST:
2040 case PW_ACCOUNTING_REQUEST:
2041 if (calc_acctdigest(packet, secret) > 1) {
2042 fr_strerror_printf("Received %s packet "
2043 "from %s with invalid signature! (Shared secret is incorrect.)",
2044 fr_packet_codes[packet->code],
2045 inet_ntop(packet->src_ipaddr.af,
2046 &packet->src_ipaddr.ipaddr,
2047 buffer, sizeof(buffer)));
2052 /* Verify the reply digest */
2053 case PW_AUTHENTICATION_ACK:
2054 case PW_AUTHENTICATION_REJECT:
2055 case PW_ACCESS_CHALLENGE:
2056 case PW_ACCOUNTING_RESPONSE:
2057 case PW_DISCONNECT_ACK:
2058 case PW_DISCONNECT_NAK:
2061 rcode = calc_replydigest(packet, original, secret);
2063 fr_strerror_printf("Received %s packet "
2064 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2065 fr_packet_codes[packet->code],
2066 inet_ntop(packet->src_ipaddr.af,
2067 &packet->src_ipaddr.ipaddr,
2068 buffer, sizeof(buffer)),
2076 fr_strerror_printf("Received Unknown packet code %d "
2077 "from client %s port %d: Cannot validate signature",
2079 inet_ntop(packet->src_ipaddr.af,
2080 &packet->src_ipaddr.ipaddr,
2081 buffer, sizeof(buffer)),
2090 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2091 const RADIUS_PACKET *original,
2092 const char *secret, int attribute, int length,
2093 const uint8_t *data, VALUE_PAIR *vp)
2098 * If length is greater than 253, something is SERIOUSLY
2101 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2103 vp->length = length;
2104 vp->operator = T_OP_EQ;
2110 if (vp->flags.has_tag) {
2111 if (TAG_VALID(data[0]) ||
2112 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2114 * Tunnel passwords REQUIRE a tag, even
2115 * if don't have a valid tag.
2117 vp->flags.tag = data[0];
2119 if ((vp->type == PW_TYPE_STRING) ||
2120 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2125 * Copy the data to be decrypted
2127 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2128 vp->length -= offset;
2131 * Decrypt the attribute.
2133 switch (vp->flags.encrypt) {
2137 case FLAG_ENCRYPT_USER_PASSWORD:
2139 rad_pwdecode((char *)vp->vp_strvalue,
2143 rad_pwdecode((char *)vp->vp_strvalue,
2147 if (vp->attribute == PW_USER_PASSWORD) {
2148 vp->length = strlen(vp->vp_strvalue);
2153 * Tunnel-Password's may go ONLY
2154 * in response packets.
2156 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2157 if (!original) goto raw;
2159 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2160 secret, original->vector) < 0) {
2166 * Ascend-Send-Secret
2167 * Ascend-Receive-Secret
2169 case FLAG_ENCRYPT_ASCEND_SECRET:
2173 uint8_t my_digest[AUTH_VECTOR_LEN];
2174 make_secret(my_digest,
2177 memcpy(vp->vp_strvalue, my_digest,
2179 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2180 vp->length = strlen(vp->vp_strvalue);
2186 } /* switch over encryption flags */
2190 case PW_TYPE_STRING:
2191 case PW_TYPE_OCTETS:
2192 case PW_TYPE_ABINARY:
2193 /* nothing more to do */
2197 if (vp->length != 1) goto raw;
2199 vp->vp_integer = vp->vp_octets[0];
2204 if (vp->length != 2) goto raw;
2206 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2209 case PW_TYPE_INTEGER:
2210 if (vp->length != 4) goto raw;
2212 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2213 vp->vp_integer = ntohl(vp->vp_integer);
2215 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2218 * Try to get named VALUEs
2222 dval = dict_valbyattr(vp->attribute,
2225 strlcpy(vp->vp_strvalue,
2227 sizeof(vp->vp_strvalue));
2233 if (vp->length != 4) goto raw;
2235 memcpy(&vp->vp_date, vp->vp_octets, 4);
2236 vp->vp_date = ntohl(vp->vp_date);
2240 case PW_TYPE_IPADDR:
2241 if (vp->length != 4) goto raw;
2243 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2247 * IPv6 interface ID is 8 octets long.
2250 if (vp->length != 8) goto raw;
2251 /* vp->vp_ifid == vp->vp_octets */
2255 * IPv6 addresses are 16 octets long
2257 case PW_TYPE_IPV6ADDR:
2258 if (vp->length != 16) goto raw;
2259 /* vp->vp_ipv6addr == vp->vp_octets */
2263 * IPv6 prefixes are 2 to 18 octets long.
2265 * RFC 3162: The first octet is unused.
2266 * The second is the length of the prefix
2267 * the rest are the prefix data.
2269 * The prefix length can have value 0 to 128.
2271 case PW_TYPE_IPV6PREFIX:
2272 if (vp->length < 2 || vp->length > 18) goto raw;
2273 if (vp->vp_octets[1] > 128) goto raw;
2276 * FIXME: double-check that
2277 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2279 if (vp->length < 18) {
2280 memset(vp->vp_octets + vp->length, 0,
2285 case PW_TYPE_SIGNED:
2286 if (vp->length != 4) goto raw;
2289 * Overload vp_integer for ntohl, which takes
2290 * uint32_t, not int32_t
2292 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2293 vp->vp_integer = ntohl(vp->vp_integer);
2294 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2298 vp->length = length;
2299 vp->vp_tlv = malloc(length);
2302 fr_strerror_printf("No memory");
2305 memcpy(vp->vp_tlv, data, length);
2308 case PW_TYPE_COMBO_IP:
2309 if (vp->length == 4) {
2310 vp->type = PW_TYPE_IPADDR;
2311 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2314 } else if (vp->length == 16) {
2315 vp->type = PW_TYPE_IPV6ADDR;
2316 /* vp->vp_ipv6addr == vp->vp_octets */
2324 vp->type = PW_TYPE_OCTETS;
2325 vp->length = length;
2326 memcpy(vp->vp_octets, data, length);
2330 * Ensure there's no encryption or tag stuff,
2331 * we just pass the attribute as-is.
2333 memset(&vp->flags, 0, sizeof(vp->flags));
2339 static void rad_sortvp(VALUE_PAIR **head)
2342 VALUE_PAIR *vp, **tail;
2345 * Walk over the VP's, sorting them in order. Did I
2346 * mention that I hate WiMAX continuations?
2348 * And bubble sort! WTF is up with that?
2355 if (!vp->next) break;
2357 if (vp->attribute > vp->next->attribute) {
2359 vp->next = (*tail)->next;
2370 * Walk the packet, looking for continuations of this attribute.
2372 * This is (worst-case) O(N^2) in the number of RADIUS
2373 * attributes. That happens only when perverse clients create
2374 * continued attributes, AND separate the fragmented portions
2375 * with a lot of other attributes.
2377 * Sane clients should put the fragments next to each other, in
2378 * which case this is O(N), in the number of fragments.
2380 static uint8_t *rad_coalesce(int attribute, size_t length, uint8_t *data,
2381 size_t packet_length, size_t *ptlv_length)
2385 size_t tlv_length = length;
2386 uint8_t *ptr, *tlv, *tlv_data;
2388 for (ptr = data + length;
2389 ptr != (data + packet_length);
2391 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2392 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2393 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2397 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2398 lvalue = ntohl(lvalue);
2400 lvalue |= ptr[2 + 4]; /* add in VSA number */
2401 if (lvalue != attribute) continue;
2404 * If the vendor-length is too small, it's badly
2405 * formed, so we stop.
2407 if ((ptr[2 + 4 + 1]) < 3) break;
2409 tlv_length += ptr[2 + 4 + 1] - 3;
2410 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2413 tlv = tlv_data = malloc(tlv_length);
2414 if (!tlv_data) return NULL;
2416 memcpy(tlv, data, length);
2420 * Now we walk the list again, copying the data over to
2421 * our newly created memory.
2423 for (ptr = data + length;
2424 ptr != (data + packet_length);
2428 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2429 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2430 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2434 memcpy(&lvalue, ptr + 2, 4);
2435 lvalue = ntohl(lvalue);
2437 lvalue |= ptr[2 + 4];
2438 if (lvalue != attribute) continue;
2441 * If the vendor-length is too small, it's badly
2442 * formed, so we stop.
2444 if ((ptr[2 + 4 + 1]) < 3) break;
2446 this_length = ptr[2 + 4 + 1] - 3;
2447 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2450 ptr[2 + 4] = 0; /* What a hack! */
2451 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2454 *ptlv_length = tlv_length;
2459 * Start at the *data* portion of a continued attribute. search
2460 * through the rest of the attributes to find a matching one, and
2461 * add it's contents to our contents.
2463 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2464 const RADIUS_PACKET *original,
2465 const char *secret, int attribute,
2466 int length, /* CANNOT be zero */
2467 uint8_t *data, size_t packet_length,
2468 int flag, DICT_ATTR *da)
2470 size_t tlv_length, left;
2473 VALUE_PAIR *vp, *head, **tail;
2476 * Ensure we have data that hasn't been split across
2477 * multiple attributes.
2480 tlv_data = rad_coalesce(attribute, length,
2481 data, packet_length, &tlv_length);
2482 if (!tlv_data) return NULL;
2485 tlv_length = length;
2489 * Non-TLV types cannot be continued across multiple
2490 * attributes. This is true even of keys that are
2491 * encrypted with the tunnel-password method. The spec
2492 * says that they can be continued... but also that the
2493 * keys are 160 bits, which means that they CANNOT be
2496 * Note that we don't check "flag" here. The calling
2499 if (da->type != PW_TYPE_TLV) {
2501 if (tlv_data == data) { /* true if we had 'goto' */
2502 tlv_data = malloc(tlv_length);
2503 if (!tlv_data) return NULL;
2504 memcpy(tlv_data, data, tlv_length);
2507 vp = paircreate(attribute, PW_TYPE_OCTETS);
2508 if (!vp) return NULL;
2510 vp->type = PW_TYPE_TLV;
2511 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2512 vp->flags.has_tag = 0;
2513 vp->flags.is_tlv = 0;
2514 vp->vp_tlv = tlv_data;
2515 vp->length = tlv_length;
2517 } /* else it WAS a TLV, go decode the sub-tlv's */
2520 * Now (sigh) we walk over the TLV, seeing if it is
2524 for (ptr = tlv_data;
2525 ptr != (tlv_data + tlv_length);
2530 goto not_well_formed;
2536 * Now we walk over the TLV *again*, creating sub-tlv's.
2541 for (ptr = tlv_data;
2542 ptr != (tlv_data + tlv_length);
2544 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2547 goto not_well_formed;
2550 if (!data2vp(packet, original, secret,
2551 ptr[0], ptr[1] - 2, ptr + 2, vp)) {
2553 goto not_well_formed;
2561 * TLV's MAY be continued, but sometimes they're not.
2563 if (tlv_data != data) free(tlv_data);
2565 if (head->next) rad_sortvp(&head);
2572 * Parse a RADIUS attribute into a data structure.
2574 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2575 const char *secret, int attribute, int length,
2576 const uint8_t *data)
2580 vp = paircreate(attribute, PW_TYPE_OCTETS);
2581 if (!vp) return NULL;
2583 return data2vp(packet, original, secret, attribute, length, data, vp);
2588 * Calculate/check digest, and decode radius attributes.
2590 * -1 on decoding error
2593 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2597 uint32_t vendorcode;
2600 uint8_t *ptr, *vsa_ptr;
2605 radius_packet_t *hdr;
2606 int vsa_tlen, vsa_llen, vsa_offset;
2607 DICT_VENDOR *dv = NULL;
2608 int num_attributes = 0;
2611 * Extract attribute-value pairs
2613 hdr = (radius_packet_t *)packet->data;
2615 packet_length = packet->data_len - AUTH_HDR_LEN;
2618 * There may be VP's already in the packet. Don't
2621 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2627 vsa_tlen = vsa_llen = 1;
2631 * We have to read at least two bytes.
2633 * rad_recv() above ensures that this is OK.
2635 while (packet_length > 0) {
2640 * Normal attribute, handle it like normal.
2642 if (vendorcode == 0) {
2644 * No room to read attr/length,
2645 * or bad attribute, or attribute is
2646 * too short, or attribute is too long,
2647 * stop processing the packet.
2649 if ((packet_length < 2) ||
2650 (ptr[0] == 0) || (ptr[1] < 2) ||
2651 (ptr[1] > packet_length)) break;
2659 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2662 * No vendor code, or ONLY vendor code.
2664 if (attrlen <= 4) goto create_pair;
2670 * Handle Vendor-Specific
2672 if (vendorlen == 0) {
2678 * attrlen was checked above.
2680 memcpy(&lvalue, ptr, 4);
2681 myvendor = ntohl(lvalue);
2684 * Zero isn't allowed.
2686 if (myvendor == 0) goto create_pair;
2689 * This is an implementation issue.
2690 * We currently pack vendor into the upper
2691 * 16 bits of a 32-bit attribute number,
2692 * so we can't handle vendor numbers larger
2695 if (myvendor > 65535) goto create_pair;
2697 vsa_tlen = vsa_llen = 1;
2699 dv = dict_vendorbyvalue(myvendor);
2701 vsa_tlen = dv->type;
2702 vsa_llen = dv->length;
2703 if (dv->flags) vsa_offset = 1;
2707 * Sweep through the list of VSA's,
2708 * seeing if they exactly fill the
2709 * outer Vendor-Specific attribute.
2711 * If not, create a raw Vendor-Specific.
2714 sublen = attrlen - 4;
2717 * See if we can parse it.
2723 * Not enough room for one more
2726 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2729 * Ensure that the attribute number
2738 myattr = (subptr[0] << 8) | subptr[1];
2742 if ((subptr[0] != 0) ||
2743 (subptr[1] != 0)) goto create_pair;
2745 myattr = (subptr[2] << 8) | subptr[3];
2749 * Our dictionary is broken.
2757 attribute = (myvendor << 16) | myattr;
2758 ptr += 4 + vsa_tlen;
2759 attrlen -= (4 + vsa_tlen);
2760 packet_length -= 4 + vsa_tlen;
2764 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2767 if (subptr[vsa_tlen] > sublen)
2772 * Reserved bits MUST be
2776 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2779 sublen -= subptr[vsa_tlen];
2780 subptr += subptr[vsa_tlen];
2784 if (subptr[vsa_tlen] != 0) goto create_pair;
2785 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2787 if (subptr[vsa_tlen + 1] > sublen)
2789 sublen -= subptr[vsa_tlen + 1];
2790 subptr += subptr[vsa_tlen + 1];
2794 * Our dictionaries are
2800 } while (sublen > 0);
2802 vendorcode = myvendor;
2803 vendorlen = attrlen - 4;
2810 * attrlen is the length of this attribute.
2811 * total_len is the length of the encompassing
2820 attribute = (ptr[0] << 8) | ptr[1];
2823 default: /* can't hit this. */
2826 attribute |= (vendorcode << 16);
2832 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2836 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2839 default: /* can't hit this. */
2843 ptr += vsa_llen + vsa_offset;
2844 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2845 if (vendorlen == 0) vendorcode = 0;
2846 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2849 * Ignore VSAs that have no data.
2851 if (attrlen == 0) goto next;
2854 * WiMAX attributes of type 0 are ignored. They
2855 * are a secret flag to us that the attribute has
2856 * already been dealt with.
2858 if (attribute == 0x60b50000) goto next;
2863 da = dict_attrbyvalue(attribute);
2866 * If it's NOT continued, AND we know
2867 * about it, AND it's not a TLV, we can
2868 * create a normal pair.
2870 if (((vsa_ptr[2] & 0x80) == 0) &&
2871 da && (da->type != PW_TYPE_TLV)) goto create_pair;
2874 * Else it IS continued, or it's a TLV.
2875 * Go do a lot of work to find the stuff.
2877 pair = rad_continuation2vp(packet, original, secret,
2878 attribute, attrlen, ptr,
2880 ((vsa_ptr[2] & 0x80) != 0),
2886 * Create the attribute, setting the default type
2887 * to 'octets'. If the type in the dictionary
2888 * is different, then the dictionary type will
2889 * over-ride this one.
2891 * If the attribute has no data, then discard it.
2893 * Unless it's CUI. Damn you, CUI!
2897 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2899 pair = rad_attr2vp(packet, original, secret,
2900 attribute, attrlen, ptr);
2902 pairfree(&packet->vps);
2903 fr_strerror_printf("out of memory");
2917 * VSA's may not have been counted properly in
2918 * rad_packet_ok() above, as it is hard to count
2919 * then without using the dictionary. We
2920 * therefore enforce the limits here, too.
2922 if ((fr_max_attributes > 0) &&
2923 (num_attributes > fr_max_attributes)) {
2924 char host_ipaddr[128];
2926 pairfree(&packet->vps);
2927 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2928 inet_ntop(packet->src_ipaddr.af,
2929 &packet->src_ipaddr.ipaddr,
2930 host_ipaddr, sizeof(host_ipaddr)),
2931 num_attributes, fr_max_attributes);
2937 packet_length -= attrlen;
2941 * Merge information from the outside world into our
2944 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2953 * We assume that the passwd buffer passed is big enough.
2954 * RFC2138 says the password is max 128 chars, so the size
2955 * of the passwd buffer must be at least 129 characters.
2956 * Preferably it's just MAX_STRING_LEN.
2958 * int *pwlen is updated to the new length of the encrypted
2959 * password - a multiple of 16 bytes.
2961 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2962 const uint8_t *vector)
2964 FR_MD5_CTX context, old;
2965 uint8_t digest[AUTH_VECTOR_LEN];
2966 int i, n, secretlen;
2970 * RFC maximum is 128 bytes.
2972 * If length is zero, pad it out with zeros.
2974 * If the length isn't aligned to 16 bytes,
2975 * zero out the extra data.
2979 if (len > 128) len = 128;
2982 memset(passwd, 0, AUTH_PASS_LEN);
2983 len = AUTH_PASS_LEN;
2984 } else if ((len % AUTH_PASS_LEN) != 0) {
2985 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2986 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2991 * Use the secret to setup the decryption digest
2993 secretlen = strlen(secret);
2995 fr_MD5Init(&context);
2996 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2997 old = context; /* save intermediate work */
3000 * Encrypt it in place. Don't bother checking
3001 * len, as we've ensured above that it's OK.
3003 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3005 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3006 fr_MD5Final(digest, &context);
3009 fr_MD5Update(&context,
3010 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3012 fr_MD5Final(digest, &context);
3015 for (i = 0; i < AUTH_PASS_LEN; i++) {
3016 passwd[i + n] ^= digest[i];
3026 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3027 const uint8_t *vector)
3029 FR_MD5_CTX context, old;
3030 uint8_t digest[AUTH_VECTOR_LEN];
3032 size_t n, secretlen;
3035 * The RFC's say that the maximum is 128.
3036 * The buffer we're putting it into above is 254, so
3037 * we don't need to do any length checking.
3039 if (pwlen > 128) pwlen = 128;
3044 if (pwlen == 0) goto done;
3047 * Use the secret to setup the decryption digest
3049 secretlen = strlen(secret);
3051 fr_MD5Init(&context);
3052 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3053 old = context; /* save intermediate work */
3056 * The inverse of the code above.
3058 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3060 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3061 fr_MD5Final(digest, &context);
3064 if (pwlen > AUTH_PASS_LEN) {
3065 fr_MD5Update(&context, (uint8_t *) passwd,
3069 fr_MD5Final(digest, &context);
3072 if (pwlen > (n + AUTH_PASS_LEN)) {
3073 fr_MD5Update(&context, (uint8_t *) passwd + n,
3078 for (i = 0; i < AUTH_PASS_LEN; i++) {
3079 passwd[i + n] ^= digest[i];
3084 passwd[pwlen] = '\0';
3085 return strlen(passwd);
3090 * Encode Tunnel-Password attributes when sending them out on the wire.
3092 * int *pwlen is updated to the new length of the encrypted
3093 * password - a multiple of 16 bytes.
3095 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3098 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3099 const uint8_t *vector)
3101 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3102 unsigned char digest[AUTH_VECTOR_LEN];
3104 int i, n, secretlen;
3109 if (len > 127) len = 127;
3112 * Shift the password 3 positions right to place a salt and original
3113 * length, tag will be added automatically on packet send
3115 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3119 * save original password length as first password character;
3126 * Generate salt. The RFC's say:
3128 * The high bit of salt[0] must be set, each salt in a
3129 * packet should be unique, and they should be random
3131 * So, we set the high bit, add in a counter, and then
3132 * add in some CSPRNG data. should be OK..
3134 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3135 (fr_rand() & 0x07));
3136 salt[1] = fr_rand();
3139 * Padd password to multiple of AUTH_PASS_LEN bytes.
3141 n = len % AUTH_PASS_LEN;
3143 n = AUTH_PASS_LEN - n;
3144 for (; n > 0; n--, len++)
3147 /* set new password length */
3151 * Use the secret to setup the decryption digest
3153 secretlen = strlen(secret);
3154 memcpy(buffer, secret, secretlen);
3156 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3158 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3159 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3160 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3162 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3163 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3166 for (i = 0; i < AUTH_PASS_LEN; i++) {
3167 passwd[i + n2] ^= digest[i];
3175 * Decode Tunnel-Password encrypted attributes.
3177 * Defined in RFC-2868, this uses a two char SALT along with the
3178 * initial intermediate value, to differentiate it from the
3181 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3182 const uint8_t *vector)
3184 FR_MD5_CTX context, old;
3185 uint8_t digest[AUTH_VECTOR_LEN];
3187 unsigned i, n, len, reallen;
3192 * We need at least a salt.
3195 fr_strerror_printf("tunnel password is too short");
3200 * There's a salt, but no password. Or, there's a salt
3201 * and a 'data_len' octet. It's wrong, but at least we
3202 * can figure out what it means: the password is empty.
3204 * Note that this means we ignore the 'data_len' field,
3205 * if the attribute length tells us that there's no
3206 * more data. So the 'data_len' field may be wrong,
3215 len -= 2; /* discount the salt */
3218 * Use the secret to setup the decryption digest
3220 secretlen = strlen(secret);
3222 fr_MD5Init(&context);
3223 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3224 old = context; /* save intermediate work */
3227 * Set up the initial key:
3229 * b(1) = MD5(secret + vector + salt)
3231 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3232 fr_MD5Update(&context, passwd, 2);
3235 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3239 fr_MD5Final(digest, &context);
3244 * A quick check: decrypt the first octet
3245 * of the password, which is the
3246 * 'data_len' field. Ensure it's sane.
3248 reallen = passwd[2] ^ digest[0];
3249 if (reallen >= len) {
3250 fr_strerror_printf("tunnel password is too long for the attribute");
3254 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3258 fr_MD5Final(digest, &context);
3261 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3264 for (i = base; i < AUTH_PASS_LEN; i++) {
3265 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3270 * See make_tunnel_password, above.
3272 if (reallen > 239) reallen = 239;
3275 passwd[reallen] = 0;
3281 * Encode a CHAP password
3283 * FIXME: might not work with Ascend because
3284 * we use vp->length, and Ascend gear likes
3285 * to send an extra '\0' in the string!
3287 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3288 VALUE_PAIR *password)
3292 uint8_t string[MAX_STRING_LEN * 2 + 1];
3293 VALUE_PAIR *challenge;
3296 * Sanity check the input parameters
3298 if ((packet == NULL) || (password == NULL)) {
3303 * Note that the password VP can be EITHER
3304 * a User-Password attribute (from a check-item list),
3305 * or a CHAP-Password attribute (the client asking
3306 * the library to encode it).
3314 memcpy(ptr, password->vp_strvalue, password->length);
3315 ptr += password->length;
3316 i += password->length;
3319 * Use Chap-Challenge pair if present,
3320 * Request-Authenticator otherwise.
3322 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3324 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3325 i += challenge->length;
3327 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3328 i += AUTH_VECTOR_LEN;
3332 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3339 * Seed the random number generator.
3341 * May be called any number of times.
3343 void fr_rand_seed(const void *data, size_t size)
3348 * Ensure that the pool is initialized.
3350 if (!fr_rand_initialized) {
3353 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3355 fd = open("/dev/urandom", O_RDONLY);
3361 while (total < sizeof(fr_rand_pool.randrsl)) {
3362 this = read(fd, fr_rand_pool.randrsl,
3363 sizeof(fr_rand_pool.randrsl) - total);
3364 if ((this < 0) && (errno != EINTR)) break;
3365 if (this > 0) total += this;
3369 fr_rand_pool.randrsl[0] = fd;
3370 fr_rand_pool.randrsl[1] = time(NULL);
3371 fr_rand_pool.randrsl[2] = errno;
3374 fr_randinit(&fr_rand_pool, 1);
3375 fr_rand_pool.randcnt = 0;
3376 fr_rand_initialized = 1;
3382 * Hash the user data
3385 if (!hash) hash = fr_rand();
3386 hash = fr_hash_update(data, size, hash);
3388 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3393 * Return a 32-bit random number.
3395 uint32_t fr_rand(void)
3400 * Ensure that the pool is initialized.
3402 if (!fr_rand_initialized) {
3403 fr_rand_seed(NULL, 0);
3406 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3407 if (fr_rand_pool.randcnt >= 256) {
3408 fr_rand_pool.randcnt = 0;
3409 fr_isaac(&fr_rand_pool);
3417 * Allocate a new RADIUS_PACKET
3419 RADIUS_PACKET *rad_alloc(int newvector)
3423 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3424 fr_strerror_printf("out of memory");
3427 memset(rp, 0, sizeof(*rp));
3433 uint32_t hash, base;
3436 * Don't expose the actual contents of the random
3440 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3441 hash = fr_rand() ^ base;
3442 memcpy(rp->vector + i, &hash, sizeof(hash));
3445 fr_rand(); /* stir the pool again */
3450 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3452 RADIUS_PACKET *reply;
3454 if (!packet) return NULL;
3456 reply = rad_alloc(0);
3457 if (!reply) return NULL;
3460 * Initialize the fields from the request.
3462 reply->sockfd = packet->sockfd;
3463 reply->dst_ipaddr = packet->src_ipaddr;
3464 reply->src_ipaddr = packet->dst_ipaddr;
3465 reply->dst_port = packet->src_port;
3466 reply->src_port = packet->dst_port;
3467 reply->id = packet->id;
3468 reply->code = 0; /* UNKNOWN code */
3469 memcpy(reply->vector, packet->vector,
3470 sizeof(reply->vector));
3473 reply->data_len = 0;
3480 * Free a RADIUS_PACKET
3482 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3484 RADIUS_PACKET *radius_packet;
3486 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3487 radius_packet = *radius_packet_ptr;
3489 free(radius_packet->data);
3491 pairfree(&radius_packet->vps);
3493 free(radius_packet);
3495 *radius_packet_ptr = NULL;