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, size_t length)
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 < length; 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) len = AUTH_VECTOR_LEN;
793 make_secret(ptr, packet->vector, secret, data, len);
799 * Just copy the data over
801 memcpy(ptr, data, len);
804 } else { /* no packet */
805 memcpy(ptr, data, len);
812 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
816 unsigned int attribute;
818 VALUE_PAIR *vp, *tlv;
820 attribute = vps->attribute & 0xffff00ff;
821 maxattr = vps->attribute & 0x0ff;
823 tlv = paircreate(attribute, PW_TYPE_TLV);
824 if (!tlv) return NULL;
827 for (vp = vps; vp != NULL; vp = vp->next) {
829 * Group the attributes ONLY until we see a
832 if (!vp->flags.is_tlv ||
834 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
835 ((vp->attribute & 0xffff00ff) != attribute) ||
836 ((vp->attribute & 0x0000ff00) < maxattr)) {
840 maxattr = vp->attribute & 0xff00;
841 tlv->length += vp->length + 2;
849 tlv->vp_tlv = malloc(tlv->length);
856 maxattr = vps->attribute & 0x0ff;
857 for (vp = vps; vp != NULL; vp = vp->next) {
858 if (!vp->flags.is_tlv ||
860 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
861 ((vp->attribute & 0xffff00ff) != attribute) ||
862 ((vp->attribute & 0x0000ff00) < maxattr)) {
866 maxattr = vp->attribute & 0xff00;
867 end = vp2data(NULL, NULL, NULL, vp, ptr + 2,
868 tlv->vp_tlv + tlv->length - ptr);
870 vp->length = ptr - vp->vp_tlv;
871 return tlv; /* should be a more serious error... */
874 length = (end - ptr);
881 * Pack the attribute.
883 ptr[0] = (vp->attribute & 0xff00) >> 8;
887 vp->flags.encoded = 1;
894 * Pack data without any encryption.
895 * start == start of RADIUS attribute
896 * ptr == continuation byte (i.e. one after length)
898 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
902 size_t hsize = (ptr - start);
903 uint8_t *this = start;
908 * If it's too long and marked as encrypted, ignore it.
910 if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
914 memcpy(header, start, hsize);
925 data = vp->vp_octets;
936 memcpy(this, header, hsize);
943 if (left > (254 - hsize)) {
951 memcpy(ptr, data, piece);
952 this[1] = hsize + piece + 1;
957 this[hsize - 1] = hsize - 6 + 1 + piece;
964 return (ptr - start);
969 * Parse a data structure into a RADIUS attribute.
971 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
972 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
975 int len, total_length;
977 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
983 length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
986 * For interoperability, always put vendor attributes
987 * into their own VSA.
989 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
990 *(ptr++) = vp->attribute & 0xFF;
999 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
1002 * This must be an RFC-format attribute. If it
1003 * wasn't, then the "decode" function would have
1004 * made a Vendor-Specific attribute (i.e. type
1005 * 26), and we would have "vendorcode == 0" here.
1008 vsa_tlen = dv->type;
1009 vsa_llen = dv->length;
1010 if (dv->flags) vsa_offset = 1;
1014 * Build a VSA header.
1016 *ptr++ = PW_VENDOR_SPECIFIC;
1017 vsa_length_ptr = ptr;
1019 lvalue = htonl(vendorcode);
1020 memcpy(ptr, &lvalue, 4);
1026 ptr[0] = (vp->attribute & 0xFF);
1030 ptr[0] = ((vp->attribute >> 8) & 0xFF);
1031 ptr[1] = (vp->attribute & 0xFF);
1037 ptr[2] = ((vp->attribute >> 8) & 0xFF);
1038 ptr[3] = (vp->attribute & 0xFF);
1042 return 0; /* silently discard it */
1048 length_ptr = vsa_length_ptr;
1049 vsa_length_ptr = NULL;
1058 length_ptr = ptr + 1;
1062 return 0; /* silently discard it */
1067 * Allow for some continuation.
1071 * Allow TLV's to be encoded, if someone
1072 * manages to somehow encode the sub-tlv's.
1074 * FIXME: Keep track of room in the packet!
1076 if (vp->length > (((size_t) 254) - (ptr - start))) {
1077 return rad_vp2continuation(vp, start, ptr);
1084 * sub-TLV's can only be in one format.
1086 if (vp->flags.is_tlv) {
1087 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1088 tlv_length_ptr = ptr;
1094 total_length += vsa_tlen + vsa_llen + vsa_offset;
1095 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1096 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1100 * Insert tags for string attributes. They go BEFORE
1103 if (vp->flags.has_tag && (vp->type == PW_TYPE_STRING) &&
1104 (TAG_VALID(vp->flags.tag) ||
1105 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
1106 ptr[0] = vp->flags.tag;
1107 end = vp2data(packet, original, secret, vp, ptr + 1,
1110 end = vp2data(packet, original, secret, vp, ptr,
1113 if (!end) return -1;
1116 * Insert tags for integer attributes. They go at the START
1117 * of the integer, and over-write the first byte.
1119 if (vp->flags.has_tag && (vp->type == PW_TYPE_INTEGER)) {
1120 ptr[0] = vp->flags.tag;
1124 * RFC 2865 section 5 says that zero-length attributes
1127 * ... and the WiMAX forum ignores this... because of
1128 * one vendor. Don't they have anything better to do
1132 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1137 * Update the various lengths.
1140 if (vsa_length_ptr) *vsa_length_ptr += len;
1141 if (tlv_length_ptr) *tlv_length_ptr += len;
1142 total_length += len;
1144 return total_length; /* of attribute */
1151 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1154 radius_packet_t *hdr;
1156 uint16_t total_length;
1160 char ip_buffer[128];
1163 * For simplicity in the following logic, we allow
1164 * the attributes to "overflow" the 4k maximum
1165 * RADIUS packet size, by one attribute.
1167 * It's uint32_t, for alignment purposes.
1169 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
1171 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1172 what = fr_packet_codes[packet->code];
1177 DEBUG("Sending %s of id %d to %s port %d\n",
1179 inet_ntop(packet->dst_ipaddr.af,
1180 &packet->dst_ipaddr.ipaddr,
1181 ip_buffer, sizeof(ip_buffer)),
1185 * Double-check some things based on packet code.
1187 switch (packet->code) {
1188 case PW_AUTHENTICATION_ACK:
1189 case PW_AUTHENTICATION_REJECT:
1190 case PW_ACCESS_CHALLENGE:
1192 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1198 * These packet vectors start off as all zero.
1200 case PW_ACCOUNTING_REQUEST:
1201 case PW_DISCONNECT_REQUEST:
1202 case PW_COA_REQUEST:
1203 memset(packet->vector, 0, sizeof(packet->vector));
1211 * Use memory on the stack, until we know how
1212 * large the packet will be.
1214 hdr = (radius_packet_t *) data;
1217 * Build standard header
1219 hdr->code = packet->code;
1220 hdr->id = packet->id;
1222 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1224 total_length = AUTH_HDR_LEN;
1227 * Load up the configuration values for the user
1233 * FIXME: Loop twice over the reply list. The first time,
1234 * calculate the total length of data. The second time,
1235 * allocate the memory, and fill in the VP's.
1237 * Hmm... this may be slower than just doing a small
1242 * Loop over the reply attributes for the packet.
1244 for (reply = packet->vps; reply; reply = reply->next) {
1246 * Ignore non-wire attributes
1248 if ((VENDOR(reply->attribute) == 0) &&
1249 ((reply->attribute & 0xFFFF) > 0xff)) {
1252 * Permit the admin to send BADLY formatted
1253 * attributes with a debug build.
1255 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1256 memcpy(ptr, reply->vp_octets, reply->length);
1257 len = reply->length;
1265 * Set the Message-Authenticator to the correct
1266 * length and initial value.
1268 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1269 reply->length = AUTH_VECTOR_LEN;
1270 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1273 * Cache the offset to the
1274 * Message-Authenticator
1276 packet->offset = total_length;
1280 * Print out ONLY the attributes which
1281 * we're sending over the wire, and print
1282 * them out BEFORE they're encrypted.
1287 * Print them in order, even if they were encoded
1291 if (reply->flags.encoded) goto next;
1293 if (reply->flags.is_tlv) {
1294 VALUE_PAIR *tlv = rad_vp2tlv(reply);
1296 tlv->next = reply->next;
1301 * The encoded flag MUST be set in reply!
1303 reply = reply->next;
1306 len = rad_vp2attr(packet, original, secret, reply, ptr);
1308 if (len < 0) return -1;
1311 * Check that the packet is no more than 4k in
1312 * size, AFTER writing the attribute past the 4k
1313 * boundary, but BEFORE deciding to increase the
1314 * size of the packet. Note that the 'data'
1315 * buffer, above, is one attribute longer than
1316 * necessary, in order to permit this overflow.
1318 if ((total_length + len) > MAX_PACKET_LEN) {
1319 DEBUG("WARNING: Attributes are too long for packet. Discarding data past %d bytes", total_length);
1325 total_length += len;
1326 } /* done looping over all attributes */
1329 * Fill in the rest of the fields, and copy the data over
1330 * from the local stack to the newly allocated memory.
1332 * Yes, all this 'memcpy' is slow, but it means
1333 * that we only allocate the minimum amount of
1334 * memory for a request.
1336 packet->data_len = total_length;
1337 packet->data = (uint8_t *) malloc(packet->data_len);
1338 if (!packet->data) {
1339 fr_strerror_printf("Out of memory");
1343 memcpy(packet->data, hdr, packet->data_len);
1344 hdr = (radius_packet_t *) packet->data;
1346 total_length = htons(total_length);
1347 memcpy(hdr->length, &total_length, sizeof(total_length));
1354 * Sign a previously encoded packet.
1356 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1359 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1362 * It wasn't assigned an Id, this is bad!
1364 if (packet->id < 0) {
1365 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1369 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1370 (packet->offset < 0)) {
1371 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1376 * If there's a Message-Authenticator, update it
1377 * now, BEFORE updating the authentication vector.
1379 if (packet->offset > 0) {
1380 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1382 switch (packet->code) {
1383 case PW_ACCOUNTING_RESPONSE:
1384 if (original && original->code == PW_STATUS_SERVER) {
1388 case PW_ACCOUNTING_REQUEST:
1389 case PW_DISCONNECT_REQUEST:
1390 case PW_DISCONNECT_ACK:
1391 case PW_DISCONNECT_NAK:
1392 case PW_COA_REQUEST:
1395 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1399 case PW_AUTHENTICATION_ACK:
1400 case PW_AUTHENTICATION_REJECT:
1401 case PW_ACCESS_CHALLENGE:
1403 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1406 memcpy(hdr->vector, original->vector,
1410 default: /* others have vector already set to zero */
1416 * Set the authentication vector to zero,
1417 * calculate the HMAC, and put it
1418 * into the Message-Authenticator
1421 fr_hmac_md5(packet->data, packet->data_len,
1422 (const uint8_t *) secret, strlen(secret),
1424 memcpy(packet->data + packet->offset + 2,
1425 calc_auth_vector, AUTH_VECTOR_LEN);
1428 * Copy the original request vector back
1429 * to the raw packet.
1431 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1435 * Switch over the packet code, deciding how to
1438 switch (packet->code) {
1440 * Request packets are not signed, bur
1441 * have a random authentication vector.
1443 case PW_AUTHENTICATION_REQUEST:
1444 case PW_STATUS_SERVER:
1448 * Reply packets are signed with the
1449 * authentication vector of the request.
1456 fr_MD5Init(&context);
1457 fr_MD5Update(&context, packet->data, packet->data_len);
1458 fr_MD5Update(&context, (const uint8_t *) secret,
1460 fr_MD5Final(digest, &context);
1462 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1463 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1466 }/* switch over packet codes */
1472 * Reply to the request. Also attach
1473 * reply attribute value pairs and any user message provided.
1475 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1480 char ip_buffer[128];
1483 * Maybe it's a fake packet. Don't send it.
1485 if (!packet || (packet->sockfd < 0)) {
1489 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1490 what = fr_packet_codes[packet->code];
1496 * First time through, allocate room for the packet
1498 if (!packet->data) {
1500 * Encode the packet.
1502 if (rad_encode(packet, original, secret) < 0) {
1507 * Re-sign it, including updating the
1508 * Message-Authenticator.
1510 if (rad_sign(packet, original, secret) < 0) {
1515 * If packet->data points to data, then we print out
1516 * the VP list again only for debugging.
1518 } else if (fr_debug_flag) {
1519 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1520 inet_ntop(packet->dst_ipaddr.af,
1521 &packet->dst_ipaddr.ipaddr,
1522 ip_buffer, sizeof(ip_buffer)),
1525 for (reply = packet->vps; reply; reply = reply->next) {
1526 if ((VENDOR(reply->attribute) == 0) &&
1527 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1533 * And send it on it's way.
1535 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1536 &packet->src_ipaddr, packet->src_port,
1537 &packet->dst_ipaddr, packet->dst_port);
1541 * Do a comparison of two authentication digests by comparing
1542 * the FULL digest. Otehrwise, the server can be subject to
1543 * timing attacks that allow attackers find a valid message
1546 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1548 int rad_digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1553 for (i = 0; i < length; i++) {
1554 result |= a[i] ^ b[i];
1557 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1562 * Validates the requesting client NAS. Calculates the
1563 * Request Authenticator based on the clients private key.
1565 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1567 uint8_t digest[AUTH_VECTOR_LEN];
1571 * Zero out the auth_vector in the received packet.
1572 * Then append the shared secret to the received packet,
1573 * and calculate the MD5 sum. This must be the same
1574 * as the original MD5 sum (packet->vector).
1576 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1579 * MD5(packet + secret);
1581 fr_MD5Init(&context);
1582 fr_MD5Update(&context, packet->data, packet->data_len);
1583 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1584 fr_MD5Final(digest, &context);
1587 * Return 0 if OK, 2 if not OK.
1589 if (rad_digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1595 * Validates the requesting client NAS. Calculates the
1596 * Response Authenticator based on the clients private key.
1598 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1601 uint8_t calc_digest[AUTH_VECTOR_LEN];
1607 if (original == NULL) {
1612 * Copy the original vector in place.
1614 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1617 * MD5(packet + secret);
1619 fr_MD5Init(&context);
1620 fr_MD5Update(&context, packet->data, packet->data_len);
1621 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1622 fr_MD5Final(calc_digest, &context);
1625 * Copy the packet's vector back to the packet.
1627 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1630 * Return 0 if OK, 2 if not OK.
1632 if (rad_digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1638 * See if the data pointed to by PTR is a valid RADIUS packet.
1640 * packet is not 'const * const' because we may update data_len,
1641 * if there's more data in the UDP packet than in the RADIUS packet.
1643 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1648 radius_packet_t *hdr;
1649 char host_ipaddr[128];
1655 * Check for packets smaller than the packet header.
1657 * RFC 2865, Section 3., subsection 'length' says:
1659 * "The minimum length is 20 ..."
1661 if (packet->data_len < AUTH_HDR_LEN) {
1662 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1663 inet_ntop(packet->src_ipaddr.af,
1664 &packet->src_ipaddr.ipaddr,
1665 host_ipaddr, sizeof(host_ipaddr)),
1666 packet->data_len, AUTH_HDR_LEN);
1671 * RFC 2865, Section 3., subsection 'length' says:
1673 * " ... and maximum length is 4096."
1675 if (packet->data_len > MAX_PACKET_LEN) {
1676 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1677 inet_ntop(packet->src_ipaddr.af,
1678 &packet->src_ipaddr.ipaddr,
1679 host_ipaddr, sizeof(host_ipaddr)),
1680 packet->data_len, MAX_PACKET_LEN);
1685 * Check for packets with mismatched size.
1686 * i.e. We've received 128 bytes, and the packet header
1687 * says it's 256 bytes long.
1689 totallen = (packet->data[2] << 8) | packet->data[3];
1690 hdr = (radius_packet_t *)packet->data;
1693 * Code of 0 is not understood.
1694 * Code of 16 or greate is not understood.
1696 if ((hdr->code == 0) ||
1697 (hdr->code >= FR_MAX_PACKET_CODE)) {
1698 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1699 inet_ntop(packet->src_ipaddr.af,
1700 &packet->src_ipaddr.ipaddr,
1701 host_ipaddr, sizeof(host_ipaddr)),
1707 * Message-Authenticator is required in Status-Server
1708 * packets, otherwise they can be trivially forged.
1710 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1713 * It's also required if the caller asks for it.
1715 if (flags) require_ma = 1;
1718 * Repeat the length checks. This time, instead of
1719 * looking at the data we received, look at the value
1720 * of the 'length' field inside of the packet.
1722 * Check for packets smaller than the packet header.
1724 * RFC 2865, Section 3., subsection 'length' says:
1726 * "The minimum length is 20 ..."
1728 if (totallen < AUTH_HDR_LEN) {
1729 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1730 inet_ntop(packet->src_ipaddr.af,
1731 &packet->src_ipaddr.ipaddr,
1732 host_ipaddr, sizeof(host_ipaddr)),
1733 totallen, AUTH_HDR_LEN);
1738 * And again, for the value of the 'length' field.
1740 * RFC 2865, Section 3., subsection 'length' says:
1742 * " ... and maximum length is 4096."
1744 if (totallen > MAX_PACKET_LEN) {
1745 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1746 inet_ntop(packet->src_ipaddr.af,
1747 &packet->src_ipaddr.ipaddr,
1748 host_ipaddr, sizeof(host_ipaddr)),
1749 totallen, MAX_PACKET_LEN);
1754 * RFC 2865, Section 3., subsection 'length' says:
1756 * "If the packet is shorter than the Length field
1757 * indicates, it MUST be silently discarded."
1759 * i.e. No response to the NAS.
1761 if (packet->data_len < totallen) {
1762 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1763 inet_ntop(packet->src_ipaddr.af,
1764 &packet->src_ipaddr.ipaddr,
1765 host_ipaddr, sizeof(host_ipaddr)),
1766 packet->data_len, totallen);
1771 * RFC 2865, Section 3., subsection 'length' says:
1773 * "Octets outside the range of the Length field MUST be
1774 * treated as padding and ignored on reception."
1776 if (packet->data_len > totallen) {
1778 * We're shortening the packet below, but just
1779 * to be paranoid, zero out the extra data.
1781 memset(packet->data + totallen, 0, packet->data_len - totallen);
1782 packet->data_len = totallen;
1786 * Walk through the packet's attributes, ensuring that
1787 * they add up EXACTLY to the size of the packet.
1789 * If they don't, then the attributes either under-fill
1790 * or over-fill the packet. Any parsing of the packet
1791 * is impossible, and will result in unknown side effects.
1793 * This would ONLY happen with buggy RADIUS implementations,
1794 * or with an intentional attack. Either way, we do NOT want
1795 * to be vulnerable to this problem.
1798 count = totallen - AUTH_HDR_LEN;
1803 * We need at least 2 bytes to check the
1807 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
1808 inet_ntop(packet->src_ipaddr.af,
1809 &packet->src_ipaddr.ipaddr,
1810 host_ipaddr, sizeof(host_ipaddr)));
1815 * Attribute number zero is NOT defined.
1818 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1819 inet_ntop(packet->src_ipaddr.af,
1820 &packet->src_ipaddr.ipaddr,
1821 host_ipaddr, sizeof(host_ipaddr)));
1826 * Attributes are at LEAST as long as the ID & length
1827 * fields. Anything shorter is an invalid attribute.
1830 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
1831 inet_ntop(packet->src_ipaddr.af,
1832 &packet->src_ipaddr.ipaddr,
1833 host_ipaddr, sizeof(host_ipaddr)),
1839 * If there are fewer bytes in the packet than in the
1840 * attribute, it's a bad packet.
1842 if (count < attr[1]) {
1843 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
1844 inet_ntop(packet->src_ipaddr.af,
1845 &packet->src_ipaddr.ipaddr,
1846 host_ipaddr, sizeof(host_ipaddr)),
1852 * Sanity check the attributes for length.
1855 default: /* don't do anything by default */
1859 * If there's an EAP-Message, we require
1860 * a Message-Authenticator.
1862 case PW_EAP_MESSAGE:
1866 case PW_MESSAGE_AUTHENTICATOR:
1867 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1868 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1869 inet_ntop(packet->src_ipaddr.af,
1870 &packet->src_ipaddr.ipaddr,
1871 host_ipaddr, sizeof(host_ipaddr)),
1880 * FIXME: Look up the base 255 attributes in the
1881 * dictionary, and switch over their type. For
1882 * integer/date/ip, the attribute length SHOULD
1885 count -= attr[1]; /* grab the attribute length */
1887 num_attributes++; /* seen one more attribute */
1891 * If the attributes add up to a packet, it's allowed.
1893 * If not, we complain, and throw the packet away.
1896 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1897 inet_ntop(packet->src_ipaddr.af,
1898 &packet->src_ipaddr.ipaddr,
1899 host_ipaddr, sizeof(host_ipaddr)));
1904 * If we're configured to look for a maximum number of
1905 * attributes, and we've seen more than that maximum,
1906 * then throw the packet away, as a possible DoS.
1908 if ((fr_max_attributes > 0) &&
1909 (num_attributes > fr_max_attributes)) {
1910 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1911 inet_ntop(packet->src_ipaddr.af,
1912 &packet->src_ipaddr.ipaddr,
1913 host_ipaddr, sizeof(host_ipaddr)),
1914 num_attributes, fr_max_attributes);
1919 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1921 * A packet with an EAP-Message attribute MUST also have
1922 * a Message-Authenticator attribute.
1924 * A Message-Authenticator all by itself is OK, though.
1926 * Similarly, Status-Server packets MUST contain
1927 * Message-Authenticator attributes.
1929 if (require_ma && ! seen_ma) {
1930 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1931 inet_ntop(packet->src_ipaddr.af,
1932 &packet->src_ipaddr.ipaddr,
1933 host_ipaddr, sizeof(host_ipaddr)));
1938 * Fill RADIUS header fields
1940 packet->code = hdr->code;
1941 packet->id = hdr->id;
1942 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1949 * Receive UDP client requests, and fill in
1950 * the basics of a RADIUS_PACKET structure.
1952 RADIUS_PACKET *rad_recv(int fd, int flags)
1955 RADIUS_PACKET *packet;
1958 * Allocate the new request data structure
1960 if ((packet = malloc(sizeof(*packet))) == NULL) {
1961 fr_strerror_printf("out of memory");
1964 memset(packet, 0, sizeof(*packet));
1967 sock_flags = MSG_PEEK;
1971 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1972 &packet->src_ipaddr, &packet->src_port,
1973 &packet->dst_ipaddr, &packet->dst_port);
1976 * Check for socket errors.
1978 if (packet->data_len < 0) {
1979 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1980 /* packet->data is NULL */
1986 * If the packet is too big, then rad_recvfrom did NOT
1987 * allocate memory. Instead, it just discarded the
1990 if (packet->data_len > MAX_PACKET_LEN) {
1991 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1992 /* packet->data is NULL */
1998 * Read no data. Continue.
1999 * This check is AFTER the MAX_PACKET_LEN check above, because
2000 * if the packet is larger than MAX_PACKET_LEN, we also have
2001 * packet->data == NULL
2003 if ((packet->data_len == 0) || !packet->data) {
2004 fr_strerror_printf("Empty packet: Socket is not ready.");
2010 * See if it's a well-formed RADIUS packet.
2012 if (!rad_packet_ok(packet, flags)) {
2018 * Remember which socket we read the packet from.
2020 packet->sockfd = fd;
2023 * FIXME: Do even more filtering by only permitting
2024 * certain IP's. The problem is that we don't know
2025 * how to do this properly for all possible clients...
2029 * Explicitely set the VP list to empty.
2033 if (fr_debug_flag) {
2034 char host_ipaddr[128];
2036 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2037 DEBUG("rad_recv: %s packet from host %s port %d",
2038 fr_packet_codes[packet->code],
2039 inet_ntop(packet->src_ipaddr.af,
2040 &packet->src_ipaddr.ipaddr,
2041 host_ipaddr, sizeof(host_ipaddr)),
2044 DEBUG("rad_recv: Packet from host %s port %d code=%d",
2045 inet_ntop(packet->src_ipaddr.af,
2046 &packet->src_ipaddr.ipaddr,
2047 host_ipaddr, sizeof(host_ipaddr)),
2051 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
2059 * Verify the Request/Response Authenticator
2060 * (and Message-Authenticator if present) of a packet.
2062 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2069 if (!packet || !packet->data) return -1;
2072 * Before we allocate memory for the attributes, do more
2075 ptr = packet->data + AUTH_HDR_LEN;
2076 length = packet->data_len - AUTH_HDR_LEN;
2077 while (length > 0) {
2078 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2079 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2084 default: /* don't do anything. */
2088 * Note that more than one Message-Authenticator
2089 * attribute is invalid.
2091 case PW_MESSAGE_AUTHENTICATOR:
2092 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2093 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2095 switch (packet->code) {
2099 case PW_ACCOUNTING_RESPONSE:
2101 (original->code == PW_STATUS_SERVER)) {
2105 case PW_ACCOUNTING_REQUEST:
2106 case PW_DISCONNECT_REQUEST:
2107 case PW_COA_REQUEST:
2108 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2112 case PW_AUTHENTICATION_ACK:
2113 case PW_AUTHENTICATION_REJECT:
2114 case PW_ACCESS_CHALLENGE:
2115 case PW_DISCONNECT_ACK:
2116 case PW_DISCONNECT_NAK:
2120 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2123 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2127 fr_hmac_md5(packet->data, packet->data_len,
2128 (const uint8_t *) secret, strlen(secret),
2130 if (rad_digest_cmp(calc_auth_vector, msg_auth_vector,
2131 sizeof(calc_auth_vector)) != 0) {
2133 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2134 inet_ntop(packet->src_ipaddr.af,
2135 &packet->src_ipaddr.ipaddr,
2136 buffer, sizeof(buffer)));
2137 /* Silently drop packet, according to RFC 3579 */
2139 } /* else the message authenticator was good */
2142 * Reinitialize Authenticators.
2144 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2145 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2147 } /* switch over the attributes */
2151 } /* loop over the packet, sanity checking the attributes */
2154 * It looks like a RADIUS packet, but we don't know what it is
2155 * so can't validate the authenticators.
2157 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2159 fr_strerror_printf("Received Unknown packet code %d "
2160 "from client %s port %d: Cannot validate Request/Response Authenticator.",
2162 inet_ntop(packet->src_ipaddr.af,
2163 &packet->src_ipaddr.ipaddr,
2164 buffer, sizeof(buffer)),
2170 * Calculate and/or verify Request or Response Authenticator.
2172 switch(packet->code) {
2176 case PW_AUTHENTICATION_REQUEST:
2177 case PW_STATUS_SERVER:
2179 * The authentication vector is random
2180 * nonsense, invented by the client.
2184 case PW_COA_REQUEST:
2185 case PW_DISCONNECT_REQUEST:
2186 case PW_ACCOUNTING_REQUEST:
2187 if (calc_acctdigest(packet, secret) > 1) {
2188 fr_strerror_printf("Received %s packet "
2189 "from client %s with invalid Request Authenticator! (Shared secret is incorrect.)",
2190 fr_packet_codes[packet->code],
2191 inet_ntop(packet->src_ipaddr.af,
2192 &packet->src_ipaddr.ipaddr,
2193 buffer, sizeof(buffer)));
2198 /* Verify the reply digest */
2199 case PW_AUTHENTICATION_ACK:
2200 case PW_AUTHENTICATION_REJECT:
2201 case PW_ACCESS_CHALLENGE:
2202 case PW_ACCOUNTING_RESPONSE:
2203 case PW_DISCONNECT_ACK:
2204 case PW_DISCONNECT_NAK:
2207 rcode = calc_replydigest(packet, original, secret);
2209 fr_strerror_printf("Received %s packet "
2210 "from home server %s port %d with invalid Response Authenticator! (Shared secret is incorrect.)",
2211 fr_packet_codes[packet->code],
2212 inet_ntop(packet->src_ipaddr.af,
2213 &packet->src_ipaddr.ipaddr,
2214 buffer, sizeof(buffer)),
2221 fr_strerror_printf("Received Unknown packet code %d "
2222 "from client %s port %d: Cannot validate Request/Response Authenticator",
2224 inet_ntop(packet->src_ipaddr.af,
2225 &packet->src_ipaddr.ipaddr,
2226 buffer, sizeof(buffer)),
2235 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2236 const RADIUS_PACKET *original,
2238 unsigned int attribute, size_t length,
2239 const uint8_t *data, VALUE_PAIR *vp)
2244 * If length is greater than 253, something is SERIOUSLY
2247 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2249 vp->length = length;
2250 vp->operator = T_OP_EQ;
2256 if (vp->flags.has_tag) {
2257 if (TAG_VALID(data[0]) ||
2258 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2260 * Tunnel passwords REQUIRE a tag, even
2261 * if don't have a valid tag.
2263 vp->flags.tag = data[0];
2265 if ((vp->type == PW_TYPE_STRING) ||
2266 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2271 * Copy the data to be decrypted
2273 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2274 vp->length -= offset;
2277 * Decrypt the attribute.
2279 if (secret) switch (vp->flags.encrypt) {
2283 case FLAG_ENCRYPT_USER_PASSWORD:
2285 rad_pwdecode((char *)vp->vp_strvalue,
2289 rad_pwdecode((char *)vp->vp_strvalue,
2293 if (vp->attribute == PW_USER_PASSWORD) {
2294 vp->length = strlen(vp->vp_strvalue);
2299 * Tunnel-Password's may go ONLY
2300 * in response packets.
2302 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2303 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length, secret,
2304 original ? original->vector : nullvector) < 0)
2309 * Ascend-Send-Secret
2310 * Ascend-Receive-Secret
2312 case FLAG_ENCRYPT_ASCEND_SECRET:
2316 uint8_t my_digest[AUTH_VECTOR_LEN];
2319 secret_len = length;
2320 if (secret_len > AUTH_VECTOR_LEN) secret_len = AUTH_VECTOR_LEN;
2322 make_secret(my_digest,
2324 secret, data, secret_len);
2325 memcpy(vp->vp_strvalue, my_digest,
2327 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2328 vp->length = strlen(vp->vp_strvalue);
2334 } /* switch over encryption flags */
2338 case PW_TYPE_STRING:
2339 case PW_TYPE_OCTETS:
2340 case PW_TYPE_ABINARY:
2341 /* nothing more to do */
2345 if (vp->length != 1) goto raw;
2347 vp->vp_integer = vp->vp_octets[0];
2352 if (vp->length != 2) goto raw;
2354 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2357 case PW_TYPE_INTEGER:
2358 if (vp->length != 4) goto raw;
2360 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2361 vp->vp_integer = ntohl(vp->vp_integer);
2363 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2366 * Try to get named VALUEs
2370 dval = dict_valbyattr(vp->attribute,
2373 strlcpy(vp->vp_strvalue,
2375 sizeof(vp->vp_strvalue));
2381 if (vp->length != 4) goto raw;
2383 memcpy(&vp->vp_date, vp->vp_octets, 4);
2384 vp->vp_date = ntohl(vp->vp_date);
2388 case PW_TYPE_IPADDR:
2389 if (vp->length != 4) goto raw;
2391 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2395 * IPv6 interface ID is 8 octets long.
2398 if (vp->length != 8) goto raw;
2399 /* vp->vp_ifid == vp->vp_octets */
2403 * IPv6 addresses are 16 octets long
2405 case PW_TYPE_IPV6ADDR:
2406 if (vp->length != 16) goto raw;
2407 /* vp->vp_ipv6addr == vp->vp_octets */
2411 * IPv6 prefixes are 2 to 18 octets long.
2413 * RFC 3162: The first octet is unused.
2414 * The second is the length of the prefix
2415 * the rest are the prefix data.
2417 * The prefix length can have value 0 to 128.
2419 case PW_TYPE_IPV6PREFIX:
2420 if (vp->length < 2 || vp->length > 18) goto raw;
2421 if (vp->vp_octets[1] > 128) goto raw;
2424 * FIXME: double-check that
2425 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2427 if (vp->length < 18) {
2428 memset(vp->vp_octets + vp->length, 0,
2433 case PW_TYPE_SIGNED:
2434 if (vp->length != 4) goto raw;
2437 * Overload vp_integer for ntohl, which takes
2438 * uint32_t, not int32_t
2440 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2441 vp->vp_integer = ntohl(vp->vp_integer);
2442 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2446 vp->length = length;
2447 vp->vp_tlv = malloc(length);
2450 fr_strerror_printf("No memory");
2453 memcpy(vp->vp_tlv, data, length);
2456 case PW_TYPE_COMBO_IP:
2457 if (vp->length == 4) {
2458 vp->type = PW_TYPE_IPADDR;
2459 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2462 } else if (vp->length == 16) {
2463 vp->type = PW_TYPE_IPV6ADDR;
2464 /* vp->vp_ipv6addr == vp->vp_octets */
2473 * Change the name to show the user that the
2474 * attribute is not of the correct format.
2479 vp2 = pairalloc(NULL);
2488 * This sets "vp->flags" appropriately,
2491 if (!paircreate_raw(attribute, PW_TYPE_OCTETS, vp)) {
2495 vp->length = length;
2496 memcpy(vp->vp_octets, data, length);
2504 static void rad_sortvp(VALUE_PAIR **head)
2507 VALUE_PAIR *vp, **tail;
2510 * Walk over the VP's, sorting them in order. Did I
2511 * mention that I hate WiMAX continuations?
2513 * And bubble sort! WTF is up with that?
2520 if (!vp->next) break;
2522 if (vp->attribute > vp->next->attribute) {
2524 vp->next = (*tail)->next;
2535 * Walk the packet, looking for continuations of this attribute.
2537 * This is (worst-case) O(N^2) in the number of RADIUS
2538 * attributes. That happens only when perverse clients create
2539 * continued attributes, AND separate the fragmented portions
2540 * with a lot of other attributes.
2542 * Sane clients should put the fragments next to each other, in
2543 * which case this is O(N), in the number of fragments.
2545 static uint8_t *rad_coalesce(unsigned int attribute, size_t length,
2547 size_t packet_length, size_t *ptlv_length)
2551 size_t tlv_length = length;
2552 uint8_t *ptr, *tlv, *tlv_data;
2554 for (ptr = data + length;
2555 ptr < (data + packet_length);
2557 if ((ptr + 2) > (data + length)) return NULL;
2559 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2560 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2561 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2565 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2566 lvalue = ntohl(lvalue);
2568 lvalue |= ptr[2 + 4]; /* add in VSA number */
2569 if (lvalue != attribute) continue;
2572 * If the vendor-length is too small, it's badly
2573 * formed, so we stop.
2575 if ((ptr[2 + 4 + 1]) < 3) return NULL;
2578 * If it overflows the packet, it's bad.
2580 if ((ptr + ptr[2 + 4 + 1]) > (data + packet_length)) {
2584 tlv_length += ptr[2 + 4 + 1] - 3;
2585 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2588 tlv = tlv_data = malloc(tlv_length);
2589 if (!tlv_data) return NULL;
2591 memcpy(tlv, data, length);
2595 * Now we walk the list again, copying the data over to
2596 * our newly created memory.
2598 for (ptr = data + length;
2599 ptr < (data + packet_length);
2603 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2604 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2605 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2609 memcpy(&lvalue, ptr + 2, 4);
2610 lvalue = ntohl(lvalue);
2612 lvalue |= ptr[2 + 4];
2613 if (lvalue != attribute) continue;
2616 * If the vendor-length is too small, it's badly
2617 * formed, so we stop.
2619 if ((ptr[2 + 4 + 1]) < 3) break;
2621 this_length = ptr[2 + 4 + 1] - 3;
2622 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2625 ptr[2 + 4] = 0; /* What a hack! */
2626 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2629 *ptlv_length = tlv_length;
2634 * Start at the *data* portion of a continued attribute. search
2635 * through the rest of the attributes to find a matching one, and
2636 * add it's contents to our contents.
2638 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2639 const RADIUS_PACKET *original,
2640 const char *secret, int attribute,
2641 int length, /* CANNOT be zero */
2642 uint8_t *data, size_t packet_length,
2643 int flag, DICT_ATTR *da)
2645 size_t tlv_length, left;
2648 VALUE_PAIR *vp, *head, **tail;
2651 * Ensure we have data that hasn't been split across
2652 * multiple attributes.
2655 tlv_data = rad_coalesce(attribute, length,
2656 data, packet_length, &tlv_length);
2657 if (!tlv_data) return NULL;
2660 tlv_length = length;
2664 * Non-TLV types cannot be continued across multiple
2665 * attributes. This is true even of keys that are
2666 * encrypted with the tunnel-password method. The spec
2667 * says that they can be continued... but also that the
2668 * keys are 160 bits, which means that they CANNOT be
2671 * Note that we don't check "flag" here. The calling
2674 if (!da || (da->type != PW_TYPE_TLV)) {
2676 if (tlv_data == data) { /* true if we had 'goto' */
2677 tlv_data = malloc(tlv_length);
2678 if (!tlv_data) return NULL;
2679 memcpy(tlv_data, data, tlv_length);
2682 vp = paircreate(attribute, PW_TYPE_OCTETS);
2688 vp->type = PW_TYPE_TLV;
2689 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2690 vp->flags.has_tag = 0;
2691 vp->flags.is_tlv = 0;
2692 vp->vp_tlv = tlv_data;
2693 vp->length = tlv_length;
2695 } /* else it WAS a TLV, go decode the sub-tlv's */
2698 * Now (sigh) we walk over the TLV, seeing if it is
2702 for (ptr = tlv_data;
2703 ptr != (tlv_data + tlv_length);
2708 goto not_well_formed;
2714 * Now we walk over the TLV *again*, creating sub-tlv's.
2719 for (ptr = tlv_data;
2720 ptr != (tlv_data + tlv_length);
2722 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2725 goto not_well_formed;
2728 vp = data2vp(packet, original, secret,
2729 ptr[0], ptr[1] - 2, ptr + 2, vp);
2730 if (!vp) { /* called frees vp */
2732 goto not_well_formed;
2740 * TLV's MAY be continued, but sometimes they're not.
2742 if (tlv_data != data) free(tlv_data);
2744 if (head && head->next) rad_sortvp(&head);
2751 * Parse a RADIUS attribute into a data structure.
2753 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2754 const char *secret, int attribute, int length,
2755 const uint8_t *data)
2759 vp = paircreate(attribute, PW_TYPE_OCTETS);
2760 if (!vp) return NULL;
2762 return data2vp(packet, original, secret, attribute, length, data, vp);
2766 * Converts vp_data to network byte order
2768 * -1 on error, or the length of the value
2770 ssize_t rad_vp2data(const VALUE_PAIR *vp, uint8_t *out, size_t outlen)
2777 fr_strerror_printf("ERROR: rad_vp2data buffer passed too small");
2782 case PW_TYPE_STRING:
2783 case PW_TYPE_OCTETS:
2785 case PW_TYPE_IPADDR:
2786 case PW_TYPE_IPV6ADDR:
2787 case PW_TYPE_IPV6PREFIX:
2788 case PW_TYPE_ABINARY:
2790 memcpy(out, vp->vp_octets, len);
2793 out[0] = vp->vp_integer & 0xff;
2797 out[0] = (vp->vp_integer >> 8) & 0xff;
2798 out[1] = vp->vp_integer & 0xff;
2801 case PW_TYPE_INTEGER:
2802 lvalue = htonl(vp->vp_integer);
2803 memcpy(out, &lvalue, sizeof(lvalue));
2807 lvalue = htonl(vp->vp_date);
2808 memcpy(out, &lvalue, sizeof(lvalue));
2811 case PW_TYPE_SIGNED:
2815 slvalue = htonl(vp->vp_signed);
2816 memcpy(out, &slvalue, sizeof(slvalue));
2819 /* unknown type: ignore it */
2821 fr_strerror_printf("ERROR: Unknown attribute type %d",
2830 * Calculate/check digest, and decode radius attributes.
2832 * -1 on decoding error
2835 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2839 uint32_t vendorcode;
2842 uint8_t *ptr, *vsa_ptr;
2847 radius_packet_t *hdr;
2848 int vsa_tlen, vsa_llen, vsa_offset;
2849 DICT_VENDOR *dv = NULL;
2850 int num_attributes = 0;
2853 * Extract attribute-value pairs
2855 hdr = (radius_packet_t *)packet->data;
2857 packet_length = packet->data_len - AUTH_HDR_LEN;
2860 * There may be VP's already in the packet. Don't
2863 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2869 vsa_tlen = vsa_llen = 1;
2873 * We have to read at least two bytes.
2875 * rad_recv() above ensures that this is OK.
2877 while (packet_length > 0) {
2882 * Normal attribute, handle it like normal.
2884 if (vendorcode == 0) {
2886 * No room to read attr/length,
2887 * or bad attribute, or attribute is
2888 * too short, or attribute is too long,
2889 * stop processing the packet.
2891 if ((packet_length < 2) ||
2892 (ptr[0] == 0) || (ptr[1] < 2) ||
2893 (ptr[1] > packet_length)) break;
2901 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2904 * No vendor code, or ONLY vendor code.
2906 if (attrlen <= 4) goto create_pair;
2912 * Handle Vendor-Specific
2914 if (vendorlen == 0) {
2920 * attrlen was checked above.
2922 memcpy(&lvalue, ptr, 4);
2923 myvendor = ntohl(lvalue);
2926 * Zero isn't allowed.
2928 if (myvendor == 0) goto create_pair;
2931 * This is an implementation issue.
2932 * We currently pack vendor into the upper
2933 * 16 bits of a 32-bit attribute number,
2934 * so we can't handle vendor numbers larger
2937 if (myvendor > 65535) goto create_pair;
2939 vsa_tlen = vsa_llen = 1;
2941 dv = dict_vendorbyvalue(myvendor);
2943 vsa_tlen = dv->type;
2944 vsa_llen = dv->length;
2945 if (dv->flags) vsa_offset = 1;
2949 * Sweep through the list of VSA's,
2950 * seeing if they exactly fill the
2951 * outer Vendor-Specific attribute.
2953 * If not, create a raw Vendor-Specific.
2956 sublen = attrlen - 4;
2959 * See if we can parse it.
2965 * Not enough room for one more
2968 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2971 * Ensure that the attribute number
2980 myattr = (subptr[0] << 8) | subptr[1];
2984 if ((subptr[0] != 0) ||
2985 (subptr[1] != 0)) goto create_pair;
2987 myattr = (subptr[2] << 8) | subptr[3];
2991 * Our dictionary is broken.
2999 attribute = (myvendor << 16) | myattr;
3000 ptr += 4 + vsa_tlen;
3001 attrlen -= (4 + vsa_tlen);
3002 packet_length -= 4 + vsa_tlen;
3006 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
3009 if (subptr[vsa_tlen] > sublen)
3014 * Reserved bits MUST be
3018 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
3021 sublen -= subptr[vsa_tlen];
3022 subptr += subptr[vsa_tlen];
3026 if (subptr[vsa_tlen] != 0) goto create_pair;
3027 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
3029 if (subptr[vsa_tlen + 1] > sublen)
3031 sublen -= subptr[vsa_tlen + 1];
3032 subptr += subptr[vsa_tlen + 1];
3036 * Our dictionaries are
3042 } while (sublen > 0);
3044 vendorcode = myvendor;
3045 vendorlen = attrlen - 4;
3052 * attrlen is the length of this attribute.
3053 * total_len is the length of the encompassing
3062 attribute = (ptr[0] << 8) | ptr[1];
3065 default: /* can't hit this. */
3068 attribute |= (vendorcode << 16);
3074 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
3078 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
3081 default: /* can't hit this. */
3085 ptr += vsa_llen + vsa_offset;
3086 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
3087 if (vendorlen == 0) vendorcode = 0;
3088 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
3091 * Ignore VSAs that have no data.
3093 if (attrlen == 0) goto next;
3096 * WiMAX attributes of type 0 are ignored. They
3097 * are a secret flag to us that the attribute has
3098 * already been dealt with.
3100 if (attribute == 0x60b50000) goto next;
3105 da = dict_attrbyvalue(attribute);
3108 * If it's NOT continued, AND we know
3109 * about it, AND it's not a TLV, we can
3110 * create a normal pair.
3112 if (((vsa_ptr[2] & 0x80) == 0) &&
3113 da && (da->type != PW_TYPE_TLV)) goto create_pair;
3116 * Else it IS continued, or it's a TLV.
3117 * Go do a lot of work to find the stuff.
3119 pair = rad_continuation2vp(packet, original, secret,
3120 attribute, attrlen, ptr,
3122 ((vsa_ptr[2] & 0x80) != 0),
3128 * Create the attribute, setting the default type
3129 * to 'octets'. If the type in the dictionary
3130 * is different, then the dictionary type will
3131 * over-ride this one.
3133 * If the attribute has no data, then discard it.
3135 * Unless it's CUI. Damn you, CUI!
3139 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
3141 pair = rad_attr2vp(packet, original, secret,
3142 attribute, attrlen, ptr);
3144 pairfree(&packet->vps);
3145 fr_strerror_printf("out of memory");
3159 * VSA's may not have been counted properly in
3160 * rad_packet_ok() above, as it is hard to count
3161 * then without using the dictionary. We
3162 * therefore enforce the limits here, too.
3164 if ((fr_max_attributes > 0) &&
3165 (num_attributes > fr_max_attributes)) {
3166 char host_ipaddr[128];
3168 pairfree(&packet->vps);
3169 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3170 inet_ntop(packet->src_ipaddr.af,
3171 &packet->src_ipaddr.ipaddr,
3172 host_ipaddr, sizeof(host_ipaddr)),
3173 num_attributes, fr_max_attributes);
3179 packet_length -= attrlen;
3183 * Merge information from the outside world into our
3186 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3195 * We assume that the passwd buffer passed is big enough.
3196 * RFC2138 says the password is max 128 chars, so the size
3197 * of the passwd buffer must be at least 129 characters.
3198 * Preferably it's just MAX_STRING_LEN.
3200 * int *pwlen is updated to the new length of the encrypted
3201 * password - a multiple of 16 bytes.
3203 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3204 const uint8_t *vector)
3206 FR_MD5_CTX context, old;
3207 uint8_t digest[AUTH_VECTOR_LEN];
3208 int i, n, secretlen;
3212 * RFC maximum is 128 bytes.
3214 * If length is zero, pad it out with zeros.
3216 * If the length isn't aligned to 16 bytes,
3217 * zero out the extra data.
3221 if (len > 128) len = 128;
3224 memset(passwd, 0, AUTH_PASS_LEN);
3225 len = AUTH_PASS_LEN;
3226 } else if ((len % AUTH_PASS_LEN) != 0) {
3227 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3228 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3233 * Use the secret to setup the decryption digest
3235 secretlen = strlen(secret);
3237 fr_MD5Init(&context);
3238 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3239 old = context; /* save intermediate work */
3242 * Encrypt it in place. Don't bother checking
3243 * len, as we've ensured above that it's OK.
3245 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3247 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3248 fr_MD5Final(digest, &context);
3251 fr_MD5Update(&context,
3252 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3254 fr_MD5Final(digest, &context);
3257 for (i = 0; i < AUTH_PASS_LEN; i++) {
3258 passwd[i + n] ^= digest[i];
3268 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3269 const uint8_t *vector)
3271 FR_MD5_CTX context, old;
3272 uint8_t digest[AUTH_VECTOR_LEN];
3274 size_t n, secretlen;
3277 * The RFC's say that the maximum is 128.
3278 * The buffer we're putting it into above is 254, so
3279 * we don't need to do any length checking.
3281 if (pwlen > 128) pwlen = 128;
3286 if (pwlen == 0) goto done;
3289 * Use the secret to setup the decryption digest
3291 secretlen = strlen(secret);
3293 fr_MD5Init(&context);
3294 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3295 old = context; /* save intermediate work */
3298 * The inverse of the code above.
3300 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3302 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3303 fr_MD5Final(digest, &context);
3306 if (pwlen > AUTH_PASS_LEN) {
3307 fr_MD5Update(&context, (uint8_t *) passwd,
3311 fr_MD5Final(digest, &context);
3314 if (pwlen > (n + AUTH_PASS_LEN)) {
3315 fr_MD5Update(&context, (uint8_t *) passwd + n,
3320 for (i = 0; i < AUTH_PASS_LEN; i++) {
3321 passwd[i + n] ^= digest[i];
3326 passwd[pwlen] = '\0';
3327 return strlen(passwd);
3332 * Encode Tunnel-Password attributes when sending them out on the wire.
3334 * int *pwlen is updated to the new length of the encrypted
3335 * password - a multiple of 16 bytes.
3337 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3340 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3341 const uint8_t *vector)
3343 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3344 unsigned char digest[AUTH_VECTOR_LEN];
3346 int i, n, secretlen;
3351 if (len > 127) len = 127;
3354 * Shift the password 3 positions right to place a salt and original
3355 * length, tag will be added automatically on packet send
3357 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3361 * save original password length as first password character;
3368 * Generate salt. The RFC's say:
3370 * The high bit of salt[0] must be set, each salt in a
3371 * packet should be unique, and they should be random
3373 * So, we set the high bit, add in a counter, and then
3374 * add in some CSPRNG data. should be OK..
3376 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3377 (fr_rand() & 0x07));
3378 salt[1] = fr_rand();
3381 * Padd password to multiple of AUTH_PASS_LEN bytes.
3383 n = len % AUTH_PASS_LEN;
3385 n = AUTH_PASS_LEN - n;
3386 for (; n > 0; n--, len++)
3389 /* set new password length */
3393 * Use the secret to setup the decryption digest
3395 secretlen = strlen(secret);
3396 memcpy(buffer, secret, secretlen);
3398 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3400 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3401 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3402 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3404 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3405 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3408 for (i = 0; i < AUTH_PASS_LEN; i++) {
3409 passwd[i + n2] ^= digest[i];
3417 * Decode Tunnel-Password encrypted attributes.
3419 * Defined in RFC-2868, this uses a two char SALT along with the
3420 * initial intermediate value, to differentiate it from the
3423 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3424 const uint8_t *vector)
3426 FR_MD5_CTX context, old;
3427 uint8_t digest[AUTH_VECTOR_LEN];
3429 size_t i, n, encrypted_len, reallen;
3431 encrypted_len = *pwlen;
3434 * We need at least a salt.
3436 if (encrypted_len < 2) {
3437 fr_strerror_printf("tunnel password is too short");
3442 * There's a salt, but no password. Or, there's a salt
3443 * and a 'data_len' octet. It's wrong, but at least we
3444 * can figure out what it means: the password is empty.
3446 * Note that this means we ignore the 'data_len' field,
3447 * if the attribute length tells us that there's no
3448 * more data. So the 'data_len' field may be wrong,
3451 if (encrypted_len <= 3) {
3457 encrypted_len -= 2; /* discount the salt */
3460 * Use the secret to setup the decryption digest
3462 secretlen = strlen(secret);
3464 fr_MD5Init(&context);
3465 fr_MD5Update(&context, (uint8_t const *) secret, secretlen);
3466 old = context; /* save intermediate work */
3469 * Set up the initial key:
3471 * b(1) = MD5(secret + vector + salt)
3473 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3474 fr_MD5Update(&context, passwd, 2);
3477 for (n = 0; n < encrypted_len; n += AUTH_PASS_LEN) {
3479 size_t block_len = AUTH_PASS_LEN;
3482 * Ensure we don't overflow the input on MD5
3484 if ((n + 2 + AUTH_PASS_LEN) > *pwlen) {
3485 block_len = *pwlen - n - 2;
3491 fr_MD5Final(digest, &context);
3496 * A quick check: decrypt the first octet
3497 * of the password, which is the
3498 * 'data_len' field. Ensure it's sane.
3500 reallen = passwd[2] ^ digest[0];
3501 if (reallen > encrypted_len) {
3502 fr_strerror_printf("tunnel password is too long for the attribute");
3506 fr_MD5Update(&context, passwd + 2, block_len);
3511 fr_MD5Final(digest, &context);
3514 fr_MD5Update(&context, passwd + n + 2, block_len);
3517 for (i = base; i < block_len; i++) {
3518 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3523 passwd[reallen] = 0;
3529 * Encode a CHAP password
3531 * FIXME: might not work with Ascend because
3532 * we use vp->length, and Ascend gear likes
3533 * to send an extra '\0' in the string!
3535 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3536 VALUE_PAIR *password)
3540 uint8_t string[MAX_STRING_LEN * 2 + 1];
3541 VALUE_PAIR *challenge;
3544 * Sanity check the input parameters
3546 if ((packet == NULL) || (password == NULL)) {
3551 * Note that the password VP can be EITHER
3552 * a User-Password attribute (from a check-item list),
3553 * or a CHAP-Password attribute (the client asking
3554 * the library to encode it).
3562 memcpy(ptr, password->vp_strvalue, password->length);
3563 ptr += password->length;
3564 i += password->length;
3567 * Use Chap-Challenge pair if present,
3568 * Request Authenticator otherwise.
3570 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3572 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3573 i += challenge->length;
3575 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3576 i += AUTH_VECTOR_LEN;
3580 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3587 * Seed the random number generator.
3589 * May be called any number of times.
3591 void fr_rand_seed(const void *data, size_t size)
3596 * Ensure that the pool is initialized.
3598 if (!fr_rand_initialized) {
3601 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3603 fd = open("/dev/urandom", O_RDONLY);
3609 while (total < sizeof(fr_rand_pool.randrsl)) {
3610 this = read(fd, fr_rand_pool.randrsl,
3611 sizeof(fr_rand_pool.randrsl) - total);
3612 if ((this < 0) && (errno != EINTR)) break;
3613 if (this > 0) total += this;
3617 fr_rand_pool.randrsl[0] = fd;
3618 fr_rand_pool.randrsl[1] = time(NULL);
3619 fr_rand_pool.randrsl[2] = errno;
3622 fr_randinit(&fr_rand_pool, 1);
3623 fr_rand_pool.randcnt = 0;
3624 fr_rand_initialized = 1;
3630 * Hash the user data
3633 if (!hash) hash = fr_rand();
3634 hash = fr_hash_update(data, size, hash);
3636 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3641 * Return a 32-bit random number.
3643 uint32_t fr_rand(void)
3648 * Ensure that the pool is initialized.
3650 if (!fr_rand_initialized) {
3651 fr_rand_seed(NULL, 0);
3654 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3655 if (fr_rand_pool.randcnt >= 256) {
3656 fr_rand_pool.randcnt = 0;
3657 fr_isaac(&fr_rand_pool);
3665 * Allocate a new RADIUS_PACKET
3667 RADIUS_PACKET *rad_alloc(int newvector)
3671 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3672 fr_strerror_printf("out of memory");
3675 memset(rp, 0, sizeof(*rp));
3681 uint32_t hash, base;
3684 * Don't expose the actual contents of the random
3688 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3689 hash = fr_rand() ^ base;
3690 memcpy(rp->vector + i, &hash, sizeof(hash));
3693 fr_rand(); /* stir the pool again */
3698 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3700 RADIUS_PACKET *reply;
3702 if (!packet) return NULL;
3704 reply = rad_alloc(0);
3705 if (!reply) return NULL;
3708 * Initialize the fields from the request.
3710 reply->sockfd = packet->sockfd;
3711 reply->dst_ipaddr = packet->src_ipaddr;
3712 reply->src_ipaddr = packet->dst_ipaddr;
3713 reply->dst_port = packet->src_port;
3714 reply->src_port = packet->dst_port;
3715 reply->id = packet->id;
3716 reply->code = 0; /* UNKNOWN code */
3717 memcpy(reply->vector, packet->vector,
3718 sizeof(reply->vector));
3721 reply->data_len = 0;
3728 * Free a RADIUS_PACKET
3730 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3732 RADIUS_PACKET *radius_packet;
3734 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3735 radius_packet = *radius_packet_ptr;
3737 free(radius_packet->data);
3739 pairfree(&radius_packet->vps);
3741 free(radius_packet);
3743 *radius_packet_ptr = NULL;