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 uint8_t *vp2data(const RADIUS_PACKET *packet,
640 const RADIUS_PACKET *original,
641 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
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 < 18) return ptr;
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 make_tunnel_passwd(ptr, &len, data, len, room,
760 secret, original->vector);
762 case PW_ACCOUNTING_REQUEST:
763 case PW_DISCONNECT_REQUEST:
765 make_tunnel_passwd(ptr, &len, data, len, room,
766 secret, packet->vector);
772 * The code above ensures that this attribute
775 case FLAG_ENCRYPT_ASCEND_SECRET:
776 make_secret(ptr, packet->vector, secret, data);
777 len = AUTH_VECTOR_LEN;
783 * Just copy the data over
785 memcpy(ptr, data, len);
787 } /* switch over encryption flags */
794 * Parse a data structure into a RADIUS attribute.
796 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
797 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
801 int len, total_length;
803 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
804 uint8_t *end, *sub_length_ptr; /* evil */
807 vendorcode = total_length = 0;
808 length_ptr = vsa_length_ptr = tlv_length_ptr = sub_length_ptr = NULL;
811 * For interoperability, always put vendor attributes
812 * into their own VSA.
814 if ((vendorcode = vp->vendor) == 0) {
815 if (room < 2) return 0;
818 *(ptr++) = vp->attribute & 0xff;
827 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
830 * This must be an RFC-format attribute. If it
831 * wasn't, then the "decode" function would have
832 * made a Vendor-Specific attribute (i.e. type
833 * 26), and we would have "vendorcode == 0" here.
837 vsa_llen = dv->length;
838 if (dv->flags) vsa_offset = 1;
841 if (room < (6 + vsa_tlen + vsa_llen + vsa_offset)) return 0;
842 room -= 6 + vsa_tlen + vsa_llen + vsa_offset;
845 * Build a VSA header.
847 *ptr++ = PW_VENDOR_SPECIFIC;
848 vsa_length_ptr = ptr;
850 lvalue = htonl(vendorcode);
851 memcpy(ptr, &lvalue, 4);
857 ptr[0] = (vp->attribute & 0xFF);
861 ptr[0] = ((vp->attribute >> 8) & 0xFF);
862 ptr[1] = (vp->attribute & 0xFF);
868 ptr[2] = ((vp->attribute >> 8) & 0xFF);
869 ptr[3] = (vp->attribute & 0xFF);
873 return 0; /* silently discard it */
879 length_ptr = vsa_length_ptr;
880 vsa_length_ptr = NULL;
889 length_ptr = ptr + 1;
893 return 0; /* silently discard it */
898 * Allow for some continuation.
905 * Ignore TLVs that don't have data, OR
906 * have too much data to fit in the
907 * packet, OR have too much data to fit
910 * This shouldn't happen in normal
911 * operation, as the code assumes that
912 * the "tlv" type shouldn't be used.
914 if (vp->flags.has_tlv &&
915 (!vp->vp_tlv || (vp->length > room) ||
918 * 6 + 1 (vsa_tlen) + 1 (vsa_llen)
921 (vp->length > (255 - 9)))) return 0;
925 * sub-TLV's can only be in one format.
927 if (vp->flags.is_tlv) {
928 if (room < 2) return 0;
931 *(ptr++) = (vp->attribute & 0xff00) >> 8;
932 tlv_length_ptr = ptr;
937 * WiMAX is like sticking knitting
938 * needles up your nose, and claiming
941 if ((vp->attribute & 0xff0000) != 0) {
942 *(ptr++) = (vp->attribute >> 16) & 0xff;
943 sub_length_ptr = ptr;
946 *tlv_length_ptr += 2;
951 total_length += vsa_tlen + vsa_llen + vsa_offset;
952 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
953 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
957 * Insert tags for string attributes. They go BEFORE
960 if (vp->flags.has_tag && (vp->type == PW_TYPE_STRING) &&
961 (TAG_VALID(vp->flags.tag) ||
962 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
963 if (room < (1 + vp->length)) return 0;
965 ptr[0] = vp->flags.tag;
966 end = vp2data(packet, original, secret, vp, ptr + 1,
969 if (room < vp->length) return 0;
970 end = vp2data(packet, original, secret, vp, ptr,
976 * Insert tags for integer attributes. They go at the START
977 * of the integer, and over-write the first byte.
979 if (vp->flags.has_tag && (vp->type == PW_TYPE_INTEGER)) {
980 ptr[0] = vp->flags.tag;
984 * RFC 2865 section 5 says that zero-length attributes
987 * ... and the WiMAX forum ignores this... because of
988 * one vendor. Don't they have anything better to do
992 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
997 * Update the various lengths.
1000 if (vsa_length_ptr) *vsa_length_ptr += len;
1001 if (tlv_length_ptr) *tlv_length_ptr += len;
1002 if (sub_length_ptr) *sub_length_ptr += len;
1004 total_length += len;
1006 return total_length; /* of attribute */
1012 #define REORDER(x) ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000 >> 24))
1014 static int rad_encode_wimax(const RADIUS_PACKET *packet,
1015 const RADIUS_PACKET *original,
1016 const char *secret, VALUE_PAIR *reply,
1017 uint8_t *start, size_t room)
1019 int len, total_len = 0;
1020 uint8_t *wimax = NULL;
1021 uint8_t *ptr = start;
1023 VALUE_PAIR *vp = reply;
1026 * Swap the order of the WiMAX hacks, to make later
1027 * comparisons easier.
1029 maxattr = REORDER(vp->attribute);
1032 len = rad_vp2attr(packet, original, secret, vp, ptr,
1033 (start + room) - ptr);
1034 if (len <= 0) return total_len;
1037 * After adding an attribute with the simplest encoding,
1038 * check to see if we can append it to the previous one.
1041 if ((wimax[1] + (ptr[1] - 6)) <= 255) {
1045 memmove(ptr, ptr + 9, hack);
1051 * See if we can nest sub-TLVs, too, in
1052 * order to shorten the encoding.
1056 wimax[8] = 0x80; /* set continuation */
1066 vp->flags.encoded = 1;
1070 * Look at the NEXT tlv. Ensure that we encode
1071 * attributes into a common VSA *only* if they are for
1072 * the same WiMAX VSA, AND if the TLVs are in numerically
1075 if (vp && vp->flags.is_tlv && (reply->vendor == vp->vendor) &&
1076 ((reply->attribute & 0xff) == (vp->attribute & 0xff))) {
1079 attr = REORDER(vp->attribute);
1080 if (attr >= maxattr) {
1093 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1096 radius_packet_t *hdr;
1098 uint16_t total_length;
1102 char ip_buffer[128];
1105 * A 4K packet, aligned on 64-bits.
1107 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1109 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1110 what = fr_packet_codes[packet->code];
1115 DEBUG("Sending %s of id %d to %s port %d\n",
1117 inet_ntop(packet->dst_ipaddr.af,
1118 &packet->dst_ipaddr.ipaddr,
1119 ip_buffer, sizeof(ip_buffer)),
1123 * Double-check some things based on packet code.
1125 switch (packet->code) {
1126 case PW_AUTHENTICATION_ACK:
1127 case PW_AUTHENTICATION_REJECT:
1128 case PW_ACCESS_CHALLENGE:
1130 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1136 * These packet vectors start off as all zero.
1138 case PW_ACCOUNTING_REQUEST:
1139 case PW_DISCONNECT_REQUEST:
1140 case PW_COA_REQUEST:
1141 memset(packet->vector, 0, sizeof(packet->vector));
1149 * Use memory on the stack, until we know how
1150 * large the packet will be.
1152 hdr = (radius_packet_t *) data;
1155 * Build standard header
1157 hdr->code = packet->code;
1158 hdr->id = packet->id;
1160 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1162 total_length = AUTH_HDR_LEN;
1165 * Load up the configuration values for the user
1171 * FIXME: Loop twice over the reply list. The first time,
1172 * calculate the total length of data. The second time,
1173 * allocate the memory, and fill in the VP's.
1175 * Hmm... this may be slower than just doing a small
1180 * Loop over the reply attributes for the packet.
1182 for (reply = packet->vps; reply; reply = reply->next) {
1184 * Ignore non-wire attributes
1186 if ((reply->vendor == 0) &&
1187 ((reply->attribute & 0xFFFF) > 0xff)) {
1190 * Permit the admin to send BADLY formatted
1191 * attributes with a debug build.
1193 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1194 memcpy(ptr, reply->vp_octets, reply->length);
1195 len = reply->length;
1203 * Set the Message-Authenticator to the correct
1204 * length and initial value.
1206 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1207 reply->length = AUTH_VECTOR_LEN;
1208 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1211 * Cache the offset to the
1212 * Message-Authenticator
1214 packet->offset = total_length;
1218 * Print out ONLY the attributes which
1219 * we're sending over the wire, and print
1220 * them out BEFORE they're encrypted.
1225 * Skip attributes that are encoded.
1227 if (reply->flags.encoded) continue;
1229 if (reply->flags.is_tlv) {
1230 len = rad_encode_wimax(packet, original, secret,
1232 ((uint8_t *) data) + sizeof(data) - ptr);
1235 len = rad_vp2attr(packet, original, secret, reply, ptr,
1236 ((uint8_t *) data) + sizeof(data) - ptr);
1239 if (len < 0) return -1;
1243 total_length += len;
1244 } /* done looping over all attributes */
1247 * Fill in the rest of the fields, and copy the data over
1248 * from the local stack to the newly allocated memory.
1250 * Yes, all this 'memcpy' is slow, but it means
1251 * that we only allocate the minimum amount of
1252 * memory for a request.
1254 packet->data_len = total_length;
1255 packet->data = (uint8_t *) malloc(packet->data_len);
1256 if (!packet->data) {
1257 fr_strerror_printf("Out of memory");
1261 memcpy(packet->data, hdr, packet->data_len);
1262 hdr = (radius_packet_t *) packet->data;
1264 total_length = htons(total_length);
1265 memcpy(hdr->length, &total_length, sizeof(total_length));
1272 * Sign a previously encoded packet.
1274 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1277 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1280 * It wasn't assigned an Id, this is bad!
1282 if (packet->id < 0) {
1283 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1287 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1288 (packet->offset < 0)) {
1289 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1294 * If there's a Message-Authenticator, update it
1295 * now, BEFORE updating the authentication vector.
1297 if (packet->offset > 0) {
1298 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1300 switch (packet->code) {
1301 case PW_ACCOUNTING_REQUEST:
1302 case PW_ACCOUNTING_RESPONSE:
1303 case PW_DISCONNECT_REQUEST:
1304 case PW_DISCONNECT_ACK:
1305 case PW_DISCONNECT_NAK:
1306 case PW_COA_REQUEST:
1309 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1312 case PW_AUTHENTICATION_ACK:
1313 case PW_AUTHENTICATION_REJECT:
1314 case PW_ACCESS_CHALLENGE:
1316 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1319 memcpy(hdr->vector, original->vector,
1323 default: /* others have vector already set to zero */
1329 * Set the authentication vector to zero,
1330 * calculate the signature, and put it
1331 * into the Message-Authenticator
1334 fr_hmac_md5(packet->data, packet->data_len,
1335 (const uint8_t *) secret, strlen(secret),
1337 memcpy(packet->data + packet->offset + 2,
1338 calc_auth_vector, AUTH_VECTOR_LEN);
1341 * Copy the original request vector back
1342 * to the raw packet.
1344 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1348 * Switch over the packet code, deciding how to
1351 switch (packet->code) {
1353 * Request packets are not signed, bur
1354 * have a random authentication vector.
1356 case PW_AUTHENTICATION_REQUEST:
1357 case PW_STATUS_SERVER:
1361 * Reply packets are signed with the
1362 * authentication vector of the request.
1369 fr_MD5Init(&context);
1370 fr_MD5Update(&context, packet->data, packet->data_len);
1371 fr_MD5Update(&context, (const uint8_t *) secret,
1373 fr_MD5Final(digest, &context);
1375 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1376 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1379 }/* switch over packet codes */
1385 * Reply to the request. Also attach
1386 * reply attribute value pairs and any user message provided.
1388 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1393 char ip_buffer[128];
1396 * Maybe it's a fake packet. Don't send it.
1398 if (!packet || (packet->sockfd < 0)) {
1402 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1403 what = fr_packet_codes[packet->code];
1409 * First time through, allocate room for the packet
1411 if (!packet->data) {
1413 * Encode the packet.
1415 if (rad_encode(packet, original, secret) < 0) {
1420 * Re-sign it, including updating the
1421 * Message-Authenticator.
1423 if (rad_sign(packet, original, secret) < 0) {
1428 * If packet->data points to data, then we print out
1429 * the VP list again only for debugging.
1431 } else if (fr_debug_flag) {
1432 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1433 inet_ntop(packet->dst_ipaddr.af,
1434 &packet->dst_ipaddr.ipaddr,
1435 ip_buffer, sizeof(ip_buffer)),
1438 for (reply = packet->vps; reply; reply = reply->next) {
1439 if ((reply->vendor == 0) &&
1440 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1446 * And send it on it's way.
1448 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1449 &packet->src_ipaddr, packet->src_port,
1450 &packet->dst_ipaddr, packet->dst_port);
1454 * Do a comparison of two authentication digests by comparing
1455 * the FULL digest. Otehrwise, the server can be subject to
1456 * timing attacks that allow attackers find a valid message
1459 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1461 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1466 for (i = 0; i < length; i++) {
1467 result |= a[i] ^ b[i];
1470 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1475 * Validates the requesting client NAS. Calculates the
1476 * signature based on the clients private key.
1478 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1480 uint8_t digest[AUTH_VECTOR_LEN];
1484 * Zero out the auth_vector in the received packet.
1485 * Then append the shared secret to the received packet,
1486 * and calculate the MD5 sum. This must be the same
1487 * as the original MD5 sum (packet->vector).
1489 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1492 * MD5(packet + secret);
1494 fr_MD5Init(&context);
1495 fr_MD5Update(&context, packet->data, packet->data_len);
1496 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1497 fr_MD5Final(digest, &context);
1500 * Return 0 if OK, 2 if not OK.
1502 if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1508 * Validates the requesting client NAS. Calculates the
1509 * signature based on the clients private key.
1511 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1514 uint8_t calc_digest[AUTH_VECTOR_LEN];
1520 if (original == NULL) {
1525 * Copy the original vector in place.
1527 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1530 * MD5(packet + secret);
1532 fr_MD5Init(&context);
1533 fr_MD5Update(&context, packet->data, packet->data_len);
1534 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1535 fr_MD5Final(calc_digest, &context);
1538 * Copy the packet's vector back to the packet.
1540 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1543 * Return 0 if OK, 2 if not OK.
1545 if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1551 * See if the data pointed to by PTR is a valid RADIUS packet.
1553 * packet is not 'const * const' because we may update data_len,
1554 * if there's more data in the UDP packet than in the RADIUS packet.
1556 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1561 radius_packet_t *hdr;
1562 char host_ipaddr[128];
1568 * Check for packets smaller than the packet header.
1570 * RFC 2865, Section 3., subsection 'length' says:
1572 * "The minimum length is 20 ..."
1574 if (packet->data_len < AUTH_HDR_LEN) {
1575 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1576 inet_ntop(packet->src_ipaddr.af,
1577 &packet->src_ipaddr.ipaddr,
1578 host_ipaddr, sizeof(host_ipaddr)),
1579 (int) packet->data_len, AUTH_HDR_LEN);
1584 * RFC 2865, Section 3., subsection 'length' says:
1586 * " ... and maximum length is 4096."
1588 if (packet->data_len > MAX_PACKET_LEN) {
1589 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1590 inet_ntop(packet->src_ipaddr.af,
1591 &packet->src_ipaddr.ipaddr,
1592 host_ipaddr, sizeof(host_ipaddr)),
1593 (int) packet->data_len, MAX_PACKET_LEN);
1598 * Check for packets with mismatched size.
1599 * i.e. We've received 128 bytes, and the packet header
1600 * says it's 256 bytes long.
1602 totallen = (packet->data[2] << 8) | packet->data[3];
1603 hdr = (radius_packet_t *)packet->data;
1606 * Code of 0 is not understood.
1607 * Code of 16 or greate is not understood.
1609 if ((hdr->code == 0) ||
1610 (hdr->code >= FR_MAX_PACKET_CODE)) {
1611 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1612 inet_ntop(packet->src_ipaddr.af,
1613 &packet->src_ipaddr.ipaddr,
1614 host_ipaddr, sizeof(host_ipaddr)),
1620 * Message-Authenticator is required in Status-Server
1621 * packets, otherwise they can be trivially forged.
1623 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1626 * It's also required if the caller asks for it.
1628 if (flags) require_ma = 1;
1631 * Repeat the length checks. This time, instead of
1632 * looking at the data we received, look at the value
1633 * of the 'length' field inside of the packet.
1635 * Check for packets smaller than the packet header.
1637 * RFC 2865, Section 3., subsection 'length' says:
1639 * "The minimum length is 20 ..."
1641 if (totallen < AUTH_HDR_LEN) {
1642 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1643 inet_ntop(packet->src_ipaddr.af,
1644 &packet->src_ipaddr.ipaddr,
1645 host_ipaddr, sizeof(host_ipaddr)),
1646 totallen, AUTH_HDR_LEN);
1651 * And again, for the value of the 'length' field.
1653 * RFC 2865, Section 3., subsection 'length' says:
1655 * " ... and maximum length is 4096."
1657 if (totallen > MAX_PACKET_LEN) {
1658 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1659 inet_ntop(packet->src_ipaddr.af,
1660 &packet->src_ipaddr.ipaddr,
1661 host_ipaddr, sizeof(host_ipaddr)),
1662 totallen, MAX_PACKET_LEN);
1667 * RFC 2865, Section 3., subsection 'length' says:
1669 * "If the packet is shorter than the Length field
1670 * indicates, it MUST be silently discarded."
1672 * i.e. No response to the NAS.
1674 if (packet->data_len < totallen) {
1675 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1676 inet_ntop(packet->src_ipaddr.af,
1677 &packet->src_ipaddr.ipaddr,
1678 host_ipaddr, sizeof(host_ipaddr)),
1679 (int) packet->data_len, totallen);
1684 * RFC 2865, Section 3., subsection 'length' says:
1686 * "Octets outside the range of the Length field MUST be
1687 * treated as padding and ignored on reception."
1689 if (packet->data_len > totallen) {
1691 * We're shortening the packet below, but just
1692 * to be paranoid, zero out the extra data.
1694 memset(packet->data + totallen, 0, packet->data_len - totallen);
1695 packet->data_len = totallen;
1699 * Walk through the packet's attributes, ensuring that
1700 * they add up EXACTLY to the size of the packet.
1702 * If they don't, then the attributes either under-fill
1703 * or over-fill the packet. Any parsing of the packet
1704 * is impossible, and will result in unknown side effects.
1706 * This would ONLY happen with buggy RADIUS implementations,
1707 * or with an intentional attack. Either way, we do NOT want
1708 * to be vulnerable to this problem.
1711 count = totallen - AUTH_HDR_LEN;
1716 * Attribute number zero is NOT defined.
1719 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1720 inet_ntop(packet->src_ipaddr.af,
1721 &packet->src_ipaddr.ipaddr,
1722 host_ipaddr, sizeof(host_ipaddr)));
1727 * Attributes are at LEAST as long as the ID & length
1728 * fields. Anything shorter is an invalid attribute.
1731 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1732 inet_ntop(packet->src_ipaddr.af,
1733 &packet->src_ipaddr.ipaddr,
1734 host_ipaddr, sizeof(host_ipaddr)),
1740 * Sanity check the attributes for length.
1743 default: /* don't do anything by default */
1747 * If there's an EAP-Message, we require
1748 * a Message-Authenticator.
1750 case PW_EAP_MESSAGE:
1754 case PW_MESSAGE_AUTHENTICATOR:
1755 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1756 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1757 inet_ntop(packet->src_ipaddr.af,
1758 &packet->src_ipaddr.ipaddr,
1759 host_ipaddr, sizeof(host_ipaddr)),
1768 * FIXME: Look up the base 255 attributes in the
1769 * dictionary, and switch over their type. For
1770 * integer/date/ip, the attribute length SHOULD
1773 count -= attr[1]; /* grab the attribute length */
1775 num_attributes++; /* seen one more attribute */
1779 * If the attributes add up to a packet, it's allowed.
1781 * If not, we complain, and throw the packet away.
1784 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1785 inet_ntop(packet->src_ipaddr.af,
1786 &packet->src_ipaddr.ipaddr,
1787 host_ipaddr, sizeof(host_ipaddr)));
1792 * If we're configured to look for a maximum number of
1793 * attributes, and we've seen more than that maximum,
1794 * then throw the packet away, as a possible DoS.
1796 if ((fr_max_attributes > 0) &&
1797 (num_attributes > fr_max_attributes)) {
1798 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1799 inet_ntop(packet->src_ipaddr.af,
1800 &packet->src_ipaddr.ipaddr,
1801 host_ipaddr, sizeof(host_ipaddr)),
1802 num_attributes, fr_max_attributes);
1807 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1809 * A packet with an EAP-Message attribute MUST also have
1810 * a Message-Authenticator attribute.
1812 * A Message-Authenticator all by itself is OK, though.
1814 * Similarly, Status-Server packets MUST contain
1815 * Message-Authenticator attributes.
1817 if (require_ma && ! seen_ma) {
1818 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1819 inet_ntop(packet->src_ipaddr.af,
1820 &packet->src_ipaddr.ipaddr,
1821 host_ipaddr, sizeof(host_ipaddr)));
1826 * Fill RADIUS header fields
1828 packet->code = hdr->code;
1829 packet->id = hdr->id;
1830 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1837 * Receive UDP client requests, and fill in
1838 * the basics of a RADIUS_PACKET structure.
1840 RADIUS_PACKET *rad_recv(int fd, int flags)
1843 RADIUS_PACKET *packet;
1846 * Allocate the new request data structure
1848 if ((packet = malloc(sizeof(*packet))) == NULL) {
1849 fr_strerror_printf("out of memory");
1852 memset(packet, 0, sizeof(*packet));
1855 sock_flags = MSG_PEEK;
1859 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1860 &packet->src_ipaddr, &packet->src_port,
1861 &packet->dst_ipaddr, &packet->dst_port);
1864 * Check for socket errors.
1866 if (packet->data_len < 0) {
1867 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1868 /* packet->data is NULL */
1874 * If the packet is too big, then rad_recvfrom did NOT
1875 * allocate memory. Instead, it just discarded the
1878 if (packet->data_len > MAX_PACKET_LEN) {
1879 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1880 /* packet->data is NULL */
1886 * Read no data. Continue.
1887 * This check is AFTER the MAX_PACKET_LEN check above, because
1888 * if the packet is larger than MAX_PACKET_LEN, we also have
1889 * packet->data == NULL
1891 if ((packet->data_len == 0) || !packet->data) {
1892 fr_strerror_printf("Empty packet: Socket is not ready.");
1898 * See if it's a well-formed RADIUS packet.
1900 if (!rad_packet_ok(packet, flags)) {
1906 * Remember which socket we read the packet from.
1908 packet->sockfd = fd;
1911 * FIXME: Do even more filtering by only permitting
1912 * certain IP's. The problem is that we don't know
1913 * how to do this properly for all possible clients...
1917 * Explicitely set the VP list to empty.
1921 if (fr_debug_flag) {
1922 char host_ipaddr[128];
1924 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1925 DEBUG("rad_recv: %s packet from host %s port %d",
1926 fr_packet_codes[packet->code],
1927 inet_ntop(packet->src_ipaddr.af,
1928 &packet->src_ipaddr.ipaddr,
1929 host_ipaddr, sizeof(host_ipaddr)),
1932 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1933 inet_ntop(packet->src_ipaddr.af,
1934 &packet->src_ipaddr.ipaddr,
1935 host_ipaddr, sizeof(host_ipaddr)),
1939 DEBUG(", id=%d, length=%d\n",
1940 packet->id, (int) packet->data_len);
1948 * Verify the signature of a packet.
1950 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1957 if (!packet || !packet->data) return -1;
1960 * Before we allocate memory for the attributes, do more
1963 ptr = packet->data + AUTH_HDR_LEN;
1964 length = packet->data_len - AUTH_HDR_LEN;
1965 while (length > 0) {
1966 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1967 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1972 default: /* don't do anything. */
1976 * Note that more than one Message-Authenticator
1977 * attribute is invalid.
1979 case PW_MESSAGE_AUTHENTICATOR:
1980 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1981 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1983 switch (packet->code) {
1987 case PW_ACCOUNTING_REQUEST:
1988 case PW_ACCOUNTING_RESPONSE:
1989 case PW_DISCONNECT_REQUEST:
1990 case PW_DISCONNECT_ACK:
1991 case PW_DISCONNECT_NAK:
1992 case PW_COA_REQUEST:
1995 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1998 case PW_AUTHENTICATION_ACK:
1999 case PW_AUTHENTICATION_REJECT:
2000 case PW_ACCESS_CHALLENGE:
2002 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2005 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2009 fr_hmac_md5(packet->data, packet->data_len,
2010 (const uint8_t *) secret, strlen(secret),
2012 if (digest_cmp(calc_auth_vector, msg_auth_vector,
2013 sizeof(calc_auth_vector)) != 0) {
2015 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2016 inet_ntop(packet->src_ipaddr.af,
2017 &packet->src_ipaddr.ipaddr,
2018 buffer, sizeof(buffer)));
2019 /* Silently drop packet, according to RFC 3579 */
2021 } /* else the message authenticator was good */
2024 * Reinitialize Authenticators.
2026 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2027 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2029 } /* switch over the attributes */
2033 } /* loop over the packet, sanity checking the attributes */
2036 * It looks like a RADIUS packet, but we can't validate
2039 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2041 fr_strerror_printf("Received Unknown packet code %d "
2042 "from client %s port %d: Cannot validate signature.",
2044 inet_ntop(packet->src_ipaddr.af,
2045 &packet->src_ipaddr.ipaddr,
2046 buffer, sizeof(buffer)),
2052 * Calculate and/or verify digest.
2054 switch(packet->code) {
2058 case PW_AUTHENTICATION_REQUEST:
2059 case PW_STATUS_SERVER:
2061 * The authentication vector is random
2062 * nonsense, invented by the client.
2066 case PW_COA_REQUEST:
2067 case PW_DISCONNECT_REQUEST:
2068 case PW_ACCOUNTING_REQUEST:
2069 if (calc_acctdigest(packet, secret) > 1) {
2070 fr_strerror_printf("Received %s packet "
2071 "from %s with invalid signature! (Shared secret is incorrect.)",
2072 fr_packet_codes[packet->code],
2073 inet_ntop(packet->src_ipaddr.af,
2074 &packet->src_ipaddr.ipaddr,
2075 buffer, sizeof(buffer)));
2080 /* Verify the reply digest */
2081 case PW_AUTHENTICATION_ACK:
2082 case PW_AUTHENTICATION_REJECT:
2083 case PW_ACCESS_CHALLENGE:
2084 case PW_ACCOUNTING_RESPONSE:
2085 case PW_DISCONNECT_ACK:
2086 case PW_DISCONNECT_NAK:
2089 rcode = calc_replydigest(packet, original, secret);
2091 fr_strerror_printf("Received %s packet "
2092 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2093 fr_packet_codes[packet->code],
2094 inet_ntop(packet->src_ipaddr.af,
2095 &packet->src_ipaddr.ipaddr,
2096 buffer, sizeof(buffer)),
2104 fr_strerror_printf("Received Unknown packet code %d "
2105 "from client %s port %d: Cannot validate signature",
2107 inet_ntop(packet->src_ipaddr.af,
2108 &packet->src_ipaddr.ipaddr,
2109 buffer, sizeof(buffer)),
2118 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2119 const RADIUS_PACKET *original,
2120 const char *secret, size_t length,
2121 const uint8_t *data, VALUE_PAIR *vp)
2126 * If length is greater than 253, something is SERIOUSLY
2129 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2131 vp->length = length;
2132 vp->operator = T_OP_EQ;
2138 if (vp->flags.has_tag) {
2139 if (TAG_VALID(data[0]) ||
2140 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2142 * Tunnel passwords REQUIRE a tag, even
2143 * if don't have a valid tag.
2145 vp->flags.tag = data[0];
2147 if ((vp->type == PW_TYPE_STRING) ||
2148 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2153 * Copy the data to be decrypted
2155 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2156 vp->length -= offset;
2159 * Decrypt the attribute.
2161 switch (vp->flags.encrypt) {
2165 case FLAG_ENCRYPT_USER_PASSWORD:
2167 rad_pwdecode((char *)vp->vp_strvalue,
2171 rad_pwdecode((char *)vp->vp_strvalue,
2175 if (vp->attribute == PW_USER_PASSWORD) {
2176 vp->length = strlen(vp->vp_strvalue);
2181 * Tunnel-Password's may go ONLY
2182 * in response packets.
2184 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2185 if (!original) goto raw;
2187 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2188 secret, original->vector) < 0) {
2194 * Ascend-Send-Secret
2195 * Ascend-Receive-Secret
2197 case FLAG_ENCRYPT_ASCEND_SECRET:
2201 uint8_t my_digest[AUTH_VECTOR_LEN];
2202 make_secret(my_digest,
2205 memcpy(vp->vp_strvalue, my_digest,
2207 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2208 vp->length = strlen(vp->vp_strvalue);
2214 } /* switch over encryption flags */
2218 case PW_TYPE_STRING:
2219 case PW_TYPE_OCTETS:
2220 case PW_TYPE_ABINARY:
2221 /* nothing more to do */
2225 if (vp->length != 1) goto raw;
2227 vp->vp_integer = vp->vp_octets[0];
2232 if (vp->length != 2) goto raw;
2234 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2237 case PW_TYPE_INTEGER:
2238 if (vp->length != 4) goto raw;
2240 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2241 vp->vp_integer = ntohl(vp->vp_integer);
2243 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2246 * Try to get named VALUEs
2250 dval = dict_valbyattr(vp->attribute, vp->vendor,
2253 strlcpy(vp->vp_strvalue,
2255 sizeof(vp->vp_strvalue));
2261 if (vp->length != 4) goto raw;
2263 memcpy(&vp->vp_date, vp->vp_octets, 4);
2264 vp->vp_date = ntohl(vp->vp_date);
2268 case PW_TYPE_IPADDR:
2269 if (vp->length != 4) goto raw;
2271 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2275 * IPv6 interface ID is 8 octets long.
2278 if (vp->length != 8) goto raw;
2279 /* vp->vp_ifid == vp->vp_octets */
2283 * IPv6 addresses are 16 octets long
2285 case PW_TYPE_IPV6ADDR:
2286 if (vp->length != 16) goto raw;
2287 /* vp->vp_ipv6addr == vp->vp_octets */
2291 * IPv6 prefixes are 2 to 18 octets long.
2293 * RFC 3162: The first octet is unused.
2294 * The second is the length of the prefix
2295 * the rest are the prefix data.
2297 * The prefix length can have value 0 to 128.
2299 case PW_TYPE_IPV6PREFIX:
2300 if (vp->length < 2 || vp->length > 18) goto raw;
2301 if (vp->vp_octets[1] > 128) goto raw;
2304 * FIXME: double-check that
2305 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2307 if (vp->length < 18) {
2308 memset(vp->vp_octets + vp->length, 0,
2313 case PW_TYPE_SIGNED:
2314 if (vp->length != 4) goto raw;
2317 * Overload vp_integer for ntohl, which takes
2318 * uint32_t, not int32_t
2320 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2321 vp->vp_integer = ntohl(vp->vp_integer);
2322 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2326 vp->length = length;
2327 vp->vp_tlv = malloc(length);
2330 fr_strerror_printf("No memory");
2333 memcpy(vp->vp_tlv, data, length);
2336 case PW_TYPE_COMBO_IP:
2337 if (vp->length == 4) {
2338 vp->type = PW_TYPE_IPADDR;
2339 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2342 } else if (vp->length == 16) {
2343 vp->type = PW_TYPE_IPV6ADDR;
2344 /* vp->vp_ipv6addr == vp->vp_octets */
2352 vp->type = PW_TYPE_OCTETS;
2353 vp->length = length;
2354 memcpy(vp->vp_octets, data, length);
2358 * Ensure there's no encryption or tag stuff,
2359 * we just pass the attribute as-is.
2361 memset(&vp->flags, 0, sizeof(vp->flags));
2367 static void rad_sortvp(VALUE_PAIR **head)
2370 VALUE_PAIR *vp, **tail;
2373 * Walk over the VP's, sorting them in order. Did I
2374 * mention that I hate WiMAX continuations?
2376 * And bubble sort! WTF is up with that?
2383 if (!vp->next) break;
2385 if (vp->attribute > vp->next->attribute) {
2387 vp->next = (*tail)->next;
2398 * Walk the packet, looking for continuations of this attribute.
2400 * This is (worst-case) O(N^2) in the number of RADIUS
2401 * attributes. That happens only when perverse clients create
2402 * continued attributes, AND separate the fragmented portions
2403 * with a lot of other attributes.
2405 * Sane clients should put the fragments next to each other, in
2406 * which case this is O(N), in the number of fragments.
2408 static uint8_t *rad_coalesce(unsigned int attribute, int vendor,
2409 size_t length, uint8_t *data,
2410 size_t packet_length, size_t *ptlv_length)
2414 size_t tlv_length = length;
2415 uint8_t *ptr, *tlv, *tlv_data;
2417 for (ptr = data + length;
2418 ptr != (data + packet_length);
2420 /* FIXME: Check that there are 6 bytes of data here... */
2421 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2422 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2423 (ptr[2] != 0) || (ptr[3] != 0) || /* our requirement */
2424 (ptr[4] != ((vendor >> 8) & 0xff)) ||
2425 (ptr[5] != (vendor & 0xff))) {
2429 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2430 lvalue = ntohl(lvalue);
2432 lvalue |= ptr[2 + 4]; /* add in VSA number */
2433 if (lvalue != attribute) continue;
2436 * If the vendor-length is too small, it's badly
2437 * formed, so we stop.
2439 if ((ptr[2 + 4 + 1]) < 3) break;
2441 tlv_length += ptr[2 + 4 + 1] - 3;
2442 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2445 tlv = tlv_data = malloc(tlv_length);
2446 if (!tlv_data) return NULL;
2448 memcpy(tlv, data, length);
2452 * Now we walk the list again, copying the data over to
2453 * our newly created memory.
2455 for (ptr = data + length;
2456 ptr != (data + packet_length);
2460 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2461 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2462 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2466 memcpy(&lvalue, ptr + 2, 4);
2467 lvalue = ntohl(lvalue);
2469 lvalue |= ptr[2 + 4];
2470 if (lvalue != attribute) continue;
2473 * If the vendor-length is too small, it's badly
2474 * formed, so we stop.
2476 if ((ptr[2 + 4 + 1]) < 3) break;
2478 this_length = ptr[2 + 4 + 1] - 3;
2479 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2482 ptr[2 + 4] = 0; /* What a hack! */
2483 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2486 *ptlv_length = tlv_length;
2491 * Walk over Evil WIMAX Hell, creating attributes.
2493 * Won't someone think of the children? What if they read this code?
2495 static VALUE_PAIR *recurse_evil(const RADIUS_PACKET *packet,
2496 const RADIUS_PACKET *original,
2498 int attribute, int vendor,
2499 uint8_t *ptr, size_t len)
2501 VALUE_PAIR *head = NULL;
2502 VALUE_PAIR **tail = &head;
2504 uint8_t *y; /* why do I need to do this? */
2507 * Sanity check the attribute.
2509 for (y = ptr; y < (ptr + len); y += y[1]) {
2510 if ((y[0] == 0) || ((y + 2) > (ptr + len)) ||
2511 (y[1] < 2) || ((y + y[1]) > (ptr + len))) {
2516 for (y = ptr; y < (ptr + len); y += y[1]) {
2517 vp = paircreate(attribute | (ptr[0] << 16), vendor,
2525 if (!data2vp(packet, original, secret,
2526 y[1] - 2, y + 2, vp)) {
2538 * Start at the *data* portion of a continued attribute. search
2539 * through the rest of the attributes to find a matching one, and
2540 * add it's contents to our contents.
2542 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2543 const RADIUS_PACKET *original,
2544 const char *secret, int attribute,
2546 int length, /* CANNOT be zero */
2547 uint8_t *data, size_t packet_length,
2548 int flag, DICT_ATTR *da)
2550 size_t tlv_length, left;
2553 VALUE_PAIR *vp, *head, **tail;
2557 * Ensure we have data that hasn't been split across
2558 * multiple attributes.
2561 tlv_data = rad_coalesce(attribute, vendor, length,
2562 data, packet_length, &tlv_length);
2563 if (!tlv_data) return NULL;
2566 tlv_length = length;
2570 * Non-TLV types cannot be continued across multiple
2571 * attributes. This is true even of keys that are
2572 * encrypted with the tunnel-password method. The spec
2573 * says that they can be continued... but also that the
2574 * keys are 160 bits, which means that they CANNOT be
2577 * Note that we don't check "flag" here. The calling
2580 if (!da || (da->type != PW_TYPE_TLV)) {
2582 if (tlv_data == data) { /* true if we had 'goto' */
2583 tlv_data = malloc(tlv_length);
2584 if (!tlv_data) return NULL;
2585 memcpy(tlv_data, data, tlv_length);
2588 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2589 if (!vp) return NULL;
2591 vp->type = PW_TYPE_TLV;
2592 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2593 vp->flags.has_tag = 0;
2594 vp->flags.is_tlv = 0;
2595 vp->vp_tlv = tlv_data;
2596 vp->length = tlv_length;
2598 } /* else it WAS a TLV, go decode the sub-tlv's */
2601 * Now (sigh) we walk over the TLV, seeing if it is
2605 for (ptr = tlv_data;
2606 ptr != (tlv_data + tlv_length);
2611 goto not_well_formed;
2618 * Now we walk over the TLV *again*, creating sub-tlv's.
2623 for (ptr = tlv_data;
2624 ptr != (tlv_data + tlv_length);
2627 tlv_da = dict_attrbyvalue(attribute | (ptr[0] << 8), vendor);
2628 if (tlv_da && (tlv_da->type == PW_TYPE_TLV)) {
2629 vp = recurse_evil(packet, original, secret,
2630 attribute | (ptr[0] << 8),
2631 vendor, ptr + 2, ptr[1] - 2);
2635 goto not_well_formed;
2638 vp = paircreate(attribute | (ptr[0] << 8), vendor,
2642 goto not_well_formed;
2645 if (!data2vp(packet, original, secret,
2646 ptr[1] - 2, ptr + 2, vp)) {
2648 goto not_well_formed;
2654 while (*tail) tail = &((*tail)->next);
2658 * TLV's MAY be continued, but sometimes they're not.
2660 if (tlv_data != data) free(tlv_data);
2662 if (head->next) rad_sortvp(&head);
2669 * Parse a RADIUS attribute into a data structure.
2671 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet,
2672 const RADIUS_PACKET *original,
2673 const char *secret, int attribute, int vendor,
2674 int length, const uint8_t *data)
2678 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2679 if (!vp) return NULL;
2681 return data2vp(packet, original, secret, length, data, vp);
2686 * Calculate/check digest, and decode radius attributes.
2688 * -1 on decoding error
2691 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2695 uint32_t vendorcode;
2698 uint8_t *ptr, *vsa_ptr;
2703 radius_packet_t *hdr;
2704 int vsa_tlen, vsa_llen, vsa_offset;
2705 DICT_VENDOR *dv = NULL;
2706 int num_attributes = 0;
2709 * Extract attribute-value pairs
2711 hdr = (radius_packet_t *)packet->data;
2713 packet_length = packet->data_len - AUTH_HDR_LEN;
2716 * There may be VP's already in the packet. Don't
2719 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2725 vsa_tlen = vsa_llen = 1;
2729 * We have to read at least two bytes.
2731 * rad_recv() above ensures that this is OK.
2733 while (packet_length > 0) {
2738 * Normal attribute, handle it like normal.
2740 if (vendorcode == 0) {
2742 * No room to read attr/length,
2743 * or bad attribute, or attribute is
2744 * too short, or attribute is too long,
2745 * stop processing the packet.
2747 if ((packet_length < 2) ||
2748 (ptr[0] == 0) || (ptr[1] < 2) ||
2749 (ptr[1] > packet_length)) break;
2757 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2760 * No vendor code, or ONLY vendor code.
2762 if (attrlen <= 4) goto create_pair;
2768 * Handle Vendor-Specific
2770 if (vendorlen == 0) {
2776 * attrlen was checked above.
2778 memcpy(&lvalue, ptr, 4);
2779 myvendor = ntohl(lvalue);
2782 * Zero isn't allowed.
2784 if (myvendor == 0) goto create_pair;
2787 * This is an implementation issue.
2788 * We currently pack vendor into the upper
2789 * 16 bits of a 32-bit attribute number,
2790 * so we can't handle vendor numbers larger
2793 if (myvendor > 65535) goto create_pair;
2795 vsa_tlen = vsa_llen = 1;
2797 dv = dict_vendorbyvalue(myvendor);
2799 vsa_tlen = dv->type;
2800 vsa_llen = dv->length;
2801 if (dv->flags) vsa_offset = 1;
2805 * Sweep through the list of VSA's,
2806 * seeing if they exactly fill the
2807 * outer Vendor-Specific attribute.
2809 * If not, create a raw Vendor-Specific.
2812 sublen = attrlen - 4;
2815 * See if we can parse it.
2821 * Not enough room for one more
2824 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2827 * Ensure that the attribute number
2836 myattr = (subptr[0] << 8) | subptr[1];
2840 if ((subptr[0] != 0) ||
2841 (subptr[1] != 0)) goto create_pair;
2843 myattr = (subptr[2] << 8) | subptr[3];
2847 * Our dictionary is broken.
2856 ptr += 4 + vsa_tlen;
2857 attrlen -= (4 + vsa_tlen);
2858 packet_length -= 4 + vsa_tlen;
2862 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2865 if (subptr[vsa_tlen] > sublen)
2870 * Reserved bits MUST be
2874 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2877 sublen -= subptr[vsa_tlen];
2878 subptr += subptr[vsa_tlen];
2882 if (subptr[vsa_tlen] != 0) goto create_pair;
2883 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2885 if (subptr[vsa_tlen + 1] > sublen)
2887 sublen -= subptr[vsa_tlen + 1];
2888 subptr += subptr[vsa_tlen + 1];
2892 * Our dictionaries are
2898 } while (sublen > 0);
2900 vendorcode = myvendor;
2901 vendorlen = attrlen - 4;
2908 * attrlen is the length of this attribute.
2909 * total_len is the length of the encompassing
2918 attribute = (ptr[0] << 8) | ptr[1];
2921 default: /* can't hit this. */
2929 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2933 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2936 default: /* can't hit this. */
2940 ptr += vsa_llen + vsa_offset;
2941 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2942 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2945 * Ignore VSAs that have no data.
2947 if (attrlen == 0) goto next;
2950 * WiMAX attributes of type 0 are ignored. They
2951 * are a secret flag to us that the attribute has
2952 * already been dealt with.
2954 if ((vendorcode == VENDORPEC_WIMAX) && (attribute == 0)) {
2961 da = dict_attrbyvalue(attribute, vendorcode);
2964 * If it's NOT continued, AND we know
2965 * about it, AND it's not a TLV, we can
2966 * create a normal pair.
2968 if (((vsa_ptr[2] & 0x80) == 0) &&
2969 da && (da->type != PW_TYPE_TLV)) goto create_pair;
2972 * Else it IS continued, or it's a TLV.
2973 * Go do a lot of work to find the stuff.
2975 pair = rad_continuation2vp(packet, original, secret,
2976 attribute, vendorcode,
2979 ((vsa_ptr[2] & 0x80) != 0),
2985 * Create the attribute, setting the default type
2986 * to 'octets'. If the type in the dictionary
2987 * is different, then the dictionary type will
2988 * over-ride this one.
2990 * If the attribute has no data, then discard it.
2992 * Unless it's CUI. Damn you, CUI!
2996 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2998 pair = rad_attr2vp(packet, original, secret,
2999 attribute, vendorcode, attrlen, ptr);
3001 pairfree(&packet->vps);
3002 fr_strerror_printf("out of memory");
3016 * VSA's may not have been counted properly in
3017 * rad_packet_ok() above, as it is hard to count
3018 * then without using the dictionary. We
3019 * therefore enforce the limits here, too.
3021 if ((fr_max_attributes > 0) &&
3022 (num_attributes > fr_max_attributes)) {
3023 char host_ipaddr[128];
3025 pairfree(&packet->vps);
3026 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3027 inet_ntop(packet->src_ipaddr.af,
3028 &packet->src_ipaddr.ipaddr,
3029 host_ipaddr, sizeof(host_ipaddr)),
3030 num_attributes, fr_max_attributes);
3035 if (vendorlen == 0) vendorcode = 0;
3037 packet_length -= attrlen;
3041 * Merge information from the outside world into our
3044 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3053 * We assume that the passwd buffer passed is big enough.
3054 * RFC2138 says the password is max 128 chars, so the size
3055 * of the passwd buffer must be at least 129 characters.
3056 * Preferably it's just MAX_STRING_LEN.
3058 * int *pwlen is updated to the new length of the encrypted
3059 * password - a multiple of 16 bytes.
3061 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3062 const uint8_t *vector)
3064 FR_MD5_CTX context, old;
3065 uint8_t digest[AUTH_VECTOR_LEN];
3066 int i, n, secretlen;
3070 * RFC maximum is 128 bytes.
3072 * If length is zero, pad it out with zeros.
3074 * If the length isn't aligned to 16 bytes,
3075 * zero out the extra data.
3079 if (len > 128) len = 128;
3082 memset(passwd, 0, AUTH_PASS_LEN);
3083 len = AUTH_PASS_LEN;
3084 } else if ((len % AUTH_PASS_LEN) != 0) {
3085 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3086 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3091 * Use the secret to setup the decryption digest
3093 secretlen = strlen(secret);
3095 fr_MD5Init(&context);
3096 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3097 old = context; /* save intermediate work */
3100 * Encrypt it in place. Don't bother checking
3101 * len, as we've ensured above that it's OK.
3103 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3105 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3106 fr_MD5Final(digest, &context);
3109 fr_MD5Update(&context,
3110 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3112 fr_MD5Final(digest, &context);
3115 for (i = 0; i < AUTH_PASS_LEN; i++) {
3116 passwd[i + n] ^= digest[i];
3126 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3127 const uint8_t *vector)
3129 FR_MD5_CTX context, old;
3130 uint8_t digest[AUTH_VECTOR_LEN];
3132 size_t n, secretlen;
3135 * The RFC's say that the maximum is 128.
3136 * The buffer we're putting it into above is 254, so
3137 * we don't need to do any length checking.
3139 if (pwlen > 128) pwlen = 128;
3144 if (pwlen == 0) goto done;
3147 * Use the secret to setup the decryption digest
3149 secretlen = strlen(secret);
3151 fr_MD5Init(&context);
3152 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3153 old = context; /* save intermediate work */
3156 * The inverse of the code above.
3158 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3160 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3161 fr_MD5Final(digest, &context);
3164 if (pwlen > AUTH_PASS_LEN) {
3165 fr_MD5Update(&context, (uint8_t *) passwd,
3169 fr_MD5Final(digest, &context);
3172 if (pwlen > (n + AUTH_PASS_LEN)) {
3173 fr_MD5Update(&context, (uint8_t *) passwd + n,
3178 for (i = 0; i < AUTH_PASS_LEN; i++) {
3179 passwd[i + n] ^= digest[i];
3184 passwd[pwlen] = '\0';
3185 return strlen(passwd);
3190 * Encode Tunnel-Password attributes when sending them out on the wire.
3192 * int *pwlen is updated to the new length of the encrypted
3193 * password - a multiple of 16 bytes.
3195 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3198 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3199 const uint8_t *vector)
3201 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3202 unsigned char digest[AUTH_VECTOR_LEN];
3204 int i, n, secretlen;
3209 if (len > 127) len = 127;
3212 * Shift the password 3 positions right to place a salt and original
3213 * length, tag will be added automatically on packet send
3215 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3219 * save original password length as first password character;
3226 * Generate salt. The RFC's say:
3228 * The high bit of salt[0] must be set, each salt in a
3229 * packet should be unique, and they should be random
3231 * So, we set the high bit, add in a counter, and then
3232 * add in some CSPRNG data. should be OK..
3234 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3235 (fr_rand() & 0x07));
3236 salt[1] = fr_rand();
3239 * Padd password to multiple of AUTH_PASS_LEN bytes.
3241 n = len % AUTH_PASS_LEN;
3243 n = AUTH_PASS_LEN - n;
3244 for (; n > 0; n--, len++)
3247 /* set new password length */
3251 * Use the secret to setup the decryption digest
3253 secretlen = strlen(secret);
3254 memcpy(buffer, secret, secretlen);
3256 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3258 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3259 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3260 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3262 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3263 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3266 for (i = 0; i < AUTH_PASS_LEN; i++) {
3267 passwd[i + n2] ^= digest[i];
3275 * Decode Tunnel-Password encrypted attributes.
3277 * Defined in RFC-2868, this uses a two char SALT along with the
3278 * initial intermediate value, to differentiate it from the
3281 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3282 const uint8_t *vector)
3284 FR_MD5_CTX context, old;
3285 uint8_t digest[AUTH_VECTOR_LEN];
3287 unsigned i, n, len, reallen;
3292 * We need at least a salt.
3295 fr_strerror_printf("tunnel password is too short");
3300 * There's a salt, but no password. Or, there's a salt
3301 * and a 'data_len' octet. It's wrong, but at least we
3302 * can figure out what it means: the password is empty.
3304 * Note that this means we ignore the 'data_len' field,
3305 * if the attribute length tells us that there's no
3306 * more data. So the 'data_len' field may be wrong,
3315 len -= 2; /* discount the salt */
3318 * Use the secret to setup the decryption digest
3320 secretlen = strlen(secret);
3322 fr_MD5Init(&context);
3323 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3324 old = context; /* save intermediate work */
3327 * Set up the initial key:
3329 * b(1) = MD5(secret + vector + salt)
3331 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3332 fr_MD5Update(&context, passwd, 2);
3335 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3339 fr_MD5Final(digest, &context);
3344 * A quick check: decrypt the first octet
3345 * of the password, which is the
3346 * 'data_len' field. Ensure it's sane.
3348 reallen = passwd[2] ^ digest[0];
3349 if (reallen >= len) {
3350 fr_strerror_printf("tunnel password is too long for the attribute");
3354 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3358 fr_MD5Final(digest, &context);
3361 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3364 for (i = base; i < AUTH_PASS_LEN; i++) {
3365 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3370 * See make_tunnel_password, above.
3372 if (reallen > 239) reallen = 239;
3375 passwd[reallen] = 0;
3381 * Encode a CHAP password
3383 * FIXME: might not work with Ascend because
3384 * we use vp->length, and Ascend gear likes
3385 * to send an extra '\0' in the string!
3387 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3388 VALUE_PAIR *password)
3392 uint8_t string[MAX_STRING_LEN * 2 + 1];
3393 VALUE_PAIR *challenge;
3396 * Sanity check the input parameters
3398 if ((packet == NULL) || (password == NULL)) {
3403 * Note that the password VP can be EITHER
3404 * a User-Password attribute (from a check-item list),
3405 * or a CHAP-Password attribute (the client asking
3406 * the library to encode it).
3414 memcpy(ptr, password->vp_strvalue, password->length);
3415 ptr += password->length;
3416 i += password->length;
3419 * Use Chap-Challenge pair if present,
3420 * Request-Authenticator otherwise.
3422 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
3424 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3425 i += challenge->length;
3427 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3428 i += AUTH_VECTOR_LEN;
3432 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3439 * Seed the random number generator.
3441 * May be called any number of times.
3443 void fr_rand_seed(const void *data, size_t size)
3448 * Ensure that the pool is initialized.
3450 if (!fr_rand_initialized) {
3453 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3455 fd = open("/dev/urandom", O_RDONLY);
3461 while (total < sizeof(fr_rand_pool.randrsl)) {
3462 this = read(fd, fr_rand_pool.randrsl,
3463 sizeof(fr_rand_pool.randrsl) - total);
3464 if ((this < 0) && (errno != EINTR)) break;
3465 if (this > 0) total += this;
3469 fr_rand_pool.randrsl[0] = fd;
3470 fr_rand_pool.randrsl[1] = time(NULL);
3471 fr_rand_pool.randrsl[2] = errno;
3474 fr_randinit(&fr_rand_pool, 1);
3475 fr_rand_pool.randcnt = 0;
3476 fr_rand_initialized = 1;
3482 * Hash the user data
3485 if (!hash) hash = fr_rand();
3486 hash = fr_hash_update(data, size, hash);
3488 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3493 * Return a 32-bit random number.
3495 uint32_t fr_rand(void)
3500 * Ensure that the pool is initialized.
3502 if (!fr_rand_initialized) {
3503 fr_rand_seed(NULL, 0);
3506 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3507 if (fr_rand_pool.randcnt >= 256) {
3508 fr_rand_pool.randcnt = 0;
3509 fr_isaac(&fr_rand_pool);
3517 * Allocate a new RADIUS_PACKET
3519 RADIUS_PACKET *rad_alloc(int newvector)
3523 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3524 fr_strerror_printf("out of memory");
3527 memset(rp, 0, sizeof(*rp));
3533 uint32_t hash, base;
3536 * Don't expose the actual contents of the random
3540 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3541 hash = fr_rand() ^ base;
3542 memcpy(rp->vector + i, &hash, sizeof(hash));
3545 fr_rand(); /* stir the pool again */
3550 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3552 RADIUS_PACKET *reply;
3554 if (!packet) return NULL;
3556 reply = rad_alloc(0);
3557 if (!reply) return NULL;
3560 * Initialize the fields from the request.
3562 reply->sockfd = packet->sockfd;
3563 reply->dst_ipaddr = packet->src_ipaddr;
3564 reply->src_ipaddr = packet->dst_ipaddr;
3565 reply->dst_port = packet->src_port;
3566 reply->src_port = packet->dst_port;
3567 reply->id = packet->id;
3568 reply->code = 0; /* UNKNOWN code */
3569 memcpy(reply->vector, packet->vector,
3570 sizeof(reply->vector));
3573 reply->data_len = 0;
3580 * Free a RADIUS_PACKET
3582 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3584 RADIUS_PACKET *radius_packet;
3586 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3587 radius_packet = *radius_packet_ptr;
3589 free(radius_packet->data);
3591 pairfree(&radius_packet->vps);
3593 free(radius_packet);
3595 *radius_packet_ptr = NULL;