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 librad_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;
72 #define MAX_PACKET_CODE (52)
73 static const char *packet_codes[] = {
79 "Accounting-Response",
95 "Resource-Free-Request",
96 "Resource-Free-Response",
97 "Resource-Query-Request",
98 "Resource-Query-Response",
99 "Alternate-Resource-Reclaim-Request",
100 "NAS-Reboot-Request",
101 "NAS-Reboot-Response",
114 "Disconnect-Request",
124 "IP-Address-Allocate",
129 void fr_printf_log(const char *fmt, ...)
134 if ((librad_debug == 0) || !fr_log_fp) {
139 vfprintf(fr_log_fp, fmt, ap);
146 * Wrapper for sendto which handles sendfromto, IPv6, and all
147 * possible combinations.
149 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
150 fr_ipaddr_t *src_ipaddr, int src_port,
151 fr_ipaddr_t *dst_ipaddr, int dst_port)
153 struct sockaddr_storage dst;
154 socklen_t sizeof_dst = sizeof(dst);
156 #ifdef WITH_UDPFROMTO
157 struct sockaddr_storage src;
158 socklen_t sizeof_src = sizeof(src);
160 memset(&src, 0, sizeof(src));
162 memset(&dst, 0, sizeof(dst));
167 if (dst_ipaddr->af == AF_INET) {
168 struct sockaddr_in s4;
170 sizeof_dst = sizeof(s4);
172 s4.sin_family = AF_INET;
173 s4.sin_addr = dst_ipaddr->ipaddr.ip4addr;
174 s4.sin_port = htons(dst_port);
175 memset(&dst, 0, sizeof(dst));
176 memcpy(&dst, &s4, sizeof_dst);
178 #ifdef WITH_UDPFROMTO
179 sizeof_src = sizeof(s4);
181 s4.sin_family = AF_INET;
182 s4.sin_addr = src_ipaddr->ipaddr.ip4addr;
183 s4.sin_port = htons(src_port);
184 memset(&src, 0, sizeof(src));
185 memcpy(&src, &s4, sizeof_src);
187 src_port = src_port; /* -Wunused */
191 * IPv6 MAY be supported.
193 #ifdef HAVE_STRUCT_SOCKADDR_IN6
194 } else if (dst_ipaddr->af == AF_INET6) {
195 struct sockaddr_in6 s6;
197 sizeof_dst = sizeof(s6);
199 s6.sin6_family = AF_INET6;
200 s6.sin6_addr = dst_ipaddr->ipaddr.ip6addr;
201 s6.sin6_port = htons(dst_port);
202 memset(&dst, 0, sizeof(dst));
203 memcpy(&dst, &s6, sizeof_dst);
205 #ifdef WITH_UDPFROMTO
206 return -1; /* UDPFROMTO && IPv6 are not supported */
208 sizeof_src = sizeof(s6);
210 s6.sin6_family = AF_INET6;
211 s6.sin6_addr = src_ipaddr->ipaddr.ip6addr;
212 memset(&src, 0, sizeof(src));
213 memcpy(&src, &s6, sizeof_src);
215 #endif /* WITH_UDPFROMTO */
216 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
217 } else return -1; /* Unknown address family, Die Die Die! */
219 #ifdef WITH_UDPFROMTO
221 * Only IPv4 is supported for udpfromto.
223 * And if they don't specify a source IP address, don't
226 if ((dst_ipaddr->af == AF_INET) ||
227 (src_ipaddr->af != AF_UNSPEC)) {
228 return sendfromto(sockfd, data, data_len, flags,
229 (struct sockaddr *)&src, sizeof_src,
230 (struct sockaddr *)&dst, sizeof_dst);
233 src_ipaddr = src_ipaddr; /* -Wunused */
237 * No udpfromto, OR an IPv6 socket, fail gracefully.
239 return sendto(sockfd, data, data_len, flags,
240 (struct sockaddr *) &dst, sizeof_dst);
244 void rad_recv_discard(int sockfd)
247 struct sockaddr_storage src;
248 socklen_t sizeof_src = sizeof(src);
250 recvfrom(sockfd, header, sizeof(header), 0,
251 (struct sockaddr *)&src, &sizeof_src);
255 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
258 ssize_t data_len, packet_len;
260 struct sockaddr_storage src;
261 socklen_t sizeof_src = sizeof(src);
263 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
264 (struct sockaddr *)&src, &sizeof_src);
266 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
271 * Too little data is available, discard the packet.
274 recvfrom(sockfd, header, sizeof(header), 0,
275 (struct sockaddr *)&src, &sizeof_src);
278 } else { /* we got 4 bytes of data. */
280 * See how long the packet says it is.
282 packet_len = (header[2] * 256) + header[3];
285 * The length in the packet says it's less than
286 * a RADIUS header length: discard it.
288 if (packet_len < AUTH_HDR_LEN) {
289 recvfrom(sockfd, header, sizeof(header), 0,
290 (struct sockaddr *)&src, &sizeof_src);
294 * Enforce RFC requirements, for sanity.
295 * Anything after 4k will be discarded.
297 } else if (packet_len > MAX_PACKET_LEN) {
298 recvfrom(sockfd, header, sizeof(header), 0,
299 (struct sockaddr *)&src, &sizeof_src);
304 if (src.ss_family == AF_INET) {
305 struct sockaddr_in s4;
307 memcpy(&s4, &src, sizeof(s4));
308 src_ipaddr->af = AF_INET;
309 src_ipaddr->ipaddr.ip4addr = s4.sin_addr;
310 *src_port = ntohs(s4.sin_port);
312 #ifdef HAVE_STRUCT_SOCKADDR_IN6
313 } else if (src.ss_family == AF_INET6) {
314 struct sockaddr_in6 s6;
316 memcpy(&s6, &src, sizeof(s6));
317 src_ipaddr->af = AF_INET6;
318 src_ipaddr->ipaddr.ip6addr = s6.sin6_addr;
319 *src_port = ntohs(s6.sin6_port);
323 recvfrom(sockfd, header, sizeof(header), 0,
324 (struct sockaddr *)&src, &sizeof_src);
331 * The packet says it's this long, but the actual UDP
332 * size could still be smaller.
339 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
340 * possible combinations.
342 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
343 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
344 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
346 struct sockaddr_storage src;
347 struct sockaddr_storage dst;
348 socklen_t sizeof_src = sizeof(src);
349 socklen_t sizeof_dst = sizeof(dst);
355 memset(&src, 0, sizeof_src);
356 memset(&dst, 0, sizeof_dst);
359 * Get address family, etc. first, so we know if we
360 * need to do udpfromto.
362 * FIXME: udpfromto also does this, but it's not
363 * a critical problem.
365 if (getsockname(sockfd, (struct sockaddr *)&dst,
366 &sizeof_dst) < 0) return -1;
369 * Read the length of the packet, from the packet.
370 * This lets us allocate the buffer to use for
371 * reading the rest of the packet.
373 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
374 (struct sockaddr *)&src, &sizeof_src);
376 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
381 * Too little data is available, discard the packet.
384 recvfrom(sockfd, header, sizeof(header), flags,
385 (struct sockaddr *)&src, &sizeof_src);
388 } else { /* we got 4 bytes of data. */
390 * See how long the packet says it is.
392 len = (header[2] * 256) + header[3];
395 * The length in the packet says it's less than
396 * a RADIUS header length: discard it.
398 if (len < AUTH_HDR_LEN) {
399 recvfrom(sockfd, header, sizeof(header), flags,
400 (struct sockaddr *)&src, &sizeof_src);
404 * Enforce RFC requirements, for sanity.
405 * Anything after 4k will be discarded.
407 } else if (len > MAX_PACKET_LEN) {
408 recvfrom(sockfd, header, sizeof(header), flags,
409 (struct sockaddr *)&src, &sizeof_src);
418 * Receive the packet. The OS will discard any data in the
419 * packet after "len" bytes.
421 #ifdef WITH_UDPFROMTO
422 if (dst.ss_family == AF_INET) {
423 data_len = recvfromto(sockfd, buf, len, flags,
424 (struct sockaddr *)&src, &sizeof_src,
425 (struct sockaddr *)&dst, &sizeof_dst);
429 * No udpfromto, OR an IPv6 socket. Fail gracefully.
431 data_len = recvfrom(sockfd, buf, len, flags,
432 (struct sockaddr *)&src, &sizeof_src);
439 * Check address families, and update src/dst ports, etc.
441 if (src.ss_family == AF_INET) {
442 struct sockaddr_in s4;
444 memcpy(&s4, &src, sizeof(s4));
445 src_ipaddr->af = AF_INET;
446 src_ipaddr->ipaddr.ip4addr = s4.sin_addr;
447 *src_port = ntohs(s4.sin_port);
449 memcpy(&s4, &dst, sizeof(s4));
450 dst_ipaddr->af = AF_INET;
451 dst_ipaddr->ipaddr.ip4addr = s4.sin_addr;
452 *dst_port = ntohs(s4.sin_port);
454 #ifdef HAVE_STRUCT_SOCKADDR_IN6
455 } else if (src.ss_family == AF_INET6) {
456 struct sockaddr_in6 s6;
458 memcpy(&s6, &src, sizeof(s6));
459 src_ipaddr->af = AF_INET6;
460 src_ipaddr->ipaddr.ip6addr = s6.sin6_addr;
461 *src_port = ntohs(s6.sin6_port);
463 memcpy(&s6, &dst, sizeof(s6));
464 dst_ipaddr->af = AF_INET6;
465 dst_ipaddr->ipaddr.ip6addr = s6.sin6_addr;
466 *dst_port = ntohs(s6.sin6_port);
470 return -1; /* Unknown address family, Die Die Die! */
474 * Different address families should never happen.
476 if (src.ss_family != dst.ss_family) {
482 * Tell the caller about the data
490 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
491 /*************************************************************************
493 * Function: make_secret
495 * Purpose: Build an encrypted secret value to return in a reply
496 * packet. The secret is hidden by xoring with a MD5 digest
497 * created from the shared secret and the authentication
498 * vector. We put them into MD5 in the reverse order from
499 * that used when encrypting passwords to RADIUS.
501 *************************************************************************/
502 static void make_secret(uint8_t *digest, const uint8_t *vector,
503 const char *secret, const uint8_t *value)
508 fr_MD5Init(&context);
509 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
510 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
511 fr_MD5Final(digest, &context);
513 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
514 digest[i] ^= value[i];
518 #define MAX_PASS_LEN (128)
519 static void make_passwd(uint8_t *output, int *outlen,
520 const uint8_t *input, int inlen,
521 const char *secret, const uint8_t *vector)
523 FR_MD5_CTX context, old;
524 uint8_t digest[AUTH_VECTOR_LEN];
525 uint8_t passwd[MAX_PASS_LEN];
530 * If the length is zero, round it up.
536 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
538 else if ((len & 0x0f) != 0) {
544 memcpy(passwd, input, len);
545 memset(passwd + len, 0, sizeof(passwd) - len);
547 fr_MD5Init(&context);
548 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
554 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
556 for (n = 0; n < len; n += AUTH_PASS_LEN) {
559 fr_MD5Update(&context,
560 passwd + n - AUTH_PASS_LEN,
564 fr_MD5Final(digest, &context);
565 for (i = 0; i < AUTH_PASS_LEN; i++) {
566 passwd[i + n] ^= digest[i];
570 memcpy(output, passwd, len);
573 static void make_tunnel_passwd(uint8_t *output, int *outlen,
574 const uint8_t *input, int inlen, int room,
575 const char *secret, const uint8_t *vector)
577 FR_MD5_CTX context, old;
578 uint8_t digest[AUTH_VECTOR_LEN];
579 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
586 if (room > 253) room = 253;
589 * Account for 2 bytes of the salt, and round the room
590 * available down to the nearest multiple of 16. Then,
591 * subtract one from that to account for the length byte,
592 * and the resulting number is the upper bound on the data
595 * We could short-cut this calculation just be forcing
596 * inlen to be no more than 239. It would work for all
597 * VSA's, as we don't pack multiple VSA's into one
600 * However, this calculation is more general, if a little
601 * complex. And it will work in the future for all possible
602 * kinds of weird attribute packing.
605 room -= (room & 0x0f);
608 if (inlen > room) inlen = room;
611 * Length of the encrypted data is password length plus
612 * one byte for the length of the password.
615 if ((len & 0x0f) != 0) {
619 *outlen = len + 2; /* account for the salt */
622 * Copy the password over.
624 memcpy(passwd + 3, input, inlen);
625 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
628 * Generate salt. The RFC's say:
630 * The high bit of salt[0] must be set, each salt in a
631 * packet should be unique, and they should be random
633 * So, we set the high bit, add in a counter, and then
634 * add in some CSPRNG data. should be OK..
636 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
638 passwd[1] = fr_rand();
639 passwd[2] = inlen; /* length of the password string */
641 fr_MD5Init(&context);
642 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
645 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
646 fr_MD5Update(&context, &passwd[0], 2);
648 for (n = 0; n < len; n += AUTH_PASS_LEN) {
651 fr_MD5Update(&context,
652 passwd + 2 + n - AUTH_PASS_LEN,
656 fr_MD5Final(digest, &context);
657 for (i = 0; i < AUTH_PASS_LEN; i++) {
658 passwd[i + 2 + n] ^= digest[i];
661 memcpy(output, passwd, len + 2);
666 * Parse a data structure into a RADIUS attribute.
668 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
669 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
672 int offset, len, total_length;
674 uint8_t *length_ptr, *vsa_length_ptr;
675 const uint8_t *data = NULL;
678 vendorcode = total_length = 0;
679 length_ptr = vsa_length_ptr = NULL;
682 * For interoperability, always put vendor attributes
683 * into their own VSA.
685 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
686 *(ptr++) = vp->attribute & 0xFF;
694 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
697 * This must be an RFC-format attribute. If it
698 * wasn't, then the "decode" function would have
699 * made a Vendor-Specific attribute (i.e. type
700 * 26), and we would have "vendorcode == 0" here.
704 vsa_llen = dv->length;
708 * Build a VSA header.
710 *ptr++ = PW_VENDOR_SPECIFIC;
711 vsa_length_ptr = ptr;
713 lvalue = htonl(vendorcode);
714 memcpy(ptr, &lvalue, 4);
720 ptr[0] = (vp->attribute & 0xFF);
724 ptr[0] = ((vp->attribute >> 8) & 0xFF);
725 ptr[1] = (vp->attribute & 0xFF);
731 ptr[2] = ((vp->attribute >> 8) & 0xFF);
732 ptr[3] = (vp->attribute & 0xFF);
736 return 0; /* silently discard it */
742 length_ptr = vsa_length_ptr;
743 vsa_length_ptr = NULL;
752 length_ptr = ptr + 1;
756 return 0; /* silently discard it */
760 total_length += vsa_tlen + vsa_llen;
761 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
762 *length_ptr += vsa_tlen + vsa_llen;
766 if (vp->flags.has_tag) {
767 if (TAG_VALID(vp->flags.tag)) {
768 ptr[0] = vp->flags.tag & 0xff;
771 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
773 * Tunnel passwords REQUIRE a tag, even
774 * if don't have a valid tag.
778 } /* else don't write a tag */
779 } /* else the attribute doesn't have a tag */
782 * Set up the default sources for the data.
784 data = vp->vp_octets;
791 case PW_TYPE_IPV6ADDR:
792 case PW_TYPE_IPV6PREFIX:
793 case PW_TYPE_ABINARY:
794 /* nothing more to do */
798 len = 1; /* just in case */
799 array[0] = vp->vp_integer & 0xff;
806 len = 2; /* just in case */
807 array[0] = (vp->vp_integer >> 8) & 0xff;
808 array[1] = vp->vp_integer & 0xff;
813 case PW_TYPE_INTEGER:
814 len = 4; /* just in case */
815 lvalue = htonl(vp->vp_integer);
816 memcpy(array, &lvalue, sizeof(lvalue));
819 * Perhaps discard the first octet.
821 data = &array[offset];
826 data = (const uint8_t *) &vp->vp_ipaddr;
827 len = 4; /* just in case */
831 * There are no tagged date attributes.
834 lvalue = htonl(vp->vp_date);
835 data = (const uint8_t *) &lvalue;
836 len = 4; /* just in case */
839 default: /* unknown type: ignore it */
840 librad_log("ERROR: Unknown attribute type %d", vp->type);
845 * Bound the data to 255 bytes.
847 if (len + offset + total_length > 255) {
848 len = 255 - offset - total_length;
852 * Encrypt the various password styles
854 * Attributes with encrypted values MUST be less than
857 switch (vp->flags.encrypt) {
858 case FLAG_ENCRYPT_USER_PASSWORD:
859 make_passwd(ptr + offset, &len,
861 secret, packet->vector);
864 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
866 * Check if 255 - offset - total_length is less
867 * than 18. If so, we can't fit the data into
868 * the available space, and we discard the
871 * This is ONLY a problem if we have multiple VSA's
872 * in one Vendor-Specific, though.
874 if ((255 - offset - total_length) < 18) return 0;
876 switch (packet->code) {
877 case PW_AUTHENTICATION_ACK:
878 case PW_AUTHENTICATION_REJECT:
879 case PW_ACCESS_CHALLENGE:
882 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
885 make_tunnel_passwd(ptr + offset, &len,
886 data, len, 255 - offset - total_length,
887 secret, original->vector);
889 case PW_ACCOUNTING_REQUEST:
890 case PW_DISCONNECT_REQUEST:
892 make_tunnel_passwd(ptr + offset, &len,
893 data, len, 255 - offset - total_length,
894 secret, packet->vector);
900 * The code above ensures that this attribute
903 case FLAG_ENCRYPT_ASCEND_SECRET:
904 make_secret(ptr + offset, packet->vector,
906 len = AUTH_VECTOR_LEN;
912 * Just copy the data over
914 memcpy(ptr + offset, data, len);
916 } /* switch over encryption flags */
919 * Account for the tag (if any).
924 * RFC 2865 section 5 says that zero-length attributes
927 if (len == 0) return 0;
930 * Update the various lengths.
933 if (vsa_length_ptr) *vsa_length_ptr += len;
937 return total_length; /* of attribute */
944 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
947 radius_packet_t *hdr;
949 uint16_t total_length;
956 * For simplicity in the following logic, we allow
957 * the attributes to "overflow" the 4k maximum
958 * RADIUS packet size, by one attribute.
960 * It's uint32_t, for alignment purposes.
962 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
964 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
965 what = packet_codes[packet->code];
970 DEBUG("Sending %s of id %d to %s port %d\n",
972 inet_ntop(packet->dst_ipaddr.af,
973 &packet->dst_ipaddr.ipaddr,
974 ip_buffer, sizeof(ip_buffer)),
978 * Double-check some things based on packet code.
980 switch (packet->code) {
981 case PW_AUTHENTICATION_ACK:
982 case PW_AUTHENTICATION_REJECT:
983 case PW_ACCESS_CHALLENGE:
985 librad_log("ERROR: Cannot sign response packet without a request packet.");
991 * These packet vectors start off as all zero.
993 case PW_ACCOUNTING_REQUEST:
994 case PW_DISCONNECT_REQUEST:
996 memset(packet->vector, 0, sizeof(packet->vector));
1004 * Use memory on the stack, until we know how
1005 * large the packet will be.
1007 hdr = (radius_packet_t *) data;
1010 * Build standard header
1012 hdr->code = packet->code;
1013 hdr->id = packet->id;
1015 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1017 total_length = AUTH_HDR_LEN;
1020 * Load up the configuration values for the user
1026 * FIXME: Loop twice over the reply list. The first time,
1027 * calculate the total length of data. The second time,
1028 * allocate the memory, and fill in the VP's.
1030 * Hmm... this may be slower than just doing a small
1035 * Loop over the reply attributes for the packet.
1037 for (reply = packet->vps; reply; reply = reply->next) {
1039 * Ignore non-wire attributes
1041 if ((VENDOR(reply->attribute) == 0) &&
1042 ((reply->attribute & 0xFFFF) > 0xff)) {
1045 * Permit the admin to send BADLY formatted
1046 * attributes with a debug build.
1048 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1049 memcpy(ptr, reply->vp_octets, reply->length);
1050 len = reply->length;
1058 * Set the Message-Authenticator to the correct
1059 * length and initial value.
1061 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1062 reply->length = AUTH_VECTOR_LEN;
1063 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1066 * Cache the offset to the
1067 * Message-Authenticator
1069 packet->offset = total_length;
1073 * Print out ONLY the attributes which
1074 * we're sending over the wire, and print
1075 * them out BEFORE they're encrypted.
1079 len = rad_vp2attr(packet, original, secret, reply, ptr);
1081 if (len < 0) return -1;
1084 * Check that the packet is no more than 4k in
1085 * size, AFTER writing the attribute past the 4k
1086 * boundary, but BEFORE deciding to increase the
1087 * size of the packet. Note that the 'data'
1088 * buffer, above, is one attribute longer than
1089 * necessary, in order to permit this overflow.
1091 if ((total_length + len) > MAX_PACKET_LEN) {
1097 total_length += len;
1098 } /* done looping over all attributes */
1101 * Fill in the rest of the fields, and copy the data over
1102 * from the local stack to the newly allocated memory.
1104 * Yes, all this 'memcpy' is slow, but it means
1105 * that we only allocate the minimum amount of
1106 * memory for a request.
1108 packet->data_len = total_length;
1109 packet->data = (uint8_t *) malloc(packet->data_len);
1110 if (!packet->data) {
1111 librad_log("Out of memory");
1115 memcpy(packet->data, hdr, packet->data_len);
1116 hdr = (radius_packet_t *) packet->data;
1118 total_length = htons(total_length);
1119 memcpy(hdr->length, &total_length, sizeof(total_length));
1126 * Sign a previously encoded packet.
1128 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1131 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1134 * It wasn't assigned an Id, this is bad!
1136 if (packet->id < 0) {
1137 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1141 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1142 (packet->offset < 0)) {
1143 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1148 * If there's a Message-Authenticator, update it
1149 * now, BEFORE updating the authentication vector.
1151 if (packet->offset > 0) {
1152 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1154 switch (packet->code) {
1155 case PW_ACCOUNTING_REQUEST:
1156 case PW_ACCOUNTING_RESPONSE:
1157 case PW_DISCONNECT_REQUEST:
1158 case PW_DISCONNECT_ACK:
1159 case PW_DISCONNECT_NAK:
1160 case PW_COA_REQUEST:
1163 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1166 case PW_AUTHENTICATION_ACK:
1167 case PW_AUTHENTICATION_REJECT:
1168 case PW_ACCESS_CHALLENGE:
1170 librad_log("ERROR: Cannot sign response packet without a request packet.");
1173 memcpy(hdr->vector, original->vector,
1177 default: /* others have vector already set to zero */
1183 * Set the authentication vector to zero,
1184 * calculate the signature, and put it
1185 * into the Message-Authenticator
1188 fr_hmac_md5(packet->data, packet->data_len,
1189 (const uint8_t *) secret, strlen(secret),
1191 memcpy(packet->data + packet->offset + 2,
1192 calc_auth_vector, AUTH_VECTOR_LEN);
1195 * Copy the original request vector back
1196 * to the raw packet.
1198 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1202 * Switch over the packet code, deciding how to
1205 switch (packet->code) {
1207 * Request packets are not signed, bur
1208 * have a random authentication vector.
1210 case PW_AUTHENTICATION_REQUEST:
1211 case PW_STATUS_SERVER:
1215 * Reply packets are signed with the
1216 * authentication vector of the request.
1223 fr_MD5Init(&context);
1224 fr_MD5Update(&context, packet->data, packet->data_len);
1225 fr_MD5Update(&context, (const uint8_t *) secret,
1227 fr_MD5Final(digest, &context);
1229 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1230 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1233 }/* switch over packet codes */
1239 * Reply to the request. Also attach
1240 * reply attribute value pairs and any user message provided.
1242 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1247 char ip_buffer[128];
1250 * Maybe it's a fake packet. Don't send it.
1252 if (!packet || (packet->sockfd < 0)) {
1256 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1257 what = packet_codes[packet->code];
1263 * First time through, allocate room for the packet
1265 if (!packet->data) {
1267 * Encode the packet.
1269 if (rad_encode(packet, original, secret) < 0) {
1274 * Re-sign it, including updating the
1275 * Message-Authenticator.
1277 if (rad_sign(packet, original, secret) < 0) {
1282 * If packet->data points to data, then we print out
1283 * the VP list again only for debugging.
1285 } else if (librad_debug) {
1286 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1287 inet_ntop(packet->dst_ipaddr.af,
1288 &packet->dst_ipaddr.ipaddr,
1289 ip_buffer, sizeof(ip_buffer)),
1292 for (reply = packet->vps; reply; reply = reply->next) {
1293 if ((VENDOR(reply->attribute) == 0) &&
1294 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1300 * And send it on it's way.
1302 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1303 &packet->src_ipaddr, packet->src_port,
1304 &packet->dst_ipaddr, packet->dst_port);
1309 * Validates the requesting client NAS. Calculates the
1310 * signature based on the clients private key.
1312 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1314 uint8_t digest[AUTH_VECTOR_LEN];
1318 * Zero out the auth_vector in the received packet.
1319 * Then append the shared secret to the received packet,
1320 * and calculate the MD5 sum. This must be the same
1321 * as the original MD5 sum (packet->vector).
1323 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1326 * MD5(packet + secret);
1328 fr_MD5Init(&context);
1329 fr_MD5Update(&context, packet->data, packet->data_len);
1330 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1331 fr_MD5Final(digest, &context);
1334 * Return 0 if OK, 2 if not OK.
1336 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1342 * Validates the requesting client NAS. Calculates the
1343 * signature based on the clients private key.
1345 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1348 uint8_t calc_digest[AUTH_VECTOR_LEN];
1354 if (original == NULL) {
1359 * Copy the original vector in place.
1361 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1364 * MD5(packet + secret);
1366 fr_MD5Init(&context);
1367 fr_MD5Update(&context, packet->data, packet->data_len);
1368 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1369 fr_MD5Final(calc_digest, &context);
1372 * Copy the packet's vector back to the packet.
1374 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1377 * Return 0 if OK, 2 if not OK.
1379 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1385 * See if the data pointed to by PTR is a valid RADIUS packet.
1387 * packet is not 'const * const' because we may update data_len,
1388 * if there's more data in the UDP packet than in the RADIUS packet.
1390 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1395 radius_packet_t *hdr;
1396 char host_ipaddr[128];
1402 * Check for packets smaller than the packet header.
1404 * RFC 2865, Section 3., subsection 'length' says:
1406 * "The minimum length is 20 ..."
1408 if (packet->data_len < AUTH_HDR_LEN) {
1409 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1410 inet_ntop(packet->src_ipaddr.af,
1411 &packet->src_ipaddr.ipaddr,
1412 host_ipaddr, sizeof(host_ipaddr)),
1413 packet->data_len, AUTH_HDR_LEN);
1418 * RFC 2865, Section 3., subsection 'length' says:
1420 * " ... and maximum length is 4096."
1422 if (packet->data_len > MAX_PACKET_LEN) {
1423 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1424 inet_ntop(packet->src_ipaddr.af,
1425 &packet->src_ipaddr.ipaddr,
1426 host_ipaddr, sizeof(host_ipaddr)),
1427 packet->data_len, MAX_PACKET_LEN);
1432 * Check for packets with mismatched size.
1433 * i.e. We've received 128 bytes, and the packet header
1434 * says it's 256 bytes long.
1436 totallen = (packet->data[2] << 8) | packet->data[3];
1437 hdr = (radius_packet_t *)packet->data;
1440 * Code of 0 is not understood.
1441 * Code of 16 or greate is not understood.
1443 if ((hdr->code == 0) ||
1444 (hdr->code >= MAX_PACKET_CODE)) {
1445 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1446 inet_ntop(packet->src_ipaddr.af,
1447 &packet->src_ipaddr.ipaddr,
1448 host_ipaddr, sizeof(host_ipaddr)),
1454 * Message-Authenticator is required in Status-Server
1455 * packets, otherwise they can be trivially forged.
1457 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1460 * It's also required if the caller asks for it.
1462 if (flags) require_ma = 1;
1465 * Repeat the length checks. This time, instead of
1466 * looking at the data we received, look at the value
1467 * of the 'length' field inside of the packet.
1469 * Check for packets smaller than the packet header.
1471 * RFC 2865, Section 3., subsection 'length' says:
1473 * "The minimum length is 20 ..."
1475 if (totallen < AUTH_HDR_LEN) {
1476 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1477 inet_ntop(packet->src_ipaddr.af,
1478 &packet->src_ipaddr.ipaddr,
1479 host_ipaddr, sizeof(host_ipaddr)),
1480 totallen, AUTH_HDR_LEN);
1485 * And again, for the value of the 'length' field.
1487 * RFC 2865, Section 3., subsection 'length' says:
1489 * " ... and maximum length is 4096."
1491 if (totallen > MAX_PACKET_LEN) {
1492 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1493 inet_ntop(packet->src_ipaddr.af,
1494 &packet->src_ipaddr.ipaddr,
1495 host_ipaddr, sizeof(host_ipaddr)),
1496 totallen, MAX_PACKET_LEN);
1501 * RFC 2865, Section 3., subsection 'length' says:
1503 * "If the packet is shorter than the Length field
1504 * indicates, it MUST be silently discarded."
1506 * i.e. No response to the NAS.
1508 if (packet->data_len < totallen) {
1509 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1510 inet_ntop(packet->src_ipaddr.af,
1511 &packet->src_ipaddr.ipaddr,
1512 host_ipaddr, sizeof(host_ipaddr)),
1513 packet->data_len, totallen);
1518 * RFC 2865, Section 3., subsection 'length' says:
1520 * "Octets outside the range of the Length field MUST be
1521 * treated as padding and ignored on reception."
1523 if (packet->data_len > totallen) {
1525 * We're shortening the packet below, but just
1526 * to be paranoid, zero out the extra data.
1528 memset(packet->data + totallen, 0, packet->data_len - totallen);
1529 packet->data_len = totallen;
1533 * Walk through the packet's attributes, ensuring that
1534 * they add up EXACTLY to the size of the packet.
1536 * If they don't, then the attributes either under-fill
1537 * or over-fill the packet. Any parsing of the packet
1538 * is impossible, and will result in unknown side effects.
1540 * This would ONLY happen with buggy RADIUS implementations,
1541 * or with an intentional attack. Either way, we do NOT want
1542 * to be vulnerable to this problem.
1545 count = totallen - AUTH_HDR_LEN;
1550 * Attribute number zero is NOT defined.
1553 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1554 inet_ntop(packet->src_ipaddr.af,
1555 &packet->src_ipaddr.ipaddr,
1556 host_ipaddr, sizeof(host_ipaddr)));
1561 * Attributes are at LEAST as long as the ID & length
1562 * fields. Anything shorter is an invalid attribute.
1565 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1566 inet_ntop(packet->src_ipaddr.af,
1567 &packet->src_ipaddr.ipaddr,
1568 host_ipaddr, sizeof(host_ipaddr)),
1574 * Sanity check the attributes for length.
1577 default: /* don't do anything by default */
1581 * If there's an EAP-Message, we require
1582 * a Message-Authenticator.
1584 case PW_EAP_MESSAGE:
1588 case PW_MESSAGE_AUTHENTICATOR:
1589 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1590 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1591 inet_ntop(packet->src_ipaddr.af,
1592 &packet->src_ipaddr.ipaddr,
1593 host_ipaddr, sizeof(host_ipaddr)),
1602 * FIXME: Look up the base 255 attributes in the
1603 * dictionary, and switch over their type. For
1604 * integer/date/ip, the attribute length SHOULD
1607 count -= attr[1]; /* grab the attribute length */
1609 num_attributes++; /* seen one more attribute */
1613 * If the attributes add up to a packet, it's allowed.
1615 * If not, we complain, and throw the packet away.
1618 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1619 inet_ntop(packet->src_ipaddr.af,
1620 &packet->src_ipaddr.ipaddr,
1621 host_ipaddr, sizeof(host_ipaddr)));
1626 * If we're configured to look for a maximum number of
1627 * attributes, and we've seen more than that maximum,
1628 * then throw the packet away, as a possible DoS.
1630 if ((librad_max_attributes > 0) &&
1631 (num_attributes > librad_max_attributes)) {
1632 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1633 inet_ntop(packet->src_ipaddr.af,
1634 &packet->src_ipaddr.ipaddr,
1635 host_ipaddr, sizeof(host_ipaddr)),
1636 num_attributes, librad_max_attributes);
1641 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1643 * A packet with an EAP-Message attribute MUST also have
1644 * a Message-Authenticator attribute.
1646 * A Message-Authenticator all by itself is OK, though.
1648 * Similarly, Status-Server packets MUST contain
1649 * Message-Authenticator attributes.
1651 if (require_ma && ! seen_ma) {
1652 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1653 inet_ntop(packet->src_ipaddr.af,
1654 &packet->src_ipaddr.ipaddr,
1655 host_ipaddr, sizeof(host_ipaddr)));
1660 * Fill RADIUS header fields
1662 packet->code = hdr->code;
1663 packet->id = hdr->id;
1664 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1671 * Receive UDP client requests, and fill in
1672 * the basics of a RADIUS_PACKET structure.
1674 RADIUS_PACKET *rad_recv(int fd, int flags)
1676 RADIUS_PACKET *packet;
1679 * Allocate the new request data structure
1681 if ((packet = malloc(sizeof(*packet))) == NULL) {
1682 librad_log("out of memory");
1685 memset(packet, 0, sizeof(*packet));
1687 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1688 &packet->src_ipaddr, &packet->src_port,
1689 &packet->dst_ipaddr, &packet->dst_port);
1692 * Check for socket errors.
1694 if (packet->data_len < 0) {
1695 librad_log("Error receiving packet: %s", strerror(errno));
1696 /* packet->data is NULL */
1702 * If the packet is too big, then rad_recvfrom did NOT
1703 * allocate memory. Instead, it just discarded the
1706 if (packet->data_len > MAX_PACKET_LEN) {
1707 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1708 /* packet->data is NULL */
1714 * Read no data. Continue.
1715 * This check is AFTER the MAX_PACKET_LEN check above, because
1716 * if the packet is larger than MAX_PACKET_LEN, we also have
1717 * packet->data == NULL
1719 if ((packet->data_len == 0) || !packet->data) {
1720 librad_log("Empty packet: Socket is not ready.");
1726 * See if it's a well-formed RADIUS packet.
1728 if (!rad_packet_ok(packet, flags)) {
1734 * Remember which socket we read the packet from.
1736 packet->sockfd = fd;
1739 * FIXME: Do even more filtering by only permitting
1740 * certain IP's. The problem is that we don't know
1741 * how to do this properly for all possible clients...
1745 * Explicitely set the VP list to empty.
1750 char host_ipaddr[128];
1752 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1753 DEBUG("rad_recv: %s packet from host %s port %d",
1754 packet_codes[packet->code],
1755 inet_ntop(packet->src_ipaddr.af,
1756 &packet->src_ipaddr.ipaddr,
1757 host_ipaddr, sizeof(host_ipaddr)),
1760 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1761 inet_ntop(packet->src_ipaddr.af,
1762 &packet->src_ipaddr.ipaddr,
1763 host_ipaddr, sizeof(host_ipaddr)),
1767 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1775 * Verify the signature of a packet.
1777 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1784 if (!packet || !packet->data) return -1;
1787 * Before we allocate memory for the attributes, do more
1790 ptr = packet->data + AUTH_HDR_LEN;
1791 length = packet->data_len - AUTH_HDR_LEN;
1792 while (length > 0) {
1793 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1794 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1799 default: /* don't do anything. */
1803 * Note that more than one Message-Authenticator
1804 * attribute is invalid.
1806 case PW_MESSAGE_AUTHENTICATOR:
1807 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1808 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1810 switch (packet->code) {
1814 case PW_ACCOUNTING_REQUEST:
1815 case PW_ACCOUNTING_RESPONSE:
1816 case PW_DISCONNECT_REQUEST:
1817 case PW_DISCONNECT_ACK:
1818 case PW_DISCONNECT_NAK:
1819 case PW_COA_REQUEST:
1822 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1825 case PW_AUTHENTICATION_ACK:
1826 case PW_AUTHENTICATION_REJECT:
1827 case PW_ACCESS_CHALLENGE:
1829 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1832 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1836 fr_hmac_md5(packet->data, packet->data_len,
1837 (const uint8_t *) secret, strlen(secret),
1839 if (memcmp(calc_auth_vector, msg_auth_vector,
1840 sizeof(calc_auth_vector)) != 0) {
1842 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1843 inet_ntop(packet->src_ipaddr.af,
1844 &packet->src_ipaddr.ipaddr,
1845 buffer, sizeof(buffer)));
1846 /* Silently drop packet, according to RFC 3579 */
1848 } /* else the message authenticator was good */
1851 * Reinitialize Authenticators.
1853 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1854 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1856 } /* switch over the attributes */
1860 } /* loop over the packet, sanity checking the attributes */
1863 * It looks like a RADIUS packet, but we can't validate
1866 if ((packet->code == 0) || (packet->code >= MAX_PACKET_CODE)) {
1868 librad_log("Received Unknown packet code %d "
1869 "from client %s port %d: Cannot validate signature.",
1871 inet_ntop(packet->src_ipaddr.af,
1872 &packet->src_ipaddr.ipaddr,
1873 buffer, sizeof(buffer)),
1879 * Calculate and/or verify digest.
1881 switch(packet->code) {
1885 case PW_AUTHENTICATION_REQUEST:
1886 case PW_STATUS_SERVER:
1888 * The authentication vector is random
1889 * nonsense, invented by the client.
1893 case PW_COA_REQUEST:
1894 case PW_DISCONNECT_REQUEST:
1895 case PW_ACCOUNTING_REQUEST:
1896 if (calc_acctdigest(packet, secret) > 1) {
1897 librad_log("Received %s packet "
1898 "from %s with invalid signature! (Shared secret is incorrect.)",
1899 packet_codes[packet->code],
1900 inet_ntop(packet->src_ipaddr.af,
1901 &packet->src_ipaddr.ipaddr,
1902 buffer, sizeof(buffer)));
1907 /* Verify the reply digest */
1908 case PW_AUTHENTICATION_ACK:
1909 case PW_AUTHENTICATION_REJECT:
1910 case PW_ACCESS_CHALLENGE:
1911 case PW_ACCOUNTING_RESPONSE:
1912 case PW_DISCONNECT_ACK:
1913 case PW_DISCONNECT_NAK:
1916 rcode = calc_replydigest(packet, original, secret);
1918 librad_log("Received %s packet "
1919 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1920 packet_codes[packet->code],
1921 inet_ntop(packet->src_ipaddr.af,
1922 &packet->src_ipaddr.ipaddr,
1923 buffer, sizeof(buffer)),
1931 librad_log("Received Unknown packet code %d "
1932 "from client %s port %d: Cannot validate signature",
1934 inet_ntop(packet->src_ipaddr.af,
1935 &packet->src_ipaddr.ipaddr,
1936 buffer, sizeof(buffer)),
1946 * Parse a RADIUS attribute into a data structure.
1948 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1949 const char *secret, int attribute, int length,
1950 const uint8_t *data)
1955 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1960 * If length is greater than 253, something is SERIOUSLY
1963 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1965 vp->length = length;
1966 vp->operator = T_OP_EQ;
1972 if (vp->flags.has_tag) {
1973 if (TAG_VALID(data[0]) ||
1974 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1976 * Tunnel passwords REQUIRE a tag, even
1977 * if don't have a valid tag.
1979 vp->flags.tag = data[0];
1981 if ((vp->type == PW_TYPE_STRING) ||
1982 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1987 * Copy the data to be decrypted
1989 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1990 vp->length -= offset;
1993 * Decrypt the attribute.
1995 switch (vp->flags.encrypt) {
1999 case FLAG_ENCRYPT_USER_PASSWORD:
2001 rad_pwdecode((char *)vp->vp_strvalue,
2005 rad_pwdecode((char *)vp->vp_strvalue,
2009 if (vp->attribute == PW_USER_PASSWORD) {
2010 vp->length = strlen(vp->vp_strvalue);
2015 * Tunnel-Password's may go ONLY
2016 * in response packets.
2018 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2019 if (!original) goto raw;
2021 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2022 secret, original->vector) < 0) {
2028 * Ascend-Send-Secret
2029 * Ascend-Receive-Secret
2031 case FLAG_ENCRYPT_ASCEND_SECRET:
2035 uint8_t my_digest[AUTH_VECTOR_LEN];
2036 make_secret(my_digest,
2039 memcpy(vp->vp_strvalue, my_digest,
2041 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2042 vp->length = strlen(vp->vp_strvalue);
2048 } /* switch over encryption flags */
2052 case PW_TYPE_STRING:
2053 case PW_TYPE_OCTETS:
2054 case PW_TYPE_ABINARY:
2055 /* nothing more to do */
2059 if (vp->length != 1) goto raw;
2061 vp->vp_integer = vp->vp_octets[0];
2066 if (vp->length != 2) goto raw;
2068 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2071 case PW_TYPE_INTEGER:
2072 if (vp->length != 4) goto raw;
2074 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2075 vp->vp_integer = ntohl(vp->vp_integer);
2077 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2080 * Try to get named VALUEs
2084 dval = dict_valbyattr(vp->attribute,
2087 strlcpy(vp->vp_strvalue,
2089 sizeof(vp->vp_strvalue));
2095 if (vp->length != 4) goto raw;
2097 memcpy(&vp->vp_date, vp->vp_octets, 4);
2098 vp->vp_date = ntohl(vp->vp_date);
2102 case PW_TYPE_IPADDR:
2103 if (vp->length != 4) goto raw;
2105 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2109 * IPv6 interface ID is 8 octets long.
2112 if (vp->length != 8) goto raw;
2113 /* vp->vp_ifid == vp->vp_octets */
2117 * IPv6 addresses are 16 octets long
2119 case PW_TYPE_IPV6ADDR:
2120 if (vp->length != 16) goto raw;
2121 /* vp->vp_ipv6addr == vp->vp_octets */
2125 * IPv6 prefixes are 2 to 18 octets long.
2127 * RFC 3162: The first octet is unused.
2128 * The second is the length of the prefix
2129 * the rest are the prefix data.
2131 * The prefix length can have value 0 to 128.
2133 case PW_TYPE_IPV6PREFIX:
2134 if (vp->length < 2 || vp->length > 18) goto raw;
2135 if (vp->vp_octets[1] > 128) goto raw;
2138 * FIXME: double-check that
2139 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2141 if (vp->length < 18) {
2142 memset(vp->vp_octets + vp->length, 0,
2149 vp->type = PW_TYPE_OCTETS;
2150 vp->length = length;
2151 memcpy(vp->vp_octets, data, length);
2155 * Ensure there's no encryption or tag stuff,
2156 * we just pass the attribute as-is.
2158 memset(&vp->flags, 0, sizeof(vp->flags));
2166 * Calculate/check digest, and decode radius attributes.
2168 * -1 on decoding error
2171 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2175 uint32_t vendorcode;
2183 radius_packet_t *hdr;
2184 int vsa_tlen, vsa_llen;
2185 DICT_VENDOR *dv = NULL;
2186 int num_attributes = 0;
2189 * Extract attribute-value pairs
2191 hdr = (radius_packet_t *)packet->data;
2193 packet_length = packet->data_len - AUTH_HDR_LEN;
2196 * There may be VP's already in the packet. Don't
2199 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2205 vsa_tlen = vsa_llen = 1;
2208 * We have to read at least two bytes.
2210 * rad_recv() above ensures that this is OK.
2212 while (packet_length > 0) {
2217 * Normal attribute, handle it like normal.
2219 if (vendorcode == 0) {
2221 * No room to read attr/length,
2222 * or bad attribute, or attribute is
2223 * too short, or attribute is too long,
2224 * stop processing the packet.
2226 if ((packet_length < 2) ||
2227 (ptr[0] == 0) || (ptr[1] < 2) ||
2228 (ptr[1] > packet_length)) break;
2236 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2239 * No vendor code, or ONLY vendor code.
2241 if (attrlen <= 4) goto create_pair;
2247 * Handle Vendor-Specific
2249 if (vendorlen == 0) {
2255 * attrlen was checked above.
2257 memcpy(&lvalue, ptr, 4);
2258 myvendor = ntohl(lvalue);
2261 * Zero isn't allowed.
2263 if (myvendor == 0) goto create_pair;
2266 * This is an implementation issue.
2267 * We currently pack vendor into the upper
2268 * 16 bits of a 32-bit attribute number,
2269 * so we can't handle vendor numbers larger
2272 if (myvendor > 65535) goto create_pair;
2274 vsa_tlen = vsa_llen = 1;
2275 dv = dict_vendorbyvalue(myvendor);
2277 vsa_tlen = dv->type;
2278 vsa_llen = dv->length;
2282 * Sweep through the list of VSA's,
2283 * seeing if they exactly fill the
2284 * outer Vendor-Specific attribute.
2286 * If not, create a raw Vendor-Specific.
2289 sublen = attrlen - 4;
2292 * See if we can parse it.
2298 * Don't have a type, it's bad.
2300 if (sublen < vsa_tlen) goto create_pair;
2303 * Ensure that the attribute number
2312 myattr = (subptr[0] << 8) | subptr[1];
2316 if ((subptr[0] != 0) ||
2317 (subptr[1] != 0)) goto create_pair;
2319 myattr = (subptr[2] << 8) | subptr[3];
2323 * Our dictionary is broken.
2330 * Not enough room for one more
2333 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2336 attribute = (myvendor << 16) | myattr;
2337 ptr += 4 + vsa_tlen;
2338 attrlen -= (4 + vsa_tlen);
2339 packet_length -= 4 + vsa_tlen;
2343 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2346 if (subptr[vsa_tlen] > sublen)
2348 sublen -= subptr[vsa_tlen];
2349 subptr += subptr[vsa_tlen];
2353 if (subptr[vsa_tlen] != 0) goto create_pair;
2354 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2356 if (subptr[vsa_tlen + 1] > sublen)
2358 sublen -= subptr[vsa_tlen + 1];
2359 subptr += subptr[vsa_tlen + 1];
2363 * Our dictionaries are
2369 } while (sublen > 0);
2371 vendorcode = myvendor;
2372 vendorlen = attrlen - 4;
2379 * attrlen is the length of this attribute.
2380 * total_len is the length of the encompassing
2389 attribute = (ptr[0] << 8) | ptr[1];
2392 default: /* can't hit this. */
2395 attribute |= (vendorcode << 16);
2400 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2404 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2407 default: /* can't hit this. */
2411 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2412 if (vendorlen == 0) vendorcode = 0;
2413 packet_length -= (vsa_tlen + vsa_llen);
2416 * Create the attribute, setting the default type
2417 * to 'octets'. If the type in the dictionary
2418 * is different, then the dictionary type will
2419 * over-ride this one.
2421 * If the attribute has no data, then discard it.
2424 if (!attrlen) goto next;
2426 pair = rad_attr2vp(packet, original, secret,
2427 attribute, attrlen, ptr);
2429 pairfree(&packet->vps);
2430 librad_log("out of memory");
2443 * VSA's may not have been counted properly in
2444 * rad_packet_ok() above, as it is hard to count
2445 * then without using the dictionary. We
2446 * therefore enforce the limits here, too.
2448 if ((librad_max_attributes > 0) &&
2449 (num_attributes > librad_max_attributes)) {
2450 char host_ipaddr[128];
2452 pairfree(&packet->vps);
2453 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2454 inet_ntop(packet->src_ipaddr.af,
2455 &packet->src_ipaddr.ipaddr,
2456 host_ipaddr, sizeof(host_ipaddr)),
2457 num_attributes, librad_max_attributes);
2463 packet_length -= attrlen;
2467 * Merge information from the outside world into our
2470 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2479 * We assume that the passwd buffer passed is big enough.
2480 * RFC2138 says the password is max 128 chars, so the size
2481 * of the passwd buffer must be at least 129 characters.
2482 * Preferably it's just MAX_STRING_LEN.
2484 * int *pwlen is updated to the new length of the encrypted
2485 * password - a multiple of 16 bytes.
2487 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2488 const uint8_t *vector)
2490 FR_MD5_CTX context, old;
2491 uint8_t digest[AUTH_VECTOR_LEN];
2492 int i, n, secretlen;
2496 * RFC maximum is 128 bytes.
2498 * If length is zero, pad it out with zeros.
2500 * If the length isn't aligned to 16 bytes,
2501 * zero out the extra data.
2505 if (len > 128) len = 128;
2508 memset(passwd, 0, AUTH_PASS_LEN);
2509 len = AUTH_PASS_LEN;
2510 } else if ((len % AUTH_PASS_LEN) != 0) {
2511 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2512 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2517 * Use the secret to setup the decryption digest
2519 secretlen = strlen(secret);
2521 fr_MD5Init(&context);
2522 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2523 old = context; /* save intermediate work */
2526 * Encrypt it in place. Don't bother checking
2527 * len, as we've ensured above that it's OK.
2529 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2531 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2532 fr_MD5Final(digest, &context);
2535 fr_MD5Update(&context,
2536 (uint8_t *) passwd + n - AUTH_PASS_LEN,
2538 fr_MD5Final(digest, &context);
2541 for (i = 0; i < AUTH_PASS_LEN; i++) {
2542 passwd[i + n] ^= digest[i];
2552 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
2553 const uint8_t *vector)
2555 FR_MD5_CTX context, old;
2556 uint8_t digest[AUTH_VECTOR_LEN];
2558 size_t n, secretlen;
2561 * The RFC's say that the maximum is 128.
2562 * The buffer we're putting it into above is 254, so
2563 * we don't need to do any length checking.
2565 if (pwlen > 128) pwlen = 128;
2570 if (pwlen == 0) goto done;
2573 * Use the secret to setup the decryption digest
2575 secretlen = strlen(secret);
2577 fr_MD5Init(&context);
2578 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2579 old = context; /* save intermediate work */
2582 * The inverse of the code above.
2584 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2586 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2587 fr_MD5Final(digest, &context);
2590 if (pwlen > AUTH_PASS_LEN) {
2591 fr_MD5Update(&context, (uint8_t *) passwd,
2595 fr_MD5Final(digest, &context);
2598 if (pwlen > (n + AUTH_PASS_LEN)) {
2599 fr_MD5Update(&context, (uint8_t *) passwd + n,
2604 for (i = 0; i < AUTH_PASS_LEN; i++) {
2605 passwd[i + n] ^= digest[i];
2610 passwd[pwlen] = '\0';
2611 return strlen(passwd);
2616 * Encode Tunnel-Password attributes when sending them out on the wire.
2618 * int *pwlen is updated to the new length of the encrypted
2619 * password - a multiple of 16 bytes.
2621 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2624 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
2625 const uint8_t *vector)
2627 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2628 unsigned char digest[AUTH_VECTOR_LEN];
2630 int i, n, secretlen;
2635 if (len > 127) len = 127;
2638 * Shift the password 3 positions right to place a salt and original
2639 * length, tag will be added automatically on packet send
2641 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2645 * save original password length as first password character;
2652 * Generate salt. The RFC's say:
2654 * The high bit of salt[0] must be set, each salt in a
2655 * packet should be unique, and they should be random
2657 * So, we set the high bit, add in a counter, and then
2658 * add in some CSPRNG data. should be OK..
2660 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2661 (fr_rand() & 0x07));
2662 salt[1] = fr_rand();
2665 * Padd password to multiple of AUTH_PASS_LEN bytes.
2667 n = len % AUTH_PASS_LEN;
2669 n = AUTH_PASS_LEN - n;
2670 for (; n > 0; n--, len++)
2673 /* set new password length */
2677 * Use the secret to setup the decryption digest
2679 secretlen = strlen(secret);
2680 memcpy(buffer, secret, secretlen);
2682 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2684 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2685 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2686 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2688 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2689 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2692 for (i = 0; i < AUTH_PASS_LEN; i++) {
2693 passwd[i + n2] ^= digest[i];
2701 * Decode Tunnel-Password encrypted attributes.
2703 * Defined in RFC-2868, this uses a two char SALT along with the
2704 * initial intermediate value, to differentiate it from the
2707 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
2708 const uint8_t *vector)
2710 FR_MD5_CTX context, old;
2711 uint8_t digest[AUTH_VECTOR_LEN];
2713 unsigned i, n, len, reallen;
2718 * We need at least a salt.
2721 librad_log("tunnel password is too short");
2726 * There's a salt, but no password. Or, there's a salt
2727 * and a 'data_len' octet. It's wrong, but at least we
2728 * can figure out what it means: the password is empty.
2730 * Note that this means we ignore the 'data_len' field,
2731 * if the attribute length tells us that there's no
2732 * more data. So the 'data_len' field may be wrong,
2741 len -= 2; /* discount the salt */
2744 * Use the secret to setup the decryption digest
2746 secretlen = strlen(secret);
2748 fr_MD5Init(&context);
2749 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2750 old = context; /* save intermediate work */
2753 * Set up the initial key:
2755 * b(1) = MD5(secret + vector + salt)
2757 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2758 fr_MD5Update(&context, passwd, 2);
2761 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2765 fr_MD5Final(digest, &context);
2770 * A quick check: decrypt the first octet
2771 * of the password, which is the
2772 * 'data_len' field. Ensure it's sane.
2774 reallen = passwd[2] ^ digest[0];
2775 if (reallen >= len) {
2776 librad_log("tunnel password is too long for the attribute");
2780 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2784 fr_MD5Final(digest, &context);
2787 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2790 for (i = base; i < AUTH_PASS_LEN; i++) {
2791 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2796 * See make_tunnel_password, above.
2798 if (reallen > 239) reallen = 239;
2801 passwd[reallen] = 0;
2807 * Encode a CHAP password
2809 * FIXME: might not work with Ascend because
2810 * we use vp->length, and Ascend gear likes
2811 * to send an extra '\0' in the string!
2813 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2814 VALUE_PAIR *password)
2818 uint8_t string[MAX_STRING_LEN * 2 + 1];
2819 VALUE_PAIR *challenge;
2822 * Sanity check the input parameters
2824 if ((packet == NULL) || (password == NULL)) {
2829 * Note that the password VP can be EITHER
2830 * a User-Password attribute (from a check-item list),
2831 * or a CHAP-Password attribute (the client asking
2832 * the library to encode it).
2840 memcpy(ptr, password->vp_strvalue, password->length);
2841 ptr += password->length;
2842 i += password->length;
2845 * Use Chap-Challenge pair if present,
2846 * Request-Authenticator otherwise.
2848 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2850 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2851 i += challenge->length;
2853 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2854 i += AUTH_VECTOR_LEN;
2858 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2865 * Seed the random number generator.
2867 * May be called any number of times.
2869 void fr_rand_seed(const void *data, size_t size)
2874 * Ensure that the pool is initialized.
2876 if (!fr_rand_initialized) {
2879 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2881 fd = open("/dev/urandom", O_RDONLY);
2887 while (total < sizeof(fr_rand_pool.randrsl)) {
2888 this = read(fd, fr_rand_pool.randrsl,
2889 sizeof(fr_rand_pool.randrsl) - total);
2890 if ((this < 0) && (errno != EINTR)) break;
2891 if (this > 0) total += this;
2895 fr_rand_pool.randrsl[0] = fd;
2896 fr_rand_pool.randrsl[1] = time(NULL);
2897 fr_rand_pool.randrsl[2] = errno;
2900 fr_randinit(&fr_rand_pool, 1);
2901 fr_rand_pool.randcnt = 0;
2902 fr_rand_initialized = 1;
2908 * Hash the user data
2911 if (!hash) hash = fr_rand();
2912 hash = fr_hash_update(data, size, hash);
2914 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2919 * Return a 32-bit random number.
2921 uint32_t fr_rand(void)
2926 * Ensure that the pool is initialized.
2928 if (!fr_rand_initialized) {
2929 fr_rand_seed(NULL, 0);
2932 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2933 if (fr_rand_pool.randcnt >= 256) {
2934 fr_rand_pool.randcnt = 0;
2935 fr_isaac(&fr_rand_pool);
2943 * Allocate a new RADIUS_PACKET
2945 RADIUS_PACKET *rad_alloc(int newvector)
2949 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2950 librad_log("out of memory");
2953 memset(rp, 0, sizeof(*rp));
2959 uint32_t hash, base;
2962 * Don't expose the actual contents of the random
2966 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2967 hash = fr_rand() ^ base;
2968 memcpy(rp->vector + i, &hash, sizeof(hash));
2971 fr_rand(); /* stir the pool again */
2977 * Free a RADIUS_PACKET
2979 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2981 RADIUS_PACKET *radius_packet;
2983 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2984 radius_packet = *radius_packet_ptr;
2986 free(radius_packet->data);
2988 pairfree(&radius_packet->vps);
2990 free(radius_packet);
2992 *radius_packet_ptr = NULL;