2 * radius.c Functions to send/receive radius packets.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000-2003,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/libradius.h>
27 #include <freeradius-devel/md5.h>
33 #include <freeradius-devel/udpfromto.h>
41 * The RFC says 4096 octets max, and most packets are less than 256.
43 #define MAX_PACKET_LEN 4096
46 * The maximum number of attributes which we allow in an incoming
47 * request. If there are more attributes than this, the request
50 * This helps to minimize the potential for a DoS, when an
51 * attacker spoofs Access-Request packets, which don't have a
52 * Message-Authenticator attribute. This means that the packet
53 * is unsigned, and the attacker can use resources on the server,
54 * even if the end request is rejected.
56 int fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
59 typedef struct radius_packet_t {
63 uint8_t vector[AUTH_VECTOR_LEN];
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
77 "Accounting-Response",
93 "Resource-Free-Request",
94 "Resource-Free-Response",
95 "Resource-Query-Request",
96 "Resource-Query-Response",
97 "Alternate-Resource-Reclaim-Request",
99 "NAS-Reboot-Response",
112 "Disconnect-Request",
122 "IP-Address-Allocate",
127 void fr_printf_log(const char *fmt, ...)
132 if ((fr_debug_flag == 0) || !fr_log_fp) {
137 vfprintf(fr_log_fp, fmt, ap);
143 static void print_hex(RADIUS_PACKET *packet)
147 if (!packet->data) return;
149 printf(" Code:\t\t%u\n", packet->data[0]);
150 printf(" Id:\t\t%u\n", packet->data[1]);
151 printf(" Length:\t%u\n", ((packet->data[2] << 8) |
153 printf(" Vector:\t");
154 for (i = 4; i < 20; i++) {
155 printf("%02x", packet->data[i]);
159 if (packet->data_len > 20) {
164 total = packet->data_len - 20;
165 ptr = packet->data + 20;
171 if (total < 2) { /* too short */
172 printf("%02x\n", *ptr);
176 if (ptr[1] > total) { /* too long */
177 for (i = 0; i < total; i++) {
178 printf("%02x ", ptr[i]);
183 printf("%02x %02x ", ptr[0], ptr[1]);
184 attrlen = ptr[1] - 2;
188 for (i = 0; i < attrlen; i++) {
189 if ((i > 0) && ((i & 0x0f) == 0x00))
191 printf("%02x ", ptr[i]);
192 if ((i & 0x0f) == 0x0f) printf("\n");
195 if ((attrlen & 0x0f) != 0x00) printf("\n");
206 * Wrapper for sendto which handles sendfromto, IPv6, and all
207 * possible combinations.
209 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
210 fr_ipaddr_t *src_ipaddr, int src_port,
211 fr_ipaddr_t *dst_ipaddr, int dst_port)
213 struct sockaddr_storage dst;
214 socklen_t sizeof_dst;
216 #ifdef WITH_UDPFROMTO
217 struct sockaddr_storage src;
218 socklen_t sizeof_src;
220 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
222 src_port = src_port; /* -Wunused */
225 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
229 #ifdef WITH_UDPFROMTO
231 * Only IPv4 is supported for udpfromto.
233 * And if they don't specify a source IP address, don't
236 if ((dst_ipaddr->af == AF_INET) ||
237 (src_ipaddr->af != AF_UNSPEC)) {
238 return sendfromto(sockfd, data, data_len, flags,
239 (struct sockaddr *)&src, sizeof_src,
240 (struct sockaddr *)&dst, sizeof_dst);
243 src_ipaddr = src_ipaddr; /* -Wunused */
247 * No udpfromto, OR an IPv6 socket, fail gracefully.
249 return sendto(sockfd, data, data_len, flags,
250 (struct sockaddr *) &dst, sizeof_dst);
254 void rad_recv_discard(int sockfd)
257 struct sockaddr_storage src;
258 socklen_t sizeof_src = sizeof(src);
260 recvfrom(sockfd, header, sizeof(header), 0,
261 (struct sockaddr *)&src, &sizeof_src);
265 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
268 ssize_t data_len, packet_len;
270 struct sockaddr_storage src;
271 socklen_t sizeof_src = sizeof(src);
273 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
274 (struct sockaddr *)&src, &sizeof_src);
276 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
281 * Too little data is available, discard the packet.
284 recvfrom(sockfd, header, sizeof(header), 0,
285 (struct sockaddr *)&src, &sizeof_src);
288 } else { /* we got 4 bytes of data. */
290 * See how long the packet says it is.
292 packet_len = (header[2] * 256) + header[3];
295 * The length in the packet says it's less than
296 * a RADIUS header length: discard it.
298 if (packet_len < AUTH_HDR_LEN) {
299 recvfrom(sockfd, header, sizeof(header), 0,
300 (struct sockaddr *)&src, &sizeof_src);
304 * Enforce RFC requirements, for sanity.
305 * Anything after 4k will be discarded.
307 } else if (packet_len > MAX_PACKET_LEN) {
308 recvfrom(sockfd, header, sizeof(header), 0,
309 (struct sockaddr *)&src, &sizeof_src);
315 * Convert AF. If unknown, discard packet.
317 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
318 recvfrom(sockfd, header, sizeof(header), 0,
319 (struct sockaddr *)&src, &sizeof_src);
326 * The packet says it's this long, but the actual UDP
327 * size could still be smaller.
334 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
335 * possible combinations.
337 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
338 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
339 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
341 struct sockaddr_storage src;
342 struct sockaddr_storage dst;
343 socklen_t sizeof_src = sizeof(src);
344 socklen_t sizeof_dst = sizeof(dst);
351 memset(&src, 0, sizeof_src);
352 memset(&dst, 0, sizeof_dst);
355 * Get address family, etc. first, so we know if we
356 * need to do udpfromto.
358 * FIXME: udpfromto also does this, but it's not
359 * a critical problem.
361 if (getsockname(sockfd, (struct sockaddr *)&dst,
362 &sizeof_dst) < 0) return -1;
365 * Read the length of the packet, from the packet.
366 * This lets us allocate the buffer to use for
367 * reading the rest of the packet.
369 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
370 (struct sockaddr *)&src, &sizeof_src);
372 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
377 * Too little data is available, discard the packet.
380 recvfrom(sockfd, header, sizeof(header), flags,
381 (struct sockaddr *)&src, &sizeof_src);
384 } else { /* we got 4 bytes of data. */
386 * See how long the packet says it is.
388 len = (header[2] * 256) + header[3];
391 * The length in the packet says it's less than
392 * a RADIUS header length: discard it.
394 if (len < AUTH_HDR_LEN) {
395 recvfrom(sockfd, header, sizeof(header), flags,
396 (struct sockaddr *)&src, &sizeof_src);
400 * Enforce RFC requirements, for sanity.
401 * Anything after 4k will be discarded.
403 } else if (len > MAX_PACKET_LEN) {
404 recvfrom(sockfd, header, sizeof(header), flags,
405 (struct sockaddr *)&src, &sizeof_src);
414 * Receive the packet. The OS will discard any data in the
415 * packet after "len" bytes.
417 #ifdef WITH_UDPFROMTO
418 if (dst.ss_family == AF_INET) {
419 data_len = recvfromto(sockfd, buf, len, flags,
420 (struct sockaddr *)&src, &sizeof_src,
421 (struct sockaddr *)&dst, &sizeof_dst);
425 * No udpfromto, OR an IPv6 socket. Fail gracefully.
427 data_len = recvfrom(sockfd, buf, len, flags,
428 (struct sockaddr *)&src, &sizeof_src);
434 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
436 return -1; /* Unknown address family, Die Die Die! */
440 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
444 * Different address families should never happen.
446 if (src.ss_family != dst.ss_family) {
452 * Tell the caller about the data
460 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
461 /*************************************************************************
463 * Function: make_secret
465 * Purpose: Build an encrypted secret value to return in a reply
466 * packet. The secret is hidden by xoring with a MD5 digest
467 * created from the shared secret and the authentication
468 * vector. We put them into MD5 in the reverse order from
469 * that used when encrypting passwords to RADIUS.
471 *************************************************************************/
472 static void make_secret(uint8_t *digest, const uint8_t *vector,
473 const char *secret, const uint8_t *value)
478 fr_MD5Init(&context);
479 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
480 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
481 fr_MD5Final(digest, &context);
483 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
484 digest[i] ^= value[i];
488 #define MAX_PASS_LEN (128)
489 static void make_passwd(uint8_t *output, size_t *outlen,
490 const uint8_t *input, size_t inlen,
491 const char *secret, const uint8_t *vector)
493 FR_MD5_CTX context, old;
494 uint8_t digest[AUTH_VECTOR_LEN];
495 uint8_t passwd[MAX_PASS_LEN];
500 * If the length is zero, round it up.
504 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
506 memcpy(passwd, input, len);
507 memset(passwd + len, 0, sizeof(passwd) - len);
513 else if ((len & 0x0f) != 0) {
519 fr_MD5Init(&context);
520 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
526 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
528 for (n = 0; n < len; n += AUTH_PASS_LEN) {
531 fr_MD5Update(&context,
532 passwd + n - AUTH_PASS_LEN,
536 fr_MD5Final(digest, &context);
537 for (i = 0; i < AUTH_PASS_LEN; i++) {
538 passwd[i + n] ^= digest[i];
542 memcpy(output, passwd, len);
545 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
546 const uint8_t *input, size_t inlen, size_t room,
547 const char *secret, const uint8_t *vector)
549 FR_MD5_CTX context, old;
550 uint8_t digest[AUTH_VECTOR_LEN];
551 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
558 if (room > 253) room = 253;
561 * Account for 2 bytes of the salt, and round the room
562 * available down to the nearest multiple of 16. Then,
563 * subtract one from that to account for the length byte,
564 * and the resulting number is the upper bound on the data
567 * We could short-cut this calculation just be forcing
568 * inlen to be no more than 239. It would work for all
569 * VSA's, as we don't pack multiple VSA's into one
572 * However, this calculation is more general, if a little
573 * complex. And it will work in the future for all possible
574 * kinds of weird attribute packing.
577 room -= (room & 0x0f);
580 if (inlen > room) inlen = room;
583 * Length of the encrypted data is password length plus
584 * one byte for the length of the password.
587 if ((len & 0x0f) != 0) {
591 *outlen = len + 2; /* account for the salt */
594 * Copy the password over.
596 memcpy(passwd + 3, input, inlen);
597 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
600 * Generate salt. The RFC's say:
602 * The high bit of salt[0] must be set, each salt in a
603 * packet should be unique, and they should be random
605 * So, we set the high bit, add in a counter, and then
606 * add in some CSPRNG data. should be OK..
608 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
610 passwd[1] = fr_rand();
611 passwd[2] = inlen; /* length of the password string */
613 fr_MD5Init(&context);
614 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
617 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
618 fr_MD5Update(&context, &passwd[0], 2);
620 for (n = 0; n < len; n += AUTH_PASS_LEN) {
623 fr_MD5Update(&context,
624 passwd + 2 + n - AUTH_PASS_LEN,
628 fr_MD5Final(digest, &context);
629 for (i = 0; i < AUTH_PASS_LEN; i++) {
630 passwd[i + 2 + n] ^= digest[i];
633 memcpy(output, passwd, len + 2);
637 * Returns the end of the data.
639 static uint8_t *vp2data(const RADIUS_PACKET *packet,
640 const RADIUS_PACKET *original,
641 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr,
650 * Set up the default sources for the data.
652 data = vp->vp_octets;
659 case PW_TYPE_IPV6ADDR:
660 case PW_TYPE_IPV6PREFIX:
661 case PW_TYPE_ABINARY:
662 /* nothing more to do */
666 len = 1; /* just in case */
667 array[0] = vp->vp_integer & 0xff;
672 len = 2; /* just in case */
673 array[0] = (vp->vp_integer >> 8) & 0xff;
674 array[1] = vp->vp_integer & 0xff;
678 case PW_TYPE_INTEGER:
679 len = 4; /* just in case */
680 lvalue = htonl(vp->vp_integer);
681 memcpy(array, &lvalue, sizeof(lvalue));
686 data = (const uint8_t *) &vp->vp_ipaddr;
687 len = 4; /* just in case */
691 * There are no tagged date attributes.
694 lvalue = htonl(vp->vp_date);
695 data = (const uint8_t *) &lvalue;
696 len = 4; /* just in case */
703 len = 4; /* just in case */
704 slvalue = htonl(vp->vp_signed);
705 memcpy(array, &slvalue, sizeof(slvalue));
712 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
717 default: /* unknown type: ignore it */
718 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
723 * Bound the data to the calling size
725 if (len > room) len = room;
728 * Encrypt the various password styles
730 * Attributes with encrypted values MUST be less than
733 switch (vp->flags.encrypt) {
734 case FLAG_ENCRYPT_USER_PASSWORD:
735 make_passwd(ptr, &len, data, len,
736 secret, packet->vector);
739 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
741 * Check if there's enough room. If there isn't,
742 * we discard the attribute.
744 * This is ONLY a problem if we have multiple VSA's
745 * in one Vendor-Specific, though.
747 if (room < 18) return ptr;
749 switch (packet->code) {
750 case PW_AUTHENTICATION_ACK:
751 case PW_AUTHENTICATION_REJECT:
752 case PW_ACCESS_CHALLENGE:
755 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
758 make_tunnel_passwd(ptr, &len, data, len, room,
759 secret, original->vector);
761 case PW_ACCOUNTING_REQUEST:
762 case PW_DISCONNECT_REQUEST:
764 make_tunnel_passwd(ptr, &len, data, len, room,
765 secret, packet->vector);
771 * The code above ensures that this attribute
774 case FLAG_ENCRYPT_ASCEND_SECRET:
775 make_secret(ptr, packet->vector, secret, data);
776 len = AUTH_VECTOR_LEN;
782 * Just copy the data over
784 memcpy(ptr, data, len);
786 } /* switch over encryption flags */
792 static VALUE_PAIR *rad_vp2tlv(VALUE_PAIR *vps)
796 unsigned int attribute;
798 VALUE_PAIR *vp, *tlv;
800 attribute = vps->attribute & 0xffff00ff;
801 maxattr = vps->attribute & 0x0ff;
803 tlv = paircreate(attribute, PW_TYPE_TLV);
804 if (!tlv) return NULL;
807 for (vp = vps; vp != NULL; vp = vp->next) {
809 * Group the attributes ONLY until we see a
812 if (!vp->flags.is_tlv ||
814 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
815 ((vp->attribute & 0xffff00ff) != attribute) ||
816 ((vp->attribute & 0x0000ff00) <= maxattr)) {
820 maxattr = vp->attribute & 0xff00;
821 tlv->length += vp->length + 2;
829 tlv->vp_tlv = malloc(tlv->length);
836 maxattr = vps->attribute & 0x0ff;
837 for (vp = vps; vp != NULL; vp = vp->next) {
838 if (!vp->flags.is_tlv ||
840 (vp->flags.encrypt != FLAG_ENCRYPT_NONE) ||
841 ((vp->attribute & 0xffff00ff) != attribute) ||
842 ((vp->attribute & 0x0000ff00) <= maxattr)) {
846 maxattr = vp->attribute & 0xff00;
847 end = vp2data(NULL, NULL, NULL, vp, ptr + 2,
848 tlv->vp_tlv + tlv->length - ptr);
850 vp->length = ptr - vp->vp_tlv;
851 return tlv; /* should be a more serious error... */
854 length = (end - ptr);
855 if (length > 255) return NULL;
858 * Pack the attribute.
860 ptr[0] = (vp->attribute & 0xff00) >> 8;
864 vp->flags.encoded = 1;
871 * Pack data without any encryption.
872 * start == start of RADIUS attribute
873 * ptr == continuation byte (i.e. one after length)
875 static int rad_vp2continuation(const VALUE_PAIR *vp, uint8_t *start,
879 size_t hsize = (ptr - start);
880 uint8_t *this = start;
885 * If it's too long and marked as encrypted, ignore it.
887 if (vp->flags.encrypt != FLAG_ENCRYPT_NONE) {
891 memcpy(header, start, hsize);
902 data = vp->vp_octets;
913 memcpy(this, header, hsize);
920 if (left > (254 - hsize)) {
928 memcpy(ptr, data, piece);
929 this[1] = hsize + piece + 1;
934 this[hsize - 1] = hsize - 6 + 1 + piece;
941 return (ptr - start);
946 * Parse a data structure into a RADIUS attribute.
948 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
949 const char *secret, const VALUE_PAIR *vp, uint8_t *start)
952 int len, total_length;
954 uint8_t *ptr, *length_ptr, *vsa_length_ptr, *tlv_length_ptr;
959 vendorcode = total_length = 0;
960 length_ptr = vsa_length_ptr = tlv_length_ptr = NULL;
963 * For interoperability, always put vendor attributes
964 * into their own VSA.
966 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
967 *(ptr++) = vp->attribute & 0xFF;
976 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
979 * This must be an RFC-format attribute. If it
980 * wasn't, then the "decode" function would have
981 * made a Vendor-Specific attribute (i.e. type
982 * 26), and we would have "vendorcode == 0" here.
986 vsa_llen = dv->length;
987 if (dv->flags) vsa_offset = 1;
991 * Build a VSA header.
993 *ptr++ = PW_VENDOR_SPECIFIC;
994 vsa_length_ptr = ptr;
996 lvalue = htonl(vendorcode);
997 memcpy(ptr, &lvalue, 4);
1003 ptr[0] = (vp->attribute & 0xFF);
1007 ptr[0] = ((vp->attribute >> 8) & 0xFF);
1008 ptr[1] = (vp->attribute & 0xFF);
1014 ptr[2] = ((vp->attribute >> 8) & 0xFF);
1015 ptr[3] = (vp->attribute & 0xFF);
1019 return 0; /* silently discard it */
1025 length_ptr = vsa_length_ptr;
1026 vsa_length_ptr = NULL;
1035 length_ptr = ptr + 1;
1039 return 0; /* silently discard it */
1044 * Allow for some continuation.
1048 * Allow TLV's to be encoded, if someone
1049 * manages to somehow encode the sub-tlv's.
1051 * FIXME: Keep track of room in the packet!
1053 if (vp->length > (((size_t) 254) - (ptr - start))) {
1054 return rad_vp2continuation(vp, start, ptr);
1061 * sub-TLV's can only be in one format.
1063 if (vp->flags.is_tlv) {
1064 *(ptr++) = (vp->attribute & 0xff00) >> 8;
1065 tlv_length_ptr = ptr;
1071 total_length += vsa_tlen + vsa_llen + vsa_offset;
1072 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1073 *length_ptr += vsa_tlen + vsa_llen + vsa_offset;
1077 * Insert tags for string attributes. They go BEFORE
1080 if (vp->flags.has_tag && (vp->type == PW_TYPE_STRING) &&
1081 (TAG_VALID(vp->flags.tag) ||
1082 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD))) {
1083 ptr[0] = vp->flags.tag;
1084 end = vp2data(packet, original, secret, vp, ptr + 1,
1087 end = vp2data(packet, original, secret, vp, ptr,
1090 if (!end) return -1;
1093 * Insert tags for integer attributes. They go at the START
1094 * of the integer, and over-write the first byte.
1096 if (vp->flags.has_tag && (vp->type == PW_TYPE_INTEGER)) {
1097 ptr[0] = vp->flags.tag;
1101 * RFC 2865 section 5 says that zero-length attributes
1104 * ... and the WiMAX forum ignores this... because of
1105 * one vendor. Don't they have anything better to do
1109 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
1114 * Update the various lengths.
1117 if (vsa_length_ptr) *vsa_length_ptr += len;
1118 if (tlv_length_ptr) *tlv_length_ptr += len;
1120 total_length += len;
1122 return total_length; /* of attribute */
1129 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1132 radius_packet_t *hdr;
1134 uint16_t total_length;
1138 char ip_buffer[128];
1141 * For simplicity in the following logic, we allow
1142 * the attributes to "overflow" the 4k maximum
1143 * RADIUS packet size, by one attribute.
1145 * It's uint32_t, for alignment purposes.
1147 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
1149 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1150 what = fr_packet_codes[packet->code];
1155 DEBUG("Sending %s of id %d to %s port %d\n",
1157 inet_ntop(packet->dst_ipaddr.af,
1158 &packet->dst_ipaddr.ipaddr,
1159 ip_buffer, sizeof(ip_buffer)),
1163 * Double-check some things based on packet code.
1165 switch (packet->code) {
1166 case PW_AUTHENTICATION_ACK:
1167 case PW_AUTHENTICATION_REJECT:
1168 case PW_ACCESS_CHALLENGE:
1170 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1176 * These packet vectors start off as all zero.
1178 case PW_ACCOUNTING_REQUEST:
1179 case PW_DISCONNECT_REQUEST:
1180 case PW_COA_REQUEST:
1181 memset(packet->vector, 0, sizeof(packet->vector));
1189 * Use memory on the stack, until we know how
1190 * large the packet will be.
1192 hdr = (radius_packet_t *) data;
1195 * Build standard header
1197 hdr->code = packet->code;
1198 hdr->id = packet->id;
1200 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1202 total_length = AUTH_HDR_LEN;
1205 * Load up the configuration values for the user
1211 * FIXME: Loop twice over the reply list. The first time,
1212 * calculate the total length of data. The second time,
1213 * allocate the memory, and fill in the VP's.
1215 * Hmm... this may be slower than just doing a small
1220 * Loop over the reply attributes for the packet.
1222 for (reply = packet->vps; reply; reply = reply->next) {
1224 * Ignore non-wire attributes
1226 if ((VENDOR(reply->attribute) == 0) &&
1227 ((reply->attribute & 0xFFFF) > 0xff)) {
1230 * Permit the admin to send BADLY formatted
1231 * attributes with a debug build.
1233 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1234 memcpy(ptr, reply->vp_octets, reply->length);
1235 len = reply->length;
1243 * Set the Message-Authenticator to the correct
1244 * length and initial value.
1246 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1247 reply->length = AUTH_VECTOR_LEN;
1248 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1251 * Cache the offset to the
1252 * Message-Authenticator
1254 packet->offset = total_length;
1258 * Print out ONLY the attributes which
1259 * we're sending over the wire, and print
1260 * them out BEFORE they're encrypted.
1265 * Print them in order, even if they were encoded
1269 if (reply->flags.encoded) goto next;
1271 if (reply->flags.is_tlv) {
1272 VALUE_PAIR *tlv = rad_vp2tlv(reply);
1274 tlv->next = reply->next;
1279 * The encoded flag MUST be set in reply!
1281 reply = reply->next;
1284 len = rad_vp2attr(packet, original, secret, reply, ptr);
1286 if (len < 0) return -1;
1289 * Check that the packet is no more than 4k in
1290 * size, AFTER writing the attribute past the 4k
1291 * boundary, but BEFORE deciding to increase the
1292 * size of the packet. Note that the 'data'
1293 * buffer, above, is one attribute longer than
1294 * necessary, in order to permit this overflow.
1296 if ((total_length + len) > MAX_PACKET_LEN) {
1302 total_length += len;
1303 } /* done looping over all attributes */
1306 * Fill in the rest of the fields, and copy the data over
1307 * from the local stack to the newly allocated memory.
1309 * Yes, all this 'memcpy' is slow, but it means
1310 * that we only allocate the minimum amount of
1311 * memory for a request.
1313 packet->data_len = total_length;
1314 packet->data = (uint8_t *) malloc(packet->data_len);
1315 if (!packet->data) {
1316 fr_strerror_printf("Out of memory");
1320 memcpy(packet->data, hdr, packet->data_len);
1321 hdr = (radius_packet_t *) packet->data;
1323 total_length = htons(total_length);
1324 memcpy(hdr->length, &total_length, sizeof(total_length));
1331 * Sign a previously encoded packet.
1333 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1336 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1339 * It wasn't assigned an Id, this is bad!
1341 if (packet->id < 0) {
1342 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1346 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1347 (packet->offset < 0)) {
1348 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1353 * If there's a Message-Authenticator, update it
1354 * now, BEFORE updating the authentication vector.
1356 if (packet->offset > 0) {
1357 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1359 switch (packet->code) {
1360 case PW_ACCOUNTING_REQUEST:
1361 case PW_ACCOUNTING_RESPONSE:
1362 case PW_DISCONNECT_REQUEST:
1363 case PW_DISCONNECT_ACK:
1364 case PW_DISCONNECT_NAK:
1365 case PW_COA_REQUEST:
1368 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1371 case PW_AUTHENTICATION_ACK:
1372 case PW_AUTHENTICATION_REJECT:
1373 case PW_ACCESS_CHALLENGE:
1375 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1378 memcpy(hdr->vector, original->vector,
1382 default: /* others have vector already set to zero */
1388 * Set the authentication vector to zero,
1389 * calculate the signature, and put it
1390 * into the Message-Authenticator
1393 fr_hmac_md5(packet->data, packet->data_len,
1394 (const uint8_t *) secret, strlen(secret),
1396 memcpy(packet->data + packet->offset + 2,
1397 calc_auth_vector, AUTH_VECTOR_LEN);
1400 * Copy the original request vector back
1401 * to the raw packet.
1403 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1407 * Switch over the packet code, deciding how to
1410 switch (packet->code) {
1412 * Request packets are not signed, bur
1413 * have a random authentication vector.
1415 case PW_AUTHENTICATION_REQUEST:
1416 case PW_STATUS_SERVER:
1420 * Reply packets are signed with the
1421 * authentication vector of the request.
1428 fr_MD5Init(&context);
1429 fr_MD5Update(&context, packet->data, packet->data_len);
1430 fr_MD5Update(&context, (const uint8_t *) secret,
1432 fr_MD5Final(digest, &context);
1434 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1435 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1438 }/* switch over packet codes */
1444 * Reply to the request. Also attach
1445 * reply attribute value pairs and any user message provided.
1447 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1452 char ip_buffer[128];
1455 * Maybe it's a fake packet. Don't send it.
1457 if (!packet || (packet->sockfd < 0)) {
1461 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1462 what = fr_packet_codes[packet->code];
1468 * First time through, allocate room for the packet
1470 if (!packet->data) {
1472 * Encode the packet.
1474 if (rad_encode(packet, original, secret) < 0) {
1479 * Re-sign it, including updating the
1480 * Message-Authenticator.
1482 if (rad_sign(packet, original, secret) < 0) {
1487 * If packet->data points to data, then we print out
1488 * the VP list again only for debugging.
1490 } else if (fr_debug_flag) {
1491 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1492 inet_ntop(packet->dst_ipaddr.af,
1493 &packet->dst_ipaddr.ipaddr,
1494 ip_buffer, sizeof(ip_buffer)),
1497 for (reply = packet->vps; reply; reply = reply->next) {
1498 if ((VENDOR(reply->attribute) == 0) &&
1499 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1505 * And send it on it's way.
1507 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1508 &packet->src_ipaddr, packet->src_port,
1509 &packet->dst_ipaddr, packet->dst_port);
1513 * Do a comparison of two authentication digests by comparing
1514 * the FULL digest. Otehrwise, the server can be subject to
1515 * timing attacks that allow attackers find a valid message
1518 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1520 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1525 for (i = 0; i < length; i++) {
1526 result |= a[i] ^ b[i];
1529 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1534 * Validates the requesting client NAS. Calculates the
1535 * signature based on the clients private key.
1537 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1539 uint8_t digest[AUTH_VECTOR_LEN];
1543 * Zero out the auth_vector in the received packet.
1544 * Then append the shared secret to the received packet,
1545 * and calculate the MD5 sum. This must be the same
1546 * as the original MD5 sum (packet->vector).
1548 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1551 * MD5(packet + secret);
1553 fr_MD5Init(&context);
1554 fr_MD5Update(&context, packet->data, packet->data_len);
1555 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1556 fr_MD5Final(digest, &context);
1559 * Return 0 if OK, 2 if not OK.
1561 if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1567 * Validates the requesting client NAS. Calculates the
1568 * signature based on the clients private key.
1570 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1573 uint8_t calc_digest[AUTH_VECTOR_LEN];
1579 if (original == NULL) {
1584 * Copy the original vector in place.
1586 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1589 * MD5(packet + secret);
1591 fr_MD5Init(&context);
1592 fr_MD5Update(&context, packet->data, packet->data_len);
1593 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1594 fr_MD5Final(calc_digest, &context);
1597 * Copy the packet's vector back to the packet.
1599 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1602 * Return 0 if OK, 2 if not OK.
1604 if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1610 * See if the data pointed to by PTR is a valid RADIUS packet.
1612 * packet is not 'const * const' because we may update data_len,
1613 * if there's more data in the UDP packet than in the RADIUS packet.
1615 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1620 radius_packet_t *hdr;
1621 char host_ipaddr[128];
1627 * Check for packets smaller than the packet header.
1629 * RFC 2865, Section 3., subsection 'length' says:
1631 * "The minimum length is 20 ..."
1633 if (packet->data_len < AUTH_HDR_LEN) {
1634 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1635 inet_ntop(packet->src_ipaddr.af,
1636 &packet->src_ipaddr.ipaddr,
1637 host_ipaddr, sizeof(host_ipaddr)),
1638 packet->data_len, AUTH_HDR_LEN);
1643 * RFC 2865, Section 3., subsection 'length' says:
1645 * " ... and maximum length is 4096."
1647 if (packet->data_len > MAX_PACKET_LEN) {
1648 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1649 inet_ntop(packet->src_ipaddr.af,
1650 &packet->src_ipaddr.ipaddr,
1651 host_ipaddr, sizeof(host_ipaddr)),
1652 packet->data_len, MAX_PACKET_LEN);
1657 * Check for packets with mismatched size.
1658 * i.e. We've received 128 bytes, and the packet header
1659 * says it's 256 bytes long.
1661 totallen = (packet->data[2] << 8) | packet->data[3];
1662 hdr = (radius_packet_t *)packet->data;
1665 * Code of 0 is not understood.
1666 * Code of 16 or greate is not understood.
1668 if ((hdr->code == 0) ||
1669 (hdr->code >= FR_MAX_PACKET_CODE)) {
1670 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1671 inet_ntop(packet->src_ipaddr.af,
1672 &packet->src_ipaddr.ipaddr,
1673 host_ipaddr, sizeof(host_ipaddr)),
1679 * Message-Authenticator is required in Status-Server
1680 * packets, otherwise they can be trivially forged.
1682 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1685 * It's also required if the caller asks for it.
1687 if (flags) require_ma = 1;
1690 * Repeat the length checks. This time, instead of
1691 * looking at the data we received, look at the value
1692 * of the 'length' field inside of the packet.
1694 * Check for packets smaller than the packet header.
1696 * RFC 2865, Section 3., subsection 'length' says:
1698 * "The minimum length is 20 ..."
1700 if (totallen < AUTH_HDR_LEN) {
1701 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1702 inet_ntop(packet->src_ipaddr.af,
1703 &packet->src_ipaddr.ipaddr,
1704 host_ipaddr, sizeof(host_ipaddr)),
1705 totallen, AUTH_HDR_LEN);
1710 * And again, for the value of the 'length' field.
1712 * RFC 2865, Section 3., subsection 'length' says:
1714 * " ... and maximum length is 4096."
1716 if (totallen > MAX_PACKET_LEN) {
1717 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1718 inet_ntop(packet->src_ipaddr.af,
1719 &packet->src_ipaddr.ipaddr,
1720 host_ipaddr, sizeof(host_ipaddr)),
1721 totallen, MAX_PACKET_LEN);
1726 * RFC 2865, Section 3., subsection 'length' says:
1728 * "If the packet is shorter than the Length field
1729 * indicates, it MUST be silently discarded."
1731 * i.e. No response to the NAS.
1733 if (packet->data_len < totallen) {
1734 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1735 inet_ntop(packet->src_ipaddr.af,
1736 &packet->src_ipaddr.ipaddr,
1737 host_ipaddr, sizeof(host_ipaddr)),
1738 packet->data_len, totallen);
1743 * RFC 2865, Section 3., subsection 'length' says:
1745 * "Octets outside the range of the Length field MUST be
1746 * treated as padding and ignored on reception."
1748 if (packet->data_len > totallen) {
1750 * We're shortening the packet below, but just
1751 * to be paranoid, zero out the extra data.
1753 memset(packet->data + totallen, 0, packet->data_len - totallen);
1754 packet->data_len = totallen;
1758 * Walk through the packet's attributes, ensuring that
1759 * they add up EXACTLY to the size of the packet.
1761 * If they don't, then the attributes either under-fill
1762 * or over-fill the packet. Any parsing of the packet
1763 * is impossible, and will result in unknown side effects.
1765 * This would ONLY happen with buggy RADIUS implementations,
1766 * or with an intentional attack. Either way, we do NOT want
1767 * to be vulnerable to this problem.
1770 count = totallen - AUTH_HDR_LEN;
1775 * Attribute number zero is NOT defined.
1778 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1779 inet_ntop(packet->src_ipaddr.af,
1780 &packet->src_ipaddr.ipaddr,
1781 host_ipaddr, sizeof(host_ipaddr)));
1786 * Attributes are at LEAST as long as the ID & length
1787 * fields. Anything shorter is an invalid attribute.
1790 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1791 inet_ntop(packet->src_ipaddr.af,
1792 &packet->src_ipaddr.ipaddr,
1793 host_ipaddr, sizeof(host_ipaddr)),
1799 * Sanity check the attributes for length.
1802 default: /* don't do anything by default */
1806 * If there's an EAP-Message, we require
1807 * a Message-Authenticator.
1809 case PW_EAP_MESSAGE:
1813 case PW_MESSAGE_AUTHENTICATOR:
1814 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1815 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1816 inet_ntop(packet->src_ipaddr.af,
1817 &packet->src_ipaddr.ipaddr,
1818 host_ipaddr, sizeof(host_ipaddr)),
1827 * FIXME: Look up the base 255 attributes in the
1828 * dictionary, and switch over their type. For
1829 * integer/date/ip, the attribute length SHOULD
1832 count -= attr[1]; /* grab the attribute length */
1834 num_attributes++; /* seen one more attribute */
1838 * If the attributes add up to a packet, it's allowed.
1840 * If not, we complain, and throw the packet away.
1843 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1844 inet_ntop(packet->src_ipaddr.af,
1845 &packet->src_ipaddr.ipaddr,
1846 host_ipaddr, sizeof(host_ipaddr)));
1851 * If we're configured to look for a maximum number of
1852 * attributes, and we've seen more than that maximum,
1853 * then throw the packet away, as a possible DoS.
1855 if ((fr_max_attributes > 0) &&
1856 (num_attributes > fr_max_attributes)) {
1857 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1858 inet_ntop(packet->src_ipaddr.af,
1859 &packet->src_ipaddr.ipaddr,
1860 host_ipaddr, sizeof(host_ipaddr)),
1861 num_attributes, fr_max_attributes);
1866 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1868 * A packet with an EAP-Message attribute MUST also have
1869 * a Message-Authenticator attribute.
1871 * A Message-Authenticator all by itself is OK, though.
1873 * Similarly, Status-Server packets MUST contain
1874 * Message-Authenticator attributes.
1876 if (require_ma && ! seen_ma) {
1877 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1878 inet_ntop(packet->src_ipaddr.af,
1879 &packet->src_ipaddr.ipaddr,
1880 host_ipaddr, sizeof(host_ipaddr)));
1885 * Fill RADIUS header fields
1887 packet->code = hdr->code;
1888 packet->id = hdr->id;
1889 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1896 * Receive UDP client requests, and fill in
1897 * the basics of a RADIUS_PACKET structure.
1899 RADIUS_PACKET *rad_recv(int fd, int flags)
1902 RADIUS_PACKET *packet;
1905 * Allocate the new request data structure
1907 if ((packet = malloc(sizeof(*packet))) == NULL) {
1908 fr_strerror_printf("out of memory");
1911 memset(packet, 0, sizeof(*packet));
1914 sock_flags = MSG_PEEK;
1918 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1919 &packet->src_ipaddr, &packet->src_port,
1920 &packet->dst_ipaddr, &packet->dst_port);
1923 * Check for socket errors.
1925 if (packet->data_len < 0) {
1926 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1927 /* packet->data is NULL */
1933 * If the packet is too big, then rad_recvfrom did NOT
1934 * allocate memory. Instead, it just discarded the
1937 if (packet->data_len > MAX_PACKET_LEN) {
1938 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1939 /* packet->data is NULL */
1945 * Read no data. Continue.
1946 * This check is AFTER the MAX_PACKET_LEN check above, because
1947 * if the packet is larger than MAX_PACKET_LEN, we also have
1948 * packet->data == NULL
1950 if ((packet->data_len == 0) || !packet->data) {
1951 fr_strerror_printf("Empty packet: Socket is not ready.");
1957 * See if it's a well-formed RADIUS packet.
1959 if (!rad_packet_ok(packet, flags)) {
1965 * Remember which socket we read the packet from.
1967 packet->sockfd = fd;
1970 * FIXME: Do even more filtering by only permitting
1971 * certain IP's. The problem is that we don't know
1972 * how to do this properly for all possible clients...
1976 * Explicitely set the VP list to empty.
1980 if (fr_debug_flag) {
1981 char host_ipaddr[128];
1983 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1984 DEBUG("rad_recv: %s packet from host %s port %d",
1985 fr_packet_codes[packet->code],
1986 inet_ntop(packet->src_ipaddr.af,
1987 &packet->src_ipaddr.ipaddr,
1988 host_ipaddr, sizeof(host_ipaddr)),
1991 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1992 inet_ntop(packet->src_ipaddr.af,
1993 &packet->src_ipaddr.ipaddr,
1994 host_ipaddr, sizeof(host_ipaddr)),
1998 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
2006 * Verify the signature of a packet.
2008 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2015 if (!packet || !packet->data) return -1;
2018 * Before we allocate memory for the attributes, do more
2021 ptr = packet->data + AUTH_HDR_LEN;
2022 length = packet->data_len - AUTH_HDR_LEN;
2023 while (length > 0) {
2024 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2025 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2030 default: /* don't do anything. */
2034 * Note that more than one Message-Authenticator
2035 * attribute is invalid.
2037 case PW_MESSAGE_AUTHENTICATOR:
2038 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2039 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2041 switch (packet->code) {
2045 case PW_ACCOUNTING_REQUEST:
2046 case PW_ACCOUNTING_RESPONSE:
2047 case PW_DISCONNECT_REQUEST:
2048 case PW_DISCONNECT_ACK:
2049 case PW_DISCONNECT_NAK:
2050 case PW_COA_REQUEST:
2053 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2056 case PW_AUTHENTICATION_ACK:
2057 case PW_AUTHENTICATION_REJECT:
2058 case PW_ACCESS_CHALLENGE:
2060 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2063 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2067 fr_hmac_md5(packet->data, packet->data_len,
2068 (const uint8_t *) secret, strlen(secret),
2070 if (digest_cmp(calc_auth_vector, msg_auth_vector,
2071 sizeof(calc_auth_vector)) != 0) {
2073 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2074 inet_ntop(packet->src_ipaddr.af,
2075 &packet->src_ipaddr.ipaddr,
2076 buffer, sizeof(buffer)));
2077 /* Silently drop packet, according to RFC 3579 */
2079 } /* else the message authenticator was good */
2082 * Reinitialize Authenticators.
2084 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2085 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2087 } /* switch over the attributes */
2091 } /* loop over the packet, sanity checking the attributes */
2094 * It looks like a RADIUS packet, but we can't validate
2097 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2099 fr_strerror_printf("Received Unknown packet code %d "
2100 "from client %s port %d: Cannot validate signature.",
2102 inet_ntop(packet->src_ipaddr.af,
2103 &packet->src_ipaddr.ipaddr,
2104 buffer, sizeof(buffer)),
2110 * Calculate and/or verify digest.
2112 switch(packet->code) {
2116 case PW_AUTHENTICATION_REQUEST:
2117 case PW_STATUS_SERVER:
2119 * The authentication vector is random
2120 * nonsense, invented by the client.
2124 case PW_COA_REQUEST:
2125 case PW_DISCONNECT_REQUEST:
2126 case PW_ACCOUNTING_REQUEST:
2127 if (calc_acctdigest(packet, secret) > 1) {
2128 fr_strerror_printf("Received %s packet "
2129 "from %s with invalid signature! (Shared secret is incorrect.)",
2130 fr_packet_codes[packet->code],
2131 inet_ntop(packet->src_ipaddr.af,
2132 &packet->src_ipaddr.ipaddr,
2133 buffer, sizeof(buffer)));
2138 /* Verify the reply digest */
2139 case PW_AUTHENTICATION_ACK:
2140 case PW_AUTHENTICATION_REJECT:
2141 case PW_ACCESS_CHALLENGE:
2142 case PW_ACCOUNTING_RESPONSE:
2143 case PW_DISCONNECT_ACK:
2144 case PW_DISCONNECT_NAK:
2147 rcode = calc_replydigest(packet, original, secret);
2149 fr_strerror_printf("Received %s packet "
2150 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2151 fr_packet_codes[packet->code],
2152 inet_ntop(packet->src_ipaddr.af,
2153 &packet->src_ipaddr.ipaddr,
2154 buffer, sizeof(buffer)),
2162 fr_strerror_printf("Received Unknown packet code %d "
2163 "from client %s port %d: Cannot validate signature",
2165 inet_ntop(packet->src_ipaddr.af,
2166 &packet->src_ipaddr.ipaddr,
2167 buffer, sizeof(buffer)),
2176 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2177 const RADIUS_PACKET *original,
2179 UNUSED unsigned int attribute, size_t length,
2180 const uint8_t *data, VALUE_PAIR *vp)
2185 * If length is greater than 253, something is SERIOUSLY
2188 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2190 vp->length = length;
2191 vp->operator = T_OP_EQ;
2197 if (vp->flags.has_tag) {
2198 if (TAG_VALID(data[0]) ||
2199 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2201 * Tunnel passwords REQUIRE a tag, even
2202 * if don't have a valid tag.
2204 vp->flags.tag = data[0];
2206 if ((vp->type == PW_TYPE_STRING) ||
2207 (vp->type == PW_TYPE_OCTETS)) offset = 1;
2212 * Copy the data to be decrypted
2214 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2215 vp->length -= offset;
2218 * Decrypt the attribute.
2220 switch (vp->flags.encrypt) {
2224 case FLAG_ENCRYPT_USER_PASSWORD:
2226 rad_pwdecode((char *)vp->vp_strvalue,
2230 rad_pwdecode((char *)vp->vp_strvalue,
2234 if (vp->attribute == PW_USER_PASSWORD) {
2235 vp->length = strlen(vp->vp_strvalue);
2240 * Tunnel-Password's may go ONLY
2241 * in response packets.
2243 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2244 if (!original) goto raw;
2246 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2247 secret, original->vector) < 0) {
2253 * Ascend-Send-Secret
2254 * Ascend-Receive-Secret
2256 case FLAG_ENCRYPT_ASCEND_SECRET:
2260 uint8_t my_digest[AUTH_VECTOR_LEN];
2261 make_secret(my_digest,
2264 memcpy(vp->vp_strvalue, my_digest,
2266 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2267 vp->length = strlen(vp->vp_strvalue);
2273 } /* switch over encryption flags */
2277 case PW_TYPE_STRING:
2278 case PW_TYPE_OCTETS:
2279 case PW_TYPE_ABINARY:
2280 /* nothing more to do */
2284 if (vp->length != 1) goto raw;
2286 vp->vp_integer = vp->vp_octets[0];
2291 if (vp->length != 2) goto raw;
2293 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2296 case PW_TYPE_INTEGER:
2297 if (vp->length != 4) goto raw;
2299 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2300 vp->vp_integer = ntohl(vp->vp_integer);
2302 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2305 * Try to get named VALUEs
2309 dval = dict_valbyattr(vp->attribute,
2312 strlcpy(vp->vp_strvalue,
2314 sizeof(vp->vp_strvalue));
2320 if (vp->length != 4) goto raw;
2322 memcpy(&vp->vp_date, vp->vp_octets, 4);
2323 vp->vp_date = ntohl(vp->vp_date);
2327 case PW_TYPE_IPADDR:
2328 if (vp->length != 4) goto raw;
2330 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2334 * IPv6 interface ID is 8 octets long.
2337 if (vp->length != 8) goto raw;
2338 /* vp->vp_ifid == vp->vp_octets */
2342 * IPv6 addresses are 16 octets long
2344 case PW_TYPE_IPV6ADDR:
2345 if (vp->length != 16) goto raw;
2346 /* vp->vp_ipv6addr == vp->vp_octets */
2350 * IPv6 prefixes are 2 to 18 octets long.
2352 * RFC 3162: The first octet is unused.
2353 * The second is the length of the prefix
2354 * the rest are the prefix data.
2356 * The prefix length can have value 0 to 128.
2358 case PW_TYPE_IPV6PREFIX:
2359 if (vp->length < 2 || vp->length > 18) goto raw;
2360 if (vp->vp_octets[1] > 128) goto raw;
2363 * FIXME: double-check that
2364 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2366 if (vp->length < 18) {
2367 memset(vp->vp_octets + vp->length, 0,
2372 case PW_TYPE_SIGNED:
2373 if (vp->length != 4) goto raw;
2376 * Overload vp_integer for ntohl, which takes
2377 * uint32_t, not int32_t
2379 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2380 vp->vp_integer = ntohl(vp->vp_integer);
2381 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2385 vp->length = length;
2386 vp->vp_tlv = malloc(length);
2389 fr_strerror_printf("No memory");
2392 memcpy(vp->vp_tlv, data, length);
2395 case PW_TYPE_COMBO_IP:
2396 if (vp->length == 4) {
2397 vp->type = PW_TYPE_IPADDR;
2398 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2401 } else if (vp->length == 16) {
2402 vp->type = PW_TYPE_IPV6ADDR;
2403 /* vp->vp_ipv6addr == vp->vp_octets */
2411 vp->type = PW_TYPE_OCTETS;
2412 vp->length = length;
2413 memcpy(vp->vp_octets, data, length);
2417 * Ensure there's no encryption or tag stuff,
2418 * we just pass the attribute as-is.
2420 memset(&vp->flags, 0, sizeof(vp->flags));
2426 static void rad_sortvp(VALUE_PAIR **head)
2429 VALUE_PAIR *vp, **tail;
2432 * Walk over the VP's, sorting them in order. Did I
2433 * mention that I hate WiMAX continuations?
2435 * And bubble sort! WTF is up with that?
2442 if (!vp->next) break;
2444 if (vp->attribute > vp->next->attribute) {
2446 vp->next = (*tail)->next;
2457 * Walk the packet, looking for continuations of this attribute.
2459 * This is (worst-case) O(N^2) in the number of RADIUS
2460 * attributes. That happens only when perverse clients create
2461 * continued attributes, AND separate the fragmented portions
2462 * with a lot of other attributes.
2464 * Sane clients should put the fragments next to each other, in
2465 * which case this is O(N), in the number of fragments.
2467 static uint8_t *rad_coalesce(unsigned int attribute, size_t length,
2469 size_t packet_length, size_t *ptlv_length)
2473 size_t tlv_length = length;
2474 uint8_t *ptr, *tlv, *tlv_data;
2476 for (ptr = data + length;
2477 ptr != (data + packet_length);
2479 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2480 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2481 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2485 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2486 lvalue = ntohl(lvalue);
2488 lvalue |= ptr[2 + 4]; /* add in VSA number */
2489 if (lvalue != attribute) continue;
2492 * If the vendor-length is too small, it's badly
2493 * formed, so we stop.
2495 if ((ptr[2 + 4 + 1]) < 3) break;
2497 tlv_length += ptr[2 + 4 + 1] - 3;
2498 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2501 tlv = tlv_data = malloc(tlv_length);
2502 if (!tlv_data) return NULL;
2504 memcpy(tlv, data, length);
2508 * Now we walk the list again, copying the data over to
2509 * our newly created memory.
2511 for (ptr = data + length;
2512 ptr != (data + packet_length);
2516 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2517 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2518 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2522 memcpy(&lvalue, ptr + 2, 4);
2523 lvalue = ntohl(lvalue);
2525 lvalue |= ptr[2 + 4];
2526 if (lvalue != attribute) continue;
2529 * If the vendor-length is too small, it's badly
2530 * formed, so we stop.
2532 if ((ptr[2 + 4 + 1]) < 3) break;
2534 this_length = ptr[2 + 4 + 1] - 3;
2535 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2538 ptr[2 + 4] = 0; /* What a hack! */
2539 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2542 *ptlv_length = tlv_length;
2547 * Start at the *data* portion of a continued attribute. search
2548 * through the rest of the attributes to find a matching one, and
2549 * add it's contents to our contents.
2551 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2552 const RADIUS_PACKET *original,
2553 const char *secret, int attribute,
2554 int length, /* CANNOT be zero */
2555 uint8_t *data, size_t packet_length,
2556 int flag, DICT_ATTR *da)
2558 size_t tlv_length, left;
2561 VALUE_PAIR *vp, *head, **tail;
2564 * Ensure we have data that hasn't been split across
2565 * multiple attributes.
2568 tlv_data = rad_coalesce(attribute, length,
2569 data, packet_length, &tlv_length);
2570 if (!tlv_data) return NULL;
2573 tlv_length = length;
2577 * Non-TLV types cannot be continued across multiple
2578 * attributes. This is true even of keys that are
2579 * encrypted with the tunnel-password method. The spec
2580 * says that they can be continued... but also that the
2581 * keys are 160 bits, which means that they CANNOT be
2584 * Note that we don't check "flag" here. The calling
2587 if (!da || (da->type != PW_TYPE_TLV)) {
2589 if (tlv_data == data) { /* true if we had 'goto' */
2590 tlv_data = malloc(tlv_length);
2591 if (!tlv_data) return NULL;
2592 memcpy(tlv_data, data, tlv_length);
2595 vp = paircreate(attribute, PW_TYPE_OCTETS);
2596 if (!vp) return NULL;
2598 vp->type = PW_TYPE_TLV;
2599 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2600 vp->flags.has_tag = 0;
2601 vp->flags.is_tlv = 0;
2602 vp->vp_tlv = tlv_data;
2603 vp->length = tlv_length;
2605 } /* else it WAS a TLV, go decode the sub-tlv's */
2608 * Now (sigh) we walk over the TLV, seeing if it is
2612 for (ptr = tlv_data;
2613 ptr != (tlv_data + tlv_length);
2618 goto not_well_formed;
2624 * Now we walk over the TLV *again*, creating sub-tlv's.
2629 for (ptr = tlv_data;
2630 ptr != (tlv_data + tlv_length);
2632 vp = paircreate(attribute | (ptr[0] << 8), PW_TYPE_OCTETS);
2635 goto not_well_formed;
2638 if (!data2vp(packet, original, secret,
2639 ptr[0], ptr[1] - 2, ptr + 2, vp)) {
2641 goto not_well_formed;
2649 * TLV's MAY be continued, but sometimes they're not.
2651 if (tlv_data != data) free(tlv_data);
2653 if (head->next) rad_sortvp(&head);
2660 * Parse a RADIUS attribute into a data structure.
2662 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
2663 const char *secret, int attribute, int length,
2664 const uint8_t *data)
2668 vp = paircreate(attribute, PW_TYPE_OCTETS);
2669 if (!vp) return NULL;
2671 return data2vp(packet, original, secret, attribute, length, data, vp);
2676 * Calculate/check digest, and decode radius attributes.
2678 * -1 on decoding error
2681 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2685 uint32_t vendorcode;
2688 uint8_t *ptr, *vsa_ptr;
2693 radius_packet_t *hdr;
2694 int vsa_tlen, vsa_llen, vsa_offset;
2695 DICT_VENDOR *dv = NULL;
2696 int num_attributes = 0;
2699 * Extract attribute-value pairs
2701 hdr = (radius_packet_t *)packet->data;
2703 packet_length = packet->data_len - AUTH_HDR_LEN;
2706 * There may be VP's already in the packet. Don't
2709 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2715 vsa_tlen = vsa_llen = 1;
2719 * We have to read at least two bytes.
2721 * rad_recv() above ensures that this is OK.
2723 while (packet_length > 0) {
2728 * Normal attribute, handle it like normal.
2730 if (vendorcode == 0) {
2732 * No room to read attr/length,
2733 * or bad attribute, or attribute is
2734 * too short, or attribute is too long,
2735 * stop processing the packet.
2737 if ((packet_length < 2) ||
2738 (ptr[0] == 0) || (ptr[1] < 2) ||
2739 (ptr[1] > packet_length)) break;
2747 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2750 * No vendor code, or ONLY vendor code.
2752 if (attrlen <= 4) goto create_pair;
2758 * Handle Vendor-Specific
2760 if (vendorlen == 0) {
2766 * attrlen was checked above.
2768 memcpy(&lvalue, ptr, 4);
2769 myvendor = ntohl(lvalue);
2772 * Zero isn't allowed.
2774 if (myvendor == 0) goto create_pair;
2777 * This is an implementation issue.
2778 * We currently pack vendor into the upper
2779 * 16 bits of a 32-bit attribute number,
2780 * so we can't handle vendor numbers larger
2783 if (myvendor > 65535) goto create_pair;
2785 vsa_tlen = vsa_llen = 1;
2787 dv = dict_vendorbyvalue(myvendor);
2789 vsa_tlen = dv->type;
2790 vsa_llen = dv->length;
2791 if (dv->flags) vsa_offset = 1;
2795 * Sweep through the list of VSA's,
2796 * seeing if they exactly fill the
2797 * outer Vendor-Specific attribute.
2799 * If not, create a raw Vendor-Specific.
2802 sublen = attrlen - 4;
2805 * See if we can parse it.
2811 * Not enough room for one more
2814 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2817 * Ensure that the attribute number
2826 myattr = (subptr[0] << 8) | subptr[1];
2830 if ((subptr[0] != 0) ||
2831 (subptr[1] != 0)) goto create_pair;
2833 myattr = (subptr[2] << 8) | subptr[3];
2837 * Our dictionary is broken.
2845 attribute = (myvendor << 16) | myattr;
2846 ptr += 4 + vsa_tlen;
2847 attrlen -= (4 + vsa_tlen);
2848 packet_length -= 4 + vsa_tlen;
2852 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2855 if (subptr[vsa_tlen] > sublen)
2860 * Reserved bits MUST be
2864 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2867 sublen -= subptr[vsa_tlen];
2868 subptr += subptr[vsa_tlen];
2872 if (subptr[vsa_tlen] != 0) goto create_pair;
2873 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2875 if (subptr[vsa_tlen + 1] > sublen)
2877 sublen -= subptr[vsa_tlen + 1];
2878 subptr += subptr[vsa_tlen + 1];
2882 * Our dictionaries are
2888 } while (sublen > 0);
2890 vendorcode = myvendor;
2891 vendorlen = attrlen - 4;
2898 * attrlen is the length of this attribute.
2899 * total_len is the length of the encompassing
2908 attribute = (ptr[0] << 8) | ptr[1];
2911 default: /* can't hit this. */
2914 attribute |= (vendorcode << 16);
2920 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
2924 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2927 default: /* can't hit this. */
2931 ptr += vsa_llen + vsa_offset;
2932 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
2933 if (vendorlen == 0) vendorcode = 0;
2934 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
2937 * Ignore VSAs that have no data.
2939 if (attrlen == 0) goto next;
2942 * WiMAX attributes of type 0 are ignored. They
2943 * are a secret flag to us that the attribute has
2944 * already been dealt with.
2946 if (attribute == 0x60b50000) goto next;
2951 da = dict_attrbyvalue(attribute);
2954 * If it's NOT continued, AND we know
2955 * about it, AND it's not a TLV, we can
2956 * create a normal pair.
2958 if (((vsa_ptr[2] & 0x80) == 0) &&
2959 da && (da->type != PW_TYPE_TLV)) goto create_pair;
2962 * Else it IS continued, or it's a TLV.
2963 * Go do a lot of work to find the stuff.
2965 pair = rad_continuation2vp(packet, original, secret,
2966 attribute, attrlen, ptr,
2968 ((vsa_ptr[2] & 0x80) != 0),
2974 * Create the attribute, setting the default type
2975 * to 'octets'. If the type in the dictionary
2976 * is different, then the dictionary type will
2977 * over-ride this one.
2979 * If the attribute has no data, then discard it.
2981 * Unless it's CUI. Damn you, CUI!
2985 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
2987 pair = rad_attr2vp(packet, original, secret,
2988 attribute, attrlen, ptr);
2990 pairfree(&packet->vps);
2991 fr_strerror_printf("out of memory");
3005 * VSA's may not have been counted properly in
3006 * rad_packet_ok() above, as it is hard to count
3007 * then without using the dictionary. We
3008 * therefore enforce the limits here, too.
3010 if ((fr_max_attributes > 0) &&
3011 (num_attributes > fr_max_attributes)) {
3012 char host_ipaddr[128];
3014 pairfree(&packet->vps);
3015 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3016 inet_ntop(packet->src_ipaddr.af,
3017 &packet->src_ipaddr.ipaddr,
3018 host_ipaddr, sizeof(host_ipaddr)),
3019 num_attributes, fr_max_attributes);
3025 packet_length -= attrlen;
3029 * Merge information from the outside world into our
3032 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3041 * We assume that the passwd buffer passed is big enough.
3042 * RFC2138 says the password is max 128 chars, so the size
3043 * of the passwd buffer must be at least 129 characters.
3044 * Preferably it's just MAX_STRING_LEN.
3046 * int *pwlen is updated to the new length of the encrypted
3047 * password - a multiple of 16 bytes.
3049 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3050 const uint8_t *vector)
3052 FR_MD5_CTX context, old;
3053 uint8_t digest[AUTH_VECTOR_LEN];
3054 int i, n, secretlen;
3058 * RFC maximum is 128 bytes.
3060 * If length is zero, pad it out with zeros.
3062 * If the length isn't aligned to 16 bytes,
3063 * zero out the extra data.
3067 if (len > 128) len = 128;
3070 memset(passwd, 0, AUTH_PASS_LEN);
3071 len = AUTH_PASS_LEN;
3072 } else if ((len % AUTH_PASS_LEN) != 0) {
3073 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3074 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3079 * Use the secret to setup the decryption digest
3081 secretlen = strlen(secret);
3083 fr_MD5Init(&context);
3084 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3085 old = context; /* save intermediate work */
3088 * Encrypt it in place. Don't bother checking
3089 * len, as we've ensured above that it's OK.
3091 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3093 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3094 fr_MD5Final(digest, &context);
3097 fr_MD5Update(&context,
3098 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3100 fr_MD5Final(digest, &context);
3103 for (i = 0; i < AUTH_PASS_LEN; i++) {
3104 passwd[i + n] ^= digest[i];
3114 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3115 const uint8_t *vector)
3117 FR_MD5_CTX context, old;
3118 uint8_t digest[AUTH_VECTOR_LEN];
3120 size_t n, secretlen;
3123 * The RFC's say that the maximum is 128.
3124 * The buffer we're putting it into above is 254, so
3125 * we don't need to do any length checking.
3127 if (pwlen > 128) pwlen = 128;
3132 if (pwlen == 0) goto done;
3135 * Use the secret to setup the decryption digest
3137 secretlen = strlen(secret);
3139 fr_MD5Init(&context);
3140 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3141 old = context; /* save intermediate work */
3144 * The inverse of the code above.
3146 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3148 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3149 fr_MD5Final(digest, &context);
3152 if (pwlen > AUTH_PASS_LEN) {
3153 fr_MD5Update(&context, (uint8_t *) passwd,
3157 fr_MD5Final(digest, &context);
3160 if (pwlen > (n + AUTH_PASS_LEN)) {
3161 fr_MD5Update(&context, (uint8_t *) passwd + n,
3166 for (i = 0; i < AUTH_PASS_LEN; i++) {
3167 passwd[i + n] ^= digest[i];
3172 passwd[pwlen] = '\0';
3173 return strlen(passwd);
3178 * Encode Tunnel-Password attributes when sending them out on the wire.
3180 * int *pwlen is updated to the new length of the encrypted
3181 * password - a multiple of 16 bytes.
3183 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3186 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3187 const uint8_t *vector)
3189 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3190 unsigned char digest[AUTH_VECTOR_LEN];
3192 int i, n, secretlen;
3197 if (len > 127) len = 127;
3200 * Shift the password 3 positions right to place a salt and original
3201 * length, tag will be added automatically on packet send
3203 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3207 * save original password length as first password character;
3214 * Generate salt. The RFC's say:
3216 * The high bit of salt[0] must be set, each salt in a
3217 * packet should be unique, and they should be random
3219 * So, we set the high bit, add in a counter, and then
3220 * add in some CSPRNG data. should be OK..
3222 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3223 (fr_rand() & 0x07));
3224 salt[1] = fr_rand();
3227 * Padd password to multiple of AUTH_PASS_LEN bytes.
3229 n = len % AUTH_PASS_LEN;
3231 n = AUTH_PASS_LEN - n;
3232 for (; n > 0; n--, len++)
3235 /* set new password length */
3239 * Use the secret to setup the decryption digest
3241 secretlen = strlen(secret);
3242 memcpy(buffer, secret, secretlen);
3244 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3246 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3247 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3248 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3250 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3251 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3254 for (i = 0; i < AUTH_PASS_LEN; i++) {
3255 passwd[i + n2] ^= digest[i];
3263 * Decode Tunnel-Password encrypted attributes.
3265 * Defined in RFC-2868, this uses a two char SALT along with the
3266 * initial intermediate value, to differentiate it from the
3269 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3270 const uint8_t *vector)
3272 FR_MD5_CTX context, old;
3273 uint8_t digest[AUTH_VECTOR_LEN];
3275 unsigned i, n, len, reallen;
3280 * We need at least a salt.
3283 fr_strerror_printf("tunnel password is too short");
3288 * There's a salt, but no password. Or, there's a salt
3289 * and a 'data_len' octet. It's wrong, but at least we
3290 * can figure out what it means: the password is empty.
3292 * Note that this means we ignore the 'data_len' field,
3293 * if the attribute length tells us that there's no
3294 * more data. So the 'data_len' field may be wrong,
3303 len -= 2; /* discount the salt */
3306 * Use the secret to setup the decryption digest
3308 secretlen = strlen(secret);
3310 fr_MD5Init(&context);
3311 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3312 old = context; /* save intermediate work */
3315 * Set up the initial key:
3317 * b(1) = MD5(secret + vector + salt)
3319 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3320 fr_MD5Update(&context, passwd, 2);
3323 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3327 fr_MD5Final(digest, &context);
3332 * A quick check: decrypt the first octet
3333 * of the password, which is the
3334 * 'data_len' field. Ensure it's sane.
3336 reallen = passwd[2] ^ digest[0];
3337 if (reallen >= len) {
3338 fr_strerror_printf("tunnel password is too long for the attribute");
3342 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3346 fr_MD5Final(digest, &context);
3349 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3352 for (i = base; i < AUTH_PASS_LEN; i++) {
3353 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3358 * See make_tunnel_password, above.
3360 if (reallen > 239) reallen = 239;
3363 passwd[reallen] = 0;
3369 * Encode a CHAP password
3371 * FIXME: might not work with Ascend because
3372 * we use vp->length, and Ascend gear likes
3373 * to send an extra '\0' in the string!
3375 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3376 VALUE_PAIR *password)
3380 uint8_t string[MAX_STRING_LEN * 2 + 1];
3381 VALUE_PAIR *challenge;
3384 * Sanity check the input parameters
3386 if ((packet == NULL) || (password == NULL)) {
3391 * Note that the password VP can be EITHER
3392 * a User-Password attribute (from a check-item list),
3393 * or a CHAP-Password attribute (the client asking
3394 * the library to encode it).
3402 memcpy(ptr, password->vp_strvalue, password->length);
3403 ptr += password->length;
3404 i += password->length;
3407 * Use Chap-Challenge pair if present,
3408 * Request-Authenticator otherwise.
3410 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
3412 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3413 i += challenge->length;
3415 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3416 i += AUTH_VECTOR_LEN;
3420 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3427 * Seed the random number generator.
3429 * May be called any number of times.
3431 void fr_rand_seed(const void *data, size_t size)
3436 * Ensure that the pool is initialized.
3438 if (!fr_rand_initialized) {
3441 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3443 fd = open("/dev/urandom", O_RDONLY);
3449 while (total < sizeof(fr_rand_pool.randrsl)) {
3450 this = read(fd, fr_rand_pool.randrsl,
3451 sizeof(fr_rand_pool.randrsl) - total);
3452 if ((this < 0) && (errno != EINTR)) break;
3453 if (this > 0) total += this;
3457 fr_rand_pool.randrsl[0] = fd;
3458 fr_rand_pool.randrsl[1] = time(NULL);
3459 fr_rand_pool.randrsl[2] = errno;
3462 fr_randinit(&fr_rand_pool, 1);
3463 fr_rand_pool.randcnt = 0;
3464 fr_rand_initialized = 1;
3470 * Hash the user data
3473 if (!hash) hash = fr_rand();
3474 hash = fr_hash_update(data, size, hash);
3476 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3481 * Return a 32-bit random number.
3483 uint32_t fr_rand(void)
3488 * Ensure that the pool is initialized.
3490 if (!fr_rand_initialized) {
3491 fr_rand_seed(NULL, 0);
3494 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3495 if (fr_rand_pool.randcnt >= 256) {
3496 fr_rand_pool.randcnt = 0;
3497 fr_isaac(&fr_rand_pool);
3505 * Allocate a new RADIUS_PACKET
3507 RADIUS_PACKET *rad_alloc(int newvector)
3511 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3512 fr_strerror_printf("out of memory");
3515 memset(rp, 0, sizeof(*rp));
3521 uint32_t hash, base;
3524 * Don't expose the actual contents of the random
3528 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3529 hash = fr_rand() ^ base;
3530 memcpy(rp->vector + i, &hash, sizeof(hash));
3533 fr_rand(); /* stir the pool again */
3538 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3540 RADIUS_PACKET *reply;
3542 if (!packet) return NULL;
3544 reply = rad_alloc(0);
3545 if (!reply) return NULL;
3548 * Initialize the fields from the request.
3550 reply->sockfd = packet->sockfd;
3551 reply->dst_ipaddr = packet->src_ipaddr;
3552 reply->src_ipaddr = packet->dst_ipaddr;
3553 reply->dst_port = packet->src_port;
3554 reply->src_port = packet->dst_port;
3555 reply->id = packet->id;
3556 reply->code = 0; /* UNKNOWN code */
3557 memcpy(reply->vector, packet->vector,
3558 sizeof(reply->vector));
3561 reply->data_len = 0;
3568 * Free a RADIUS_PACKET
3570 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3572 RADIUS_PACKET *radius_packet;
3574 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3575 radius_packet = *radius_packet_ptr;
3577 free(radius_packet->data);
3579 pairfree(&radius_packet->vps);
3581 free(radius_packet);
3583 *radius_packet_ptr = NULL;