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;
58 typedef struct radius_packet_t {
62 uint8_t vector[AUTH_VECTOR_LEN];
66 static fr_randctx fr_rand_pool; /* across multiple calls */
67 static int fr_rand_initialized = 0;
68 static unsigned int salt_offset = 0;
71 #define MAX_PACKET_CODE (52)
72 static const char *packet_codes[] = {
78 "Accounting-Response",
94 "Resource-Free-Request",
95 "Resource-Free-Response",
96 "Resource-Query-Request",
97 "Resource-Query-Response",
98 "Alternate-Resource-Reclaim-Request",
100 "NAS-Reboot-Response",
113 "Disconnect-Request",
123 "IP-Address-Allocate",
129 * Wrapper for sendto which handles sendfromto, IPv6, and all
130 * possible combinations.
132 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
133 fr_ipaddr_t *src_ipaddr, int src_port,
134 fr_ipaddr_t *dst_ipaddr, int dst_port)
136 struct sockaddr_storage dst;
137 socklen_t sizeof_dst = sizeof(dst);
139 #ifdef WITH_UDPFROMTO
140 struct sockaddr_storage src;
141 socklen_t sizeof_src = sizeof(src);
143 memset(&src, 0, sizeof(src));
145 memset(&dst, 0, sizeof(dst));
150 if (dst_ipaddr->af == AF_INET) {
151 struct sockaddr_in *s4;
153 s4 = (struct sockaddr_in *)&dst;
154 sizeof_dst = sizeof(struct sockaddr_in);
156 s4->sin_family = AF_INET;
157 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
158 s4->sin_port = htons(dst_port);
160 #ifdef WITH_UDPFROMTO
161 s4 = (struct sockaddr_in *)&src;
162 sizeof_src = sizeof(struct sockaddr_in);
164 s4->sin_family = AF_INET;
165 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
166 s4->sin_port = htons(src_port);
168 src_port = src_port; /* -Wunused */
172 * IPv6 MAY be supported.
174 #ifdef HAVE_STRUCT_SOCKADDR_IN6
175 } else if (dst_ipaddr->af == AF_INET6) {
176 struct sockaddr_in6 *s6;
178 s6 = (struct sockaddr_in6 *)&dst;
179 sizeof_dst = sizeof(struct sockaddr_in6);
181 s6->sin6_family = AF_INET6;
182 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
183 s6->sin6_port = htons(dst_port);
185 #ifdef WITH_UDPFROMTO
186 return -1; /* UDPFROMTO && IPv6 are not supported */
188 s6 = (struct sockaddr_in6 *)&src;
189 sizeof_src = sizeof(struct sockaddr_in6);
191 s6->sin6_family = AF_INET6;
192 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
194 #endif /* WITH_UDPFROMTO */
195 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
196 } else return -1; /* Unknown address family, Die Die Die! */
198 #ifdef WITH_UDPFROMTO
200 * Only IPv4 is supported for udpfromto.
202 * And if they don't specify a source IP address, don't
205 if ((dst_ipaddr->af == AF_INET) ||
206 (src_ipaddr->af != AF_UNSPEC)) {
207 return sendfromto(sockfd, data, data_len, flags,
208 (struct sockaddr *)&src, sizeof_src,
209 (struct sockaddr *)&dst, sizeof_dst);
212 src_ipaddr = src_ipaddr; /* -Wunused */
216 * No udpfromto, OR an IPv6 socket, fail gracefully.
218 return sendto(sockfd, data, data_len, flags,
219 (struct sockaddr *)&dst, sizeof_dst);
223 void rad_recv_discard(int sockfd)
226 struct sockaddr_storage src;
227 socklen_t sizeof_src = sizeof(src);
229 recvfrom(sockfd, header, sizeof(header), 0,
230 (struct sockaddr *)&src, &sizeof_src);
234 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
237 ssize_t data_len, packet_len;
239 struct sockaddr_storage src;
240 socklen_t sizeof_src = sizeof(src);
242 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
243 (struct sockaddr *)&src, &sizeof_src);
245 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
250 * Too little data is available, discard the packet.
253 recvfrom(sockfd, header, sizeof(header), 0,
254 (struct sockaddr *)&src, &sizeof_src);
257 } else { /* we got 4 bytes of data. */
259 * See how long the packet says it is.
261 packet_len = (header[2] * 256) + header[3];
264 * The length in the packet says it's less than
265 * a RADIUS header length: discard it.
267 if (packet_len < AUTH_HDR_LEN) {
268 recvfrom(sockfd, header, sizeof(header), 0,
269 (struct sockaddr *)&src, &sizeof_src);
273 * Enforce RFC requirements, for sanity.
274 * Anything after 4k will be discarded.
276 } else if (packet_len > MAX_PACKET_LEN) {
277 recvfrom(sockfd, header, sizeof(header), 0,
278 (struct sockaddr *)&src, &sizeof_src);
283 if (src.ss_family == AF_INET) {
284 struct sockaddr_in *s4;
286 s4 = (struct sockaddr_in *)&src;
287 src_ipaddr->af = AF_INET;
288 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
289 *src_port = ntohs(s4->sin_port);
291 #ifdef HAVE_STRUCT_SOCKADDR_IN6
292 } else if (src.ss_family == AF_INET6) {
293 struct sockaddr_in6 *s6;
295 s6 = (struct sockaddr_in6 *)&src;
296 src_ipaddr->af = AF_INET6;
297 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
298 *src_port = ntohs(s6->sin6_port);
302 recvfrom(sockfd, header, sizeof(header), 0,
303 (struct sockaddr *)&src, &sizeof_src);
310 * The packet says it's this long, but the actual UDP
311 * size could still be smaller.
318 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
319 * possible combinations.
321 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
322 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
323 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
325 struct sockaddr_storage src;
326 struct sockaddr_storage dst;
327 socklen_t sizeof_src = sizeof(src);
328 socklen_t sizeof_dst = sizeof(dst);
334 memset(&src, 0, sizeof_src);
335 memset(&dst, 0, sizeof_dst);
338 * Get address family, etc. first, so we know if we
339 * need to do udpfromto.
341 * FIXME: udpfromto also does this, but it's not
342 * a critical problem.
344 if (getsockname(sockfd, (struct sockaddr *)&dst,
345 &sizeof_dst) < 0) return -1;
348 * Read the length of the packet, from the packet.
349 * This lets us allocate the buffer to use for
350 * reading the rest of the packet.
352 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
353 (struct sockaddr *)&src, &sizeof_src);
355 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
360 * Too little data is available, discard the packet.
363 recvfrom(sockfd, header, sizeof(header), flags,
364 (struct sockaddr *)&src, &sizeof_src);
367 } else { /* we got 4 bytes of data. */
369 * See how long the packet says it is.
371 len = (header[2] * 256) + header[3];
374 * The length in the packet says it's less than
375 * a RADIUS header length: discard it.
377 if (len < AUTH_HDR_LEN) {
378 recvfrom(sockfd, header, sizeof(header), flags,
379 (struct sockaddr *)&src, &sizeof_src);
383 * Enforce RFC requirements, for sanity.
384 * Anything after 4k will be discarded.
386 } else if (len > MAX_PACKET_LEN) {
387 recvfrom(sockfd, header, sizeof(header), flags,
388 (struct sockaddr *)&src, &sizeof_src);
397 * Receive the packet. The OS will discard any data in the
398 * packet after "len" bytes.
400 #ifdef WITH_UDPFROMTO
401 if (dst.ss_family == AF_INET) {
402 data_len = recvfromto(sockfd, buf, len, flags,
403 (struct sockaddr *)&src, &sizeof_src,
404 (struct sockaddr *)&dst, &sizeof_dst);
408 * No udpfromto, OR an IPv6 socket. Fail gracefully.
410 data_len = recvfrom(sockfd, buf, len, flags,
411 (struct sockaddr *)&src, &sizeof_src);
418 * Check address families, and update src/dst ports, etc.
420 if (src.ss_family == AF_INET) {
421 struct sockaddr_in *s4;
423 s4 = (struct sockaddr_in *)&src;
424 src_ipaddr->af = AF_INET;
425 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
426 *src_port = ntohs(s4->sin_port);
428 s4 = (struct sockaddr_in *)&dst;
429 dst_ipaddr->af = AF_INET;
430 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
431 *dst_port = ntohs(s4->sin_port);
433 #ifdef HAVE_STRUCT_SOCKADDR_IN6
434 } else if (src.ss_family == AF_INET6) {
435 struct sockaddr_in6 *s6;
437 s6 = (struct sockaddr_in6 *)&src;
438 src_ipaddr->af = AF_INET6;
439 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
440 *src_port = ntohs(s6->sin6_port);
442 s6 = (struct sockaddr_in6 *)&dst;
443 dst_ipaddr->af = AF_INET6;
444 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
445 *dst_port = ntohs(s6->sin6_port);
449 return -1; /* Unknown address family, Die Die Die! */
453 * Different address families should never happen.
455 if (src.ss_family != dst.ss_family) {
461 * Tell the caller about the data
469 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
470 /*************************************************************************
472 * Function: make_secret
474 * Purpose: Build an encrypted secret value to return in a reply
475 * packet. The secret is hidden by xoring with a MD5 digest
476 * created from the shared secret and the authentication
477 * vector. We put them into MD5 in the reverse order from
478 * that used when encrypting passwords to RADIUS.
480 *************************************************************************/
481 static void make_secret(uint8_t *digest, const uint8_t *vector,
482 const char *secret, const uint8_t *value)
487 fr_MD5Init(&context);
488 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
489 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
490 fr_MD5Final(digest, &context);
492 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
493 digest[i] ^= value[i];
497 #define MAX_PASS_LEN (128)
498 static void make_passwd(uint8_t *output, int *outlen,
499 const uint8_t *input, int inlen,
500 const char *secret, const uint8_t *vector)
502 FR_MD5_CTX context, old;
503 uint8_t digest[AUTH_VECTOR_LEN];
504 uint8_t passwd[MAX_PASS_LEN];
509 * If the length is zero, round it up.
515 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
517 else if ((len & 0x0f) != 0) {
523 memcpy(passwd, input, len);
524 memset(passwd + len, 0, sizeof(passwd) - len);
526 fr_MD5Init(&context);
527 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
533 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
535 for (n = 0; n < len; n += AUTH_PASS_LEN) {
538 fr_MD5Update(&context,
539 passwd + n - AUTH_PASS_LEN,
543 fr_MD5Final(digest, &context);
544 for (i = 0; i < AUTH_PASS_LEN; i++) {
545 passwd[i + n] ^= digest[i];
549 memcpy(output, passwd, len);
552 static void make_tunnel_passwd(uint8_t *output, int *outlen,
553 const uint8_t *input, int inlen, int room,
554 const char *secret, const uint8_t *vector)
556 FR_MD5_CTX context, old;
557 uint8_t digest[AUTH_VECTOR_LEN];
558 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
565 if (room > 253) room = 253;
568 * Account for 2 bytes of the salt, and round the room
569 * available down to the nearest multiple of 16. Then,
570 * subtract one from that to account for the length byte,
571 * and the resulting number is the upper bound on the data
574 * We could short-cut this calculation just be forcing
575 * inlen to be no more than 239. It would work for all
576 * VSA's, as we don't pack multiple VSA's into one
579 * However, this calculation is more general, if a little
580 * complex. And it will work in the future for all possible
581 * kinds of weird attribute packing.
584 room -= (room & 0x0f);
587 if (inlen > room) inlen = room;
590 * Length of the encrypted data is password length plus
591 * one byte for the length of the password.
594 if ((len & 0x0f) != 0) {
598 *outlen = len + 2; /* account for the salt */
601 * Copy the password over.
603 memcpy(passwd + 3, input, inlen);
604 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
607 * Generate salt. The RFC's say:
609 * The high bit of salt[0] must be set, each salt in a
610 * packet should be unique, and they should be random
612 * So, we set the high bit, add in a counter, and then
613 * add in some CSPRNG data. should be OK..
615 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
617 passwd[1] = fr_rand();
618 passwd[2] = inlen; /* length of the password string */
620 fr_MD5Init(&context);
621 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
624 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
625 fr_MD5Update(&context, &passwd[0], 2);
627 for (n = 0; n < len; n += AUTH_PASS_LEN) {
630 fr_MD5Update(&context,
631 passwd + 2 + n - AUTH_PASS_LEN,
635 fr_MD5Final(digest, &context);
636 for (i = 0; i < AUTH_PASS_LEN; i++) {
637 passwd[i + 2 + n] ^= digest[i];
640 memcpy(output, passwd, len + 2);
645 * Parse a data structure into a RADIUS attribute.
647 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
648 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
651 int offset, len, total_length;
653 uint8_t *length_ptr, *vsa_length_ptr;
654 const uint8_t *data = NULL;
657 vendorcode = total_length = 0;
658 length_ptr = vsa_length_ptr = NULL;
661 * For interoperability, always put vendor attributes
662 * into their own VSA.
664 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
665 *(ptr++) = vp->attribute & 0xFF;
673 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
676 * This must be an RFC-format attribute. If it
677 * wasn't, then the "decode" function would have
678 * made a Vendor-Specific attribute (i.e. type
679 * 26), and we would have "vendorcode == 0" here.
683 vsa_llen = dv->length;
687 * Build a VSA header.
689 *ptr++ = PW_VENDOR_SPECIFIC;
690 vsa_length_ptr = ptr;
692 lvalue = htonl(vendorcode);
693 memcpy(ptr, &lvalue, 4);
699 ptr[0] = (vp->attribute & 0xFF);
703 ptr[0] = ((vp->attribute >> 8) & 0xFF);
704 ptr[1] = (vp->attribute & 0xFF);
710 ptr[2] = ((vp->attribute >> 8) & 0xFF);
711 ptr[3] = (vp->attribute & 0xFF);
715 return 0; /* silently discard it */
721 length_ptr = vsa_length_ptr;
722 vsa_length_ptr = NULL;
731 length_ptr = ptr + 1;
735 return 0; /* silently discard it */
739 total_length += vsa_tlen + vsa_llen;
740 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
741 *length_ptr += vsa_tlen + vsa_llen;
745 if (vp->flags.has_tag) {
746 if (TAG_VALID(vp->flags.tag)) {
747 ptr[0] = vp->flags.tag & 0xff;
750 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
752 * Tunnel passwords REQUIRE a tag, even
753 * if don't have a valid tag.
757 } /* else don't write a tag */
758 } /* else the attribute doesn't have a tag */
761 * Set up the default sources for the data.
763 data = vp->vp_octets;
770 case PW_TYPE_IPV6ADDR:
771 case PW_TYPE_IPV6PREFIX:
772 case PW_TYPE_ABINARY:
773 /* nothing more to do */
777 len = 1; /* just in case */
778 array[0] = vp->vp_integer & 0xff;
785 len = 2; /* just in case */
786 array[0] = (vp->vp_integer >> 8) & 0xff;
787 array[1] = vp->vp_integer & 0xff;
792 case PW_TYPE_INTEGER:
793 len = 4; /* just in case */
794 lvalue = htonl(vp->vp_integer);
795 memcpy(array, &lvalue, sizeof(lvalue));
798 * Perhaps discard the first octet.
800 data = &array[offset];
805 data = (const uint8_t *) &vp->vp_ipaddr;
806 len = 4; /* just in case */
810 * There are no tagged date attributes.
813 lvalue = htonl(vp->vp_date);
814 data = (const uint8_t *) &lvalue;
815 len = 4; /* just in case */
818 default: /* unknown type: ignore it */
819 librad_log("ERROR: Unknown attribute type %d", vp->type);
824 * Bound the data to 255 bytes.
826 if (len + offset + total_length > 255) {
827 len = 255 - offset - total_length;
831 * Encrypt the various password styles
833 * Attributes with encrypted values MUST be less than
836 switch (vp->flags.encrypt) {
837 case FLAG_ENCRYPT_USER_PASSWORD:
838 make_passwd(ptr + offset, &len,
840 secret, packet->vector);
843 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
845 * Check if 255 - offset - total_length is less
846 * than 18. If so, we can't fit the data into
847 * the available space, and we discard the
850 * This is ONLY a problem if we have multiple VSA's
851 * in one Vendor-Specific, though.
853 if ((255 - offset - total_length) < 18) return 0;
855 switch (packet->code) {
856 case PW_AUTHENTICATION_ACK:
857 case PW_AUTHENTICATION_REJECT:
858 case PW_ACCESS_CHALLENGE:
861 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
864 make_tunnel_passwd(ptr + offset, &len,
865 data, len, 255 - offset - total_length,
866 secret, original->vector);
868 case PW_ACCOUNTING_REQUEST:
869 case PW_DISCONNECT_REQUEST:
871 make_tunnel_passwd(ptr + offset, &len,
872 data, len, 255 - offset - total_length,
873 secret, packet->vector);
879 * The code above ensures that this attribute
882 case FLAG_ENCRYPT_ASCEND_SECRET:
883 make_secret(ptr + offset, packet->vector,
885 len = AUTH_VECTOR_LEN;
891 * Just copy the data over
893 memcpy(ptr + offset, data, len);
895 } /* switch over encryption flags */
898 * Account for the tag (if any).
903 * RFC 2865 section 5 says that zero-length attributes
906 if (len == 0) return 0;
909 * Update the various lengths.
912 if (vsa_length_ptr) *vsa_length_ptr += len;
916 return total_length; /* of attribute */
923 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
926 radius_packet_t *hdr;
928 uint16_t total_length;
935 * For simplicity in the following logic, we allow
936 * the attributes to "overflow" the 4k maximum
937 * RADIUS packet size, by one attribute.
939 * It's uint32_t, for alignment purposes.
941 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
943 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
944 what = packet_codes[packet->code];
949 DEBUG("Sending %s of id %d to %s port %d\n",
951 inet_ntop(packet->dst_ipaddr.af,
952 &packet->dst_ipaddr.ipaddr,
953 ip_buffer, sizeof(ip_buffer)),
957 * Double-check some things based on packet code.
959 switch (packet->code) {
960 case PW_AUTHENTICATION_ACK:
961 case PW_AUTHENTICATION_REJECT:
962 case PW_ACCESS_CHALLENGE:
964 librad_log("ERROR: Cannot sign response packet without a request packet.");
970 * These packet vectors start off as all zero.
972 case PW_ACCOUNTING_REQUEST:
973 case PW_DISCONNECT_REQUEST:
975 memset(packet->vector, 0, sizeof(packet->vector));
983 * Use memory on the stack, until we know how
984 * large the packet will be.
986 hdr = (radius_packet_t *) data;
989 * Build standard header
991 hdr->code = packet->code;
992 hdr->id = packet->id;
994 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
996 total_length = AUTH_HDR_LEN;
999 * Load up the configuration values for the user
1005 * FIXME: Loop twice over the reply list. The first time,
1006 * calculate the total length of data. The second time,
1007 * allocate the memory, and fill in the VP's.
1009 * Hmm... this may be slower than just doing a small
1014 * Loop over the reply attributes for the packet.
1016 for (reply = packet->vps; reply; reply = reply->next) {
1018 * Ignore non-wire attributes
1020 if ((VENDOR(reply->attribute) == 0) &&
1021 ((reply->attribute & 0xFFFF) > 0xff)) {
1024 * Permit the admin to send BADLY formatted
1025 * attributes with a debug build.
1027 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1028 memcpy(ptr, reply->vp_octets, reply->length);
1029 len = reply->length;
1037 * Set the Message-Authenticator to the correct
1038 * length and initial value.
1040 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1041 reply->length = AUTH_VECTOR_LEN;
1042 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1045 * Cache the offset to the
1046 * Message-Authenticator
1048 packet->offset = total_length;
1052 * Print out ONLY the attributes which
1053 * we're sending over the wire, and print
1054 * them out BEFORE they're encrypted.
1058 len = rad_vp2attr(packet, original, secret, reply, ptr);
1060 if (len < 0) return -1;
1063 * Check that the packet is no more than 4k in
1064 * size, AFTER writing the attribute past the 4k
1065 * boundary, but BEFORE deciding to increase the
1066 * size of the packet. Note that the 'data'
1067 * buffer, above, is one attribute longer than
1068 * necessary, in order to permit this overflow.
1070 if ((total_length + len) > MAX_PACKET_LEN) {
1076 total_length += len;
1077 } /* done looping over all attributes */
1080 * Fill in the rest of the fields, and copy the data over
1081 * from the local stack to the newly allocated memory.
1083 * Yes, all this 'memcpy' is slow, but it means
1084 * that we only allocate the minimum amount of
1085 * memory for a request.
1087 packet->data_len = total_length;
1088 packet->data = (uint8_t *) malloc(packet->data_len);
1089 if (!packet->data) {
1090 librad_log("Out of memory");
1094 memcpy(packet->data, data, packet->data_len);
1095 hdr = (radius_packet_t *) packet->data;
1097 total_length = htons(total_length);
1098 memcpy(hdr->length, &total_length, sizeof(total_length));
1105 * Sign a previously encoded packet.
1107 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1110 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1113 * It wasn't assigned an Id, this is bad!
1115 if (packet->id < 0) {
1116 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1120 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1121 (packet->offset < 0)) {
1122 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1127 * If there's a Message-Authenticator, update it
1128 * now, BEFORE updating the authentication vector.
1130 if (packet->offset > 0) {
1131 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1133 switch (packet->code) {
1134 case PW_ACCOUNTING_REQUEST:
1135 case PW_ACCOUNTING_RESPONSE:
1136 case PW_DISCONNECT_REQUEST:
1137 case PW_DISCONNECT_ACK:
1138 case PW_DISCONNECT_NAK:
1139 case PW_COA_REQUEST:
1142 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1145 case PW_AUTHENTICATION_ACK:
1146 case PW_AUTHENTICATION_REJECT:
1147 case PW_ACCESS_CHALLENGE:
1149 librad_log("ERROR: Cannot sign response packet without a request packet.");
1152 memcpy(hdr->vector, original->vector,
1156 default: /* others have vector already set to zero */
1162 * Set the authentication vector to zero,
1163 * calculate the signature, and put it
1164 * into the Message-Authenticator
1167 fr_hmac_md5(packet->data, packet->data_len,
1168 (const uint8_t *) secret, strlen(secret),
1170 memcpy(packet->data + packet->offset + 2,
1171 calc_auth_vector, AUTH_VECTOR_LEN);
1174 * Copy the original request vector back
1175 * to the raw packet.
1177 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1181 * Switch over the packet code, deciding how to
1184 switch (packet->code) {
1186 * Request packets are not signed, bur
1187 * have a random authentication vector.
1189 case PW_AUTHENTICATION_REQUEST:
1190 case PW_STATUS_SERVER:
1194 * Reply packets are signed with the
1195 * authentication vector of the request.
1202 fr_MD5Init(&context);
1203 fr_MD5Update(&context, packet->data, packet->data_len);
1204 fr_MD5Update(&context, (const uint8_t *) secret,
1206 fr_MD5Final(digest, &context);
1208 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1209 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1212 }/* switch over packet codes */
1218 * Reply to the request. Also attach
1219 * reply attribute value pairs and any user message provided.
1221 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1226 char ip_buffer[128];
1229 * Maybe it's a fake packet. Don't send it.
1231 if (!packet || (packet->sockfd < 0)) {
1235 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1236 what = packet_codes[packet->code];
1242 * First time through, allocate room for the packet
1244 if (!packet->data) {
1246 * Encode the packet.
1248 if (rad_encode(packet, original, secret) < 0) {
1253 * Re-sign it, including updating the
1254 * Message-Authenticator.
1256 if (rad_sign(packet, original, secret) < 0) {
1261 * If packet->data points to data, then we print out
1262 * the VP list again only for debugging.
1264 } else if (librad_debug) {
1265 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1266 inet_ntop(packet->dst_ipaddr.af,
1267 &packet->dst_ipaddr.ipaddr,
1268 ip_buffer, sizeof(ip_buffer)),
1271 for (reply = packet->vps; reply; reply = reply->next) {
1272 /* FIXME: ignore attributes > 0xff */
1278 * And send it on it's way.
1280 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1281 &packet->src_ipaddr, packet->src_port,
1282 &packet->dst_ipaddr, packet->dst_port);
1287 * Validates the requesting client NAS. Calculates the
1288 * signature based on the clients private key.
1290 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1292 uint8_t digest[AUTH_VECTOR_LEN];
1296 * Zero out the auth_vector in the received packet.
1297 * Then append the shared secret to the received packet,
1298 * and calculate the MD5 sum. This must be the same
1299 * as the original MD5 sum (packet->vector).
1301 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1304 * MD5(packet + secret);
1306 fr_MD5Init(&context);
1307 fr_MD5Update(&context, packet->data, packet->data_len);
1308 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1309 fr_MD5Final(digest, &context);
1312 * Return 0 if OK, 2 if not OK.
1314 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1320 * Validates the requesting client NAS. Calculates the
1321 * signature based on the clients private key.
1323 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1326 uint8_t calc_digest[AUTH_VECTOR_LEN];
1332 if (original == NULL) {
1337 * Copy the original vector in place.
1339 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1342 * MD5(packet + secret);
1344 fr_MD5Init(&context);
1345 fr_MD5Update(&context, packet->data, packet->data_len);
1346 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1347 fr_MD5Final(calc_digest, &context);
1350 * Copy the packet's vector back to the packet.
1352 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1355 * Return 0 if OK, 2 if not OK.
1357 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1363 * See if the data pointed to by PTR is a valid RADIUS packet.
1365 * packet is not 'const * const' because we may update data_len,
1366 * if there's more data in the UDP packet than in the RADIUS packet.
1368 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1373 radius_packet_t *hdr;
1374 char host_ipaddr[128];
1380 * Check for packets smaller than the packet header.
1382 * RFC 2865, Section 3., subsection 'length' says:
1384 * "The minimum length is 20 ..."
1386 if (packet->data_len < AUTH_HDR_LEN) {
1387 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1388 inet_ntop(packet->src_ipaddr.af,
1389 &packet->src_ipaddr.ipaddr,
1390 host_ipaddr, sizeof(host_ipaddr)),
1391 packet->data_len, AUTH_HDR_LEN);
1396 * RFC 2865, Section 3., subsection 'length' says:
1398 * " ... and maximum length is 4096."
1400 if (packet->data_len > MAX_PACKET_LEN) {
1401 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1402 inet_ntop(packet->src_ipaddr.af,
1403 &packet->src_ipaddr.ipaddr,
1404 host_ipaddr, sizeof(host_ipaddr)),
1405 packet->data_len, MAX_PACKET_LEN);
1410 * Check for packets with mismatched size.
1411 * i.e. We've received 128 bytes, and the packet header
1412 * says it's 256 bytes long.
1414 totallen = (packet->data[2] << 8) | packet->data[3];
1415 hdr = (radius_packet_t *)packet->data;
1418 * Code of 0 is not understood.
1419 * Code of 16 or greate is not understood.
1421 if ((hdr->code == 0) ||
1422 (hdr->code >= MAX_PACKET_CODE)) {
1423 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1424 inet_ntop(packet->src_ipaddr.af,
1425 &packet->src_ipaddr.ipaddr,
1426 host_ipaddr, sizeof(host_ipaddr)),
1432 * Message-Authenticator is required in Status-Server
1433 * packets, otherwise they can be trivially forged.
1435 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1438 * It's also required if the caller asks for it.
1440 if (flags) require_ma = 1;
1443 * Repeat the length checks. This time, instead of
1444 * looking at the data we received, look at the value
1445 * of the 'length' field inside of the packet.
1447 * Check for packets smaller than the packet header.
1449 * RFC 2865, Section 3., subsection 'length' says:
1451 * "The minimum length is 20 ..."
1453 if (totallen < AUTH_HDR_LEN) {
1454 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1455 inet_ntop(packet->src_ipaddr.af,
1456 &packet->src_ipaddr.ipaddr,
1457 host_ipaddr, sizeof(host_ipaddr)),
1458 totallen, AUTH_HDR_LEN);
1463 * And again, for the value of the 'length' field.
1465 * RFC 2865, Section 3., subsection 'length' says:
1467 * " ... and maximum length is 4096."
1469 if (totallen > MAX_PACKET_LEN) {
1470 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1471 inet_ntop(packet->src_ipaddr.af,
1472 &packet->src_ipaddr.ipaddr,
1473 host_ipaddr, sizeof(host_ipaddr)),
1474 totallen, MAX_PACKET_LEN);
1479 * RFC 2865, Section 3., subsection 'length' says:
1481 * "If the packet is shorter than the Length field
1482 * indicates, it MUST be silently discarded."
1484 * i.e. No response to the NAS.
1486 if (packet->data_len < totallen) {
1487 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1488 inet_ntop(packet->src_ipaddr.af,
1489 &packet->src_ipaddr.ipaddr,
1490 host_ipaddr, sizeof(host_ipaddr)),
1491 packet->data_len, totallen);
1496 * RFC 2865, Section 3., subsection 'length' says:
1498 * "Octets outside the range of the Length field MUST be
1499 * treated as padding and ignored on reception."
1501 if (packet->data_len > totallen) {
1503 * We're shortening the packet below, but just
1504 * to be paranoid, zero out the extra data.
1506 memset(packet->data + totallen, 0, packet->data_len - totallen);
1507 packet->data_len = totallen;
1511 * Walk through the packet's attributes, ensuring that
1512 * they add up EXACTLY to the size of the packet.
1514 * If they don't, then the attributes either under-fill
1515 * or over-fill the packet. Any parsing of the packet
1516 * is impossible, and will result in unknown side effects.
1518 * This would ONLY happen with buggy RADIUS implementations,
1519 * or with an intentional attack. Either way, we do NOT want
1520 * to be vulnerable to this problem.
1523 count = totallen - AUTH_HDR_LEN;
1528 * Attribute number zero is NOT defined.
1531 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1532 inet_ntop(packet->src_ipaddr.af,
1533 &packet->src_ipaddr.ipaddr,
1534 host_ipaddr, sizeof(host_ipaddr)));
1539 * Attributes are at LEAST as long as the ID & length
1540 * fields. Anything shorter is an invalid attribute.
1543 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1544 inet_ntop(packet->src_ipaddr.af,
1545 &packet->src_ipaddr.ipaddr,
1546 host_ipaddr, sizeof(host_ipaddr)),
1552 * Sanity check the attributes for length.
1555 default: /* don't do anything by default */
1559 * If there's an EAP-Message, we require
1560 * a Message-Authenticator.
1562 case PW_EAP_MESSAGE:
1566 case PW_MESSAGE_AUTHENTICATOR:
1567 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1568 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1569 inet_ntop(packet->src_ipaddr.af,
1570 &packet->src_ipaddr.ipaddr,
1571 host_ipaddr, sizeof(host_ipaddr)),
1580 * FIXME: Look up the base 255 attributes in the
1581 * dictionary, and switch over their type. For
1582 * integer/date/ip, the attribute length SHOULD
1585 count -= attr[1]; /* grab the attribute length */
1587 num_attributes++; /* seen one more attribute */
1591 * If the attributes add up to a packet, it's allowed.
1593 * If not, we complain, and throw the packet away.
1596 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1597 inet_ntop(packet->src_ipaddr.af,
1598 &packet->src_ipaddr.ipaddr,
1599 host_ipaddr, sizeof(host_ipaddr)));
1604 * If we're configured to look for a maximum number of
1605 * attributes, and we've seen more than that maximum,
1606 * then throw the packet away, as a possible DoS.
1608 if ((librad_max_attributes > 0) &&
1609 (num_attributes > librad_max_attributes)) {
1610 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1611 inet_ntop(packet->src_ipaddr.af,
1612 &packet->src_ipaddr.ipaddr,
1613 host_ipaddr, sizeof(host_ipaddr)),
1614 num_attributes, librad_max_attributes);
1619 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1621 * A packet with an EAP-Message attribute MUST also have
1622 * a Message-Authenticator attribute.
1624 * A Message-Authenticator all by itself is OK, though.
1626 * Similarly, Status-Server packets MUST contain
1627 * Message-Authenticator attributes.
1629 if (require_ma && ! seen_ma) {
1630 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1631 inet_ntop(packet->src_ipaddr.af,
1632 &packet->src_ipaddr.ipaddr,
1633 host_ipaddr, sizeof(host_ipaddr)));
1638 * Fill RADIUS header fields
1640 packet->code = hdr->code;
1641 packet->id = hdr->id;
1642 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1649 * Receive UDP client requests, and fill in
1650 * the basics of a RADIUS_PACKET structure.
1652 RADIUS_PACKET *rad_recv(int fd, int flags)
1654 RADIUS_PACKET *packet;
1657 * Allocate the new request data structure
1659 if ((packet = malloc(sizeof(*packet))) == NULL) {
1660 librad_log("out of memory");
1663 memset(packet, 0, sizeof(*packet));
1665 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1666 &packet->src_ipaddr, &packet->src_port,
1667 &packet->dst_ipaddr, &packet->dst_port);
1670 * Check for socket errors.
1672 if (packet->data_len < 0) {
1673 librad_log("Error receiving packet: %s", strerror(errno));
1674 /* packet->data is NULL */
1680 * If the packet is too big, then rad_recvfrom did NOT
1681 * allocate memory. Instead, it just discarded the
1684 if (packet->data_len > MAX_PACKET_LEN) {
1685 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1686 /* packet->data is NULL */
1692 * Read no data. Continue.
1693 * This check is AFTER the MAX_PACKET_LEN check above, because
1694 * if the packet is larger than MAX_PACKET_LEN, we also have
1695 * packet->data == NULL
1697 if ((packet->data_len == 0) || !packet->data) {
1698 librad_log("Empty packet: Socket is not ready.");
1704 * See if it's a well-formed RADIUS packet.
1706 if (!rad_packet_ok(packet, flags)) {
1712 * Remember which socket we read the packet from.
1714 packet->sockfd = fd;
1717 * FIXME: Do even more filtering by only permitting
1718 * certain IP's. The problem is that we don't know
1719 * how to do this properly for all possible clients...
1723 * Explicitely set the VP list to empty.
1728 char host_ipaddr[128];
1730 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1731 printf("rad_recv: %s packet from host %s port %d",
1732 packet_codes[packet->code],
1733 inet_ntop(packet->src_ipaddr.af,
1734 &packet->src_ipaddr.ipaddr,
1735 host_ipaddr, sizeof(host_ipaddr)),
1738 printf("rad_recv: Packet from host %s port %d code=%d",
1739 inet_ntop(packet->src_ipaddr.af,
1740 &packet->src_ipaddr.ipaddr,
1741 host_ipaddr, sizeof(host_ipaddr)),
1745 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1753 * Verify the signature of a packet.
1755 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1762 if (!packet || !packet->data) return -1;
1765 * Before we allocate memory for the attributes, do more
1768 ptr = packet->data + AUTH_HDR_LEN;
1769 length = packet->data_len - AUTH_HDR_LEN;
1770 while (length > 0) {
1771 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1772 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1777 default: /* don't do anything. */
1781 * Note that more than one Message-Authenticator
1782 * attribute is invalid.
1784 case PW_MESSAGE_AUTHENTICATOR:
1785 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1786 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1788 switch (packet->code) {
1792 case PW_ACCOUNTING_REQUEST:
1793 case PW_ACCOUNTING_RESPONSE:
1794 case PW_DISCONNECT_REQUEST:
1795 case PW_DISCONNECT_ACK:
1796 case PW_DISCONNECT_NAK:
1797 case PW_COA_REQUEST:
1800 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1803 case PW_AUTHENTICATION_ACK:
1804 case PW_AUTHENTICATION_REJECT:
1805 case PW_ACCESS_CHALLENGE:
1807 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1810 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1814 fr_hmac_md5(packet->data, packet->data_len,
1815 (const uint8_t *) secret, strlen(secret),
1817 if (memcmp(calc_auth_vector, msg_auth_vector,
1818 sizeof(calc_auth_vector)) != 0) {
1820 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1821 inet_ntop(packet->src_ipaddr.af,
1822 &packet->src_ipaddr.ipaddr,
1823 buffer, sizeof(buffer)));
1824 /* Silently drop packet, according to RFC 3579 */
1826 } /* else the message authenticator was good */
1829 * Reinitialize Authenticators.
1831 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1832 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1834 } /* switch over the attributes */
1838 } /* loop over the packet, sanity checking the attributes */
1841 * It looks like a RADIUS packet, but we can't validate
1844 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1846 librad_log("Received Unknown packet code %d"
1847 "from client %s port %d: Cannot validate signature",
1849 inet_ntop(packet->src_ipaddr.af,
1850 &packet->src_ipaddr.ipaddr,
1851 buffer, sizeof(buffer)),
1857 * Calculate and/or verify digest.
1859 switch(packet->code) {
1863 case PW_AUTHENTICATION_REQUEST:
1864 case PW_STATUS_SERVER:
1865 case PW_DISCONNECT_REQUEST:
1867 * The authentication vector is random
1868 * nonsense, invented by the client.
1872 case PW_ACCOUNTING_REQUEST:
1873 if (calc_acctdigest(packet, secret) > 1) {
1874 librad_log("Received Accounting-Request packet "
1875 "from %s with invalid signature! (Shared secret is incorrect.)",
1876 inet_ntop(packet->src_ipaddr.af,
1877 &packet->src_ipaddr.ipaddr,
1878 buffer, sizeof(buffer)));
1883 /* Verify the reply digest */
1884 case PW_AUTHENTICATION_ACK:
1885 case PW_AUTHENTICATION_REJECT:
1886 case PW_ACCESS_CHALLENGE:
1887 case PW_ACCOUNTING_RESPONSE:
1888 case PW_DISCONNECT_ACK:
1889 case PW_DISCONNECT_NAK:
1892 rcode = calc_replydigest(packet, original, secret);
1894 librad_log("Received %s packet "
1895 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1896 packet_codes[packet->code],
1897 inet_ntop(packet->src_ipaddr.af,
1898 &packet->src_ipaddr.ipaddr,
1899 buffer, sizeof(buffer)),
1907 librad_log("Received Unknown packet code %d"
1908 "from client %s port %d: Cannot validate signature",
1910 inet_ntop(packet->src_ipaddr.af,
1911 &packet->src_ipaddr.ipaddr,
1912 buffer, sizeof(buffer)),
1922 * Parse a RADIUS attribute into a data structure.
1924 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1925 const char *secret, int attribute, int length,
1926 const uint8_t *data)
1931 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1936 * If length is greater than 253, something is SERIOUSLY
1939 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1941 vp->length = length;
1942 vp->operator = T_OP_EQ;
1948 if (vp->flags.has_tag) {
1949 if (TAG_VALID(data[0]) ||
1950 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1952 * Tunnel passwords REQUIRE a tag, even
1953 * if don't have a valid tag.
1955 vp->flags.tag = data[0];
1957 if ((vp->type == PW_TYPE_STRING) ||
1958 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1963 * Copy the data to be decrypted
1965 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1966 vp->length -= offset;
1969 * Decrypt the attribute.
1971 switch (vp->flags.encrypt) {
1975 case FLAG_ENCRYPT_USER_PASSWORD:
1977 rad_pwdecode((char *)vp->vp_strvalue,
1981 rad_pwdecode((char *)vp->vp_strvalue,
1985 if (vp->attribute == PW_USER_PASSWORD) {
1986 vp->length = strlen(vp->vp_strvalue);
1991 * Tunnel-Password's may go ONLY
1992 * in response packets.
1994 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1995 if (!original) goto raw;
1997 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1998 secret, original->vector) < 0) {
2004 * Ascend-Send-Secret
2005 * Ascend-Receive-Secret
2007 case FLAG_ENCRYPT_ASCEND_SECRET:
2011 uint8_t my_digest[AUTH_VECTOR_LEN];
2012 make_secret(my_digest,
2015 memcpy(vp->vp_strvalue, my_digest,
2017 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2018 vp->length = strlen(vp->vp_strvalue);
2024 } /* switch over encryption flags */
2028 case PW_TYPE_STRING:
2029 case PW_TYPE_OCTETS:
2030 case PW_TYPE_ABINARY:
2031 /* nothing more to do */
2035 if (vp->length != 1) goto raw;
2037 vp->vp_integer = vp->vp_octets[0];
2042 if (vp->length != 2) goto raw;
2044 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2047 case PW_TYPE_INTEGER:
2048 if (vp->length != 4) goto raw;
2050 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2051 vp->vp_integer = ntohl(vp->vp_integer);
2053 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2056 * Try to get named VALUEs
2060 dval = dict_valbyattr(vp->attribute,
2063 strlcpy(vp->vp_strvalue,
2065 sizeof(vp->vp_strvalue));
2071 if (vp->length != 4) goto raw;
2073 memcpy(&vp->vp_date, vp->vp_octets, 4);
2074 vp->vp_date = ntohl(vp->vp_date);
2078 case PW_TYPE_IPADDR:
2079 if (vp->length != 4) goto raw;
2081 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2085 * IPv6 interface ID is 8 octets long.
2088 if (vp->length != 8) goto raw;
2089 /* vp->vp_ifid == vp->vp_octets */
2093 * IPv6 addresses are 16 octets long
2095 case PW_TYPE_IPV6ADDR:
2096 if (vp->length != 16) goto raw;
2097 /* vp->vp_ipv6addr == vp->vp_octets */
2101 * IPv6 prefixes are 2 to 18 octets long.
2103 * RFC 3162: The first octet is unused.
2104 * The second is the length of the prefix
2105 * the rest are the prefix data.
2107 * The prefix length can have value 0 to 128.
2109 case PW_TYPE_IPV6PREFIX:
2110 if (vp->length < 2 || vp->length > 18) goto raw;
2111 if (vp->vp_octets[1] > 128) goto raw;
2114 * FIXME: double-check that
2115 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2117 if (vp->length < 18) {
2118 memset(vp->vp_octets + vp->length, 0,
2125 vp->type = PW_TYPE_OCTETS;
2126 vp->length = length;
2127 memcpy(vp->vp_octets, data, length);
2131 * Ensure there's no encryption or tag stuff,
2132 * we just pass the attribute as-is.
2134 memset(&vp->flags, 0, sizeof(vp->flags));
2142 * Calculate/check digest, and decode radius attributes.
2144 * -1 on decoding error
2147 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2151 uint32_t vendorcode;
2159 radius_packet_t *hdr;
2160 int vsa_tlen, vsa_llen;
2161 DICT_VENDOR *dv = NULL;
2162 int num_attributes = 0;
2165 * Extract attribute-value pairs
2167 hdr = (radius_packet_t *)packet->data;
2169 packet_length = packet->data_len - AUTH_HDR_LEN;
2172 * There may be VP's already in the packet. Don't
2175 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2181 vsa_tlen = vsa_llen = 1;
2184 * We have to read at least two bytes.
2186 * rad_recv() above ensures that this is OK.
2188 while (packet_length > 0) {
2193 * Normal attribute, handle it like normal.
2195 if (vendorcode == 0) {
2197 * No room to read attr/length,
2198 * or bad attribute, or attribute is
2199 * too short, or attribute is too long,
2200 * stop processing the packet.
2202 if ((packet_length < 2) ||
2203 (ptr[0] == 0) || (ptr[1] < 2) ||
2204 (ptr[1] > packet_length)) break;
2212 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2215 * No vendor code, or ONLY vendor code.
2217 if (attrlen <= 4) goto create_pair;
2223 * Handle Vendor-Specific
2225 if (vendorlen == 0) {
2231 * attrlen was checked above.
2233 memcpy(&lvalue, ptr, 4);
2234 myvendor = ntohl(lvalue);
2237 * Zero isn't allowed.
2239 if (myvendor == 0) goto create_pair;
2242 * This is an implementation issue.
2243 * We currently pack vendor into the upper
2244 * 16 bits of a 32-bit attribute number,
2245 * so we can't handle vendor numbers larger
2248 if (myvendor > 65535) goto create_pair;
2250 vsa_tlen = vsa_llen = 1;
2251 dv = dict_vendorbyvalue(myvendor);
2253 vsa_tlen = dv->type;
2254 vsa_llen = dv->length;
2258 * Sweep through the list of VSA's,
2259 * seeing if they exactly fill the
2260 * outer Vendor-Specific attribute.
2262 * If not, create a raw Vendor-Specific.
2265 sublen = attrlen - 4;
2268 * See if we can parse it.
2274 * Don't have a type, it's bad.
2276 if (sublen < vsa_tlen) goto create_pair;
2279 * Ensure that the attribute number
2288 myattr = (subptr[0] << 8) | subptr[1];
2292 if ((subptr[0] != 0) ||
2293 (subptr[1] != 0)) goto create_pair;
2295 myattr = (subptr[2] << 8) | subptr[3];
2299 * Our dictionary is broken.
2306 * Not enough room for one more
2309 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2312 attribute = (myvendor << 16) | myattr;
2313 ptr += 4 + vsa_tlen;
2314 attrlen -= (4 + vsa_tlen);
2315 packet_length -= 4 + vsa_tlen;
2319 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2322 if (subptr[vsa_tlen] > sublen)
2324 sublen -= subptr[vsa_tlen];
2325 subptr += subptr[vsa_tlen];
2329 if (subptr[vsa_tlen] != 0) goto create_pair;
2330 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2332 if (subptr[vsa_tlen + 1] > sublen)
2334 sublen -= subptr[vsa_tlen + 1];
2335 subptr += subptr[vsa_tlen + 1];
2339 * Our dictionaries are
2345 } while (sublen > 0);
2347 vendorcode = myvendor;
2348 vendorlen = attrlen - 4;
2355 * attrlen is the length of this attribute.
2356 * total_len is the length of the encompassing
2365 attribute = (ptr[0] << 8) | ptr[1];
2368 default: /* can't hit this. */
2371 attribute |= (vendorcode << 16);
2376 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2380 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2383 default: /* can't hit this. */
2387 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2388 if (vendorlen == 0) vendorcode = 0;
2389 packet_length -= (vsa_tlen + vsa_llen);
2392 * Create the attribute, setting the default type
2393 * to 'octets'. If the type in the dictionary
2394 * is different, then the dictionary type will
2395 * over-ride this one.
2397 * If the attribute has no data, then discard it.
2400 if (!attrlen) goto next;
2402 pair = rad_attr2vp(packet, original, secret,
2403 attribute, attrlen, ptr);
2405 pairfree(&packet->vps);
2406 librad_log("out of memory");
2419 * VSA's may not have been counted properly in
2420 * rad_packet_ok() above, as it is hard to count
2421 * then without using the dictionary. We
2422 * therefore enforce the limits here, too.
2424 if ((librad_max_attributes > 0) &&
2425 (num_attributes > librad_max_attributes)) {
2426 char host_ipaddr[128];
2428 pairfree(&packet->vps);
2429 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2430 inet_ntop(packet->src_ipaddr.af,
2431 &packet->src_ipaddr.ipaddr,
2432 host_ipaddr, sizeof(host_ipaddr)),
2433 num_attributes, librad_max_attributes);
2439 packet_length -= attrlen;
2443 * Merge information from the outside world into our
2446 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2455 * We assume that the passwd buffer passed is big enough.
2456 * RFC2138 says the password is max 128 chars, so the size
2457 * of the passwd buffer must be at least 129 characters.
2458 * Preferably it's just MAX_STRING_LEN.
2460 * int *pwlen is updated to the new length of the encrypted
2461 * password - a multiple of 16 bytes.
2463 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2464 const uint8_t *vector)
2466 FR_MD5_CTX context, old;
2467 uint8_t digest[AUTH_VECTOR_LEN];
2468 int i, n, secretlen;
2472 * RFC maximum is 128 bytes.
2474 * If length is zero, pad it out with zeros.
2476 * If the length isn't aligned to 16 bytes,
2477 * zero out the extra data.
2481 if (len > 128) len = 128;
2484 memset(passwd, 0, AUTH_PASS_LEN);
2485 len = AUTH_PASS_LEN;
2486 } else if ((len % AUTH_PASS_LEN) != 0) {
2487 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2488 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2493 * Use the secret to setup the decryption digest
2495 secretlen = strlen(secret);
2497 fr_MD5Init(&context);
2498 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2499 old = context; /* save intermediate work */
2502 * Encrypt it in place. Don't bother checking
2503 * len, as we've ensured above that it's OK.
2505 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2507 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2508 fr_MD5Final(digest, &context);
2511 fr_MD5Update(&context,
2512 (uint8_t *) passwd + n - AUTH_PASS_LEN,
2514 fr_MD5Final(digest, &context);
2517 for (i = 0; i < AUTH_PASS_LEN; i++) {
2518 passwd[i + n] ^= digest[i];
2528 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
2529 const uint8_t *vector)
2531 FR_MD5_CTX context, old;
2532 uint8_t digest[AUTH_VECTOR_LEN];
2534 size_t n, secretlen;
2537 * The RFC's say that the maximum is 128.
2538 * The buffer we're putting it into above is 254, so
2539 * we don't need to do any length checking.
2541 if (pwlen > 128) pwlen = 128;
2546 if (pwlen == 0) goto done;
2549 * Use the secret to setup the decryption digest
2551 secretlen = strlen(secret);
2553 fr_MD5Init(&context);
2554 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2555 old = context; /* save intermediate work */
2558 * The inverse of the code above.
2560 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2562 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2563 fr_MD5Final(digest, &context);
2566 if (pwlen > AUTH_PASS_LEN) {
2567 fr_MD5Update(&context, (uint8_t *) passwd,
2571 fr_MD5Final(digest, &context);
2574 if (pwlen > (n + AUTH_PASS_LEN)) {
2575 fr_MD5Update(&context, (uint8_t *) passwd + n,
2580 for (i = 0; i < AUTH_PASS_LEN; i++) {
2581 passwd[i + n] ^= digest[i];
2586 passwd[pwlen] = '\0';
2587 return strlen(passwd);
2592 * Encode Tunnel-Password attributes when sending them out on the wire.
2594 * int *pwlen is updated to the new length of the encrypted
2595 * password - a multiple of 16 bytes.
2597 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2600 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
2601 const uint8_t *vector)
2603 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2604 unsigned char digest[AUTH_VECTOR_LEN];
2606 int i, n, secretlen;
2611 if (len > 127) len = 127;
2614 * Shift the password 3 positions right to place a salt and original
2615 * length, tag will be added automatically on packet send
2617 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2621 * save original password length as first password character;
2628 * Generate salt. The RFC's say:
2630 * The high bit of salt[0] must be set, each salt in a
2631 * packet should be unique, and they should be random
2633 * So, we set the high bit, add in a counter, and then
2634 * add in some CSPRNG data. should be OK..
2636 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2637 (fr_rand() & 0x07));
2638 salt[1] = fr_rand();
2641 * Padd password to multiple of AUTH_PASS_LEN bytes.
2643 n = len % AUTH_PASS_LEN;
2645 n = AUTH_PASS_LEN - n;
2646 for (; n > 0; n--, len++)
2649 /* set new password length */
2653 * Use the secret to setup the decryption digest
2655 secretlen = strlen(secret);
2656 memcpy(buffer, secret, secretlen);
2658 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2660 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2661 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2662 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2664 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2665 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2668 for (i = 0; i < AUTH_PASS_LEN; i++) {
2669 passwd[i + n2] ^= digest[i];
2677 * Decode Tunnel-Password encrypted attributes.
2679 * Defined in RFC-2868, this uses a two char SALT along with the
2680 * initial intermediate value, to differentiate it from the
2683 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
2684 const uint8_t *vector)
2686 FR_MD5_CTX context, old;
2687 uint8_t digest[AUTH_VECTOR_LEN];
2689 unsigned i, n, len, reallen;
2694 * We need at least a salt.
2697 librad_log("tunnel password is too short");
2702 * There's a salt, but no password. Or, there's a salt
2703 * and a 'data_len' octet. It's wrong, but at least we
2704 * can figure out what it means: the password is empty.
2706 * Note that this means we ignore the 'data_len' field,
2707 * if the attribute length tells us that there's no
2708 * more data. So the 'data_len' field may be wrong,
2717 len -= 2; /* discount the salt */
2720 * Use the secret to setup the decryption digest
2722 secretlen = strlen(secret);
2724 fr_MD5Init(&context);
2725 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2726 old = context; /* save intermediate work */
2729 * Set up the initial key:
2731 * b(1) = MD5(secret + vector + salt)
2733 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2734 fr_MD5Update(&context, passwd, 2);
2737 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2741 fr_MD5Final(digest, &context);
2746 * A quick check: decrypt the first octet
2747 * of the password, which is the
2748 * 'data_len' field. Ensure it's sane.
2750 reallen = passwd[2] ^ digest[0];
2751 if (reallen >= len) {
2752 librad_log("tunnel password is too long for the attribute");
2756 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2760 fr_MD5Final(digest, &context);
2763 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2766 for (i = base; i < AUTH_PASS_LEN; i++) {
2767 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2772 * See make_tunnel_password, above.
2774 if (reallen > 239) reallen = 239;
2777 passwd[reallen] = 0;
2783 * Encode a CHAP password
2785 * FIXME: might not work with Ascend because
2786 * we use vp->length, and Ascend gear likes
2787 * to send an extra '\0' in the string!
2789 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2790 VALUE_PAIR *password)
2794 uint8_t string[MAX_STRING_LEN * 2 + 1];
2795 VALUE_PAIR *challenge;
2798 * Sanity check the input parameters
2800 if ((packet == NULL) || (password == NULL)) {
2805 * Note that the password VP can be EITHER
2806 * a User-Password attribute (from a check-item list),
2807 * or a CHAP-Password attribute (the client asking
2808 * the library to encode it).
2816 memcpy(ptr, password->vp_strvalue, password->length);
2817 ptr += password->length;
2818 i += password->length;
2821 * Use Chap-Challenge pair if present,
2822 * Request-Authenticator otherwise.
2824 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2826 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2827 i += challenge->length;
2829 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2830 i += AUTH_VECTOR_LEN;
2834 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2841 * Seed the random number generator.
2843 * May be called any number of times.
2845 void fr_rand_seed(const void *data, size_t size)
2850 * Ensure that the pool is initialized.
2852 if (!fr_rand_initialized) {
2855 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2857 fd = open("/dev/urandom", O_RDONLY);
2863 while (total < sizeof(fr_rand_pool.randrsl)) {
2864 this = read(fd, fr_rand_pool.randrsl,
2865 sizeof(fr_rand_pool.randrsl) - total);
2866 if ((this < 0) && (errno != EINTR)) break;
2867 if (this > 0) total += this;
2871 fr_rand_pool.randrsl[0] = fd;
2872 fr_rand_pool.randrsl[1] = time(NULL);
2873 fr_rand_pool.randrsl[2] = errno;
2876 fr_randinit(&fr_rand_pool, 1);
2877 fr_rand_pool.randcnt = 0;
2878 fr_rand_initialized = 1;
2884 * Hash the user data
2887 if (!hash) hash = fr_rand();
2888 hash = fr_hash_update(data, size, hash);
2890 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2895 * Return a 32-bit random number.
2897 uint32_t fr_rand(void)
2902 * Ensure that the pool is initialized.
2904 if (!fr_rand_initialized) {
2905 fr_rand_seed(NULL, 0);
2908 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2909 if (fr_rand_pool.randcnt == 256) {
2910 fr_rand_pool.randcnt = 0;
2911 fr_isaac(&fr_rand_pool);
2919 * Allocate a new RADIUS_PACKET
2921 RADIUS_PACKET *rad_alloc(int newvector)
2925 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2926 librad_log("out of memory");
2929 memset(rp, 0, sizeof(*rp));
2935 uint32_t hash, base;
2938 * Don't expose the actual contents of the random
2942 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2943 hash = fr_rand() ^ base;
2944 memcpy(rp->vector + i, &hash, sizeof(hash));
2947 fr_rand(); /* stir the pool again */
2953 * Free a RADIUS_PACKET
2955 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2957 RADIUS_PACKET *radius_packet;
2959 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2960 radius_packet = *radius_packet_ptr;
2962 free(radius_packet->data);
2964 pairfree(&radius_packet->vps);
2966 free(radius_packet);
2968 *radius_packet_ptr = NULL;