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);
143 static void print_hex(RADIUS_PACKET *packet)
147 if (!packet->data) return;
149 printf(" Code:\t\t%u\n", packet->data[0]);
150 printf(" Id:\t\t%u\n", packet->data[1]);
151 printf(" Length:\t%u\n", ((packet->data[2] << 8) |
153 printf(" Vector:\t");
154 for (i = 4; i < 20; i++) {
155 printf("%02x", packet->data[i]);
159 if (packet->data_len > 20) {
164 total = packet->data_len - 20;
165 ptr = packet->data + 20;
171 if (total < 2) { /* too short */
172 printf("%02x\n", *ptr);
176 if (ptr[1] > total) { /* too long */
177 for (i = 0; i < total; i++) {
178 printf("%02x ", ptr[i]);
183 printf("%02x %02x ", ptr[0], ptr[1]);
184 attrlen = ptr[1] - 2;
188 for (i = 0; i < attrlen; i++) {
189 if ((i > 0) && ((i & 0x0f) == 0x00))
191 printf("%02x ", ptr[i]);
192 if ((i & 0x0f) == 0x0f) printf("\n");
195 if ((attrlen & 0x0f) != 0x00) printf("\n");
206 * Wrapper for sendto which handles sendfromto, IPv6, and all
207 * possible combinations.
209 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
210 fr_ipaddr_t *src_ipaddr, int src_port,
211 fr_ipaddr_t *dst_ipaddr, int dst_port)
213 struct sockaddr_storage dst;
214 socklen_t sizeof_dst;
216 #ifdef WITH_UDPFROMTO
217 struct sockaddr_storage src;
218 socklen_t sizeof_src;
220 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
222 src_port = src_port; /* -Wunused */
225 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
229 #ifdef WITH_UDPFROMTO
231 * Only IPv4 is supported for udpfromto.
233 * And if they don't specify a source IP address, don't
236 if ((dst_ipaddr->af == AF_INET) ||
237 (src_ipaddr->af != AF_UNSPEC)) {
238 return sendfromto(sockfd, data, data_len, flags,
239 (struct sockaddr *)&src, sizeof_src,
240 (struct sockaddr *)&dst, sizeof_dst);
243 src_ipaddr = src_ipaddr; /* -Wunused */
247 * No udpfromto, OR an IPv6 socket, fail gracefully.
249 return sendto(sockfd, data, data_len, flags,
250 (struct sockaddr *) &dst, sizeof_dst);
254 void rad_recv_discard(int sockfd)
257 struct sockaddr_storage src;
258 socklen_t sizeof_src = sizeof(src);
260 recvfrom(sockfd, header, sizeof(header), 0,
261 (struct sockaddr *)&src, &sizeof_src);
265 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
268 ssize_t data_len, packet_len;
270 struct sockaddr_storage src;
271 socklen_t sizeof_src = sizeof(src);
273 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
274 (struct sockaddr *)&src, &sizeof_src);
276 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
281 * Too little data is available, discard the packet.
284 recvfrom(sockfd, header, sizeof(header), 0,
285 (struct sockaddr *)&src, &sizeof_src);
288 } else { /* we got 4 bytes of data. */
290 * See how long the packet says it is.
292 packet_len = (header[2] * 256) + header[3];
295 * The length in the packet says it's less than
296 * a RADIUS header length: discard it.
298 if (packet_len < AUTH_HDR_LEN) {
299 recvfrom(sockfd, header, sizeof(header), 0,
300 (struct sockaddr *)&src, &sizeof_src);
304 * Enforce RFC requirements, for sanity.
305 * Anything after 4k will be discarded.
307 } else if (packet_len > MAX_PACKET_LEN) {
308 recvfrom(sockfd, header, sizeof(header), 0,
309 (struct sockaddr *)&src, &sizeof_src);
315 * Convert AF. If unknown, discard packet.
317 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
318 recvfrom(sockfd, header, sizeof(header), 0,
319 (struct sockaddr *)&src, &sizeof_src);
326 * The packet says it's this long, but the actual UDP
327 * size could still be smaller.
334 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
335 * possible combinations.
337 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
338 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
339 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
341 struct sockaddr_storage src;
342 struct sockaddr_storage dst;
343 socklen_t sizeof_src = sizeof(src);
344 socklen_t sizeof_dst = sizeof(dst);
351 memset(&src, 0, sizeof_src);
352 memset(&dst, 0, sizeof_dst);
355 * Get address family, etc. first, so we know if we
356 * need to do udpfromto.
358 * FIXME: udpfromto also does this, but it's not
359 * a critical problem.
361 if (getsockname(sockfd, (struct sockaddr *)&dst,
362 &sizeof_dst) < 0) return -1;
365 * Read the length of the packet, from the packet.
366 * This lets us allocate the buffer to use for
367 * reading the rest of the packet.
369 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
370 (struct sockaddr *)&src, &sizeof_src);
372 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
377 * Too little data is available, discard the packet.
380 recvfrom(sockfd, header, sizeof(header), flags,
381 (struct sockaddr *)&src, &sizeof_src);
384 } else { /* we got 4 bytes of data. */
386 * See how long the packet says it is.
388 len = (header[2] * 256) + header[3];
391 * The length in the packet says it's less than
392 * a RADIUS header length: discard it.
394 if (len < AUTH_HDR_LEN) {
395 recvfrom(sockfd, header, sizeof(header), flags,
396 (struct sockaddr *)&src, &sizeof_src);
400 * Enforce RFC requirements, for sanity.
401 * Anything after 4k will be discarded.
403 } else if (len > MAX_PACKET_LEN) {
404 recvfrom(sockfd, header, sizeof(header), flags,
405 (struct sockaddr *)&src, &sizeof_src);
414 * Receive the packet. The OS will discard any data in the
415 * packet after "len" bytes.
417 #ifdef WITH_UDPFROMTO
418 if (dst.ss_family == AF_INET) {
419 data_len = recvfromto(sockfd, buf, len, flags,
420 (struct sockaddr *)&src, &sizeof_src,
421 (struct sockaddr *)&dst, &sizeof_dst);
425 * No udpfromto, OR an IPv6 socket. Fail gracefully.
427 data_len = recvfrom(sockfd, buf, len, flags,
428 (struct sockaddr *)&src, &sizeof_src);
434 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
436 return -1; /* Unknown address family, Die Die Die! */
440 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
444 * Different address families should never happen.
446 if (src.ss_family != dst.ss_family) {
452 * Tell the caller about the data
460 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
461 /*************************************************************************
463 * Function: make_secret
465 * Purpose: Build an encrypted secret value to return in a reply
466 * packet. The secret is hidden by xoring with a MD5 digest
467 * created from the shared secret and the authentication
468 * vector. We put them into MD5 in the reverse order from
469 * that used when encrypting passwords to RADIUS.
471 *************************************************************************/
472 static void make_secret(uint8_t *digest, const uint8_t *vector,
473 const char *secret, const uint8_t *value)
478 fr_MD5Init(&context);
479 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
480 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
481 fr_MD5Final(digest, &context);
483 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
484 digest[i] ^= value[i];
488 #define MAX_PASS_LEN (128)
489 static void make_passwd(uint8_t *output, size_t *outlen,
490 const uint8_t *input, size_t inlen,
491 const char *secret, const uint8_t *vector)
493 FR_MD5_CTX context, old;
494 uint8_t digest[AUTH_VECTOR_LEN];
495 uint8_t passwd[MAX_PASS_LEN];
500 * If the length is zero, round it up.
504 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
506 memcpy(passwd, input, len);
507 memset(passwd + len, 0, sizeof(passwd) - len);
513 else if ((len & 0x0f) != 0) {
519 fr_MD5Init(&context);
520 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
526 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
528 for (n = 0; n < len; n += AUTH_PASS_LEN) {
531 fr_MD5Update(&context,
532 passwd + n - AUTH_PASS_LEN,
536 fr_MD5Final(digest, &context);
537 for (i = 0; i < AUTH_PASS_LEN; i++) {
538 passwd[i + n] ^= digest[i];
542 memcpy(output, passwd, len);
545 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
546 const uint8_t *input, size_t inlen, size_t room,
547 const char *secret, const uint8_t *vector)
549 FR_MD5_CTX context, old;
550 uint8_t digest[AUTH_VECTOR_LEN];
551 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
558 if (room > 253) room = 253;
561 * Account for 2 bytes of the salt, and round the room
562 * available down to the nearest multiple of 16. Then,
563 * subtract one from that to account for the length byte,
564 * and the resulting number is the upper bound on the data
567 * We could short-cut this calculation just be forcing
568 * inlen to be no more than 239. It would work for all
569 * VSA's, as we don't pack multiple VSA's into one
572 * However, this calculation is more general, if a little
573 * complex. And it will work in the future for all possible
574 * kinds of weird attribute packing.
577 room -= (room & 0x0f);
580 if (inlen > room) inlen = room;
583 * Length of the encrypted data is password length plus
584 * one byte for the length of the password.
587 if ((len & 0x0f) != 0) {
591 *outlen = len + 2; /* account for the salt */
594 * Copy the password over.
596 memcpy(passwd + 3, input, inlen);
597 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
600 * Generate salt. The RFC's say:
602 * The high bit of salt[0] must be set, each salt in a
603 * packet should be unique, and they should be random
605 * So, we set the high bit, add in a counter, and then
606 * add in some CSPRNG data. should be OK..
608 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
610 passwd[1] = fr_rand();
611 passwd[2] = inlen; /* length of the password string */
613 fr_MD5Init(&context);
614 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
617 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
618 fr_MD5Update(&context, &passwd[0], 2);
620 for (n = 0; n < len; n += AUTH_PASS_LEN) {
623 fr_MD5Update(&context,
624 passwd + 2 + n - AUTH_PASS_LEN,
628 fr_MD5Final(digest, &context);
629 for (i = 0; i < AUTH_PASS_LEN; i++) {
630 passwd[i + 2 + n] ^= digest[i];
633 memcpy(output, passwd, len + 2);
637 * Returns the end of the data.
639 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
640 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
646 uint8_t *ptr = start;
650 * Set up the default sources for the data.
652 data = vp->vp_octets;
659 case PW_TYPE_IPV6ADDR:
660 case PW_TYPE_IPV6PREFIX:
661 case PW_TYPE_ABINARY:
662 /* nothing more to do */
666 len = 1; /* just in case */
667 array[0] = vp->vp_integer & 0xff;
672 len = 2; /* just in case */
673 array[0] = (vp->vp_integer >> 8) & 0xff;
674 array[1] = vp->vp_integer & 0xff;
678 case PW_TYPE_INTEGER:
679 len = 4; /* just in case */
680 lvalue = htonl(vp->vp_integer);
681 memcpy(array, &lvalue, sizeof(lvalue));
686 data = (const uint8_t *) &vp->vp_ipaddr;
687 len = 4; /* just in case */
691 * There are no tagged date attributes.
694 lvalue = htonl(vp->vp_date);
695 data = (const uint8_t *) &lvalue;
696 len = 4; /* just in case */
703 len = 4; /* just in case */
704 slvalue = htonl(vp->vp_signed);
705 memcpy(array, &slvalue, sizeof(slvalue));
712 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
715 if (vp->length > room) return 0; /* can't chop TLVs to fit */
718 default: /* unknown type: ignore it */
719 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
724 * Bound the data to the calling size
726 if (len > room) len = room;
729 * Encrypt the various password styles
731 * Attributes with encrypted values MUST be less than
734 switch (vp->flags.encrypt) {
735 case FLAG_ENCRYPT_USER_PASSWORD:
736 make_passwd(ptr, &len, data, len,
737 secret, packet->vector);
740 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
742 * Check if there's enough room. If there isn't,
743 * we discard the attribute.
745 * This is ONLY a problem if we have multiple VSA's
746 * in one Vendor-Specific, though.
748 if (room < 19) return 0;
750 switch (packet->code) {
751 case PW_AUTHENTICATION_ACK:
752 case PW_AUTHENTICATION_REJECT:
753 case PW_ACCESS_CHALLENGE:
756 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
759 ptr[0] = vp->flags.tag;
760 make_tunnel_passwd(ptr + 1, &len, data, len, room - 1,
761 secret, original->vector);
763 case PW_ACCOUNTING_REQUEST:
764 case PW_DISCONNECT_REQUEST:
766 ptr[0] = vp->flags.tag;
767 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
768 secret, packet->vector);
774 * The code above ensures that this attribute
777 case FLAG_ENCRYPT_ASCEND_SECRET:
778 make_secret(ptr, packet->vector, secret, data);
779 len = AUTH_VECTOR_LEN;
784 if (vp->flags.has_tag && TAG_VALID(vp->flags.tag)) {
785 if (vp->type == PW_TYPE_STRING) {
786 if (len > (room - 1)) len = room - 1;
787 ptr[0] = vp->flags.tag;
789 } else if (vp->type == PW_TYPE_INTEGER) {
790 array[0] = vp->flags.tag;
791 } /* else it can't be any other type */
793 memcpy(ptr, data, len);
795 } /* switch over encryption flags */
797 return len + (ptr - start);;
801 static int rad_vp2rfc(const RADIUS_PACKET *packet,
802 const RADIUS_PACKET *original,
803 const char *secret, const VALUE_PAIR *vp,
804 unsigned int attribute, uint8_t *ptr, size_t room)
808 if (room < 2) return 0;
810 ptr[0] = attribute & 0xff; /* NOT vp->attribute */
813 len = vp2data(packet, original, secret, vp, ptr + 2, room - 2);
814 if (len < 0) return len;
821 static int wimax2data(const RADIUS_PACKET *packet,
822 const RADIUS_PACKET *original,
823 const char *secret, const VALUE_PAIR *vp,
824 uint8_t *start, size_t room, uint8_t *ptr)
829 * Offsets to Vendor-Specific length, and to length of
835 if (room < 1) return 0;
839 * Account for continuation bytes. The caller has
840 * already accounting for the continuation byte in the
841 * Vendor-Specific "length" field.
847 * Chop everything to fit in one attribute.
849 if (room > (255 - 9)) room = (255 - 9);
852 * The attribute contains TLVs that we have NOT decoded
853 * properly, OR it contains TLV that the user has encoded
854 * manually. If it has no data, OR it's too long,
855 * discard it. We're not going to walk through its
856 * contents trying to figure out how to chop it across
857 * multiple continuations.
859 if (vp->flags.has_tlv && (!vp->vp_tlv || (vp->length > room))) {
864 * The attribute is a top-level integer, ipaddr, etc.
867 if (!vp->flags.is_tlv) {
868 len = vp2data(packet, original, secret, vp, ptr, room);
869 if (len <= 0) return -1;
871 start[VS_OFF] += len;
872 start[WM_OFF] += len;
874 return start[VS_OFF];
878 * Otherwise it's a TLV. We need to do more work to
887 * Parse a data structure into a RADIUS attribute.
889 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
890 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
899 * RFC format attributes take the fast path.
901 if (vp->vendor == 0) {
902 len = rad_vp2rfc(packet, original, secret, vp,
903 vp->attribute, start, room);
904 if (len < 0) return -1;
907 * RFC 2865 section 5 says that zero-length
908 * attributes MUST NOT be sent.
910 * ... and the WiMAX forum ignores
911 * this... because of one vendor. Don't they
912 * have anything better to do with their time?
915 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
922 * Not enough room for:
923 * attr, len, vendor-id, vsa, vsalen
925 if (room < 8) return 0;
928 * Build the Vendor-Specific header
931 *ptr++ = PW_VENDOR_SPECIFIC;
934 lvalue = htonl(vp->vendor);
935 memcpy(ptr, &lvalue, 4);
939 * Unknown vendors, and type=1,length=1,no-continuation
940 * are RFC format attributes.
942 dv = dict_vendorbyvalue(vp->vendor);
944 ((dv->type == 1) && (dv->length = 1) && !dv->flags)) {
945 len = rad_vp2rfc(packet, original, secret, vp,
946 vp->attribute, ptr, room);
947 if (len <= 0) return len;
953 if (room < (dv->type + dv->length + dv->flags)) return 0;
954 room -= (dv->type + dv->length + dv->flags);
955 start[1] += (dv->type + dv->length + dv->flags);
959 ptr[0] = (vp->attribute & 0xFF);
963 ptr[0] = ((vp->attribute >> 8) & 0xFF);
964 ptr[1] = (vp->attribute & 0xFF);
969 ptr[1] = ((vp->attribute >> 16) & 0xFF);
970 ptr[2] = ((vp->attribute >> 8) & 0xFF);
971 ptr[3] = (vp->attribute & 0xFF);
975 return 0; /* silently discard it */
979 switch (dv->length) {
983 ptr[0] = dv->type + 1;
987 ptr[1] = dv->type + 2;
991 return 0; /* silently discard it */
996 * WiMAX attributes take their own path through the
999 if (dv->flags) return wimax2data(packet, original, secret, vp,
1002 len = vp2data(packet, original, secret, vp, ptr, room);
1003 if (len <= 0) return len;
1005 if (dv->length != 0) ptr[-1] += len;
1015 #define REORDER(x) ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000 >> 24))
1017 static int rad_encode_wimax(const RADIUS_PACKET *packet,
1018 const RADIUS_PACKET *original,
1019 const char *secret, VALUE_PAIR *reply,
1020 uint8_t *start, size_t room)
1022 int len, total_len = 0;
1023 uint8_t *wimax = NULL;
1024 uint8_t *ptr = start;
1026 VALUE_PAIR *vp = reply;
1029 * Swap the order of the WiMAX hacks, to make later
1030 * comparisons easier.
1032 maxattr = REORDER(vp->attribute);
1035 len = rad_vp2attr(packet, original, secret, vp, ptr,
1036 (start + room) - ptr);
1037 if (len <= 0) return total_len;
1040 * After adding an attribute with the simplest encoding,
1041 * check to see if we can append it to the previous one.
1044 if ((wimax[1] + (ptr[1] - 6)) <= 255) {
1048 memmove(ptr, ptr + 9, hack);
1054 * See if we can nest sub-TLVs, too, in
1055 * order to shorten the encoding.
1059 wimax[8] = 0x80; /* set continuation */
1069 vp->flags.encoded = 1;
1073 * Look at the NEXT tlv. Ensure that we encode
1074 * attributes into a common VSA *only* if they are for
1075 * the same WiMAX VSA, AND if the TLVs are in numerically
1078 if (vp && vp->flags.is_tlv && (reply->vendor == vp->vendor) &&
1079 ((reply->attribute & 0xff) == (vp->attribute & 0xff))) {
1082 attr = REORDER(vp->attribute);
1083 if (attr >= maxattr) {
1096 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1099 radius_packet_t *hdr;
1101 uint16_t total_length;
1105 char ip_buffer[128];
1108 * A 4K packet, aligned on 64-bits.
1110 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1112 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1113 what = fr_packet_codes[packet->code];
1118 DEBUG("Sending %s of id %d to %s port %d\n",
1120 inet_ntop(packet->dst_ipaddr.af,
1121 &packet->dst_ipaddr.ipaddr,
1122 ip_buffer, sizeof(ip_buffer)),
1126 * Double-check some things based on packet code.
1128 switch (packet->code) {
1129 case PW_AUTHENTICATION_ACK:
1130 case PW_AUTHENTICATION_REJECT:
1131 case PW_ACCESS_CHALLENGE:
1133 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1139 * These packet vectors start off as all zero.
1141 case PW_ACCOUNTING_REQUEST:
1142 case PW_DISCONNECT_REQUEST:
1143 case PW_COA_REQUEST:
1144 memset(packet->vector, 0, sizeof(packet->vector));
1152 * Use memory on the stack, until we know how
1153 * large the packet will be.
1155 hdr = (radius_packet_t *) data;
1158 * Build standard header
1160 hdr->code = packet->code;
1161 hdr->id = packet->id;
1163 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1165 total_length = AUTH_HDR_LEN;
1168 * Load up the configuration values for the user
1174 * FIXME: Loop twice over the reply list. The first time,
1175 * calculate the total length of data. The second time,
1176 * allocate the memory, and fill in the VP's.
1178 * Hmm... this may be slower than just doing a small
1183 * Loop over the reply attributes for the packet.
1185 for (reply = packet->vps; reply; reply = reply->next) {
1187 * Ignore non-wire attributes
1189 if ((reply->vendor == 0) &&
1190 ((reply->attribute & 0xFFFF) > 0xff)) {
1193 * Permit the admin to send BADLY formatted
1194 * attributes with a debug build.
1196 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1197 memcpy(ptr, reply->vp_octets, reply->length);
1198 len = reply->length;
1206 * Set the Message-Authenticator to the correct
1207 * length and initial value.
1209 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1210 reply->length = AUTH_VECTOR_LEN;
1211 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1214 * Cache the offset to the
1215 * Message-Authenticator
1217 packet->offset = total_length;
1221 * Print out ONLY the attributes which
1222 * we're sending over the wire, and print
1223 * them out BEFORE they're encrypted.
1228 * Skip attributes that are encoded.
1230 if (reply->flags.encoded) continue;
1232 if (reply->flags.is_tlv) {
1233 len = rad_encode_wimax(packet, original, secret,
1235 ((uint8_t *) data) + sizeof(data) - ptr);
1238 len = rad_vp2attr(packet, original, secret, reply, ptr,
1239 ((uint8_t *) data) + sizeof(data) - ptr);
1242 if (len < 0) return -1;
1246 total_length += len;
1247 } /* done looping over all attributes */
1250 * Fill in the rest of the fields, and copy the data over
1251 * from the local stack to the newly allocated memory.
1253 * Yes, all this 'memcpy' is slow, but it means
1254 * that we only allocate the minimum amount of
1255 * memory for a request.
1257 packet->data_len = total_length;
1258 packet->data = (uint8_t *) malloc(packet->data_len);
1259 if (!packet->data) {
1260 fr_strerror_printf("Out of memory");
1264 memcpy(packet->data, hdr, packet->data_len);
1265 hdr = (radius_packet_t *) packet->data;
1267 total_length = htons(total_length);
1268 memcpy(hdr->length, &total_length, sizeof(total_length));
1275 * Sign a previously encoded packet.
1277 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1280 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1283 * It wasn't assigned an Id, this is bad!
1285 if (packet->id < 0) {
1286 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1290 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1291 (packet->offset < 0)) {
1292 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1297 * If there's a Message-Authenticator, update it
1298 * now, BEFORE updating the authentication vector.
1300 if (packet->offset > 0) {
1301 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1303 switch (packet->code) {
1304 case PW_ACCOUNTING_REQUEST:
1305 case PW_ACCOUNTING_RESPONSE:
1306 case PW_DISCONNECT_REQUEST:
1307 case PW_DISCONNECT_ACK:
1308 case PW_DISCONNECT_NAK:
1309 case PW_COA_REQUEST:
1312 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1315 case PW_AUTHENTICATION_ACK:
1316 case PW_AUTHENTICATION_REJECT:
1317 case PW_ACCESS_CHALLENGE:
1319 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1322 memcpy(hdr->vector, original->vector,
1326 default: /* others have vector already set to zero */
1332 * Set the authentication vector to zero,
1333 * calculate the signature, and put it
1334 * into the Message-Authenticator
1337 fr_hmac_md5(packet->data, packet->data_len,
1338 (const uint8_t *) secret, strlen(secret),
1340 memcpy(packet->data + packet->offset + 2,
1341 calc_auth_vector, AUTH_VECTOR_LEN);
1344 * Copy the original request vector back
1345 * to the raw packet.
1347 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1351 * Switch over the packet code, deciding how to
1354 switch (packet->code) {
1356 * Request packets are not signed, bur
1357 * have a random authentication vector.
1359 case PW_AUTHENTICATION_REQUEST:
1360 case PW_STATUS_SERVER:
1364 * Reply packets are signed with the
1365 * authentication vector of the request.
1372 fr_MD5Init(&context);
1373 fr_MD5Update(&context, packet->data, packet->data_len);
1374 fr_MD5Update(&context, (const uint8_t *) secret,
1376 fr_MD5Final(digest, &context);
1378 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1379 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1382 }/* switch over packet codes */
1388 * Reply to the request. Also attach
1389 * reply attribute value pairs and any user message provided.
1391 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1396 char ip_buffer[128];
1399 * Maybe it's a fake packet. Don't send it.
1401 if (!packet || (packet->sockfd < 0)) {
1405 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1406 what = fr_packet_codes[packet->code];
1412 * First time through, allocate room for the packet
1414 if (!packet->data) {
1416 * Encode the packet.
1418 if (rad_encode(packet, original, secret) < 0) {
1423 * Re-sign it, including updating the
1424 * Message-Authenticator.
1426 if (rad_sign(packet, original, secret) < 0) {
1431 * If packet->data points to data, then we print out
1432 * the VP list again only for debugging.
1434 } else if (fr_debug_flag) {
1435 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1436 inet_ntop(packet->dst_ipaddr.af,
1437 &packet->dst_ipaddr.ipaddr,
1438 ip_buffer, sizeof(ip_buffer)),
1441 for (reply = packet->vps; reply; reply = reply->next) {
1442 if ((reply->vendor == 0) &&
1443 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1449 * And send it on it's way.
1451 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1452 &packet->src_ipaddr, packet->src_port,
1453 &packet->dst_ipaddr, packet->dst_port);
1457 * Do a comparison of two authentication digests by comparing
1458 * the FULL digest. Otehrwise, the server can be subject to
1459 * timing attacks that allow attackers find a valid message
1462 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1464 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1469 for (i = 0; i < length; i++) {
1470 result |= a[i] ^ b[i];
1473 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1478 * Validates the requesting client NAS. Calculates the
1479 * signature based on the clients private key.
1481 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1483 uint8_t digest[AUTH_VECTOR_LEN];
1487 * Zero out the auth_vector in the received packet.
1488 * Then append the shared secret to the received packet,
1489 * and calculate the MD5 sum. This must be the same
1490 * as the original MD5 sum (packet->vector).
1492 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1495 * MD5(packet + secret);
1497 fr_MD5Init(&context);
1498 fr_MD5Update(&context, packet->data, packet->data_len);
1499 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1500 fr_MD5Final(digest, &context);
1503 * Return 0 if OK, 2 if not OK.
1505 if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1511 * Validates the requesting client NAS. Calculates the
1512 * signature based on the clients private key.
1514 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1517 uint8_t calc_digest[AUTH_VECTOR_LEN];
1523 if (original == NULL) {
1528 * Copy the original vector in place.
1530 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1533 * MD5(packet + secret);
1535 fr_MD5Init(&context);
1536 fr_MD5Update(&context, packet->data, packet->data_len);
1537 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1538 fr_MD5Final(calc_digest, &context);
1541 * Copy the packet's vector back to the packet.
1543 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1546 * Return 0 if OK, 2 if not OK.
1548 if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1554 * See if the data pointed to by PTR is a valid RADIUS packet.
1556 * packet is not 'const * const' because we may update data_len,
1557 * if there's more data in the UDP packet than in the RADIUS packet.
1559 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1564 radius_packet_t *hdr;
1565 char host_ipaddr[128];
1571 * Check for packets smaller than the packet header.
1573 * RFC 2865, Section 3., subsection 'length' says:
1575 * "The minimum length is 20 ..."
1577 if (packet->data_len < AUTH_HDR_LEN) {
1578 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1579 inet_ntop(packet->src_ipaddr.af,
1580 &packet->src_ipaddr.ipaddr,
1581 host_ipaddr, sizeof(host_ipaddr)),
1582 (int) packet->data_len, AUTH_HDR_LEN);
1587 * RFC 2865, Section 3., subsection 'length' says:
1589 * " ... and maximum length is 4096."
1591 if (packet->data_len > MAX_PACKET_LEN) {
1592 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1593 inet_ntop(packet->src_ipaddr.af,
1594 &packet->src_ipaddr.ipaddr,
1595 host_ipaddr, sizeof(host_ipaddr)),
1596 (int) packet->data_len, MAX_PACKET_LEN);
1601 * Check for packets with mismatched size.
1602 * i.e. We've received 128 bytes, and the packet header
1603 * says it's 256 bytes long.
1605 totallen = (packet->data[2] << 8) | packet->data[3];
1606 hdr = (radius_packet_t *)packet->data;
1609 * Code of 0 is not understood.
1610 * Code of 16 or greate is not understood.
1612 if ((hdr->code == 0) ||
1613 (hdr->code >= FR_MAX_PACKET_CODE)) {
1614 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1615 inet_ntop(packet->src_ipaddr.af,
1616 &packet->src_ipaddr.ipaddr,
1617 host_ipaddr, sizeof(host_ipaddr)),
1623 * Message-Authenticator is required in Status-Server
1624 * packets, otherwise they can be trivially forged.
1626 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1629 * It's also required if the caller asks for it.
1631 if (flags) require_ma = 1;
1634 * Repeat the length checks. This time, instead of
1635 * looking at the data we received, look at the value
1636 * of the 'length' field inside of the packet.
1638 * Check for packets smaller than the packet header.
1640 * RFC 2865, Section 3., subsection 'length' says:
1642 * "The minimum length is 20 ..."
1644 if (totallen < AUTH_HDR_LEN) {
1645 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1646 inet_ntop(packet->src_ipaddr.af,
1647 &packet->src_ipaddr.ipaddr,
1648 host_ipaddr, sizeof(host_ipaddr)),
1649 totallen, AUTH_HDR_LEN);
1654 * And again, for the value of the 'length' field.
1656 * RFC 2865, Section 3., subsection 'length' says:
1658 * " ... and maximum length is 4096."
1660 if (totallen > MAX_PACKET_LEN) {
1661 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1662 inet_ntop(packet->src_ipaddr.af,
1663 &packet->src_ipaddr.ipaddr,
1664 host_ipaddr, sizeof(host_ipaddr)),
1665 totallen, MAX_PACKET_LEN);
1670 * RFC 2865, Section 3., subsection 'length' says:
1672 * "If the packet is shorter than the Length field
1673 * indicates, it MUST be silently discarded."
1675 * i.e. No response to the NAS.
1677 if (packet->data_len < totallen) {
1678 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1679 inet_ntop(packet->src_ipaddr.af,
1680 &packet->src_ipaddr.ipaddr,
1681 host_ipaddr, sizeof(host_ipaddr)),
1682 (int) packet->data_len, totallen);
1687 * RFC 2865, Section 3., subsection 'length' says:
1689 * "Octets outside the range of the Length field MUST be
1690 * treated as padding and ignored on reception."
1692 if (packet->data_len > totallen) {
1694 * We're shortening the packet below, but just
1695 * to be paranoid, zero out the extra data.
1697 memset(packet->data + totallen, 0, packet->data_len - totallen);
1698 packet->data_len = totallen;
1702 * Walk through the packet's attributes, ensuring that
1703 * they add up EXACTLY to the size of the packet.
1705 * If they don't, then the attributes either under-fill
1706 * or over-fill the packet. Any parsing of the packet
1707 * is impossible, and will result in unknown side effects.
1709 * This would ONLY happen with buggy RADIUS implementations,
1710 * or with an intentional attack. Either way, we do NOT want
1711 * to be vulnerable to this problem.
1714 count = totallen - AUTH_HDR_LEN;
1719 * Attribute number zero is NOT defined.
1722 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1723 inet_ntop(packet->src_ipaddr.af,
1724 &packet->src_ipaddr.ipaddr,
1725 host_ipaddr, sizeof(host_ipaddr)));
1730 * Attributes are at LEAST as long as the ID & length
1731 * fields. Anything shorter is an invalid attribute.
1734 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1735 inet_ntop(packet->src_ipaddr.af,
1736 &packet->src_ipaddr.ipaddr,
1737 host_ipaddr, sizeof(host_ipaddr)),
1743 * Sanity check the attributes for length.
1746 default: /* don't do anything by default */
1750 * If there's an EAP-Message, we require
1751 * a Message-Authenticator.
1753 case PW_EAP_MESSAGE:
1757 case PW_MESSAGE_AUTHENTICATOR:
1758 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1759 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1760 inet_ntop(packet->src_ipaddr.af,
1761 &packet->src_ipaddr.ipaddr,
1762 host_ipaddr, sizeof(host_ipaddr)),
1771 * FIXME: Look up the base 255 attributes in the
1772 * dictionary, and switch over their type. For
1773 * integer/date/ip, the attribute length SHOULD
1776 count -= attr[1]; /* grab the attribute length */
1778 num_attributes++; /* seen one more attribute */
1782 * If the attributes add up to a packet, it's allowed.
1784 * If not, we complain, and throw the packet away.
1787 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1788 inet_ntop(packet->src_ipaddr.af,
1789 &packet->src_ipaddr.ipaddr,
1790 host_ipaddr, sizeof(host_ipaddr)));
1795 * If we're configured to look for a maximum number of
1796 * attributes, and we've seen more than that maximum,
1797 * then throw the packet away, as a possible DoS.
1799 if ((fr_max_attributes > 0) &&
1800 (num_attributes > fr_max_attributes)) {
1801 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1802 inet_ntop(packet->src_ipaddr.af,
1803 &packet->src_ipaddr.ipaddr,
1804 host_ipaddr, sizeof(host_ipaddr)),
1805 num_attributes, fr_max_attributes);
1810 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1812 * A packet with an EAP-Message attribute MUST also have
1813 * a Message-Authenticator attribute.
1815 * A Message-Authenticator all by itself is OK, though.
1817 * Similarly, Status-Server packets MUST contain
1818 * Message-Authenticator attributes.
1820 if (require_ma && ! seen_ma) {
1821 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1822 inet_ntop(packet->src_ipaddr.af,
1823 &packet->src_ipaddr.ipaddr,
1824 host_ipaddr, sizeof(host_ipaddr)));
1829 * Fill RADIUS header fields
1831 packet->code = hdr->code;
1832 packet->id = hdr->id;
1833 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1840 * Receive UDP client requests, and fill in
1841 * the basics of a RADIUS_PACKET structure.
1843 RADIUS_PACKET *rad_recv(int fd, int flags)
1846 RADIUS_PACKET *packet;
1849 * Allocate the new request data structure
1851 if ((packet = malloc(sizeof(*packet))) == NULL) {
1852 fr_strerror_printf("out of memory");
1855 memset(packet, 0, sizeof(*packet));
1858 sock_flags = MSG_PEEK;
1862 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1863 &packet->src_ipaddr, &packet->src_port,
1864 &packet->dst_ipaddr, &packet->dst_port);
1867 * Check for socket errors.
1869 if (packet->data_len < 0) {
1870 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1871 /* packet->data is NULL */
1877 * If the packet is too big, then rad_recvfrom did NOT
1878 * allocate memory. Instead, it just discarded the
1881 if (packet->data_len > MAX_PACKET_LEN) {
1882 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1883 /* packet->data is NULL */
1889 * Read no data. Continue.
1890 * This check is AFTER the MAX_PACKET_LEN check above, because
1891 * if the packet is larger than MAX_PACKET_LEN, we also have
1892 * packet->data == NULL
1894 if ((packet->data_len == 0) || !packet->data) {
1895 fr_strerror_printf("Empty packet: Socket is not ready.");
1901 * See if it's a well-formed RADIUS packet.
1903 if (!rad_packet_ok(packet, flags)) {
1909 * Remember which socket we read the packet from.
1911 packet->sockfd = fd;
1914 * FIXME: Do even more filtering by only permitting
1915 * certain IP's. The problem is that we don't know
1916 * how to do this properly for all possible clients...
1920 * Explicitely set the VP list to empty.
1924 if (fr_debug_flag) {
1925 char host_ipaddr[128];
1927 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1928 DEBUG("rad_recv: %s packet from host %s port %d",
1929 fr_packet_codes[packet->code],
1930 inet_ntop(packet->src_ipaddr.af,
1931 &packet->src_ipaddr.ipaddr,
1932 host_ipaddr, sizeof(host_ipaddr)),
1935 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1936 inet_ntop(packet->src_ipaddr.af,
1937 &packet->src_ipaddr.ipaddr,
1938 host_ipaddr, sizeof(host_ipaddr)),
1942 DEBUG(", id=%d, length=%d\n",
1943 packet->id, (int) packet->data_len);
1951 * Verify the signature of a packet.
1953 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1960 if (!packet || !packet->data) return -1;
1963 * Before we allocate memory for the attributes, do more
1966 ptr = packet->data + AUTH_HDR_LEN;
1967 length = packet->data_len - AUTH_HDR_LEN;
1968 while (length > 0) {
1969 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1970 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1975 default: /* don't do anything. */
1979 * Note that more than one Message-Authenticator
1980 * attribute is invalid.
1982 case PW_MESSAGE_AUTHENTICATOR:
1983 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1984 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1986 switch (packet->code) {
1990 case PW_ACCOUNTING_REQUEST:
1991 case PW_ACCOUNTING_RESPONSE:
1992 case PW_DISCONNECT_REQUEST:
1993 case PW_DISCONNECT_ACK:
1994 case PW_DISCONNECT_NAK:
1995 case PW_COA_REQUEST:
1998 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2001 case PW_AUTHENTICATION_ACK:
2002 case PW_AUTHENTICATION_REJECT:
2003 case PW_ACCESS_CHALLENGE:
2005 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2008 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2012 fr_hmac_md5(packet->data, packet->data_len,
2013 (const uint8_t *) secret, strlen(secret),
2015 if (digest_cmp(calc_auth_vector, msg_auth_vector,
2016 sizeof(calc_auth_vector)) != 0) {
2018 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2019 inet_ntop(packet->src_ipaddr.af,
2020 &packet->src_ipaddr.ipaddr,
2021 buffer, sizeof(buffer)));
2022 /* Silently drop packet, according to RFC 3579 */
2024 } /* else the message authenticator was good */
2027 * Reinitialize Authenticators.
2029 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2030 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2032 } /* switch over the attributes */
2036 } /* loop over the packet, sanity checking the attributes */
2039 * It looks like a RADIUS packet, but we can't validate
2042 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2044 fr_strerror_printf("Received Unknown packet code %d "
2045 "from client %s port %d: Cannot validate signature.",
2047 inet_ntop(packet->src_ipaddr.af,
2048 &packet->src_ipaddr.ipaddr,
2049 buffer, sizeof(buffer)),
2055 * Calculate and/or verify digest.
2057 switch(packet->code) {
2061 case PW_AUTHENTICATION_REQUEST:
2062 case PW_STATUS_SERVER:
2064 * The authentication vector is random
2065 * nonsense, invented by the client.
2069 case PW_COA_REQUEST:
2070 case PW_DISCONNECT_REQUEST:
2071 case PW_ACCOUNTING_REQUEST:
2072 if (calc_acctdigest(packet, secret) > 1) {
2073 fr_strerror_printf("Received %s packet "
2074 "from %s with invalid signature! (Shared secret is incorrect.)",
2075 fr_packet_codes[packet->code],
2076 inet_ntop(packet->src_ipaddr.af,
2077 &packet->src_ipaddr.ipaddr,
2078 buffer, sizeof(buffer)));
2083 /* Verify the reply digest */
2084 case PW_AUTHENTICATION_ACK:
2085 case PW_AUTHENTICATION_REJECT:
2086 case PW_ACCESS_CHALLENGE:
2087 case PW_ACCOUNTING_RESPONSE:
2088 case PW_DISCONNECT_ACK:
2089 case PW_DISCONNECT_NAK:
2092 rcode = calc_replydigest(packet, original, secret);
2094 fr_strerror_printf("Received %s packet "
2095 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2096 fr_packet_codes[packet->code],
2097 inet_ntop(packet->src_ipaddr.af,
2098 &packet->src_ipaddr.ipaddr,
2099 buffer, sizeof(buffer)),
2107 fr_strerror_printf("Received Unknown packet code %d "
2108 "from client %s port %d: Cannot validate signature",
2110 inet_ntop(packet->src_ipaddr.af,
2111 &packet->src_ipaddr.ipaddr,
2112 buffer, sizeof(buffer)),
2121 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2122 const RADIUS_PACKET *original,
2123 const char *secret, size_t length,
2124 const uint8_t *data, VALUE_PAIR *vp)
2129 * If length is greater than 253, something is SERIOUSLY
2132 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2134 vp->length = length;
2135 vp->operator = T_OP_EQ;
2141 if (vp->flags.has_tag) {
2142 if (TAG_VALID(data[0]) ||
2143 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2145 * Tunnel passwords REQUIRE a tag, even
2146 * if don't have a valid tag.
2148 vp->flags.tag = data[0];
2150 if ((vp->type == PW_TYPE_STRING) ||
2151 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2156 * Copy the data to be decrypted
2158 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2159 vp->length -= offset;
2162 * Decrypt the attribute.
2164 switch (vp->flags.encrypt) {
2168 case FLAG_ENCRYPT_USER_PASSWORD:
2170 rad_pwdecode((char *)vp->vp_strvalue,
2174 rad_pwdecode((char *)vp->vp_strvalue,
2178 if (vp->attribute == PW_USER_PASSWORD) {
2179 vp->length = strlen(vp->vp_strvalue);
2184 * Tunnel-Password's may go ONLY
2185 * in response packets.
2187 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2188 if (!original) goto raw;
2190 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2191 secret, original->vector) < 0) {
2197 * Ascend-Send-Secret
2198 * Ascend-Receive-Secret
2200 case FLAG_ENCRYPT_ASCEND_SECRET:
2204 uint8_t my_digest[AUTH_VECTOR_LEN];
2205 make_secret(my_digest,
2208 memcpy(vp->vp_strvalue, my_digest,
2210 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2211 vp->length = strlen(vp->vp_strvalue);
2217 } /* switch over encryption flags */
2221 case PW_TYPE_STRING:
2222 case PW_TYPE_OCTETS:
2223 case PW_TYPE_ABINARY:
2224 /* nothing more to do */
2228 if (vp->length != 1) goto raw;
2230 vp->vp_integer = vp->vp_octets[0];
2235 if (vp->length != 2) goto raw;
2237 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2240 case PW_TYPE_INTEGER:
2241 if (vp->length != 4) goto raw;
2243 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2244 vp->vp_integer = ntohl(vp->vp_integer);
2246 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2249 * Try to get named VALUEs
2253 dval = dict_valbyattr(vp->attribute, vp->vendor,
2256 strlcpy(vp->vp_strvalue,
2258 sizeof(vp->vp_strvalue));
2264 if (vp->length != 4) goto raw;
2266 memcpy(&vp->vp_date, vp->vp_octets, 4);
2267 vp->vp_date = ntohl(vp->vp_date);
2271 case PW_TYPE_IPADDR:
2272 if (vp->length != 4) goto raw;
2274 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2278 * IPv6 interface ID is 8 octets long.
2281 if (vp->length != 8) goto raw;
2282 /* vp->vp_ifid == vp->vp_octets */
2286 * IPv6 addresses are 16 octets long
2288 case PW_TYPE_IPV6ADDR:
2289 if (vp->length != 16) goto raw;
2290 /* vp->vp_ipv6addr == vp->vp_octets */
2294 * IPv6 prefixes are 2 to 18 octets long.
2296 * RFC 3162: The first octet is unused.
2297 * The second is the length of the prefix
2298 * the rest are the prefix data.
2300 * The prefix length can have value 0 to 128.
2302 case PW_TYPE_IPV6PREFIX:
2303 if (vp->length < 2 || vp->length > 18) goto raw;
2304 if (vp->vp_octets[1] > 128) goto raw;
2307 * FIXME: double-check that
2308 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2310 if (vp->length < 18) {
2311 memset(vp->vp_octets + vp->length, 0,
2316 case PW_TYPE_SIGNED:
2317 if (vp->length != 4) goto raw;
2320 * Overload vp_integer for ntohl, which takes
2321 * uint32_t, not int32_t
2323 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2324 vp->vp_integer = ntohl(vp->vp_integer);
2325 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2329 vp->length = length;
2330 vp->vp_tlv = malloc(length);
2333 fr_strerror_printf("No memory");
2336 memcpy(vp->vp_tlv, data, length);
2339 case PW_TYPE_COMBO_IP:
2340 if (vp->length == 4) {
2341 vp->type = PW_TYPE_IPADDR;
2342 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2345 } else if (vp->length == 16) {
2346 vp->type = PW_TYPE_IPV6ADDR;
2347 /* vp->vp_ipv6addr == vp->vp_octets */
2355 vp->type = PW_TYPE_OCTETS;
2356 vp->length = length;
2357 memcpy(vp->vp_octets, data, length);
2361 * Ensure there's no encryption or tag stuff,
2362 * we just pass the attribute as-is.
2364 memset(&vp->flags, 0, sizeof(vp->flags));
2370 static void rad_sortvp(VALUE_PAIR **head)
2373 VALUE_PAIR *vp, **tail;
2376 * Walk over the VP's, sorting them in order. Did I
2377 * mention that I hate WiMAX continuations?
2379 * And bubble sort! WTF is up with that?
2386 if (!vp->next) break;
2388 if (vp->attribute > vp->next->attribute) {
2390 vp->next = (*tail)->next;
2401 * Walk the packet, looking for continuations of this attribute.
2403 * This is (worst-case) O(N^2) in the number of RADIUS
2404 * attributes. That happens only when perverse clients create
2405 * continued attributes, AND separate the fragmented portions
2406 * with a lot of other attributes.
2408 * Sane clients should put the fragments next to each other, in
2409 * which case this is O(N), in the number of fragments.
2411 static uint8_t *rad_coalesce(unsigned int attribute, int vendor,
2412 size_t length, uint8_t *data,
2413 size_t packet_length, size_t *ptlv_length)
2417 size_t tlv_length = length;
2418 uint8_t *ptr, *tlv, *tlv_data;
2420 for (ptr = data + length;
2421 ptr != (data + packet_length);
2423 /* FIXME: Check that there are 6 bytes of data here... */
2424 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2425 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2426 (ptr[2] != 0) || (ptr[3] != 0) || /* our requirement */
2427 (ptr[4] != ((vendor >> 8) & 0xff)) ||
2428 (ptr[5] != (vendor & 0xff))) {
2432 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2433 lvalue = ntohl(lvalue);
2435 lvalue |= ptr[2 + 4]; /* add in VSA number */
2436 if (lvalue != attribute) continue;
2439 * If the vendor-length is too small, it's badly
2440 * formed, so we stop.
2442 if ((ptr[2 + 4 + 1]) < 3) break;
2444 tlv_length += ptr[2 + 4 + 1] - 3;
2445 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2448 tlv = tlv_data = malloc(tlv_length);
2449 if (!tlv_data) return NULL;
2451 memcpy(tlv, data, length);
2455 * Now we walk the list again, copying the data over to
2456 * our newly created memory.
2458 for (ptr = data + length;
2459 ptr != (data + packet_length);
2463 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2464 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2465 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2469 memcpy(&lvalue, ptr + 2, 4);
2470 lvalue = ntohl(lvalue);
2472 lvalue |= ptr[2 + 4];
2473 if (lvalue != attribute) continue;
2476 * If the vendor-length is too small, it's badly
2477 * formed, so we stop.
2479 if ((ptr[2 + 4 + 1]) < 3) break;
2481 this_length = ptr[2 + 4 + 1] - 3;
2482 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2485 ptr[2 + 4] = 0; /* What a hack! */
2486 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2489 *ptlv_length = tlv_length;
2494 * Walk over Evil WIMAX Hell, creating attributes.
2496 * Won't someone think of the children? What if they read this code?
2498 static VALUE_PAIR *recurse_evil(const RADIUS_PACKET *packet,
2499 const RADIUS_PACKET *original,
2501 int attribute, int vendor,
2502 uint8_t *ptr, size_t len)
2504 VALUE_PAIR *head = NULL;
2505 VALUE_PAIR **tail = &head;
2507 uint8_t *y; /* why do I need to do this? */
2510 * Sanity check the attribute.
2512 for (y = ptr; y < (ptr + len); y += y[1]) {
2513 if ((y[0] == 0) || ((y + 2) > (ptr + len)) ||
2514 (y[1] < 2) || ((y + y[1]) > (ptr + len))) {
2519 for (y = ptr; y < (ptr + len); y += y[1]) {
2520 vp = paircreate(attribute | (ptr[0] << 16), vendor,
2528 if (!data2vp(packet, original, secret,
2529 y[1] - 2, y + 2, vp)) {
2541 * Start at the *data* portion of a continued attribute. search
2542 * through the rest of the attributes to find a matching one, and
2543 * add it's contents to our contents.
2545 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2546 const RADIUS_PACKET *original,
2547 const char *secret, int attribute,
2549 int length, /* CANNOT be zero */
2550 uint8_t *data, size_t packet_length,
2551 int flag, DICT_ATTR *da)
2553 size_t tlv_length, left;
2556 VALUE_PAIR *vp, *head, **tail;
2560 * Ensure we have data that hasn't been split across
2561 * multiple attributes.
2564 tlv_data = rad_coalesce(attribute, vendor, length,
2565 data, packet_length, &tlv_length);
2566 if (!tlv_data) return NULL;
2569 tlv_length = length;
2573 * Non-TLV types cannot be continued across multiple
2574 * attributes. This is true even of keys that are
2575 * encrypted with the tunnel-password method. The spec
2576 * says that they can be continued... but also that the
2577 * keys are 160 bits, which means that they CANNOT be
2580 * Note that we don't check "flag" here. The calling
2583 if (!da || (da->type != PW_TYPE_TLV)) {
2585 if (tlv_data == data) { /* true if we had 'goto' */
2586 tlv_data = malloc(tlv_length);
2587 if (!tlv_data) return NULL;
2588 memcpy(tlv_data, data, tlv_length);
2591 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2592 if (!vp) return NULL;
2594 vp->type = PW_TYPE_TLV;
2595 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2596 vp->flags.has_tag = 0;
2597 vp->flags.is_tlv = 0;
2598 vp->vp_tlv = tlv_data;
2599 vp->length = tlv_length;
2601 } /* else it WAS a TLV, go decode the sub-tlv's */
2604 * Now (sigh) we walk over the TLV, seeing if it is
2608 for (ptr = tlv_data;
2609 ptr != (tlv_data + tlv_length);
2614 goto not_well_formed;
2621 * Now we walk over the TLV *again*, creating sub-tlv's.
2626 for (ptr = tlv_data;
2627 ptr != (tlv_data + tlv_length);
2630 tlv_da = dict_attrbyvalue(attribute | (ptr[0] << 8), vendor);
2631 if (tlv_da && (tlv_da->type == PW_TYPE_TLV)) {
2632 vp = recurse_evil(packet, original, secret,
2633 attribute | (ptr[0] << 8),
2634 vendor, ptr + 2, ptr[1] - 2);
2638 goto not_well_formed;
2641 vp = paircreate(attribute | (ptr[0] << 8), vendor,
2645 goto not_well_formed;
2648 if (!data2vp(packet, original, secret,
2649 ptr[1] - 2, ptr + 2, vp)) {
2651 goto not_well_formed;
2657 while (*tail) tail = &((*tail)->next);
2661 * TLV's MAY be continued, but sometimes they're not.
2663 if (tlv_data != data) free(tlv_data);
2665 if (head->next) rad_sortvp(&head);
2672 * Parse a RADIUS attribute into a data structure.
2674 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet,
2675 const RADIUS_PACKET *original,
2676 const char *secret, int attribute, int vendor,
2677 int length, const uint8_t *data)
2681 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2682 if (!vp) return NULL;
2684 return data2vp(packet, original, secret, length, data, vp);
2689 * Calculate/check digest, and decode radius attributes.
2691 * -1 on decoding error
2694 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2698 uint32_t vendorcode;
2701 uint8_t *ptr, *vsa_ptr;
2706 radius_packet_t *hdr;
2707 int vsa_tlen, vsa_llen, vsa_offset;
2708 DICT_VENDOR *dv = NULL;
2709 int num_attributes = 0;
2712 * Extract attribute-value pairs
2714 hdr = (radius_packet_t *)packet->data;
2716 packet_length = packet->data_len - AUTH_HDR_LEN;
2719 * There may be VP's already in the packet. Don't
2722 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2728 vsa_tlen = vsa_llen = 1;
2732 * We have to read at least two bytes.
2734 * rad_recv() above ensures that this is OK.
2736 while (packet_length > 0) {
2741 * Normal attribute, handle it like normal.
2743 if (vendorcode == 0) {
2745 * No room to read attr/length,
2746 * or bad attribute, or attribute is
2747 * too short, or attribute is too long,
2748 * stop processing the packet.
2750 if ((packet_length < 2) ||
2751 (ptr[0] == 0) || (ptr[1] < 2) ||
2752 (ptr[1] > packet_length)) break;
2760 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2763 * No vendor code, or ONLY vendor code.
2765 if (attrlen <= 4) goto create_pair;
2771 * Handle Vendor-Specific
2773 if (vendorlen == 0) {
2779 * attrlen was checked above.
2781 memcpy(&lvalue, ptr, 4);
2782 myvendor = ntohl(lvalue);
2785 * Zero isn't allowed.
2787 if (myvendor == 0) goto create_pair;
2790 * This is an implementation issue.
2791 * We currently pack vendor into the upper
2792 * 16 bits of a 32-bit attribute number,
2793 * so we can't handle vendor numbers larger
2796 if (myvendor > 65535) goto create_pair;
2798 vsa_tlen = vsa_llen = 1;
2800 dv = dict_vendorbyvalue(myvendor);
2802 vsa_tlen = dv->type;
2803 vsa_llen = dv->length;
2804 if (dv->flags) vsa_offset = 1;
2808 * Sweep through the list of VSA's,
2809 * seeing if they exactly fill the
2810 * outer Vendor-Specific attribute.
2812 * If not, create a raw Vendor-Specific.
2815 sublen = attrlen - 4;
2818 * See if we can parse it.
2824 * Not enough room for one more
2827 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2830 * Ensure that the attribute number
2839 myattr = (subptr[0] << 8) | subptr[1];
2843 if ((subptr[0] != 0) ||
2844 (subptr[1] != 0)) goto create_pair;
2846 myattr = (subptr[2] << 8) | subptr[3];
2850 * Our dictionary is broken.
2859 ptr += 4 + vsa_tlen;
2860 attrlen -= (4 + vsa_tlen);
2861 packet_length -= 4 + vsa_tlen;
2865 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2868 if (subptr[vsa_tlen] > sublen)
2873 * Reserved bits MUST be
2877 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2880 sublen -= subptr[vsa_tlen];
2881 subptr += subptr[vsa_tlen];
2885 if (subptr[vsa_tlen] != 0) goto create_pair;
2886 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2888 if (subptr[vsa_tlen + 1] > sublen)
2890 sublen -= subptr[vsa_tlen + 1];
2891 subptr += subptr[vsa_tlen + 1];
2895 * Our dictionaries are
2901 } while (sublen > 0);
2903 vendorcode = myvendor;
2904 vendorlen = attrlen - 4;
2911 * attrlen is the length of this attribute.
2912 * total_len is the length of the encompassing
2921 attribute = (ptr[0] << 8) | ptr[1];
2924 default: /* can't hit this. */
2932 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2936 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2939 default: /* can't hit this. */
2943 ptr += vsa_llen + vsa_offset;
2944 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2945 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2948 * Ignore VSAs that have no data.
2950 if (attrlen == 0) goto next;
2953 * WiMAX attributes of type 0 are ignored. They
2954 * are a secret flag to us that the attribute has
2955 * already been dealt with.
2957 if ((vendorcode == VENDORPEC_WIMAX) && (attribute == 0)) {
2964 da = dict_attrbyvalue(attribute, vendorcode);
2967 * If it's NOT continued, AND we know
2968 * about it, AND it's not a TLV, we can
2969 * create a normal pair.
2971 if (((vsa_ptr[2] & 0x80) == 0) &&
2972 da && (da->type != PW_TYPE_TLV)) goto create_pair;
2975 * Else it IS continued, or it's a TLV.
2976 * Go do a lot of work to find the stuff.
2978 pair = rad_continuation2vp(packet, original, secret,
2979 attribute, vendorcode,
2982 ((vsa_ptr[2] & 0x80) != 0),
2988 * Create the attribute, setting the default type
2989 * to 'octets'. If the type in the dictionary
2990 * is different, then the dictionary type will
2991 * over-ride this one.
2993 * If the attribute has no data, then discard it.
2995 * Unless it's CUI. Damn you, CUI!
2999 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
3001 pair = rad_attr2vp(packet, original, secret,
3002 attribute, vendorcode, attrlen, ptr);
3004 pairfree(&packet->vps);
3005 fr_strerror_printf("out of memory");
3019 * VSA's may not have been counted properly in
3020 * rad_packet_ok() above, as it is hard to count
3021 * then without using the dictionary. We
3022 * therefore enforce the limits here, too.
3024 if ((fr_max_attributes > 0) &&
3025 (num_attributes > fr_max_attributes)) {
3026 char host_ipaddr[128];
3028 pairfree(&packet->vps);
3029 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3030 inet_ntop(packet->src_ipaddr.af,
3031 &packet->src_ipaddr.ipaddr,
3032 host_ipaddr, sizeof(host_ipaddr)),
3033 num_attributes, fr_max_attributes);
3038 if (vendorlen == 0) vendorcode = 0;
3040 packet_length -= attrlen;
3044 * Merge information from the outside world into our
3047 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3056 * We assume that the passwd buffer passed is big enough.
3057 * RFC2138 says the password is max 128 chars, so the size
3058 * of the passwd buffer must be at least 129 characters.
3059 * Preferably it's just MAX_STRING_LEN.
3061 * int *pwlen is updated to the new length of the encrypted
3062 * password - a multiple of 16 bytes.
3064 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3065 const uint8_t *vector)
3067 FR_MD5_CTX context, old;
3068 uint8_t digest[AUTH_VECTOR_LEN];
3069 int i, n, secretlen;
3073 * RFC maximum is 128 bytes.
3075 * If length is zero, pad it out with zeros.
3077 * If the length isn't aligned to 16 bytes,
3078 * zero out the extra data.
3082 if (len > 128) len = 128;
3085 memset(passwd, 0, AUTH_PASS_LEN);
3086 len = AUTH_PASS_LEN;
3087 } else if ((len % AUTH_PASS_LEN) != 0) {
3088 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3089 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3094 * Use the secret to setup the decryption digest
3096 secretlen = strlen(secret);
3098 fr_MD5Init(&context);
3099 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3100 old = context; /* save intermediate work */
3103 * Encrypt it in place. Don't bother checking
3104 * len, as we've ensured above that it's OK.
3106 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3108 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3109 fr_MD5Final(digest, &context);
3112 fr_MD5Update(&context,
3113 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3115 fr_MD5Final(digest, &context);
3118 for (i = 0; i < AUTH_PASS_LEN; i++) {
3119 passwd[i + n] ^= digest[i];
3129 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3130 const uint8_t *vector)
3132 FR_MD5_CTX context, old;
3133 uint8_t digest[AUTH_VECTOR_LEN];
3135 size_t n, secretlen;
3138 * The RFC's say that the maximum is 128.
3139 * The buffer we're putting it into above is 254, so
3140 * we don't need to do any length checking.
3142 if (pwlen > 128) pwlen = 128;
3147 if (pwlen == 0) goto done;
3150 * Use the secret to setup the decryption digest
3152 secretlen = strlen(secret);
3154 fr_MD5Init(&context);
3155 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3156 old = context; /* save intermediate work */
3159 * The inverse of the code above.
3161 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3163 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3164 fr_MD5Final(digest, &context);
3167 if (pwlen > AUTH_PASS_LEN) {
3168 fr_MD5Update(&context, (uint8_t *) passwd,
3172 fr_MD5Final(digest, &context);
3175 if (pwlen > (n + AUTH_PASS_LEN)) {
3176 fr_MD5Update(&context, (uint8_t *) passwd + n,
3181 for (i = 0; i < AUTH_PASS_LEN; i++) {
3182 passwd[i + n] ^= digest[i];
3187 passwd[pwlen] = '\0';
3188 return strlen(passwd);
3193 * Encode Tunnel-Password attributes when sending them out on the wire.
3195 * int *pwlen is updated to the new length of the encrypted
3196 * password - a multiple of 16 bytes.
3198 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3201 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3202 const uint8_t *vector)
3204 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3205 unsigned char digest[AUTH_VECTOR_LEN];
3207 int i, n, secretlen;
3212 if (len > 127) len = 127;
3215 * Shift the password 3 positions right to place a salt and original
3216 * length, tag will be added automatically on packet send
3218 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3222 * save original password length as first password character;
3229 * Generate salt. The RFC's say:
3231 * The high bit of salt[0] must be set, each salt in a
3232 * packet should be unique, and they should be random
3234 * So, we set the high bit, add in a counter, and then
3235 * add in some CSPRNG data. should be OK..
3237 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3238 (fr_rand() & 0x07));
3239 salt[1] = fr_rand();
3242 * Padd password to multiple of AUTH_PASS_LEN bytes.
3244 n = len % AUTH_PASS_LEN;
3246 n = AUTH_PASS_LEN - n;
3247 for (; n > 0; n--, len++)
3250 /* set new password length */
3254 * Use the secret to setup the decryption digest
3256 secretlen = strlen(secret);
3257 memcpy(buffer, secret, secretlen);
3259 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3261 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3262 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3263 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3265 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3266 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3269 for (i = 0; i < AUTH_PASS_LEN; i++) {
3270 passwd[i + n2] ^= digest[i];
3278 * Decode Tunnel-Password encrypted attributes.
3280 * Defined in RFC-2868, this uses a two char SALT along with the
3281 * initial intermediate value, to differentiate it from the
3284 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3285 const uint8_t *vector)
3287 FR_MD5_CTX context, old;
3288 uint8_t digest[AUTH_VECTOR_LEN];
3290 unsigned i, n, len, reallen;
3295 * We need at least a salt.
3298 fr_strerror_printf("tunnel password is too short");
3303 * There's a salt, but no password. Or, there's a salt
3304 * and a 'data_len' octet. It's wrong, but at least we
3305 * can figure out what it means: the password is empty.
3307 * Note that this means we ignore the 'data_len' field,
3308 * if the attribute length tells us that there's no
3309 * more data. So the 'data_len' field may be wrong,
3318 len -= 2; /* discount the salt */
3321 * Use the secret to setup the decryption digest
3323 secretlen = strlen(secret);
3325 fr_MD5Init(&context);
3326 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3327 old = context; /* save intermediate work */
3330 * Set up the initial key:
3332 * b(1) = MD5(secret + vector + salt)
3334 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3335 fr_MD5Update(&context, passwd, 2);
3338 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3342 fr_MD5Final(digest, &context);
3347 * A quick check: decrypt the first octet
3348 * of the password, which is the
3349 * 'data_len' field. Ensure it's sane.
3351 reallen = passwd[2] ^ digest[0];
3352 if (reallen >= len) {
3353 fr_strerror_printf("tunnel password is too long for the attribute");
3357 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3361 fr_MD5Final(digest, &context);
3364 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3367 for (i = base; i < AUTH_PASS_LEN; i++) {
3368 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3373 * See make_tunnel_password, above.
3375 if (reallen > 239) reallen = 239;
3378 passwd[reallen] = 0;
3384 * Encode a CHAP password
3386 * FIXME: might not work with Ascend because
3387 * we use vp->length, and Ascend gear likes
3388 * to send an extra '\0' in the string!
3390 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3391 VALUE_PAIR *password)
3395 uint8_t string[MAX_STRING_LEN * 2 + 1];
3396 VALUE_PAIR *challenge;
3399 * Sanity check the input parameters
3401 if ((packet == NULL) || (password == NULL)) {
3406 * Note that the password VP can be EITHER
3407 * a User-Password attribute (from a check-item list),
3408 * or a CHAP-Password attribute (the client asking
3409 * the library to encode it).
3417 memcpy(ptr, password->vp_strvalue, password->length);
3418 ptr += password->length;
3419 i += password->length;
3422 * Use Chap-Challenge pair if present,
3423 * Request-Authenticator otherwise.
3425 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
3427 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3428 i += challenge->length;
3430 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3431 i += AUTH_VECTOR_LEN;
3435 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3442 * Seed the random number generator.
3444 * May be called any number of times.
3446 void fr_rand_seed(const void *data, size_t size)
3451 * Ensure that the pool is initialized.
3453 if (!fr_rand_initialized) {
3456 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3458 fd = open("/dev/urandom", O_RDONLY);
3464 while (total < sizeof(fr_rand_pool.randrsl)) {
3465 this = read(fd, fr_rand_pool.randrsl,
3466 sizeof(fr_rand_pool.randrsl) - total);
3467 if ((this < 0) && (errno != EINTR)) break;
3468 if (this > 0) total += this;
3472 fr_rand_pool.randrsl[0] = fd;
3473 fr_rand_pool.randrsl[1] = time(NULL);
3474 fr_rand_pool.randrsl[2] = errno;
3477 fr_randinit(&fr_rand_pool, 1);
3478 fr_rand_pool.randcnt = 0;
3479 fr_rand_initialized = 1;
3485 * Hash the user data
3488 if (!hash) hash = fr_rand();
3489 hash = fr_hash_update(data, size, hash);
3491 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3496 * Return a 32-bit random number.
3498 uint32_t fr_rand(void)
3503 * Ensure that the pool is initialized.
3505 if (!fr_rand_initialized) {
3506 fr_rand_seed(NULL, 0);
3509 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3510 if (fr_rand_pool.randcnt >= 256) {
3511 fr_rand_pool.randcnt = 0;
3512 fr_isaac(&fr_rand_pool);
3520 * Allocate a new RADIUS_PACKET
3522 RADIUS_PACKET *rad_alloc(int newvector)
3526 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3527 fr_strerror_printf("out of memory");
3530 memset(rp, 0, sizeof(*rp));
3536 uint32_t hash, base;
3539 * Don't expose the actual contents of the random
3543 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3544 hash = fr_rand() ^ base;
3545 memcpy(rp->vector + i, &hash, sizeof(hash));
3548 fr_rand(); /* stir the pool again */
3553 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3555 RADIUS_PACKET *reply;
3557 if (!packet) return NULL;
3559 reply = rad_alloc(0);
3560 if (!reply) return NULL;
3563 * Initialize the fields from the request.
3565 reply->sockfd = packet->sockfd;
3566 reply->dst_ipaddr = packet->src_ipaddr;
3567 reply->src_ipaddr = packet->dst_ipaddr;
3568 reply->dst_port = packet->src_port;
3569 reply->src_port = packet->dst_port;
3570 reply->id = packet->id;
3571 reply->code = 0; /* UNKNOWN code */
3572 memcpy(reply->vector, packet->vector,
3573 sizeof(reply->vector));
3576 reply->data_len = 0;
3583 * Free a RADIUS_PACKET
3585 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3587 RADIUS_PACKET *radius_packet;
3589 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3590 radius_packet = *radius_packet_ptr;
3592 free(radius_packet->data);
3594 pairfree(&radius_packet->vps);
3596 free(radius_packet);
3598 *radius_packet_ptr = NULL;