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;
70 static uint8_t nullvector[AUTH_VECTOR_LEN] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* for CoA decode */
72 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
78 "Accounting-Response",
94 "Resource-Free-Request",
95 "Resource-Free-Response",
96 "Resource-Query-Request",
97 "Resource-Query-Response",
98 "Alternate-Resource-Reclaim-Request",
100 "NAS-Reboot-Response",
113 "Disconnect-Request",
123 "IP-Address-Allocate",
128 void fr_printf_log(const char *fmt, ...)
133 if ((fr_debug_flag == 0) || !fr_log_fp) {
138 vfprintf(fr_log_fp, fmt, ap);
144 void rad_print_hex(RADIUS_PACKET *packet)
148 if (!packet->data) return;
150 printf(" Code:\t\t%u\n", packet->data[0]);
151 printf(" Id:\t\t%u\n", packet->data[1]);
152 printf(" Length:\t%u\n", ((packet->data[2] << 8) |
154 printf(" Vector:\t");
155 for (i = 4; i < 20; i++) {
156 printf("%02x", packet->data[i]);
160 if (packet->data_len > 20) {
165 total = packet->data_len - 20;
166 ptr = packet->data + 20;
172 if (total < 2) { /* too short */
173 printf("%02x\n", *ptr);
177 if (ptr[1] > total) { /* too long */
178 for (i = 0; i < total; i++) {
179 printf("%02x ", ptr[i]);
184 printf("%02x %02x ", ptr[0], ptr[1]);
185 attrlen = ptr[1] - 2;
189 for (i = 0; i < attrlen; i++) {
190 if ((i > 0) && ((i & 0x0f) == 0x00))
192 printf("%02x ", ptr[i]);
193 if ((i & 0x0f) == 0x0f) printf("\n");
196 if ((attrlen & 0x0f) != 0x00) printf("\n");
207 * Wrapper for sendto which handles sendfromto, IPv6, and all
208 * possible combinations.
210 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
211 fr_ipaddr_t *src_ipaddr, int src_port,
212 fr_ipaddr_t *dst_ipaddr, int dst_port)
215 struct sockaddr_storage dst;
216 socklen_t sizeof_dst;
218 #ifdef WITH_UDPFROMTO
219 struct sockaddr_storage src;
220 socklen_t sizeof_src;
222 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
224 src_port = src_port; /* -Wunused */
227 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
231 #ifdef WITH_UDPFROMTO
233 * And if they don't specify a source IP address, don't
236 if (((dst_ipaddr->af == AF_INET) || (dst_ipaddr->af == AF_INET6)) &&
237 (src_ipaddr->af != AF_UNSPEC) &&
238 !fr_inaddr_any(src_ipaddr)) {
239 rcode = sendfromto(sockfd, data, data_len, flags,
240 (struct sockaddr *)&src, sizeof_src,
241 (struct sockaddr *)&dst, sizeof_dst);
245 src_ipaddr = src_ipaddr; /* -Wunused */
249 * No udpfromto, fail gracefully.
251 rcode = sendto(sockfd, data, data_len, flags,
252 (struct sockaddr *) &dst, sizeof_dst);
253 #ifdef WITH_UDPFROMTO
257 DEBUG("rad_send() failed: %s\n", strerror(errno));
264 void rad_recv_discard(int sockfd)
267 struct sockaddr_storage src;
268 socklen_t sizeof_src = sizeof(src);
270 recvfrom(sockfd, header, sizeof(header), 0,
271 (struct sockaddr *)&src, &sizeof_src);
275 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
278 ssize_t data_len, packet_len;
280 struct sockaddr_storage src;
281 socklen_t sizeof_src = sizeof(src);
283 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
284 (struct sockaddr *)&src, &sizeof_src);
286 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
291 * Too little data is available, discard the packet.
294 recvfrom(sockfd, header, sizeof(header), 0,
295 (struct sockaddr *)&src, &sizeof_src);
298 } else { /* we got 4 bytes of data. */
300 * See how long the packet says it is.
302 packet_len = (header[2] * 256) + header[3];
305 * The length in the packet says it's less than
306 * a RADIUS header length: discard it.
308 if (packet_len < AUTH_HDR_LEN) {
309 recvfrom(sockfd, header, sizeof(header), 0,
310 (struct sockaddr *)&src, &sizeof_src);
314 * Enforce RFC requirements, for sanity.
315 * Anything after 4k will be discarded.
317 } else if (packet_len > MAX_PACKET_LEN) {
318 recvfrom(sockfd, header, sizeof(header), 0,
319 (struct sockaddr *)&src, &sizeof_src);
325 * Convert AF. If unknown, discard packet.
327 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
328 recvfrom(sockfd, header, sizeof(header), 0,
329 (struct sockaddr *)&src, &sizeof_src);
336 * The packet says it's this long, but the actual UDP
337 * size could still be smaller.
344 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
345 * possible combinations.
347 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
348 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
349 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
351 struct sockaddr_storage src;
352 struct sockaddr_storage dst;
353 socklen_t sizeof_src = sizeof(src);
354 socklen_t sizeof_dst = sizeof(dst);
361 memset(&src, 0, sizeof_src);
362 memset(&dst, 0, sizeof_dst);
365 * Get address family, etc. first, so we know if we
366 * need to do udpfromto.
368 * FIXME: udpfromto also does this, but it's not
369 * a critical problem.
371 if (getsockname(sockfd, (struct sockaddr *)&dst,
372 &sizeof_dst) < 0) return -1;
375 * Read the length of the packet, from the packet.
376 * This lets us allocate the buffer to use for
377 * reading the rest of the packet.
379 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
380 (struct sockaddr *)&src, &sizeof_src);
382 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
387 * Too little data is available, discard the packet.
390 recvfrom(sockfd, header, sizeof(header), flags,
391 (struct sockaddr *)&src, &sizeof_src);
394 } else { /* we got 4 bytes of data. */
396 * See how long the packet says it is.
398 len = (header[2] * 256) + header[3];
401 * The length in the packet says it's less than
402 * a RADIUS header length: discard it.
404 if (len < AUTH_HDR_LEN) {
405 recvfrom(sockfd, header, sizeof(header), flags,
406 (struct sockaddr *)&src, &sizeof_src);
410 * Enforce RFC requirements, for sanity.
411 * Anything after 4k will be discarded.
413 } else if (len > MAX_PACKET_LEN) {
414 recvfrom(sockfd, header, sizeof(header), flags,
415 (struct sockaddr *)&src, &sizeof_src);
424 * Receive the packet. The OS will discard any data in the
425 * packet after "len" bytes.
427 #ifdef WITH_UDPFROMTO
428 if ((dst.ss_family == AF_INET) || (dst.ss_family == AF_INET6)) {
429 data_len = recvfromto(sockfd, buf, len, flags,
430 (struct sockaddr *)&src, &sizeof_src,
431 (struct sockaddr *)&dst, &sizeof_dst);
435 * No udpfromto, fail gracefully.
437 data_len = recvfrom(sockfd, buf, len, flags,
438 (struct sockaddr *)&src, &sizeof_src);
444 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
446 return -1; /* Unknown address family, Die Die Die! */
450 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
454 * Different address families should never happen.
456 if (src.ss_family != dst.ss_family) {
462 * Tell the caller about the data
470 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
471 /*************************************************************************
473 * Function: make_secret
475 * Purpose: Build an encrypted secret value to return in a reply
476 * packet. The secret is hidden by xoring with a MD5 digest
477 * created from the shared secret and the authentication
478 * vector. We put them into MD5 in the reverse order from
479 * that used when encrypting passwords to RADIUS.
481 *************************************************************************/
482 static void make_secret(uint8_t *digest, const uint8_t *vector,
483 const char *secret, const uint8_t *value)
488 fr_MD5Init(&context);
489 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
490 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
491 fr_MD5Final(digest, &context);
493 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
494 digest[i] ^= value[i];
498 #define MAX_PASS_LEN (128)
499 static void make_passwd(uint8_t *output, size_t *outlen,
500 const uint8_t *input, size_t inlen,
501 const char *secret, const uint8_t *vector)
503 FR_MD5_CTX context, old;
504 uint8_t digest[AUTH_VECTOR_LEN];
505 uint8_t passwd[MAX_PASS_LEN];
510 * If the length is zero, round it up.
514 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
516 memcpy(passwd, input, len);
517 if (len < sizeof(passwd)) memset(passwd + len, 0, sizeof(passwd) - len);
523 else if ((len & 0x0f) != 0) {
529 fr_MD5Init(&context);
530 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
536 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
538 for (n = 0; n < len; n += AUTH_PASS_LEN) {
541 fr_MD5Update(&context,
542 passwd + n - AUTH_PASS_LEN,
546 fr_MD5Final(digest, &context);
547 for (i = 0; i < AUTH_PASS_LEN; i++) {
548 passwd[i + n] ^= digest[i];
552 memcpy(output, passwd, len);
555 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
556 const uint8_t *input, size_t inlen, size_t room,
557 const char *secret, const uint8_t *vector)
559 FR_MD5_CTX context, old;
560 uint8_t digest[AUTH_VECTOR_LEN];
562 size_t encrypted_len;
565 * The password gets encoded with a 1-byte "length"
566 * field. Ensure that it doesn't overflow.
568 if (room > 253) room = 253;
571 * Limit the maximum size of the input password. 2 bytes
572 * are taken up by the salt, and one by the encoded
573 * "length" field. Note that if we have a tag, the
574 * "room" will be 252 octets, not 253 octets.
576 if (inlen > (room - 3)) inlen = room - 3;
579 * Length of the encrypted data is the clear-text
580 * password length plus one byte which encodes the length
581 * of the password. We round up to the nearest encoding
582 * block. Note that this can result in the encoding
583 * length being more than 253 octets.
585 encrypted_len = inlen + 1;
586 if ((encrypted_len & 0x0f) != 0) {
587 encrypted_len += 0x0f;
588 encrypted_len &= ~0x0f;
592 * We need 2 octets for the salt, followed by the actual
595 if (encrypted_len > (room - 2)) encrypted_len = room - 2;
597 *outlen = encrypted_len + 2; /* account for the salt */
600 * Copy the password over, and zero-fill the remainder.
602 memcpy(output + 3, input, inlen);
603 memset(output + 3 + inlen, 0, *outlen - 3 - inlen);
606 * Generate salt. The RFCs say:
608 * The high bit of salt[0] must be set, each salt in a
609 * packet should be unique, and they should be random
611 * So, we set the high bit, add in a counter, and then
612 * add in some CSPRNG data. should be OK..
614 output[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
616 output[1] = fr_rand();
617 output[2] = inlen; /* length of the password string */
619 fr_MD5Init(&context);
620 fr_MD5Update(&context, (uint8_t const *) secret, strlen(secret));
623 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
624 fr_MD5Update(&context, &output[0], 2);
626 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
631 fr_MD5Update(&context,
632 output + 2 + n - AUTH_PASS_LEN,
636 fr_MD5Final(digest, &context);
638 if ((2 + n + AUTH_PASS_LEN) < room) {
639 block_len = AUTH_PASS_LEN;
641 block_len = room - 2 - n;
644 for (i = 0; i < block_len; i++) {
645 output[i + 2 + n] ^= digest[i];
651 * Returns the end of the data.
653 static uint8_t *vp2data(const RADIUS_PACKET *packet,
654 const RADIUS_PACKET *original,
655 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
664 * Set up the default sources for the data.
666 data = vp->vp_octets;
673 case PW_TYPE_IPV6ADDR:
674 case PW_TYPE_IPV6PREFIX:
675 case PW_TYPE_ABINARY:
676 /* nothing more to do */
680 len = 1; /* just in case */
681 array[0] = vp->vp_integer & 0xff;
686 len = 2; /* just in case */
687 array[0] = (vp->vp_integer >> 8) & 0xff;
688 array[1] = vp->vp_integer & 0xff;
692 case PW_TYPE_INTEGER:
693 len = 4; /* just in case */
694 lvalue = htonl(vp->vp_integer);
695 memcpy(array, &lvalue, sizeof(lvalue));
700 data = (const uint8_t *) &vp->vp_ipaddr;
701 len = 4; /* just in case */
705 * There are no tagged date attributes.
708 lvalue = htonl(vp->vp_date);
709 data = (const uint8_t *) &lvalue;
710 len = 4; /* just in case */
717 len = 4; /* just in case */
718 slvalue = htonl(vp->vp_signed);
719 memcpy(array, &slvalue, sizeof(slvalue));
726 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
731 default: /* unknown type: ignore it */
732 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
737 * Bound the data to the calling size
739 if (len > room) len = room;
742 * Encrypt the various password styles
744 * Attributes with encrypted values MUST be less than
747 if (packet) switch (vp->flags.encrypt) {
748 case FLAG_ENCRYPT_USER_PASSWORD:
749 make_passwd(ptr, &len, data, len,
750 secret, packet->vector);
753 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
755 * Check if there's enough room. If there isn't,
756 * we discard the attribute.
758 * This is ONLY a problem if we have multiple VSA's
759 * in one Vendor-Specific, though.
761 if (room < 18) return ptr;
763 switch (packet->code) {
764 case PW_AUTHENTICATION_ACK:
765 case PW_AUTHENTICATION_REJECT:
766 case PW_ACCESS_CHALLENGE:
769 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
772 make_tunnel_passwd(ptr, &len, data, len, room,
773 secret, original->vector);
775 case PW_ACCOUNTING_REQUEST:
776 case PW_DISCONNECT_REQUEST:
778 make_tunnel_passwd(ptr, &len, data, len, room,
779 secret, packet->vector);
785 * The code above ensures that this attribute
788 case FLAG_ENCRYPT_ASCEND_SECRET:
790 if (data == array) return NULL;
792 if (len != AUTH_VECTOR_LEN) return NULL;
793 make_secret(ptr, packet->vector, secret, data);
794 len = AUTH_VECTOR_LEN;
800 * Just copy the data over
802 memcpy(ptr, data, len);
805 } else { /* no packet */
806 memcpy(ptr, data, len);
813 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
817 unsigned int attribute;
819 VALUE_PAIR *vp, *tlv;
821 attribute = vps->attribute & 0xffff00ff;
822 maxattr = vps->attribute & 0x0ff;
824 tlv = paircreate(attribute, PW_TYPE_TLV);
825 if (!tlv) return NULL;
828 for (vp = vps; vp != NULL; vp = vp->next) {
830 * Group the attributes ONLY until we see a
833 if (!vp->flags.is_tlv ||
835 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
836 ((vp->attribute & 0xffff00ff) != attribute) ||
837 ((vp->attribute & 0x0000ff00) < maxattr)) {
841 maxattr = vp->attribute & 0xff00;
842 tlv->length += vp->length + 2;
850 tlv->vp_tlv = malloc(tlv->length);
857 maxattr = vps->attribute & 0x0ff;
858 for (vp = vps; vp != NULL; vp = vp->next) {
859 if (!vp->flags.is_tlv ||
861 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
862 ((vp->attribute & 0xffff00ff) != attribute) ||
863 ((vp->attribute & 0x0000ff00) < maxattr)) {
867 maxattr = vp->attribute & 0xff00;
868 end = vp2data(NULL, NULL, NULL, vp, ptr + 2,
869 tlv->vp_tlv + tlv->length - ptr);
871 vp->length = ptr - vp->vp_tlv;
872 return tlv; /* should be a more serious error... */
875 length = (end - ptr);
882 * Pack the attribute.
884 ptr[0] = (vp->attribute & 0xff00) >> 8;
888 vp->flags.encoded = 1;
895 * Pack data without any encryption.
896 * start == start of RADIUS attribute
897 * ptr == continuation byte (i.e. one after length)
899 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
903 size_t hsize = (ptr - start);
904 uint8_t *this = start;
909 * If it's too long and marked as encrypted, ignore it.
911 if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
915 memcpy(header, start, hsize);
926 data = vp->vp_octets;
937 memcpy(this, header, hsize);
944 if (left > (254 - hsize)) {
952 memcpy(ptr, data, piece);
953 this[1] = hsize + piece + 1;
958 this[hsize - 1] = hsize - 6 + 1 + piece;
965 return (ptr - start);
970 * Parse a data structure into a RADIUS attribute.
972 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
973 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
976 int len, total_length;
978 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
984 length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
987 * For interoperability, always put vendor attributes
988 * into their own VSA.
990 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
991 *(ptr++) = vp->attribute & 0xFF;
1000 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
1003 * This must be an RFC-format attribute. If it
1004 * wasn't, then the "decode" function would have
1005 * made a Vendor-Specific attribute (i.e. type
1006 * 26), and we would have "vendorcode == 0" here.
1009 vsa_tlen = dv->type;
1010 vsa_llen = dv->length;
1011 if (dv->flags) vsa_offset = 1;
1015 * Build a VSA header.
1017 *ptr++ = PW_VENDOR_SPECIFIC;
1018 vsa_length_ptr = ptr;
1020 lvalue = htonl(vendorcode);
1021 memcpy(ptr, &lvalue, 4);
1027 ptr[0] = (vp->attribute & 0xFF);
1031 ptr[0] = ((vp->attribute >> 8) & 0xFF);
1032 ptr[1] = (vp->attribute & 0xFF);
1038 ptr[2] = ((vp->attribute >> 8) & 0xFF);
1039 ptr[3] = (vp->attribute & 0xFF);
1043 return 0; /* silently discard it */
1049 length_ptr = vsa_length_ptr;
1050 vsa_length_ptr = NULL;
1059 length_ptr = ptr + 1;
1063 return 0; /* silently discard it */
1068 * Allow for some continuation.
1072 * Allow TLV's to be encoded, if someone
1073 * manages to somehow encode the sub-tlv's.
1075 * FIXME: Keep track of room in the packet!
1077 if (vp->length > (((size_t) 254) - (ptr - start))) {
1078 return rad_vp2continuation(vp, start, ptr);
1085 * sub-TLV's can only be in one format.
1087 if (vp->flags.is_tlv) {
1088 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1089 tlv_length_ptr = ptr;
1095 total_length += vsa_tlen + vsa_llen + vsa_offset;
1096 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1097 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1101 * Insert tags for string attributes. They go BEFORE
1104 if (vp->flags.has_tag && (vp->type == PW_TYPE_STRING) &&
1105 (TAG_VALID(vp->flags.tag) ||
1106 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
1107 ptr[0] = vp->flags.tag;
1108 end = vp2data(packet, original, secret, vp, ptr + 1,
1111 end = vp2data(packet, original, secret, vp, ptr,
1114 if (!end) return -1;
1117 * Insert tags for integer attributes. They go at the START
1118 * of the integer, and over-write the first byte.
1120 if (vp->flags.has_tag && (vp->type == PW_TYPE_INTEGER)) {
1121 ptr[0] = vp->flags.tag;
1125 * RFC 2865 section 5 says that zero-length attributes
1128 * ... and the WiMAX forum ignores this... because of
1129 * one vendor. Don't they have anything better to do
1133 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1138 * Update the various lengths.
1141 if (vsa_length_ptr) *vsa_length_ptr += len;
1142 if (tlv_length_ptr) *tlv_length_ptr += len;
1143 total_length += len;
1145 return total_length; /* of attribute */
1152 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1155 radius_packet_t *hdr;
1157 uint16_t total_length;
1161 char ip_buffer[128];
1164 * For simplicity in the following logic, we allow
1165 * the attributes to "overflow" the 4k maximum
1166 * RADIUS packet size, by one attribute.
1168 * It's uint32_t, for alignment purposes.
1170 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
1172 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1173 what = fr_packet_codes[packet->code];
1178 DEBUG("Sending %s of id %d to %s port %d\n",
1180 inet_ntop(packet->dst_ipaddr.af,
1181 &packet->dst_ipaddr.ipaddr,
1182 ip_buffer, sizeof(ip_buffer)),
1186 * Double-check some things based on packet code.
1188 switch (packet->code) {
1189 case PW_AUTHENTICATION_ACK:
1190 case PW_AUTHENTICATION_REJECT:
1191 case PW_ACCESS_CHALLENGE:
1193 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1199 * These packet vectors start off as all zero.
1201 case PW_ACCOUNTING_REQUEST:
1202 case PW_DISCONNECT_REQUEST:
1203 case PW_COA_REQUEST:
1204 memset(packet->vector, 0, sizeof(packet->vector));
1212 * Use memory on the stack, until we know how
1213 * large the packet will be.
1215 hdr = (radius_packet_t *) data;
1218 * Build standard header
1220 hdr->code = packet->code;
1221 hdr->id = packet->id;
1223 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1225 total_length = AUTH_HDR_LEN;
1228 * Load up the configuration values for the user
1234 * FIXME: Loop twice over the reply list. The first time,
1235 * calculate the total length of data. The second time,
1236 * allocate the memory, and fill in the VP's.
1238 * Hmm... this may be slower than just doing a small
1243 * Loop over the reply attributes for the packet.
1245 for (reply = packet->vps; reply; reply = reply->next) {
1247 * Ignore non-wire attributes
1249 if ((VENDOR(reply->attribute) == 0) &&
1250 ((reply->attribute & 0xFFFF) > 0xff)) {
1253 * Permit the admin to send BADLY formatted
1254 * attributes with a debug build.
1256 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1257 memcpy(ptr, reply->vp_octets, reply->length);
1258 len = reply->length;
1266 * Set the Message-Authenticator to the correct
1267 * length and initial value.
1269 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1270 reply->length = AUTH_VECTOR_LEN;
1271 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1274 * Cache the offset to the
1275 * Message-Authenticator
1277 packet->offset = total_length;
1281 * Print out ONLY the attributes which
1282 * we're sending over the wire, and print
1283 * them out BEFORE they're encrypted.
1288 * Print them in order, even if they were encoded
1292 if (reply->flags.encoded) goto next;
1294 if (reply->flags.is_tlv) {
1295 VALUE_PAIR *tlv = rad_vp2tlv(reply);
1297 tlv->next = reply->next;
1302 * The encoded flag MUST be set in reply!
1304 reply = reply->next;
1307 len = rad_vp2attr(packet, original, secret, reply, ptr);
1309 if (len < 0) return -1;
1312 * Check that the packet is no more than 4k in
1313 * size, AFTER writing the attribute past the 4k
1314 * boundary, but BEFORE deciding to increase the
1315 * size of the packet. Note that the 'data'
1316 * buffer, above, is one attribute longer than
1317 * necessary, in order to permit this overflow.
1319 if ((total_length + len) > MAX_PACKET_LEN) {
1320 DEBUG("WARNING: Attributes are too long for packet. Discarding data past %d bytes", total_length);
1326 total_length += len;
1327 } /* done looping over all attributes */
1330 * Fill in the rest of the fields, and copy the data over
1331 * from the local stack to the newly allocated memory.
1333 * Yes, all this 'memcpy' is slow, but it means
1334 * that we only allocate the minimum amount of
1335 * memory for a request.
1337 packet->data_len = total_length;
1338 packet->data = (uint8_t *) malloc(packet->data_len);
1339 if (!packet->data) {
1340 fr_strerror_printf("Out of memory");
1344 memcpy(packet->data, hdr, packet->data_len);
1345 hdr = (radius_packet_t *) packet->data;
1347 total_length = htons(total_length);
1348 memcpy(hdr->length, &total_length, sizeof(total_length));
1355 * Sign a previously encoded packet.
1357 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1360 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1363 * It wasn't assigned an Id, this is bad!
1365 if (packet->id < 0) {
1366 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1370 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1371 (packet->offset < 0)) {
1372 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1377 * If there's a Message-Authenticator, update it
1378 * now, BEFORE updating the authentication vector.
1380 if (packet->offset > 0) {
1381 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1383 switch (packet->code) {
1384 case PW_ACCOUNTING_RESPONSE:
1385 if (original && original->code == PW_STATUS_SERVER) {
1389 case PW_ACCOUNTING_REQUEST:
1390 case PW_DISCONNECT_REQUEST:
1391 case PW_DISCONNECT_ACK:
1392 case PW_DISCONNECT_NAK:
1393 case PW_COA_REQUEST:
1396 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1400 case PW_AUTHENTICATION_ACK:
1401 case PW_AUTHENTICATION_REJECT:
1402 case PW_ACCESS_CHALLENGE:
1404 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1407 memcpy(hdr->vector, original->vector,
1411 default: /* others have vector already set to zero */
1417 * Set the authentication vector to zero,
1418 * calculate the HMAC, and put it
1419 * into the Message-Authenticator
1422 fr_hmac_md5(packet->data, packet->data_len,
1423 (const uint8_t *) secret, strlen(secret),
1425 memcpy(packet->data + packet->offset + 2,
1426 calc_auth_vector, AUTH_VECTOR_LEN);
1429 * Copy the original request vector back
1430 * to the raw packet.
1432 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1436 * Switch over the packet code, deciding how to
1439 switch (packet->code) {
1441 * Request packets are not signed, bur
1442 * have a random authentication vector.
1444 case PW_AUTHENTICATION_REQUEST:
1445 case PW_STATUS_SERVER:
1449 * Reply packets are signed with the
1450 * authentication vector of the request.
1457 fr_MD5Init(&context);
1458 fr_MD5Update(&context, packet->data, packet->data_len);
1459 fr_MD5Update(&context, (const uint8_t *) secret,
1461 fr_MD5Final(digest, &context);
1463 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1464 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1467 }/* switch over packet codes */
1473 * Reply to the request. Also attach
1474 * reply attribute value pairs and any user message provided.
1476 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1481 char ip_buffer[128];
1484 * Maybe it's a fake packet. Don't send it.
1486 if (!packet || (packet->sockfd < 0)) {
1490 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1491 what = fr_packet_codes[packet->code];
1497 * First time through, allocate room for the packet
1499 if (!packet->data) {
1501 * Encode the packet.
1503 if (rad_encode(packet, original, secret) < 0) {
1508 * Re-sign it, including updating the
1509 * Message-Authenticator.
1511 if (rad_sign(packet, original, secret) < 0) {
1516 * If packet->data points to data, then we print out
1517 * the VP list again only for debugging.
1519 } else if (fr_debug_flag) {
1520 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1521 inet_ntop(packet->dst_ipaddr.af,
1522 &packet->dst_ipaddr.ipaddr,
1523 ip_buffer, sizeof(ip_buffer)),
1526 for (reply = packet->vps; reply; reply = reply->next) {
1527 if ((VENDOR(reply->attribute) == 0) &&
1528 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1534 * And send it on it's way.
1536 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1537 &packet->src_ipaddr, packet->src_port,
1538 &packet->dst_ipaddr, packet->dst_port);
1542 * Do a comparison of two authentication digests by comparing
1543 * the FULL digest. Otehrwise, the server can be subject to
1544 * timing attacks that allow attackers find a valid message
1547 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1549 int rad_digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1554 for (i = 0; i < length; i++) {
1555 result |= a[i] ^ b[i];
1558 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1563 * Validates the requesting client NAS. Calculates the
1564 * Request Authenticator based on the clients private key.
1566 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1568 uint8_t digest[AUTH_VECTOR_LEN];
1572 * Zero out the auth_vector in the received packet.
1573 * Then append the shared secret to the received packet,
1574 * and calculate the MD5 sum. This must be the same
1575 * as the original MD5 sum (packet->vector).
1577 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1580 * MD5(packet + secret);
1582 fr_MD5Init(&context);
1583 fr_MD5Update(&context, packet->data, packet->data_len);
1584 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1585 fr_MD5Final(digest, &context);
1588 * Return 0 if OK, 2 if not OK.
1590 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1596 * Validates the requesting client NAS. Calculates the
1597 * Response Authenticator based on the clients private key.
1599 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1602 uint8_t calc_digest[AUTH_VECTOR_LEN];
1608 if (original == NULL) {
1613 * Copy the original vector in place.
1615 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1618 * MD5(packet + secret);
1620 fr_MD5Init(&context);
1621 fr_MD5Update(&context, packet->data, packet->data_len);
1622 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1623 fr_MD5Final(calc_digest, &context);
1626 * Copy the packet's vector back to the packet.
1628 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1631 * Return 0 if OK, 2 if not OK.
1633 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1639 * See if the data pointed to by PTR is a valid RADIUS packet.
1641 * packet is not 'const * const' because we may update data_len,
1642 * if there's more data in the UDP packet than in the RADIUS packet.
1644 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1649 radius_packet_t *hdr;
1650 char host_ipaddr[128];
1656 * Check for packets smaller than the packet header.
1658 * RFC 2865, Section 3., subsection 'length' says:
1660 * "The minimum length is 20 ..."
1662 if (packet->data_len < AUTH_HDR_LEN) {
1663 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1664 inet_ntop(packet->src_ipaddr.af,
1665 &packet->src_ipaddr.ipaddr,
1666 host_ipaddr, sizeof(host_ipaddr)),
1667 packet->data_len, AUTH_HDR_LEN);
1672 * RFC 2865, Section 3., subsection 'length' says:
1674 * " ... and maximum length is 4096."
1676 if (packet->data_len > MAX_PACKET_LEN) {
1677 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1678 inet_ntop(packet->src_ipaddr.af,
1679 &packet->src_ipaddr.ipaddr,
1680 host_ipaddr, sizeof(host_ipaddr)),
1681 packet->data_len, MAX_PACKET_LEN);
1686 * Check for packets with mismatched size.
1687 * i.e. We've received 128 bytes, and the packet header
1688 * says it's 256 bytes long.
1690 totallen = (packet->data[2] << 8) | packet->data[3];
1691 hdr = (radius_packet_t *)packet->data;
1694 * Code of 0 is not understood.
1695 * Code of 16 or greate is not understood.
1697 if ((hdr->code == 0) ||
1698 (hdr->code >= FR_MAX_PACKET_CODE)) {
1699 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1700 inet_ntop(packet->src_ipaddr.af,
1701 &packet->src_ipaddr.ipaddr,
1702 host_ipaddr, sizeof(host_ipaddr)),
1708 * Message-Authenticator is required in Status-Server
1709 * packets, otherwise they can be trivially forged.
1711 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1714 * It's also required if the caller asks for it.
1716 if (flags) require_ma = 1;
1719 * Repeat the length checks. This time, instead of
1720 * looking at the data we received, look at the value
1721 * of the 'length' field inside of the packet.
1723 * Check for packets smaller than the packet header.
1725 * RFC 2865, Section 3., subsection 'length' says:
1727 * "The minimum length is 20 ..."
1729 if (totallen < AUTH_HDR_LEN) {
1730 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1731 inet_ntop(packet->src_ipaddr.af,
1732 &packet->src_ipaddr.ipaddr,
1733 host_ipaddr, sizeof(host_ipaddr)),
1734 totallen, AUTH_HDR_LEN);
1739 * And again, for the value of the 'length' field.
1741 * RFC 2865, Section 3., subsection 'length' says:
1743 * " ... and maximum length is 4096."
1745 if (totallen > MAX_PACKET_LEN) {
1746 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1747 inet_ntop(packet->src_ipaddr.af,
1748 &packet->src_ipaddr.ipaddr,
1749 host_ipaddr, sizeof(host_ipaddr)),
1750 totallen, MAX_PACKET_LEN);
1755 * RFC 2865, Section 3., subsection 'length' says:
1757 * "If the packet is shorter than the Length field
1758 * indicates, it MUST be silently discarded."
1760 * i.e. No response to the NAS.
1762 if (packet->data_len < totallen) {
1763 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1764 inet_ntop(packet->src_ipaddr.af,
1765 &packet->src_ipaddr.ipaddr,
1766 host_ipaddr, sizeof(host_ipaddr)),
1767 packet->data_len, totallen);
1772 * RFC 2865, Section 3., subsection 'length' says:
1774 * "Octets outside the range of the Length field MUST be
1775 * treated as padding and ignored on reception."
1777 if (packet->data_len > totallen) {
1779 * We're shortening the packet below, but just
1780 * to be paranoid, zero out the extra data.
1782 memset(packet->data + totallen, 0, packet->data_len - totallen);
1783 packet->data_len = totallen;
1787 * Walk through the packet's attributes, ensuring that
1788 * they add up EXACTLY to the size of the packet.
1790 * If they don't, then the attributes either under-fill
1791 * or over-fill the packet. Any parsing of the packet
1792 * is impossible, and will result in unknown side effects.
1794 * This would ONLY happen with buggy RADIUS implementations,
1795 * or with an intentional attack. Either way, we do NOT want
1796 * to be vulnerable to this problem.
1799 count = totallen - AUTH_HDR_LEN;
1804 * We need at least 2 bytes to check the
1808 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
1809 inet_ntop(packet->src_ipaddr.af,
1810 &packet->src_ipaddr.ipaddr,
1811 host_ipaddr, sizeof(host_ipaddr)));
1816 * Attribute number zero is NOT defined.
1819 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1820 inet_ntop(packet->src_ipaddr.af,
1821 &packet->src_ipaddr.ipaddr,
1822 host_ipaddr, sizeof(host_ipaddr)));
1827 * Attributes are at LEAST as long as the ID & length
1828 * fields. Anything shorter is an invalid attribute.
1831 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
1832 inet_ntop(packet->src_ipaddr.af,
1833 &packet->src_ipaddr.ipaddr,
1834 host_ipaddr, sizeof(host_ipaddr)),
1840 * If there are fewer bytes in the packet than in the
1841 * attribute, it's a bad packet.
1843 if (count < attr[1]) {
1844 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
1845 inet_ntop(packet->src_ipaddr.af,
1846 &packet->src_ipaddr.ipaddr,
1847 host_ipaddr, sizeof(host_ipaddr)),
1853 * Sanity check the attributes for length.
1856 default: /* don't do anything by default */
1860 * If there's an EAP-Message, we require
1861 * a Message-Authenticator.
1863 case PW_EAP_MESSAGE:
1867 case PW_MESSAGE_AUTHENTICATOR:
1868 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1869 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1870 inet_ntop(packet->src_ipaddr.af,
1871 &packet->src_ipaddr.ipaddr,
1872 host_ipaddr, sizeof(host_ipaddr)),
1881 * FIXME: Look up the base 255 attributes in the
1882 * dictionary, and switch over their type. For
1883 * integer/date/ip, the attribute length SHOULD
1886 count -= attr[1]; /* grab the attribute length */
1888 num_attributes++; /* seen one more attribute */
1892 * If the attributes add up to a packet, it's allowed.
1894 * If not, we complain, and throw the packet away.
1897 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1898 inet_ntop(packet->src_ipaddr.af,
1899 &packet->src_ipaddr.ipaddr,
1900 host_ipaddr, sizeof(host_ipaddr)));
1905 * If we're configured to look for a maximum number of
1906 * attributes, and we've seen more than that maximum,
1907 * then throw the packet away, as a possible DoS.
1909 if ((fr_max_attributes > 0) &&
1910 (num_attributes > fr_max_attributes)) {
1911 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1912 inet_ntop(packet->src_ipaddr.af,
1913 &packet->src_ipaddr.ipaddr,
1914 host_ipaddr, sizeof(host_ipaddr)),
1915 num_attributes, fr_max_attributes);
1920 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1922 * A packet with an EAP-Message attribute MUST also have
1923 * a Message-Authenticator attribute.
1925 * A Message-Authenticator all by itself is OK, though.
1927 * Similarly, Status-Server packets MUST contain
1928 * Message-Authenticator attributes.
1930 if (require_ma && ! seen_ma) {
1931 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1932 inet_ntop(packet->src_ipaddr.af,
1933 &packet->src_ipaddr.ipaddr,
1934 host_ipaddr, sizeof(host_ipaddr)));
1939 * Fill RADIUS header fields
1941 packet->code = hdr->code;
1942 packet->id = hdr->id;
1943 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1950 * Receive UDP client requests, and fill in
1951 * the basics of a RADIUS_PACKET structure.
1953 RADIUS_PACKET *rad_recv(int fd, int flags)
1956 RADIUS_PACKET *packet;
1959 * Allocate the new request data structure
1961 if ((packet = malloc(sizeof(*packet))) == NULL) {
1962 fr_strerror_printf("out of memory");
1965 memset(packet, 0, sizeof(*packet));
1968 sock_flags = MSG_PEEK;
1972 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1973 &packet->src_ipaddr, &packet->src_port,
1974 &packet->dst_ipaddr, &packet->dst_port);
1977 * Check for socket errors.
1979 if (packet->data_len < 0) {
1980 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1981 /* packet->data is NULL */
1987 * If the packet is too big, then rad_recvfrom did NOT
1988 * allocate memory. Instead, it just discarded the
1991 if (packet->data_len > MAX_PACKET_LEN) {
1992 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1993 /* packet->data is NULL */
1999 * Read no data. Continue.
2000 * This check is AFTER the MAX_PACKET_LEN check above, because
2001 * if the packet is larger than MAX_PACKET_LEN, we also have
2002 * packet->data == NULL
2004 if ((packet->data_len == 0) || !packet->data) {
2005 fr_strerror_printf("Empty packet: Socket is not ready.");
2011 * See if it's a well-formed RADIUS packet.
2013 if (!rad_packet_ok(packet, flags)) {
2019 * Remember which socket we read the packet from.
2021 packet->sockfd = fd;
2024 * FIXME: Do even more filtering by only permitting
2025 * certain IP's. The problem is that we don't know
2026 * how to do this properly for all possible clients...
2030 * Explicitely set the VP list to empty.
2034 if (fr_debug_flag) {
2035 char host_ipaddr[128];
2037 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2038 DEBUG("rad_recv: %s packet from host %s port %d",
2039 fr_packet_codes[packet->code],
2040 inet_ntop(packet->src_ipaddr.af,
2041 &packet->src_ipaddr.ipaddr,
2042 host_ipaddr, sizeof(host_ipaddr)),
2045 DEBUG("rad_recv: Packet from host %s port %d code=%d",
2046 inet_ntop(packet->src_ipaddr.af,
2047 &packet->src_ipaddr.ipaddr,
2048 host_ipaddr, sizeof(host_ipaddr)),
2052 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
2060 * Verify the Request/Response Authenticator
2061 * (and Message-Authenticator if present) of a packet.
2063 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2070 if (!packet || !packet->data) return -1;
2073 * Before we allocate memory for the attributes, do more
2076 ptr = packet->data + AUTH_HDR_LEN;
2077 length = packet->data_len - AUTH_HDR_LEN;
2078 while (length > 0) {
2079 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2080 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2085 default: /* don't do anything. */
2089 * Note that more than one Message-Authenticator
2090 * attribute is invalid.
2092 case PW_MESSAGE_AUTHENTICATOR:
2093 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2094 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2096 switch (packet->code) {
2100 case PW_ACCOUNTING_RESPONSE:
2102 (original->code == PW_STATUS_SERVER)) {
2106 case PW_ACCOUNTING_REQUEST:
2107 case PW_DISCONNECT_REQUEST:
2108 case PW_COA_REQUEST:
2109 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2113 case PW_AUTHENTICATION_ACK:
2114 case PW_AUTHENTICATION_REJECT:
2115 case PW_ACCESS_CHALLENGE:
2116 case PW_DISCONNECT_ACK:
2117 case PW_DISCONNECT_NAK:
2121 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2124 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2128 fr_hmac_md5(packet->data, packet->data_len,
2129 (const uint8_t *) secret, strlen(secret),
2131 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2132 sizeof(calc_auth_vector)) != 0) {
2134 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2135 inet_ntop(packet->src_ipaddr.af,
2136 &packet->src_ipaddr.ipaddr,
2137 buffer, sizeof(buffer)));
2138 /* Silently drop packet, according to RFC 3579 */
2140 } /* else the message authenticator was good */
2143 * Reinitialize Authenticators.
2145 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2146 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2148 } /* switch over the attributes */
2152 } /* loop over the packet, sanity checking the attributes */
2155 * It looks like a RADIUS packet, but we don't know what it is
2156 * so can't validate the authenticators.
2158 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2160 fr_strerror_printf("Received Unknown packet code %d "
2161 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2163 inet_ntop(packet->src_ipaddr.af,
2164 &packet->src_ipaddr.ipaddr,
2165 buffer, sizeof(buffer)),
2171 * Calculate and/or verify Request or Response Authenticator.
2173 switch(packet->code) {
2177 case PW_AUTHENTICATION_REQUEST:
2178 case PW_STATUS_SERVER:
2180 * The authentication vector is random
2181 * nonsense, invented by the client.
2185 case PW_COA_REQUEST:
2186 case PW_DISCONNECT_REQUEST:
2187 case PW_ACCOUNTING_REQUEST:
2188 if (calc_acctdigest(packet, secret) > 1) {
2189 fr_strerror_printf("Received %s packet "
2190 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2191 fr_packet_codes[packet->code],
2192 inet_ntop(packet->src_ipaddr.af,
2193 &packet->src_ipaddr.ipaddr,
2194 buffer, sizeof(buffer)));
2199 /* Verify the reply digest */
2200 case PW_AUTHENTICATION_ACK:
2201 case PW_AUTHENTICATION_REJECT:
2202 case PW_ACCESS_CHALLENGE:
2203 case PW_ACCOUNTING_RESPONSE:
2204 case PW_DISCONNECT_ACK:
2205 case PW_DISCONNECT_NAK:
2208 rcode = calc_replydigest(packet, original, secret);
2210 fr_strerror_printf("Received %s packet "
2211 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2212 fr_packet_codes[packet->code],
2213 inet_ntop(packet->src_ipaddr.af,
2214 &packet->src_ipaddr.ipaddr,
2215 buffer, sizeof(buffer)),
2222 fr_strerror_printf("Received Unknown packet code %d "
2223 "from client %s port %d: Cannot validate Request/Response Authenticator",
2225 inet_ntop(packet->src_ipaddr.af,
2226 &packet->src_ipaddr.ipaddr,
2227 buffer, sizeof(buffer)),
2236 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2237 const RADIUS_PACKET *original,
2239 unsigned int attribute, size_t length,
2240 const uint8_t *data, VALUE_PAIR *vp)
2245 * If length is greater than 253, something is SERIOUSLY
2248 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2250 vp->length = length;
2251 vp->operator = T_OP_EQ;
2257 if (vp->flags.has_tag) {
2258 if (TAG_VALID(data[0]) ||
2259 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2261 * Tunnel passwords REQUIRE a tag, even
2262 * if don't have a valid tag.
2264 vp->flags.tag = data[0];
2266 if ((vp->type == PW_TYPE_STRING) ||
2267 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2272 * Copy the data to be decrypted
2274 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2275 vp->length -= offset;
2278 * Decrypt the attribute.
2280 if (secret) switch (vp->flags.encrypt) {
2284 case FLAG_ENCRYPT_USER_PASSWORD:
2286 rad_pwdecode((char *)vp->vp_strvalue,
2290 rad_pwdecode((char *)vp->vp_strvalue,
2294 if (vp->attribute == PW_USER_PASSWORD) {
2295 vp->length = strlen(vp->vp_strvalue);
2300 * Tunnel-Password's may go ONLY
2301 * in response packets.
2303 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2304 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length, secret,
2305 original ? original->vector : nullvector) < 0)
2310 * Ascend-Send-Secret
2311 * Ascend-Receive-Secret
2313 case FLAG_ENCRYPT_ASCEND_SECRET:
2317 uint8_t my_digest[AUTH_VECTOR_LEN];
2318 make_secret(my_digest,
2321 memcpy(vp->vp_strvalue, my_digest,
2323 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2324 vp->length = strlen(vp->vp_strvalue);
2330 } /* switch over encryption flags */
2334 case PW_TYPE_STRING:
2335 case PW_TYPE_OCTETS:
2336 case PW_TYPE_ABINARY:
2337 /* nothing more to do */
2341 if (vp->length != 1) goto raw;
2343 vp->vp_integer = vp->vp_octets[0];
2348 if (vp->length != 2) goto raw;
2350 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2353 case PW_TYPE_INTEGER:
2354 if (vp->length != 4) goto raw;
2356 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2357 vp->vp_integer = ntohl(vp->vp_integer);
2359 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2362 * Try to get named VALUEs
2366 dval = dict_valbyattr(vp->attribute,
2369 strlcpy(vp->vp_strvalue,
2371 sizeof(vp->vp_strvalue));
2377 if (vp->length != 4) goto raw;
2379 memcpy(&vp->vp_date, vp->vp_octets, 4);
2380 vp->vp_date = ntohl(vp->vp_date);
2384 case PW_TYPE_IPADDR:
2385 if (vp->length != 4) goto raw;
2387 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2391 * IPv6 interface ID is 8 octets long.
2394 if (vp->length != 8) goto raw;
2395 /* vp->vp_ifid == vp->vp_octets */
2399 * IPv6 addresses are 16 octets long
2401 case PW_TYPE_IPV6ADDR:
2402 if (vp->length != 16) goto raw;
2403 /* vp->vp_ipv6addr == vp->vp_octets */
2407 * IPv6 prefixes are 2 to 18 octets long.
2409 * RFC 3162: The first octet is unused.
2410 * The second is the length of the prefix
2411 * the rest are the prefix data.
2413 * The prefix length can have value 0 to 128.
2415 case PW_TYPE_IPV6PREFIX:
2416 if (vp->length < 2 || vp->length > 18) goto raw;
2417 if (vp->vp_octets[1] > 128) goto raw;
2420 * FIXME: double-check that
2421 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2423 if (vp->length < 18) {
2424 memset(vp->vp_octets + vp->length, 0,
2429 case PW_TYPE_SIGNED:
2430 if (vp->length != 4) goto raw;
2433 * Overload vp_integer for ntohl, which takes
2434 * uint32_t, not int32_t
2436 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2437 vp->vp_integer = ntohl(vp->vp_integer);
2438 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2442 vp->length = length;
2443 vp->vp_tlv = malloc(length);
2446 fr_strerror_printf("No memory");
2449 memcpy(vp->vp_tlv, data, length);
2452 case PW_TYPE_COMBO_IP:
2453 if (vp->length == 4) {
2454 vp->type = PW_TYPE_IPADDR;
2455 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2458 } else if (vp->length == 16) {
2459 vp->type = PW_TYPE_IPV6ADDR;
2460 /* vp->vp_ipv6addr == vp->vp_octets */
2469 * Change the name to show the user that the
2470 * attribute is not of the correct format.
2475 vp2 = pairalloc(NULL);
2484 * This sets "vp->flags" appropriately,
2487 if (!paircreate_raw(attribute, PW_TYPE_OCTETS, vp)) {
2491 vp->length = length;
2492 memcpy(vp->vp_octets, data, length);
2500 static void rad_sortvp(VALUE_PAIR **head)
2503 VALUE_PAIR *vp, **tail;
2506 * Walk over the VP's, sorting them in order. Did I
2507 * mention that I hate WiMAX continuations?
2509 * And bubble sort! WTF is up with that?
2516 if (!vp->next) break;
2518 if (vp->attribute > vp->next->attribute) {
2520 vp->next = (*tail)->next;
2531 * Walk the packet, looking for continuations of this attribute.
2533 * This is (worst-case) O(N^2) in the number of RADIUS
2534 * attributes. That happens only when perverse clients create
2535 * continued attributes, AND separate the fragmented portions
2536 * with a lot of other attributes.
2538 * Sane clients should put the fragments next to each other, in
2539 * which case this is O(N), in the number of fragments.
2541 static uint8_t *rad_coalesce(unsigned int attribute, size_t length,
2543 size_t packet_length, size_t *ptlv_length)
2547 size_t tlv_length = length;
2548 uint8_t *ptr, *tlv, *tlv_data;
2550 for (ptr = data + length;
2551 ptr != (data + packet_length);
2553 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2554 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2555 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2559 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2560 lvalue = ntohl(lvalue);
2562 lvalue |= ptr[2 + 4]; /* add in VSA number */
2563 if (lvalue != attribute) continue;
2566 * If the vendor-length is too small, it's badly
2567 * formed, so we stop.
2569 if ((ptr[2 + 4 + 1]) < 3) break;
2571 tlv_length += ptr[2 + 4 + 1] - 3;
2572 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2575 tlv = tlv_data = malloc(tlv_length);
2576 if (!tlv_data) return NULL;
2578 memcpy(tlv, data, length);
2582 * Now we walk the list again, copying the data over to
2583 * our newly created memory.
2585 for (ptr = data + length;
2586 ptr != (data + packet_length);
2590 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2591 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2592 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2596 memcpy(&lvalue, ptr + 2, 4);
2597 lvalue = ntohl(lvalue);
2599 lvalue |= ptr[2 + 4];
2600 if (lvalue != attribute) continue;
2603 * If the vendor-length is too small, it's badly
2604 * formed, so we stop.
2606 if ((ptr[2 + 4 + 1]) < 3) break;
2608 this_length = ptr[2 + 4 + 1] - 3;
2609 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2612 ptr[2 + 4] = 0; /* What a hack! */
2613 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2616 *ptlv_length = tlv_length;
2621 * Start at the *data* portion of a continued attribute. search
2622 * through the rest of the attributes to find a matching one, and
2623 * add it's contents to our contents.
2625 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2626 const RADIUS_PACKET *original,
2627 const char *secret, int attribute,
2628 int length, /* CANNOT be zero */
2629 uint8_t *data, size_t packet_length,
2630 int flag, DICT_ATTR *da)
2632 size_t tlv_length, left;
2635 VALUE_PAIR *vp, *head, **tail;
2638 * Ensure we have data that hasn't been split across
2639 * multiple attributes.
2642 tlv_data = rad_coalesce(attribute, length,
2643 data, packet_length, &tlv_length);
2644 if (!tlv_data) return NULL;
2647 tlv_length = length;
2651 * Non-TLV types cannot be continued across multiple
2652 * attributes. This is true even of keys that are
2653 * encrypted with the tunnel-password method. The spec
2654 * says that they can be continued... but also that the
2655 * keys are 160 bits, which means that they CANNOT be
2658 * Note that we don't check "flag" here. The calling
2661 if (!da || (da->type != PW_TYPE_TLV)) {
2663 if (tlv_data == data) { /* true if we had 'goto' */
2664 tlv_data = malloc(tlv_length);
2665 if (!tlv_data) return NULL;
2666 memcpy(tlv_data, data, tlv_length);
2669 vp = paircreate(attribute, PW_TYPE_OCTETS);
2675 vp->type = PW_TYPE_TLV;
2676 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2677 vp->flags.has_tag = 0;
2678 vp->flags.is_tlv = 0;
2679 vp->vp_tlv = tlv_data;
2680 vp->length = tlv_length;
2682 } /* else it WAS a TLV, go decode the sub-tlv's */
2685 * Now (sigh) we walk over the TLV, seeing if it is
2689 for (ptr = tlv_data;
2690 ptr != (tlv_data + tlv_length);
2695 goto not_well_formed;
2701 * Now we walk over the TLV *again*, creating sub-tlv's.
2706 for (ptr = tlv_data;
2707 ptr != (tlv_data + tlv_length);
2709 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2712 goto not_well_formed;
2715 vp = data2vp(packet, original, secret,
2716 ptr[0], ptr[1] - 2, ptr + 2, vp);
2717 if (!vp) { /* called frees vp */
2719 goto not_well_formed;
2727 * TLV's MAY be continued, but sometimes they're not.
2729 if (tlv_data != data) free(tlv_data);
2731 if (head && head->next) rad_sortvp(&head);
2738 * Parse a RADIUS attribute into a data structure.
2740 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2741 const char *secret, int attribute, int length,
2742 const uint8_t *data)
2746 vp = paircreate(attribute, PW_TYPE_OCTETS);
2747 if (!vp) return NULL;
2749 return data2vp(packet, original, secret, attribute, length, data, vp);
2753 * Converts vp_data to network byte order
2755 * -1 on error, or the length of the value
2757 ssize_t rad_vp2data(const VALUE_PAIR *vp, uint8_t *out, size_t outlen)
2764 fr_strerror_printf("ERROR: rad_vp2data buffer passed too small");
2769 case PW_TYPE_STRING:
2770 case PW_TYPE_OCTETS:
2772 case PW_TYPE_IPADDR:
2773 case PW_TYPE_IPV6ADDR:
2774 case PW_TYPE_IPV6PREFIX:
2775 case PW_TYPE_ABINARY:
2777 memcpy(out, vp->vp_octets, len);
2780 out[0] = vp->vp_integer & 0xff;
2784 out[0] = (vp->vp_integer >> 8) & 0xff;
2785 out[1] = vp->vp_integer & 0xff;
2788 case PW_TYPE_INTEGER:
2789 lvalue = htonl(vp->vp_integer);
2790 memcpy(out, &lvalue, sizeof(lvalue));
2794 lvalue = htonl(vp->vp_date);
2795 memcpy(out, &lvalue, sizeof(lvalue));
2798 case PW_TYPE_SIGNED:
2802 slvalue = htonl(vp->vp_signed);
2803 memcpy(out, &slvalue, sizeof(slvalue));
2806 /* unknown type: ignore it */
2808 fr_strerror_printf("ERROR: Unknown attribute type %d",
2817 * Calculate/check digest, and decode radius attributes.
2819 * -1 on decoding error
2822 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2826 uint32_t vendorcode;
2829 uint8_t *ptr, *vsa_ptr;
2834 radius_packet_t *hdr;
2835 int vsa_tlen, vsa_llen, vsa_offset;
2836 DICT_VENDOR *dv = NULL;
2837 int num_attributes = 0;
2840 * Extract attribute-value pairs
2842 hdr = (radius_packet_t *)packet->data;
2844 packet_length = packet->data_len - AUTH_HDR_LEN;
2847 * There may be VP's already in the packet. Don't
2850 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2856 vsa_tlen = vsa_llen = 1;
2860 * We have to read at least two bytes.
2862 * rad_recv() above ensures that this is OK.
2864 while (packet_length > 0) {
2869 * Normal attribute, handle it like normal.
2871 if (vendorcode == 0) {
2873 * No room to read attr/length,
2874 * or bad attribute, or attribute is
2875 * too short, or attribute is too long,
2876 * stop processing the packet.
2878 if ((packet_length < 2) ||
2879 (ptr[0] == 0) || (ptr[1] < 2) ||
2880 (ptr[1] > packet_length)) break;
2888 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2891 * No vendor code, or ONLY vendor code.
2893 if (attrlen <= 4) goto create_pair;
2899 * Handle Vendor-Specific
2901 if (vendorlen == 0) {
2907 * attrlen was checked above.
2909 memcpy(&lvalue, ptr, 4);
2910 myvendor = ntohl(lvalue);
2913 * Zero isn't allowed.
2915 if (myvendor == 0) goto create_pair;
2918 * This is an implementation issue.
2919 * We currently pack vendor into the upper
2920 * 16 bits of a 32-bit attribute number,
2921 * so we can't handle vendor numbers larger
2924 if (myvendor > 65535) goto create_pair;
2926 vsa_tlen = vsa_llen = 1;
2928 dv = dict_vendorbyvalue(myvendor);
2930 vsa_tlen = dv->type;
2931 vsa_llen = dv->length;
2932 if (dv->flags) vsa_offset = 1;
2936 * Sweep through the list of VSA's,
2937 * seeing if they exactly fill the
2938 * outer Vendor-Specific attribute.
2940 * If not, create a raw Vendor-Specific.
2943 sublen = attrlen - 4;
2946 * See if we can parse it.
2952 * Not enough room for one more
2955 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2958 * Ensure that the attribute number
2967 myattr = (subptr[0] << 8) | subptr[1];
2971 if ((subptr[0] != 0) ||
2972 (subptr[1] != 0)) goto create_pair;
2974 myattr = (subptr[2] << 8) | subptr[3];
2978 * Our dictionary is broken.
2986 attribute = (myvendor << 16) | myattr;
2987 ptr += 4 + vsa_tlen;
2988 attrlen -= (4 + vsa_tlen);
2989 packet_length -= 4 + vsa_tlen;
2993 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2996 if (subptr[vsa_tlen] > sublen)
3001 * Reserved bits MUST be
3005 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
3008 sublen -= subptr[vsa_tlen];
3009 subptr += subptr[vsa_tlen];
3013 if (subptr[vsa_tlen] != 0) goto create_pair;
3014 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
3016 if (subptr[vsa_tlen + 1] > sublen)
3018 sublen -= subptr[vsa_tlen + 1];
3019 subptr += subptr[vsa_tlen + 1];
3023 * Our dictionaries are
3029 } while (sublen > 0);
3031 vendorcode = myvendor;
3032 vendorlen = attrlen - 4;
3039 * attrlen is the length of this attribute.
3040 * total_len is the length of the encompassing
3049 attribute = (ptr[0] << 8) | ptr[1];
3052 default: /* can't hit this. */
3055 attribute |= (vendorcode << 16);
3061 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
3065 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
3068 default: /* can't hit this. */
3072 ptr += vsa_llen + vsa_offset;
3073 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
3074 if (vendorlen == 0) vendorcode = 0;
3075 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
3078 * Ignore VSAs that have no data.
3080 if (attrlen == 0) goto next;
3083 * WiMAX attributes of type 0 are ignored. They
3084 * are a secret flag to us that the attribute has
3085 * already been dealt with.
3087 if (attribute == 0x60b50000) goto next;
3092 da = dict_attrbyvalue(attribute);
3095 * If it's NOT continued, AND we know
3096 * about it, AND it's not a TLV, we can
3097 * create a normal pair.
3099 if (((vsa_ptr[2] & 0x80) == 0) &&
3100 da && (da->type != PW_TYPE_TLV)) goto create_pair;
3103 * Else it IS continued, or it's a TLV.
3104 * Go do a lot of work to find the stuff.
3106 pair = rad_continuation2vp(packet, original, secret,
3107 attribute, attrlen, ptr,
3109 ((vsa_ptr[2] & 0x80) != 0),
3115 * Create the attribute, setting the default type
3116 * to 'octets'. If the type in the dictionary
3117 * is different, then the dictionary type will
3118 * over-ride this one.
3120 * If the attribute has no data, then discard it.
3122 * Unless it's CUI. Damn you, CUI!
3126 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
3128 pair = rad_attr2vp(packet, original, secret,
3129 attribute, attrlen, ptr);
3131 pairfree(&packet->vps);
3132 fr_strerror_printf("out of memory");
3146 * VSA's may not have been counted properly in
3147 * rad_packet_ok() above, as it is hard to count
3148 * then without using the dictionary. We
3149 * therefore enforce the limits here, too.
3151 if ((fr_max_attributes > 0) &&
3152 (num_attributes > fr_max_attributes)) {
3153 char host_ipaddr[128];
3155 pairfree(&packet->vps);
3156 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3157 inet_ntop(packet->src_ipaddr.af,
3158 &packet->src_ipaddr.ipaddr,
3159 host_ipaddr, sizeof(host_ipaddr)),
3160 num_attributes, fr_max_attributes);
3166 packet_length -= attrlen;
3170 * Merge information from the outside world into our
3173 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3182 * We assume that the passwd buffer passed is big enough.
3183 * RFC2138 says the password is max 128 chars, so the size
3184 * of the passwd buffer must be at least 129 characters.
3185 * Preferably it's just MAX_STRING_LEN.
3187 * int *pwlen is updated to the new length of the encrypted
3188 * password - a multiple of 16 bytes.
3190 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3191 const uint8_t *vector)
3193 FR_MD5_CTX context, old;
3194 uint8_t digest[AUTH_VECTOR_LEN];
3195 int i, n, secretlen;
3199 * RFC maximum is 128 bytes.
3201 * If length is zero, pad it out with zeros.
3203 * If the length isn't aligned to 16 bytes,
3204 * zero out the extra data.
3208 if (len > 128) len = 128;
3211 memset(passwd, 0, AUTH_PASS_LEN);
3212 len = AUTH_PASS_LEN;
3213 } else if ((len % AUTH_PASS_LEN) != 0) {
3214 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3215 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3220 * Use the secret to setup the decryption digest
3222 secretlen = strlen(secret);
3224 fr_MD5Init(&context);
3225 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3226 old = context; /* save intermediate work */
3229 * Encrypt it in place. Don't bother checking
3230 * len, as we've ensured above that it's OK.
3232 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3234 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3235 fr_MD5Final(digest, &context);
3238 fr_MD5Update(&context,
3239 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3241 fr_MD5Final(digest, &context);
3244 for (i = 0; i < AUTH_PASS_LEN; i++) {
3245 passwd[i + n] ^= digest[i];
3255 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3256 const uint8_t *vector)
3258 FR_MD5_CTX context, old;
3259 uint8_t digest[AUTH_VECTOR_LEN];
3261 size_t n, secretlen;
3264 * The RFC's say that the maximum is 128.
3265 * The buffer we're putting it into above is 254, so
3266 * we don't need to do any length checking.
3268 if (pwlen > 128) pwlen = 128;
3273 if (pwlen == 0) goto done;
3276 * Use the secret to setup the decryption digest
3278 secretlen = strlen(secret);
3280 fr_MD5Init(&context);
3281 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3282 old = context; /* save intermediate work */
3285 * The inverse of the code above.
3287 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3289 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3290 fr_MD5Final(digest, &context);
3293 if (pwlen > AUTH_PASS_LEN) {
3294 fr_MD5Update(&context, (uint8_t *) passwd,
3298 fr_MD5Final(digest, &context);
3301 if (pwlen > (n + AUTH_PASS_LEN)) {
3302 fr_MD5Update(&context, (uint8_t *) passwd + n,
3307 for (i = 0; i < AUTH_PASS_LEN; i++) {
3308 passwd[i + n] ^= digest[i];
3313 passwd[pwlen] = '\0';
3314 return strlen(passwd);
3319 * Encode Tunnel-Password attributes when sending them out on the wire.
3321 * int *pwlen is updated to the new length of the encrypted
3322 * password - a multiple of 16 bytes.
3324 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3327 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3328 const uint8_t *vector)
3330 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3331 unsigned char digest[AUTH_VECTOR_LEN];
3333 int i, n, secretlen;
3338 if (len > 127) len = 127;
3341 * Shift the password 3 positions right to place a salt and original
3342 * length, tag will be added automatically on packet send
3344 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3348 * save original password length as first password character;
3355 * Generate salt. The RFC's say:
3357 * The high bit of salt[0] must be set, each salt in a
3358 * packet should be unique, and they should be random
3360 * So, we set the high bit, add in a counter, and then
3361 * add in some CSPRNG data. should be OK..
3363 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3364 (fr_rand() & 0x07));
3365 salt[1] = fr_rand();
3368 * Padd password to multiple of AUTH_PASS_LEN bytes.
3370 n = len % AUTH_PASS_LEN;
3372 n = AUTH_PASS_LEN - n;
3373 for (; n > 0; n--, len++)
3376 /* set new password length */
3380 * Use the secret to setup the decryption digest
3382 secretlen = strlen(secret);
3383 memcpy(buffer, secret, secretlen);
3385 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3387 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3388 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3389 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3391 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3392 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3395 for (i = 0; i < AUTH_PASS_LEN; i++) {
3396 passwd[i + n2] ^= digest[i];
3404 * Decode Tunnel-Password encrypted attributes.
3406 * Defined in RFC-2868, this uses a two char SALT along with the
3407 * initial intermediate value, to differentiate it from the
3410 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3411 const uint8_t *vector)
3413 FR_MD5_CTX context, old;
3414 uint8_t digest[AUTH_VECTOR_LEN];
3416 size_t i, n, encrypted_len, reallen;
3418 encrypted_len = *pwlen;
3420 fprintf(stderr, "HERE %d\n", __LINE__);
3423 * We need at least a salt.
3425 if (encrypted_len < 2) {
3426 fr_strerror_printf("tunnel password is too short");
3431 * There's a salt, but no password. Or, there's a salt
3432 * and a 'data_len' octet. It's wrong, but at least we
3433 * can figure out what it means: the password is empty.
3435 * Note that this means we ignore the 'data_len' field,
3436 * if the attribute length tells us that there's no
3437 * more data. So the 'data_len' field may be wrong,
3440 if (encrypted_len <= 3) {
3446 encrypted_len -= 2; /* discount the salt */
3448 fprintf(stderr, "HERE %d\n", __LINE__);
3451 * Use the secret to setup the decryption digest
3453 secretlen = strlen(secret);
3455 fr_MD5Init(&context);
3456 fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
3457 old = context; /* save intermediate work */
3460 * Set up the initial key:
3462 * b(1) = MD5(secret + vector + salt)
3464 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3465 fr_MD5Update(&context, passwd, 2);
3467 fprintf(stderr, "HERE %d\n", __LINE__);
3470 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
3472 size_t block_len = AUTH_PASS_LEN;
3475 * Ensure we don't overflow the input on MD5
3477 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
3478 block_len = *pwlen - n - 2;
3484 fr_MD5Final(digest, &context);
3489 * A quick check: decrypt the first octet
3490 * of the password, which is the
3491 * 'data_len' field. Ensure it's sane.
3493 reallen = passwd[2] ^ digest[0];
3494 if (reallen > encrypted_len) {
3495 fr_strerror_printf("tunnel password is too long for the attribute");
3499 fr_MD5Update(&context, passwd + 2, block_len);
3504 fr_MD5Final(digest, &context);
3507 fr_MD5Update(&context, passwd + n + 2, block_len);
3510 for (i = base; i < block_len; i++) {
3511 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3516 passwd[reallen] = 0;
3522 * Encode a CHAP password
3524 * FIXME: might not work with Ascend because
3525 * we use vp->length, and Ascend gear likes
3526 * to send an extra '\0' in the string!
3528 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3529 VALUE_PAIR *password)
3533 uint8_t string[MAX_STRING_LEN * 2 + 1];
3534 VALUE_PAIR *challenge;
3537 * Sanity check the input parameters
3539 if ((packet == NULL) || (password == NULL)) {
3544 * Note that the password VP can be EITHER
3545 * a User-Password attribute (from a check-item list),
3546 * or a CHAP-Password attribute (the client asking
3547 * the library to encode it).
3555 memcpy(ptr, password->vp_strvalue, password->length);
3556 ptr += password->length;
3557 i += password->length;
3560 * Use Chap-Challenge pair if present,
3561 * Request Authenticator otherwise.
3563 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3565 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3566 i += challenge->length;
3568 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3569 i += AUTH_VECTOR_LEN;
3573 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3580 * Seed the random number generator.
3582 * May be called any number of times.
3584 void fr_rand_seed(const void *data, size_t size)
3589 * Ensure that the pool is initialized.
3591 if (!fr_rand_initialized) {
3594 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3596 fd = open("/dev/urandom", O_RDONLY);
3602 while (total < sizeof(fr_rand_pool.randrsl)) {
3603 this = read(fd, fr_rand_pool.randrsl,
3604 sizeof(fr_rand_pool.randrsl) - total);
3605 if ((this < 0) && (errno != EINTR)) break;
3606 if (this > 0) total += this;
3610 fr_rand_pool.randrsl[0] = fd;
3611 fr_rand_pool.randrsl[1] = time(NULL);
3612 fr_rand_pool.randrsl[2] = errno;
3615 fr_randinit(&fr_rand_pool, 1);
3616 fr_rand_pool.randcnt = 0;
3617 fr_rand_initialized = 1;
3623 * Hash the user data
3626 if (!hash) hash = fr_rand();
3627 hash = fr_hash_update(data, size, hash);
3629 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3634 * Return a 32-bit random number.
3636 uint32_t fr_rand(void)
3641 * Ensure that the pool is initialized.
3643 if (!fr_rand_initialized) {
3644 fr_rand_seed(NULL, 0);
3647 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3648 if (fr_rand_pool.randcnt >= 256) {
3649 fr_rand_pool.randcnt = 0;
3650 fr_isaac(&fr_rand_pool);
3658 * Allocate a new RADIUS_PACKET
3660 RADIUS_PACKET *rad_alloc(int newvector)
3664 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3665 fr_strerror_printf("out of memory");
3668 memset(rp, 0, sizeof(*rp));
3674 uint32_t hash, base;
3677 * Don't expose the actual contents of the random
3681 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3682 hash = fr_rand() ^ base;
3683 memcpy(rp->vector + i, &hash, sizeof(hash));
3686 fr_rand(); /* stir the pool again */
3691 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3693 RADIUS_PACKET *reply;
3695 if (!packet) return NULL;
3697 reply = rad_alloc(0);
3698 if (!reply) return NULL;
3701 * Initialize the fields from the request.
3703 reply->sockfd = packet->sockfd;
3704 reply->dst_ipaddr = packet->src_ipaddr;
3705 reply->src_ipaddr = packet->dst_ipaddr;
3706 reply->dst_port = packet->src_port;
3707 reply->src_port = packet->dst_port;
3708 reply->id = packet->id;
3709 reply->code = 0; /* UNKNOWN code */
3710 memcpy(reply->vector, packet->vector,
3711 sizeof(reply->vector));
3714 reply->data_len = 0;
3721 * Free a RADIUS_PACKET
3723 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3725 RADIUS_PACKET *radius_packet;
3727 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3728 radius_packet = *radius_packet_ptr;
3730 free(radius_packet->data);
3732 pairfree(&radius_packet->vps);
3734 free(radius_packet);
3736 *radius_packet_ptr = NULL;