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.
442 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
444 memcpy(passwd, input, len);
445 memset(passwd + len, 0, sizeof(passwd) - len);
451 else if ((len & 0x0f) != 0) {
457 fr_MD5Init(&context);
458 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
464 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
466 for (n = 0; n < len; n += AUTH_PASS_LEN) {
469 fr_MD5Update(&context,
470 passwd + n - AUTH_PASS_LEN,
474 fr_MD5Final(digest, &context);
475 for (i = 0; i < AUTH_PASS_LEN; i++) {
476 passwd[i + n] ^= digest[i];
480 memcpy(output, passwd, len);
483 static void make_tunnel_passwd(uint8_t *output, int *outlen,
484 const uint8_t *input, int inlen, int room,
485 const char *secret, const uint8_t *vector)
487 FR_MD5_CTX context, old;
488 uint8_t digest[AUTH_VECTOR_LEN];
489 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
496 if (room > 253) room = 253;
499 * Account for 2 bytes of the salt, and round the room
500 * available down to the nearest multiple of 16. Then,
501 * subtract one from that to account for the length byte,
502 * and the resulting number is the upper bound on the data
505 * We could short-cut this calculation just be forcing
506 * inlen to be no more than 239. It would work for all
507 * VSA's, as we don't pack multiple VSA's into one
510 * However, this calculation is more general, if a little
511 * complex. And it will work in the future for all possible
512 * kinds of weird attribute packing.
515 room -= (room & 0x0f);
518 if (inlen > room) inlen = room;
521 * Length of the encrypted data is password length plus
522 * one byte for the length of the password.
525 if ((len & 0x0f) != 0) {
529 *outlen = len + 2; /* account for the salt */
532 * Copy the password over.
534 memcpy(passwd + 3, input, inlen);
535 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
538 * Generate salt. The RFC's say:
540 * The high bit of salt[0] must be set, each salt in a
541 * packet should be unique, and they should be random
543 * So, we set the high bit, add in a counter, and then
544 * add in some CSPRNG data. should be OK..
546 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
548 passwd[1] = fr_rand();
549 passwd[2] = inlen; /* length of the password string */
551 fr_MD5Init(&context);
552 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
555 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
556 fr_MD5Update(&context, &passwd[0], 2);
558 for (n = 0; n < len; n += AUTH_PASS_LEN) {
561 fr_MD5Update(&context,
562 passwd + 2 + n - AUTH_PASS_LEN,
566 fr_MD5Final(digest, &context);
567 for (i = 0; i < AUTH_PASS_LEN; i++) {
568 passwd[i + 2 + n] ^= digest[i];
571 memcpy(output, passwd, len + 2);
574 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
575 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
576 int offset, int room)
584 * Set up the default sources for the data.
586 data = vp->vp_octets;
593 case PW_TYPE_IPV6ADDR:
594 case PW_TYPE_IPV6PREFIX:
595 case PW_TYPE_ABINARY:
596 /* nothing more to do */
600 len = 1; /* just in case */
601 array[0] = vp->vp_integer & 0xff;
607 len = 2; /* just in case */
608 array[0] = (vp->vp_integer >> 8) & 0xff;
609 array[1] = vp->vp_integer & 0xff;
614 case PW_TYPE_INTEGER:
615 len = 4; /* just in case */
616 lvalue = htonl(vp->vp_integer);
617 memcpy(array, &lvalue, sizeof(lvalue));
620 * Perhaps discard the first octet.
622 data = &array[offset];
627 data = (const uint8_t *) &vp->vp_ipaddr;
628 len = 4; /* just in case */
632 * There are no tagged date attributes.
635 lvalue = htonl(vp->vp_date);
636 data = (const uint8_t *) &lvalue;
637 len = 4; /* just in case */
644 len = 4; /* just in case */
645 slvalue = htonl(vp->vp_signed);
646 memcpy(array, &slvalue, sizeof(slvalue));
653 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
658 default: /* unknown type: ignore it */
659 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
664 * Bound the data to 255 bytes.
666 if (len + offset > room) {
671 * Encrypt the various password styles
673 * Attributes with encrypted values MUST be less than
676 switch (vp->flags.encrypt) {
677 case FLAG_ENCRYPT_USER_PASSWORD:
678 make_passwd(ptr + offset, &len,
680 secret, packet->vector);
683 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
685 * Check if 255 - offset - total_length is less
686 * than 18. If so, we can't fit the data into
687 * the available space, and we discard the
690 * This is ONLY a problem if we have multiple VSA's
691 * in one Vendor-Specific, though.
693 if ((room - offset) < 18) return 0;
695 switch (packet->code) {
696 case PW_AUTHENTICATION_ACK:
697 case PW_AUTHENTICATION_REJECT:
698 case PW_ACCESS_CHALLENGE:
701 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
704 make_tunnel_passwd(ptr + offset, &len,
705 data, len, room - offset,
706 secret, original->vector);
708 case PW_ACCOUNTING_REQUEST:
709 case PW_DISCONNECT_REQUEST:
711 make_tunnel_passwd(ptr + offset, &len,
712 data, len, room - offset,
713 secret, packet->vector);
719 * The code above ensures that this attribute
722 case FLAG_ENCRYPT_ASCEND_SECRET:
723 make_secret(ptr + offset, packet->vector,
725 len = AUTH_VECTOR_LEN;
731 * Just copy the data over
733 memcpy(ptr + offset, data, len);
735 } /* switch over encryption flags */
741 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
744 int length, attribute;
746 VALUE_PAIR *vp, *tlv;
748 attribute = vps->attribute & 0xffff00ff;
749 maxattr = vps->attribute & 0x0ff;
751 tlv = paircreate(attribute, PW_TYPE_TLV);
752 if (!tlv) return NULL;
755 for (vp = vps; vp != NULL; vp = vp->next) {
757 * Group the attributes ONLY until we see a
760 if (!vp->flags.is_tlv ||
762 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
763 ((vp->attribute & 0xffff00ff) != attribute) ||
764 ((vp->attribute & 0x0000ff00) <= maxattr)) {
768 maxattr = vp->attribute & 0xff00;
769 tlv->length += vp->length + 2;
777 tlv->vp_tlv = malloc(tlv->length);
784 maxattr = vps->attribute & 0x0ff;
785 for (vp = vps; vp != NULL; vp = vp->next) {
786 if (!vp->flags.is_tlv ||
788 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
789 ((vp->attribute & 0xffff00ff) != attribute) ||
790 ((vp->attribute & 0x0000ff00) <= maxattr)) {
794 maxattr = vp->attribute & 0xff00;
795 length = vp2data(NULL, NULL, NULL, vp, ptr + 2, 0,
796 tlv->vp_tlv + tlv->length - ptr);
798 vp->length = ptr - vp->vp_tlv;
799 return tlv; /* should be a more serious error... */
803 * Pack the attribute.
805 ptr[0] = (vp->attribute & 0xff00) >> 8;
806 ptr[1] = (length & 0xff) + 2;
808 ptr += vp->length + 2;
809 vp->flags.encoded = 1;
816 * Pack data without any encryption.
817 * start == start of RADIUS attribute
818 * ptr == continuation byte (i.e. one after length)
820 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
824 size_t hsize = (ptr - start);
825 uint8_t *this = start;
830 * If it's too long and marked as encrypted, ignore it.
832 if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
836 memcpy(header, start, hsize);
847 data = vp->vp_octets;
858 memcpy(this, header, hsize);
865 if (left > (254 - hsize)) {
873 memcpy(ptr, data, piece);
874 this[1] = hsize + piece + 1;
879 this[hsize - 1] = hsize - 6 + 1 + piece;
886 return (ptr - start);
891 * Parse a data structure into a RADIUS attribute.
893 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
894 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
897 int offset, len, total_length;
899 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
902 vendorcode = total_length = 0;
903 length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
906 * For interoperability, always put vendor attributes
907 * into their own VSA.
909 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
910 *(ptr++) = vp->attribute & 0xFF;
919 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
922 * This must be an RFC-format attribute. If it
923 * wasn't, then the "decode" function would have
924 * made a Vendor-Specific attribute (i.e. type
925 * 26), and we would have "vendorcode == 0" here.
929 vsa_llen = dv->length;
930 if (dv->flags) vsa_offset = 1;
934 * Build a VSA header.
936 *ptr++ = PW_VENDOR_SPECIFIC;
937 vsa_length_ptr = ptr;
939 lvalue = htonl(vendorcode);
940 memcpy(ptr, &lvalue, 4);
946 ptr[0] = (vp->attribute & 0xFF);
950 ptr[0] = ((vp->attribute >> 8) & 0xFF);
951 ptr[1] = (vp->attribute & 0xFF);
957 ptr[2] = ((vp->attribute >> 8) & 0xFF);
958 ptr[3] = (vp->attribute & 0xFF);
962 return 0; /* silently discard it */
968 length_ptr = vsa_length_ptr;
969 vsa_length_ptr = NULL;
978 length_ptr = ptr + 1;
982 return 0; /* silently discard it */
987 * Allow for some continuation.
991 * Allow TLV's to be encoded, if someone
992 * manages to somehow encode the sub-tlv's.
994 * FIXME: Keep track of room in the packet!
996 if (vp->length > (254 - (ptr - start))) {
997 return rad_vp2continuation(vp, start, ptr);
1004 * sub-TLV's can only be in one format.
1006 if (vp->flags.is_tlv) {
1007 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1008 tlv_length_ptr = ptr;
1014 total_length += vsa_tlen + vsa_llen + vsa_offset;
1015 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1016 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1020 if (vp->flags.has_tag) {
1021 if (TAG_VALID(vp->flags.tag)) {
1022 ptr[0] = vp->flags.tag & 0xff;
1025 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
1027 * Tunnel passwords REQUIRE a tag, even
1028 * if don't have a valid tag.
1032 } /* else don't write a tag */
1033 } /* else the attribute doesn't have a tag */
1035 len = vp2data(packet, original, secret, vp, ptr, offset,
1036 255 - total_length);
1037 if (len < 0) return -1;
1040 * Account for the tag (if any).
1045 * RFC 2865 section 5 says that zero-length attributes
1048 * ... and the WiMAX forum ignores this... because of
1049 * one vendor. Don't they have anything better to do
1053 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1056 * Update the various lengths.
1059 if (vsa_length_ptr) *vsa_length_ptr += len;
1060 if (tlv_length_ptr) *tlv_length_ptr += len;
1062 total_length += len;
1064 return total_length; /* of attribute */
1071 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1074 radius_packet_t *hdr;
1076 uint16_t total_length;
1080 char ip_buffer[128];
1083 * For simplicity in the following logic, we allow
1084 * the attributes to "overflow" the 4k maximum
1085 * RADIUS packet size, by one attribute.
1087 * It's uint32_t, for alignment purposes.
1089 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
1091 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1092 what = fr_packet_codes[packet->code];
1097 DEBUG("Sending %s of id %d to %s port %d\n",
1099 inet_ntop(packet->dst_ipaddr.af,
1100 &packet->dst_ipaddr.ipaddr,
1101 ip_buffer, sizeof(ip_buffer)),
1105 * Double-check some things based on packet code.
1107 switch (packet->code) {
1108 case PW_AUTHENTICATION_ACK:
1109 case PW_AUTHENTICATION_REJECT:
1110 case PW_ACCESS_CHALLENGE:
1112 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1118 * These packet vectors start off as all zero.
1120 case PW_ACCOUNTING_REQUEST:
1121 case PW_DISCONNECT_REQUEST:
1122 case PW_COA_REQUEST:
1123 memset(packet->vector, 0, sizeof(packet->vector));
1131 * Use memory on the stack, until we know how
1132 * large the packet will be.
1134 hdr = (radius_packet_t *) data;
1137 * Build standard header
1139 hdr->code = packet->code;
1140 hdr->id = packet->id;
1142 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1144 total_length = AUTH_HDR_LEN;
1147 * Load up the configuration values for the user
1153 * FIXME: Loop twice over the reply list. The first time,
1154 * calculate the total length of data. The second time,
1155 * allocate the memory, and fill in the VP's.
1157 * Hmm... this may be slower than just doing a small
1162 * Loop over the reply attributes for the packet.
1164 for (reply = packet->vps; reply; reply = reply->next) {
1166 * Ignore non-wire attributes
1168 if ((VENDOR(reply->attribute) == 0) &&
1169 ((reply->attribute & 0xFFFF) > 0xff)) {
1172 * Permit the admin to send BADLY formatted
1173 * attributes with a debug build.
1175 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1176 memcpy(ptr, reply->vp_octets, reply->length);
1177 len = reply->length;
1185 * Set the Message-Authenticator to the correct
1186 * length and initial value.
1188 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1189 reply->length = AUTH_VECTOR_LEN;
1190 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1193 * Cache the offset to the
1194 * Message-Authenticator
1196 packet->offset = total_length;
1200 * Print out ONLY the attributes which
1201 * we're sending over the wire, and print
1202 * them out BEFORE they're encrypted.
1207 * Print them in order, even if they were encoded
1211 if (reply->flags.encoded) goto next;
1213 if (reply->flags.is_tlv) {
1214 VALUE_PAIR *tlv = rad_vp2tlv(reply);
1216 tlv->next = reply->next;
1221 * The encoded flag MUST be set in reply!
1223 reply = reply->next;
1226 len = rad_vp2attr(packet, original, secret, reply, ptr);
1228 if (len < 0) return -1;
1231 * Check that the packet is no more than 4k in
1232 * size, AFTER writing the attribute past the 4k
1233 * boundary, but BEFORE deciding to increase the
1234 * size of the packet. Note that the 'data'
1235 * buffer, above, is one attribute longer than
1236 * necessary, in order to permit this overflow.
1238 if ((total_length + len) > MAX_PACKET_LEN) {
1244 total_length += len;
1245 } /* done looping over all attributes */
1248 * Fill in the rest of the fields, and copy the data over
1249 * from the local stack to the newly allocated memory.
1251 * Yes, all this 'memcpy' is slow, but it means
1252 * that we only allocate the minimum amount of
1253 * memory for a request.
1255 packet->data_len = total_length;
1256 packet->data = (uint8_t *) malloc(packet->data_len);
1257 if (!packet->data) {
1258 fr_strerror_printf("Out of memory");
1262 memcpy(packet->data, hdr, packet->data_len);
1263 hdr = (radius_packet_t *) packet->data;
1265 total_length = htons(total_length);
1266 memcpy(hdr->length, &total_length, sizeof(total_length));
1273 * Sign a previously encoded packet.
1275 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1278 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1281 * It wasn't assigned an Id, this is bad!
1283 if (packet->id < 0) {
1284 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1288 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1289 (packet->offset < 0)) {
1290 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1295 * If there's a Message-Authenticator, update it
1296 * now, BEFORE updating the authentication vector.
1298 if (packet->offset > 0) {
1299 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1301 switch (packet->code) {
1302 case PW_ACCOUNTING_REQUEST:
1303 case PW_ACCOUNTING_RESPONSE:
1304 case PW_DISCONNECT_REQUEST:
1305 case PW_DISCONNECT_ACK:
1306 case PW_DISCONNECT_NAK:
1307 case PW_COA_REQUEST:
1310 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1313 case PW_AUTHENTICATION_ACK:
1314 case PW_AUTHENTICATION_REJECT:
1315 case PW_ACCESS_CHALLENGE:
1317 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1320 memcpy(hdr->vector, original->vector,
1324 default: /* others have vector already set to zero */
1330 * Set the authentication vector to zero,
1331 * calculate the signature, and put it
1332 * into the Message-Authenticator
1335 fr_hmac_md5(packet->data, packet->data_len,
1336 (const uint8_t *) secret, strlen(secret),
1338 memcpy(packet->data + packet->offset + 2,
1339 calc_auth_vector, AUTH_VECTOR_LEN);
1342 * Copy the original request vector back
1343 * to the raw packet.
1345 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1349 * Switch over the packet code, deciding how to
1352 switch (packet->code) {
1354 * Request packets are not signed, bur
1355 * have a random authentication vector.
1357 case PW_AUTHENTICATION_REQUEST:
1358 case PW_STATUS_SERVER:
1362 * Reply packets are signed with the
1363 * authentication vector of the request.
1370 fr_MD5Init(&context);
1371 fr_MD5Update(&context, packet->data, packet->data_len);
1372 fr_MD5Update(&context, (const uint8_t *) secret,
1374 fr_MD5Final(digest, &context);
1376 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1377 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1380 }/* switch over packet codes */
1386 * Reply to the request. Also attach
1387 * reply attribute value pairs and any user message provided.
1389 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1394 char ip_buffer[128];
1397 * Maybe it's a fake packet. Don't send it.
1399 if (!packet || (packet->sockfd < 0)) {
1403 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1404 what = fr_packet_codes[packet->code];
1410 * First time through, allocate room for the packet
1412 if (!packet->data) {
1414 * Encode the packet.
1416 if (rad_encode(packet, original, secret) < 0) {
1421 * Re-sign it, including updating the
1422 * Message-Authenticator.
1424 if (rad_sign(packet, original, secret) < 0) {
1429 * If packet->data points to data, then we print out
1430 * the VP list again only for debugging.
1432 } else if (fr_debug_flag) {
1433 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1434 inet_ntop(packet->dst_ipaddr.af,
1435 &packet->dst_ipaddr.ipaddr,
1436 ip_buffer, sizeof(ip_buffer)),
1439 for (reply = packet->vps; reply; reply = reply->next) {
1440 if ((VENDOR(reply->attribute) == 0) &&
1441 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1447 * And send it on it's way.
1449 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1450 &packet->src_ipaddr, packet->src_port,
1451 &packet->dst_ipaddr, packet->dst_port);
1456 * Validates the requesting client NAS. Calculates the
1457 * signature based on the clients private key.
1459 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1461 uint8_t digest[AUTH_VECTOR_LEN];
1465 * Zero out the auth_vector in the received packet.
1466 * Then append the shared secret to the received packet,
1467 * and calculate the MD5 sum. This must be the same
1468 * as the original MD5 sum (packet->vector).
1470 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1473 * MD5(packet + secret);
1475 fr_MD5Init(&context);
1476 fr_MD5Update(&context, packet->data, packet->data_len);
1477 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1478 fr_MD5Final(digest, &context);
1481 * Return 0 if OK, 2 if not OK.
1483 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1489 * Validates the requesting client NAS. Calculates the
1490 * signature based on the clients private key.
1492 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1495 uint8_t calc_digest[AUTH_VECTOR_LEN];
1501 if (original == NULL) {
1506 * Copy the original vector in place.
1508 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1511 * MD5(packet + secret);
1513 fr_MD5Init(&context);
1514 fr_MD5Update(&context, packet->data, packet->data_len);
1515 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1516 fr_MD5Final(calc_digest, &context);
1519 * Copy the packet's vector back to the packet.
1521 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1524 * Return 0 if OK, 2 if not OK.
1526 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1532 * See if the data pointed to by PTR is a valid RADIUS packet.
1534 * packet is not 'const * const' because we may update data_len,
1535 * if there's more data in the UDP packet than in the RADIUS packet.
1537 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1542 radius_packet_t *hdr;
1543 char host_ipaddr[128];
1549 * Check for packets smaller than the packet header.
1551 * RFC 2865, Section 3., subsection 'length' says:
1553 * "The minimum length is 20 ..."
1555 if (packet->data_len < AUTH_HDR_LEN) {
1556 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1557 inet_ntop(packet->src_ipaddr.af,
1558 &packet->src_ipaddr.ipaddr,
1559 host_ipaddr, sizeof(host_ipaddr)),
1560 packet->data_len, AUTH_HDR_LEN);
1565 * RFC 2865, Section 3., subsection 'length' says:
1567 * " ... and maximum length is 4096."
1569 if (packet->data_len > MAX_PACKET_LEN) {
1570 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1571 inet_ntop(packet->src_ipaddr.af,
1572 &packet->src_ipaddr.ipaddr,
1573 host_ipaddr, sizeof(host_ipaddr)),
1574 packet->data_len, MAX_PACKET_LEN);
1579 * Check for packets with mismatched size.
1580 * i.e. We've received 128 bytes, and the packet header
1581 * says it's 256 bytes long.
1583 totallen = (packet->data[2] << 8) | packet->data[3];
1584 hdr = (radius_packet_t *)packet->data;
1587 * Code of 0 is not understood.
1588 * Code of 16 or greate is not understood.
1590 if ((hdr->code == 0) ||
1591 (hdr->code >= FR_MAX_PACKET_CODE)) {
1592 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1593 inet_ntop(packet->src_ipaddr.af,
1594 &packet->src_ipaddr.ipaddr,
1595 host_ipaddr, sizeof(host_ipaddr)),
1601 * Message-Authenticator is required in Status-Server
1602 * packets, otherwise they can be trivially forged.
1604 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1607 * It's also required if the caller asks for it.
1609 if (flags) require_ma = 1;
1612 * Repeat the length checks. This time, instead of
1613 * looking at the data we received, look at the value
1614 * of the 'length' field inside of the packet.
1616 * Check for packets smaller than the packet header.
1618 * RFC 2865, Section 3., subsection 'length' says:
1620 * "The minimum length is 20 ..."
1622 if (totallen < AUTH_HDR_LEN) {
1623 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1624 inet_ntop(packet->src_ipaddr.af,
1625 &packet->src_ipaddr.ipaddr,
1626 host_ipaddr, sizeof(host_ipaddr)),
1627 totallen, AUTH_HDR_LEN);
1632 * And again, for the value of the 'length' field.
1634 * RFC 2865, Section 3., subsection 'length' says:
1636 * " ... and maximum length is 4096."
1638 if (totallen > MAX_PACKET_LEN) {
1639 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1640 inet_ntop(packet->src_ipaddr.af,
1641 &packet->src_ipaddr.ipaddr,
1642 host_ipaddr, sizeof(host_ipaddr)),
1643 totallen, MAX_PACKET_LEN);
1648 * RFC 2865, Section 3., subsection 'length' says:
1650 * "If the packet is shorter than the Length field
1651 * indicates, it MUST be silently discarded."
1653 * i.e. No response to the NAS.
1655 if (packet->data_len < totallen) {
1656 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1657 inet_ntop(packet->src_ipaddr.af,
1658 &packet->src_ipaddr.ipaddr,
1659 host_ipaddr, sizeof(host_ipaddr)),
1660 packet->data_len, totallen);
1665 * RFC 2865, Section 3., subsection 'length' says:
1667 * "Octets outside the range of the Length field MUST be
1668 * treated as padding and ignored on reception."
1670 if (packet->data_len > totallen) {
1672 * We're shortening the packet below, but just
1673 * to be paranoid, zero out the extra data.
1675 memset(packet->data + totallen, 0, packet->data_len - totallen);
1676 packet->data_len = totallen;
1680 * Walk through the packet's attributes, ensuring that
1681 * they add up EXACTLY to the size of the packet.
1683 * If they don't, then the attributes either under-fill
1684 * or over-fill the packet. Any parsing of the packet
1685 * is impossible, and will result in unknown side effects.
1687 * This would ONLY happen with buggy RADIUS implementations,
1688 * or with an intentional attack. Either way, we do NOT want
1689 * to be vulnerable to this problem.
1692 count = totallen - AUTH_HDR_LEN;
1697 * Attribute number zero is NOT defined.
1700 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1701 inet_ntop(packet->src_ipaddr.af,
1702 &packet->src_ipaddr.ipaddr,
1703 host_ipaddr, sizeof(host_ipaddr)));
1708 * Attributes are at LEAST as long as the ID & length
1709 * fields. Anything shorter is an invalid attribute.
1712 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1713 inet_ntop(packet->src_ipaddr.af,
1714 &packet->src_ipaddr.ipaddr,
1715 host_ipaddr, sizeof(host_ipaddr)),
1721 * Sanity check the attributes for length.
1724 default: /* don't do anything by default */
1728 * If there's an EAP-Message, we require
1729 * a Message-Authenticator.
1731 case PW_EAP_MESSAGE:
1735 case PW_MESSAGE_AUTHENTICATOR:
1736 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1737 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1738 inet_ntop(packet->src_ipaddr.af,
1739 &packet->src_ipaddr.ipaddr,
1740 host_ipaddr, sizeof(host_ipaddr)),
1749 * FIXME: Look up the base 255 attributes in the
1750 * dictionary, and switch over their type. For
1751 * integer/date/ip, the attribute length SHOULD
1754 count -= attr[1]; /* grab the attribute length */
1756 num_attributes++; /* seen one more attribute */
1760 * If the attributes add up to a packet, it's allowed.
1762 * If not, we complain, and throw the packet away.
1765 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1766 inet_ntop(packet->src_ipaddr.af,
1767 &packet->src_ipaddr.ipaddr,
1768 host_ipaddr, sizeof(host_ipaddr)));
1773 * If we're configured to look for a maximum number of
1774 * attributes, and we've seen more than that maximum,
1775 * then throw the packet away, as a possible DoS.
1777 if ((fr_max_attributes > 0) &&
1778 (num_attributes > fr_max_attributes)) {
1779 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1780 inet_ntop(packet->src_ipaddr.af,
1781 &packet->src_ipaddr.ipaddr,
1782 host_ipaddr, sizeof(host_ipaddr)),
1783 num_attributes, fr_max_attributes);
1788 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1790 * A packet with an EAP-Message attribute MUST also have
1791 * a Message-Authenticator attribute.
1793 * A Message-Authenticator all by itself is OK, though.
1795 * Similarly, Status-Server packets MUST contain
1796 * Message-Authenticator attributes.
1798 if (require_ma && ! seen_ma) {
1799 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1800 inet_ntop(packet->src_ipaddr.af,
1801 &packet->src_ipaddr.ipaddr,
1802 host_ipaddr, sizeof(host_ipaddr)));
1807 * Fill RADIUS header fields
1809 packet->code = hdr->code;
1810 packet->id = hdr->id;
1811 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1818 * Receive UDP client requests, and fill in
1819 * the basics of a RADIUS_PACKET structure.
1821 RADIUS_PACKET *rad_recv(int fd, int flags)
1824 RADIUS_PACKET *packet;
1827 * Allocate the new request data structure
1829 if ((packet = malloc(sizeof(*packet))) == NULL) {
1830 fr_strerror_printf("out of memory");
1833 memset(packet, 0, sizeof(*packet));
1836 sock_flags = MSG_PEEK;
1840 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1841 &packet->src_ipaddr, &packet->src_port,
1842 &packet->dst_ipaddr, &packet->dst_port);
1845 * Check for socket errors.
1847 if (packet->data_len < 0) {
1848 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1849 /* packet->data is NULL */
1855 * If the packet is too big, then rad_recvfrom did NOT
1856 * allocate memory. Instead, it just discarded the
1859 if (packet->data_len > MAX_PACKET_LEN) {
1860 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1861 /* packet->data is NULL */
1867 * Read no data. Continue.
1868 * This check is AFTER the MAX_PACKET_LEN check above, because
1869 * if the packet is larger than MAX_PACKET_LEN, we also have
1870 * packet->data == NULL
1872 if ((packet->data_len == 0) || !packet->data) {
1873 fr_strerror_printf("Empty packet: Socket is not ready.");
1879 * See if it's a well-formed RADIUS packet.
1881 if (!rad_packet_ok(packet, flags)) {
1887 * Remember which socket we read the packet from.
1889 packet->sockfd = fd;
1892 * FIXME: Do even more filtering by only permitting
1893 * certain IP's. The problem is that we don't know
1894 * how to do this properly for all possible clients...
1898 * Explicitely set the VP list to empty.
1902 if (fr_debug_flag) {
1903 char host_ipaddr[128];
1905 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1906 DEBUG("rad_recv: %s packet from host %s port %d",
1907 fr_packet_codes[packet->code],
1908 inet_ntop(packet->src_ipaddr.af,
1909 &packet->src_ipaddr.ipaddr,
1910 host_ipaddr, sizeof(host_ipaddr)),
1913 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1914 inet_ntop(packet->src_ipaddr.af,
1915 &packet->src_ipaddr.ipaddr,
1916 host_ipaddr, sizeof(host_ipaddr)),
1920 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1928 * Verify the signature of a packet.
1930 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1937 if (!packet || !packet->data) return -1;
1940 * Before we allocate memory for the attributes, do more
1943 ptr = packet->data + AUTH_HDR_LEN;
1944 length = packet->data_len - AUTH_HDR_LEN;
1945 while (length > 0) {
1946 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1947 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1952 default: /* don't do anything. */
1956 * Note that more than one Message-Authenticator
1957 * attribute is invalid.
1959 case PW_MESSAGE_AUTHENTICATOR:
1960 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1961 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1963 switch (packet->code) {
1967 case PW_ACCOUNTING_REQUEST:
1968 case PW_ACCOUNTING_RESPONSE:
1969 case PW_DISCONNECT_REQUEST:
1970 case PW_DISCONNECT_ACK:
1971 case PW_DISCONNECT_NAK:
1972 case PW_COA_REQUEST:
1975 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1978 case PW_AUTHENTICATION_ACK:
1979 case PW_AUTHENTICATION_REJECT:
1980 case PW_ACCESS_CHALLENGE:
1982 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1985 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1989 fr_hmac_md5(packet->data, packet->data_len,
1990 (const uint8_t *) secret, strlen(secret),
1992 if (memcmp(calc_auth_vector, msg_auth_vector,
1993 sizeof(calc_auth_vector)) != 0) {
1995 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1996 inet_ntop(packet->src_ipaddr.af,
1997 &packet->src_ipaddr.ipaddr,
1998 buffer, sizeof(buffer)));
1999 /* Silently drop packet, according to RFC 3579 */
2001 } /* else the message authenticator was good */
2004 * Reinitialize Authenticators.
2006 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2007 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2009 } /* switch over the attributes */
2013 } /* loop over the packet, sanity checking the attributes */
2016 * It looks like a RADIUS packet, but we can't validate
2019 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2021 fr_strerror_printf("Received Unknown packet code %d "
2022 "from client %s port %d: Cannot validate signature.",
2024 inet_ntop(packet->src_ipaddr.af,
2025 &packet->src_ipaddr.ipaddr,
2026 buffer, sizeof(buffer)),
2032 * Calculate and/or verify digest.
2034 switch(packet->code) {
2038 case PW_AUTHENTICATION_REQUEST:
2039 case PW_STATUS_SERVER:
2041 * The authentication vector is random
2042 * nonsense, invented by the client.
2046 case PW_COA_REQUEST:
2047 case PW_DISCONNECT_REQUEST:
2048 case PW_ACCOUNTING_REQUEST:
2049 if (calc_acctdigest(packet, secret) > 1) {
2050 fr_strerror_printf("Received %s packet "
2051 "from %s with invalid signature! (Shared secret is incorrect.)",
2052 fr_packet_codes[packet->code],
2053 inet_ntop(packet->src_ipaddr.af,
2054 &packet->src_ipaddr.ipaddr,
2055 buffer, sizeof(buffer)));
2060 /* Verify the reply digest */
2061 case PW_AUTHENTICATION_ACK:
2062 case PW_AUTHENTICATION_REJECT:
2063 case PW_ACCESS_CHALLENGE:
2064 case PW_ACCOUNTING_RESPONSE:
2065 case PW_DISCONNECT_ACK:
2066 case PW_DISCONNECT_NAK:
2069 rcode = calc_replydigest(packet, original, secret);
2071 fr_strerror_printf("Received %s packet "
2072 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2073 fr_packet_codes[packet->code],
2074 inet_ntop(packet->src_ipaddr.af,
2075 &packet->src_ipaddr.ipaddr,
2076 buffer, sizeof(buffer)),
2084 fr_strerror_printf("Received Unknown packet code %d "
2085 "from client %s port %d: Cannot validate signature",
2087 inet_ntop(packet->src_ipaddr.af,
2088 &packet->src_ipaddr.ipaddr,
2089 buffer, sizeof(buffer)),
2098 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2099 const RADIUS_PACKET *original,
2100 const char *secret, int attribute, int length,
2101 const uint8_t *data, VALUE_PAIR *vp)
2106 * If length is greater than 253, something is SERIOUSLY
2109 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2111 vp->length = length;
2112 vp->operator = T_OP_EQ;
2118 if (vp->flags.has_tag) {
2119 if (TAG_VALID(data[0]) ||
2120 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2122 * Tunnel passwords REQUIRE a tag, even
2123 * if don't have a valid tag.
2125 vp->flags.tag = data[0];
2127 if ((vp->type == PW_TYPE_STRING) ||
2128 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2133 * Copy the data to be decrypted
2135 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2136 vp->length -= offset;
2139 * Decrypt the attribute.
2141 switch (vp->flags.encrypt) {
2145 case FLAG_ENCRYPT_USER_PASSWORD:
2147 rad_pwdecode((char *)vp->vp_strvalue,
2151 rad_pwdecode((char *)vp->vp_strvalue,
2155 if (vp->attribute == PW_USER_PASSWORD) {
2156 vp->length = strlen(vp->vp_strvalue);
2161 * Tunnel-Password's may go ONLY
2162 * in response packets.
2164 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2165 if (!original) goto raw;
2167 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2168 secret, original->vector) < 0) {
2174 * Ascend-Send-Secret
2175 * Ascend-Receive-Secret
2177 case FLAG_ENCRYPT_ASCEND_SECRET:
2181 uint8_t my_digest[AUTH_VECTOR_LEN];
2182 make_secret(my_digest,
2185 memcpy(vp->vp_strvalue, my_digest,
2187 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2188 vp->length = strlen(vp->vp_strvalue);
2194 } /* switch over encryption flags */
2198 case PW_TYPE_STRING:
2199 case PW_TYPE_OCTETS:
2200 case PW_TYPE_ABINARY:
2201 /* nothing more to do */
2205 if (vp->length != 1) goto raw;
2207 vp->vp_integer = vp->vp_octets[0];
2212 if (vp->length != 2) goto raw;
2214 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2217 case PW_TYPE_INTEGER:
2218 if (vp->length != 4) goto raw;
2220 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2221 vp->vp_integer = ntohl(vp->vp_integer);
2223 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2226 * Try to get named VALUEs
2230 dval = dict_valbyattr(vp->attribute,
2233 strlcpy(vp->vp_strvalue,
2235 sizeof(vp->vp_strvalue));
2241 if (vp->length != 4) goto raw;
2243 memcpy(&vp->vp_date, vp->vp_octets, 4);
2244 vp->vp_date = ntohl(vp->vp_date);
2248 case PW_TYPE_IPADDR:
2249 if (vp->length != 4) goto raw;
2251 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2255 * IPv6 interface ID is 8 octets long.
2258 if (vp->length != 8) goto raw;
2259 /* vp->vp_ifid == vp->vp_octets */
2263 * IPv6 addresses are 16 octets long
2265 case PW_TYPE_IPV6ADDR:
2266 if (vp->length != 16) goto raw;
2267 /* vp->vp_ipv6addr == vp->vp_octets */
2271 * IPv6 prefixes are 2 to 18 octets long.
2273 * RFC 3162: The first octet is unused.
2274 * The second is the length of the prefix
2275 * the rest are the prefix data.
2277 * The prefix length can have value 0 to 128.
2279 case PW_TYPE_IPV6PREFIX:
2280 if (vp->length < 2 || vp->length > 18) goto raw;
2281 if (vp->vp_octets[1] > 128) goto raw;
2284 * FIXME: double-check that
2285 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2287 if (vp->length < 18) {
2288 memset(vp->vp_octets + vp->length, 0,
2293 case PW_TYPE_SIGNED:
2294 if (vp->length != 4) goto raw;
2297 * Overload vp_integer for ntohl, which takes
2298 * uint32_t, not int32_t
2300 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2301 vp->vp_integer = ntohl(vp->vp_integer);
2302 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2306 vp->length = length;
2307 vp->vp_tlv = malloc(length);
2310 fr_strerror_printf("No memory");
2313 memcpy(vp->vp_tlv, data, length);
2316 case PW_TYPE_COMBO_IP:
2317 if (vp->length == 4) {
2318 vp->type = PW_TYPE_IPADDR;
2319 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2322 } else if (vp->length == 16) {
2323 vp->type = PW_TYPE_IPV6ADDR;
2324 /* vp->vp_ipv6addr == vp->vp_octets */
2332 vp->type = PW_TYPE_OCTETS;
2333 vp->length = length;
2334 memcpy(vp->vp_octets, data, length);
2338 * Ensure there's no encryption or tag stuff,
2339 * we just pass the attribute as-is.
2341 memset(&vp->flags, 0, sizeof(vp->flags));
2347 static void rad_sortvp(VALUE_PAIR **head)
2350 VALUE_PAIR *vp, **tail;
2353 * Walk over the VP's, sorting them in order. Did I
2354 * mention that I hate WiMAX continuations?
2356 * And bubble sort! WTF is up with that?
2363 if (!vp->next) break;
2365 if (vp->attribute > vp->next->attribute) {
2367 vp->next = (*tail)->next;
2378 * Walk the packet, looking for continuations of this attribute.
2380 * This is (worst-case) O(N^2) in the number of RADIUS
2381 * attributes. That happens only when perverse clients create
2382 * continued attributes, AND separate the fragmented portions
2383 * with a lot of other attributes.
2385 * Sane clients should put the fragments next to each other, in
2386 * which case this is O(N), in the number of fragments.
2388 static uint8_t *rad_coalesce(int attribute, size_t length, uint8_t *data,
2389 size_t packet_length, size_t *ptlv_length)
2393 size_t tlv_length = length;
2394 uint8_t *ptr, *tlv, *tlv_data;
2396 for (ptr = data + length;
2397 ptr != (data + packet_length);
2399 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2400 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2401 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2405 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2406 lvalue = ntohl(lvalue);
2408 lvalue |= ptr[2 + 4]; /* add in VSA number */
2409 if (lvalue != attribute) continue;
2412 * If the vendor-length is too small, it's badly
2413 * formed, so we stop.
2415 if ((ptr[2 + 4 + 1]) < 3) break;
2417 tlv_length += ptr[2 + 4 + 1] - 3;
2418 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2421 tlv = tlv_data = malloc(tlv_length);
2422 if (!tlv_data) return NULL;
2424 memcpy(tlv, data, length);
2428 * Now we walk the list again, copying the data over to
2429 * our newly created memory.
2431 for (ptr = data + length;
2432 ptr != (data + packet_length);
2436 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2437 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2438 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2442 memcpy(&lvalue, ptr + 2, 4);
2443 lvalue = ntohl(lvalue);
2445 lvalue |= ptr[2 + 4];
2446 if (lvalue != attribute) continue;
2449 * If the vendor-length is too small, it's badly
2450 * formed, so we stop.
2452 if ((ptr[2 + 4 + 1]) < 3) break;
2454 this_length = ptr[2 + 4 + 1] - 3;
2455 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2458 ptr[2 + 4] = 0; /* What a hack! */
2459 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2462 *ptlv_length = tlv_length;
2467 * Start at the *data* portion of a continued attribute. search
2468 * through the rest of the attributes to find a matching one, and
2469 * add it's contents to our contents.
2471 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2472 const RADIUS_PACKET *original,
2473 const char *secret, int attribute,
2474 int length, /* CANNOT be zero */
2475 uint8_t *data, size_t packet_length,
2476 int flag, DICT_ATTR *da)
2478 size_t tlv_length, left;
2481 VALUE_PAIR *vp, *head, **tail;
2484 * Ensure we have data that hasn't been split across
2485 * multiple attributes.
2488 tlv_data = rad_coalesce(attribute, length,
2489 data, packet_length, &tlv_length);
2490 if (!tlv_data) return NULL;
2493 tlv_length = length;
2497 * Non-TLV types cannot be continued across multiple
2498 * attributes. This is true even of keys that are
2499 * encrypted with the tunnel-password method. The spec
2500 * says that they can be continued... but also that the
2501 * keys are 160 bits, which means that they CANNOT be
2504 * Note that we don't check "flag" here. The calling
2507 if (da->type != PW_TYPE_TLV) {
2509 if (tlv_data == data) { /* true if we had 'goto' */
2510 tlv_data = malloc(tlv_length);
2511 if (!tlv_data) return NULL;
2512 memcpy(tlv_data, data, tlv_length);
2515 vp = paircreate(attribute, PW_TYPE_OCTETS);
2516 if (!vp) return NULL;
2518 vp->type = PW_TYPE_TLV;
2519 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2520 vp->flags.has_tag = 0;
2521 vp->flags.is_tlv = 0;
2522 vp->vp_tlv = tlv_data;
2523 vp->length = tlv_length;
2525 } /* else it WAS a TLV, go decode the sub-tlv's */
2528 * Now (sigh) we walk over the TLV, seeing if it is
2532 for (ptr = tlv_data;
2533 ptr != (tlv_data + tlv_length);
2538 goto not_well_formed;
2544 * Now we walk over the TLV *again*, creating sub-tlv's.
2549 for (ptr = tlv_data;
2550 ptr != (tlv_data + tlv_length);
2552 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2555 goto not_well_formed;
2558 if (!data2vp(packet, original, secret,
2559 ptr[0], ptr[1] - 2, ptr + 2, vp)) {
2561 goto not_well_formed;
2569 * TLV's MAY be continued, but sometimes they're not.
2571 if (tlv_data != data) free(tlv_data);
2573 if (head->next) rad_sortvp(&head);
2580 * Parse a RADIUS attribute into a data structure.
2582 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2583 const char *secret, int attribute, int length,
2584 const uint8_t *data)
2588 vp = paircreate(attribute, PW_TYPE_OCTETS);
2589 if (!vp) return NULL;
2591 return data2vp(packet, original, secret, attribute, length, data, vp);
2596 * Calculate/check digest, and decode radius attributes.
2598 * -1 on decoding error
2601 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2605 uint32_t vendorcode;
2608 uint8_t *ptr, *vsa_ptr;
2613 radius_packet_t *hdr;
2614 int vsa_tlen, vsa_llen, vsa_offset;
2615 DICT_VENDOR *dv = NULL;
2616 int num_attributes = 0;
2619 * Extract attribute-value pairs
2621 hdr = (radius_packet_t *)packet->data;
2623 packet_length = packet->data_len - AUTH_HDR_LEN;
2626 * There may be VP's already in the packet. Don't
2629 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2635 vsa_tlen = vsa_llen = 1;
2639 * We have to read at least two bytes.
2641 * rad_recv() above ensures that this is OK.
2643 while (packet_length > 0) {
2648 * Normal attribute, handle it like normal.
2650 if (vendorcode == 0) {
2652 * No room to read attr/length,
2653 * or bad attribute, or attribute is
2654 * too short, or attribute is too long,
2655 * stop processing the packet.
2657 if ((packet_length < 2) ||
2658 (ptr[0] == 0) || (ptr[1] < 2) ||
2659 (ptr[1] > packet_length)) break;
2667 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2670 * No vendor code, or ONLY vendor code.
2672 if (attrlen <= 4) goto create_pair;
2678 * Handle Vendor-Specific
2680 if (vendorlen == 0) {
2686 * attrlen was checked above.
2688 memcpy(&lvalue, ptr, 4);
2689 myvendor = ntohl(lvalue);
2692 * Zero isn't allowed.
2694 if (myvendor == 0) goto create_pair;
2697 * This is an implementation issue.
2698 * We currently pack vendor into the upper
2699 * 16 bits of a 32-bit attribute number,
2700 * so we can't handle vendor numbers larger
2703 if (myvendor > 65535) goto create_pair;
2705 vsa_tlen = vsa_llen = 1;
2707 dv = dict_vendorbyvalue(myvendor);
2709 vsa_tlen = dv->type;
2710 vsa_llen = dv->length;
2711 if (dv->flags) vsa_offset = 1;
2715 * Sweep through the list of VSA's,
2716 * seeing if they exactly fill the
2717 * outer Vendor-Specific attribute.
2719 * If not, create a raw Vendor-Specific.
2722 sublen = attrlen - 4;
2725 * See if we can parse it.
2731 * Not enough room for one more
2734 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2737 * Ensure that the attribute number
2746 myattr = (subptr[0] << 8) | subptr[1];
2750 if ((subptr[0] != 0) ||
2751 (subptr[1] != 0)) goto create_pair;
2753 myattr = (subptr[2] << 8) | subptr[3];
2757 * Our dictionary is broken.
2765 attribute = (myvendor << 16) | myattr;
2766 ptr += 4 + vsa_tlen;
2767 attrlen -= (4 + vsa_tlen);
2768 packet_length -= 4 + vsa_tlen;
2772 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2775 if (subptr[vsa_tlen] > sublen)
2780 * Reserved bits MUST be
2784 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2787 sublen -= subptr[vsa_tlen];
2788 subptr += subptr[vsa_tlen];
2792 if (subptr[vsa_tlen] != 0) goto create_pair;
2793 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2795 if (subptr[vsa_tlen + 1] > sublen)
2797 sublen -= subptr[vsa_tlen + 1];
2798 subptr += subptr[vsa_tlen + 1];
2802 * Our dictionaries are
2808 } while (sublen > 0);
2810 vendorcode = myvendor;
2811 vendorlen = attrlen - 4;
2818 * attrlen is the length of this attribute.
2819 * total_len is the length of the encompassing
2828 attribute = (ptr[0] << 8) | ptr[1];
2831 default: /* can't hit this. */
2834 attribute |= (vendorcode << 16);
2840 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2844 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2847 default: /* can't hit this. */
2851 ptr += vsa_llen + vsa_offset;
2852 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2853 if (vendorlen == 0) vendorcode = 0;
2854 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2857 * Ignore VSAs that have no data.
2859 if (attrlen == 0) goto next;
2862 * WiMAX attributes of type 0 are ignored. They
2863 * are a secret flag to us that the attribute has
2864 * already been dealt with.
2866 if (attribute == 0x60b50000) goto next;
2871 da = dict_attrbyvalue(attribute);
2874 * If it's NOT continued, AND we know
2875 * about it, AND it's not a TLV, we can
2876 * create a normal pair.
2878 if (((vsa_ptr[2] & 0x80) == 0) &&
2879 da && (da->type != PW_TYPE_TLV)) goto create_pair;
2882 * Else it IS continued, or it's a TLV.
2883 * Go do a lot of work to find the stuff.
2885 pair = rad_continuation2vp(packet, original, secret,
2886 attribute, attrlen, ptr,
2888 ((vsa_ptr[2] & 0x80) != 0),
2894 * Create the attribute, setting the default type
2895 * to 'octets'. If the type in the dictionary
2896 * is different, then the dictionary type will
2897 * over-ride this one.
2899 * If the attribute has no data, then discard it.
2901 * Unless it's CUI. Damn you, CUI!
2905 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2907 pair = rad_attr2vp(packet, original, secret,
2908 attribute, attrlen, ptr);
2910 pairfree(&packet->vps);
2911 fr_strerror_printf("out of memory");
2925 * VSA's may not have been counted properly in
2926 * rad_packet_ok() above, as it is hard to count
2927 * then without using the dictionary. We
2928 * therefore enforce the limits here, too.
2930 if ((fr_max_attributes > 0) &&
2931 (num_attributes > fr_max_attributes)) {
2932 char host_ipaddr[128];
2934 pairfree(&packet->vps);
2935 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2936 inet_ntop(packet->src_ipaddr.af,
2937 &packet->src_ipaddr.ipaddr,
2938 host_ipaddr, sizeof(host_ipaddr)),
2939 num_attributes, fr_max_attributes);
2945 packet_length -= attrlen;
2949 * Merge information from the outside world into our
2952 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2961 * We assume that the passwd buffer passed is big enough.
2962 * RFC2138 says the password is max 128 chars, so the size
2963 * of the passwd buffer must be at least 129 characters.
2964 * Preferably it's just MAX_STRING_LEN.
2966 * int *pwlen is updated to the new length of the encrypted
2967 * password - a multiple of 16 bytes.
2969 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2970 const uint8_t *vector)
2972 FR_MD5_CTX context, old;
2973 uint8_t digest[AUTH_VECTOR_LEN];
2974 int i, n, secretlen;
2978 * RFC maximum is 128 bytes.
2980 * If length is zero, pad it out with zeros.
2982 * If the length isn't aligned to 16 bytes,
2983 * zero out the extra data.
2987 if (len > 128) len = 128;
2990 memset(passwd, 0, AUTH_PASS_LEN);
2991 len = AUTH_PASS_LEN;
2992 } else if ((len % AUTH_PASS_LEN) != 0) {
2993 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2994 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2999 * Use the secret to setup the decryption digest
3001 secretlen = strlen(secret);
3003 fr_MD5Init(&context);
3004 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3005 old = context; /* save intermediate work */
3008 * Encrypt it in place. Don't bother checking
3009 * len, as we've ensured above that it's OK.
3011 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3013 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3014 fr_MD5Final(digest, &context);
3017 fr_MD5Update(&context,
3018 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3020 fr_MD5Final(digest, &context);
3023 for (i = 0; i < AUTH_PASS_LEN; i++) {
3024 passwd[i + n] ^= digest[i];
3034 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3035 const uint8_t *vector)
3037 FR_MD5_CTX context, old;
3038 uint8_t digest[AUTH_VECTOR_LEN];
3040 size_t n, secretlen;
3043 * The RFC's say that the maximum is 128.
3044 * The buffer we're putting it into above is 254, so
3045 * we don't need to do any length checking.
3047 if (pwlen > 128) pwlen = 128;
3052 if (pwlen == 0) goto done;
3055 * Use the secret to setup the decryption digest
3057 secretlen = strlen(secret);
3059 fr_MD5Init(&context);
3060 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3061 old = context; /* save intermediate work */
3064 * The inverse of the code above.
3066 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3068 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3069 fr_MD5Final(digest, &context);
3072 if (pwlen > AUTH_PASS_LEN) {
3073 fr_MD5Update(&context, (uint8_t *) passwd,
3077 fr_MD5Final(digest, &context);
3080 if (pwlen > (n + AUTH_PASS_LEN)) {
3081 fr_MD5Update(&context, (uint8_t *) passwd + n,
3086 for (i = 0; i < AUTH_PASS_LEN; i++) {
3087 passwd[i + n] ^= digest[i];
3092 passwd[pwlen] = '\0';
3093 return strlen(passwd);
3098 * Encode Tunnel-Password attributes when sending them out on the wire.
3100 * int *pwlen is updated to the new length of the encrypted
3101 * password - a multiple of 16 bytes.
3103 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3106 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3107 const uint8_t *vector)
3109 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3110 unsigned char digest[AUTH_VECTOR_LEN];
3112 int i, n, secretlen;
3117 if (len > 127) len = 127;
3120 * Shift the password 3 positions right to place a salt and original
3121 * length, tag will be added automatically on packet send
3123 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3127 * save original password length as first password character;
3134 * Generate salt. The RFC's say:
3136 * The high bit of salt[0] must be set, each salt in a
3137 * packet should be unique, and they should be random
3139 * So, we set the high bit, add in a counter, and then
3140 * add in some CSPRNG data. should be OK..
3142 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3143 (fr_rand() & 0x07));
3144 salt[1] = fr_rand();
3147 * Padd password to multiple of AUTH_PASS_LEN bytes.
3149 n = len % AUTH_PASS_LEN;
3151 n = AUTH_PASS_LEN - n;
3152 for (; n > 0; n--, len++)
3155 /* set new password length */
3159 * Use the secret to setup the decryption digest
3161 secretlen = strlen(secret);
3162 memcpy(buffer, secret, secretlen);
3164 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3166 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3167 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3168 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3170 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3171 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3174 for (i = 0; i < AUTH_PASS_LEN; i++) {
3175 passwd[i + n2] ^= digest[i];
3183 * Decode Tunnel-Password encrypted attributes.
3185 * Defined in RFC-2868, this uses a two char SALT along with the
3186 * initial intermediate value, to differentiate it from the
3189 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3190 const uint8_t *vector)
3192 FR_MD5_CTX context, old;
3193 uint8_t digest[AUTH_VECTOR_LEN];
3195 unsigned i, n, len, reallen;
3200 * We need at least a salt.
3203 fr_strerror_printf("tunnel password is too short");
3208 * There's a salt, but no password. Or, there's a salt
3209 * and a 'data_len' octet. It's wrong, but at least we
3210 * can figure out what it means: the password is empty.
3212 * Note that this means we ignore the 'data_len' field,
3213 * if the attribute length tells us that there's no
3214 * more data. So the 'data_len' field may be wrong,
3223 len -= 2; /* discount the salt */
3226 * Use the secret to setup the decryption digest
3228 secretlen = strlen(secret);
3230 fr_MD5Init(&context);
3231 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3232 old = context; /* save intermediate work */
3235 * Set up the initial key:
3237 * b(1) = MD5(secret + vector + salt)
3239 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3240 fr_MD5Update(&context, passwd, 2);
3243 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3247 fr_MD5Final(digest, &context);
3252 * A quick check: decrypt the first octet
3253 * of the password, which is the
3254 * 'data_len' field. Ensure it's sane.
3256 reallen = passwd[2] ^ digest[0];
3257 if (reallen >= len) {
3258 fr_strerror_printf("tunnel password is too long for the attribute");
3262 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3266 fr_MD5Final(digest, &context);
3269 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3272 for (i = base; i < AUTH_PASS_LEN; i++) {
3273 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3278 * See make_tunnel_password, above.
3280 if (reallen > 239) reallen = 239;
3283 passwd[reallen] = 0;
3289 * Encode a CHAP password
3291 * FIXME: might not work with Ascend because
3292 * we use vp->length, and Ascend gear likes
3293 * to send an extra '\0' in the string!
3295 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3296 VALUE_PAIR *password)
3300 uint8_t string[MAX_STRING_LEN * 2 + 1];
3301 VALUE_PAIR *challenge;
3304 * Sanity check the input parameters
3306 if ((packet == NULL) || (password == NULL)) {
3311 * Note that the password VP can be EITHER
3312 * a User-Password attribute (from a check-item list),
3313 * or a CHAP-Password attribute (the client asking
3314 * the library to encode it).
3322 memcpy(ptr, password->vp_strvalue, password->length);
3323 ptr += password->length;
3324 i += password->length;
3327 * Use Chap-Challenge pair if present,
3328 * Request-Authenticator otherwise.
3330 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3332 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3333 i += challenge->length;
3335 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3336 i += AUTH_VECTOR_LEN;
3340 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3347 * Seed the random number generator.
3349 * May be called any number of times.
3351 void fr_rand_seed(const void *data, size_t size)
3356 * Ensure that the pool is initialized.
3358 if (!fr_rand_initialized) {
3361 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3363 fd = open("/dev/urandom", O_RDONLY);
3369 while (total < sizeof(fr_rand_pool.randrsl)) {
3370 this = read(fd, fr_rand_pool.randrsl,
3371 sizeof(fr_rand_pool.randrsl) - total);
3372 if ((this < 0) && (errno != EINTR)) break;
3373 if (this > 0) total += this;
3377 fr_rand_pool.randrsl[0] = fd;
3378 fr_rand_pool.randrsl[1] = time(NULL);
3379 fr_rand_pool.randrsl[2] = errno;
3382 fr_randinit(&fr_rand_pool, 1);
3383 fr_rand_pool.randcnt = 0;
3384 fr_rand_initialized = 1;
3390 * Hash the user data
3393 if (!hash) hash = fr_rand();
3394 hash = fr_hash_update(data, size, hash);
3396 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3401 * Return a 32-bit random number.
3403 uint32_t fr_rand(void)
3408 * Ensure that the pool is initialized.
3410 if (!fr_rand_initialized) {
3411 fr_rand_seed(NULL, 0);
3414 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3415 if (fr_rand_pool.randcnt >= 256) {
3416 fr_rand_pool.randcnt = 0;
3417 fr_isaac(&fr_rand_pool);
3425 * Allocate a new RADIUS_PACKET
3427 RADIUS_PACKET *rad_alloc(int newvector)
3431 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3432 fr_strerror_printf("out of memory");
3435 memset(rp, 0, sizeof(*rp));
3441 uint32_t hash, base;
3444 * Don't expose the actual contents of the random
3448 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3449 hash = fr_rand() ^ base;
3450 memcpy(rp->vector + i, &hash, sizeof(hash));
3453 fr_rand(); /* stir the pool again */
3458 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3460 RADIUS_PACKET *reply;
3462 if (!packet) return NULL;
3464 reply = rad_alloc(0);
3465 if (!reply) return NULL;
3468 * Initialize the fields from the request.
3470 reply->sockfd = packet->sockfd;
3471 reply->dst_ipaddr = packet->src_ipaddr;
3472 reply->src_ipaddr = packet->dst_ipaddr;
3473 reply->dst_port = packet->src_port;
3474 reply->src_port = packet->dst_port;
3475 reply->id = packet->id;
3476 reply->code = 0; /* UNKNOWN code */
3477 memcpy(reply->vector, packet->vector,
3478 sizeof(reply->vector));
3481 reply->data_len = 0;
3488 * Free a RADIUS_PACKET
3490 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3492 RADIUS_PACKET *radius_packet;
3494 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3495 radius_packet = *radius_packet_ptr;
3497 free(radius_packet->data);
3499 pairfree(&radius_packet->vps);
3501 free(radius_packet);
3503 *radius_packet_ptr = NULL;