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 s4 = (struct sockaddr_in *)&dst;
171 sizeof_dst = sizeof(struct sockaddr_in);
173 s4->sin_family = AF_INET;
174 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
175 s4->sin_port = htons(dst_port);
177 #ifdef WITH_UDPFROMTO
178 s4 = (struct sockaddr_in *)&src;
179 sizeof_src = sizeof(struct sockaddr_in);
181 s4->sin_family = AF_INET;
182 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
183 s4->sin_port = htons(src_port);
185 src_port = src_port; /* -Wunused */
189 * IPv6 MAY be supported.
191 #ifdef HAVE_STRUCT_SOCKADDR_IN6
192 } else if (dst_ipaddr->af == AF_INET6) {
193 struct sockaddr_in6 *s6;
195 s6 = (struct sockaddr_in6 *)&dst;
196 sizeof_dst = sizeof(struct sockaddr_in6);
198 s6->sin6_family = AF_INET6;
199 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
200 s6->sin6_port = htons(dst_port);
202 #ifdef WITH_UDPFROMTO
203 return -1; /* UDPFROMTO && IPv6 are not supported */
205 s6 = (struct sockaddr_in6 *)&src;
206 sizeof_src = sizeof(struct sockaddr_in6);
208 s6->sin6_family = AF_INET6;
209 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
211 #endif /* WITH_UDPFROMTO */
212 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
213 } else return -1; /* Unknown address family, Die Die Die! */
215 #ifdef WITH_UDPFROMTO
217 * Only IPv4 is supported for udpfromto.
219 * And if they don't specify a source IP address, don't
222 if ((dst_ipaddr->af == AF_INET) ||
223 (src_ipaddr->af != AF_UNSPEC)) {
224 return sendfromto(sockfd, data, data_len, flags,
225 (struct sockaddr *)&src, sizeof_src,
226 (struct sockaddr *)&dst, sizeof_dst);
229 src_ipaddr = src_ipaddr; /* -Wunused */
233 * No udpfromto, OR an IPv6 socket, fail gracefully.
235 return sendto(sockfd, data, data_len, flags,
236 (struct sockaddr *)&dst, sizeof_dst);
240 void rad_recv_discard(int sockfd)
243 struct sockaddr_storage src;
244 socklen_t sizeof_src = sizeof(src);
246 recvfrom(sockfd, header, sizeof(header), 0,
247 (struct sockaddr *)&src, &sizeof_src);
251 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
254 ssize_t data_len, packet_len;
256 struct sockaddr_storage src;
257 socklen_t sizeof_src = sizeof(src);
259 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
260 (struct sockaddr *)&src, &sizeof_src);
262 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
267 * Too little data is available, discard the packet.
270 recvfrom(sockfd, header, sizeof(header), 0,
271 (struct sockaddr *)&src, &sizeof_src);
274 } else { /* we got 4 bytes of data. */
276 * See how long the packet says it is.
278 packet_len = (header[2] * 256) + header[3];
281 * The length in the packet says it's less than
282 * a RADIUS header length: discard it.
284 if (packet_len < AUTH_HDR_LEN) {
285 recvfrom(sockfd, header, sizeof(header), 0,
286 (struct sockaddr *)&src, &sizeof_src);
290 * Enforce RFC requirements, for sanity.
291 * Anything after 4k will be discarded.
293 } else if (packet_len > MAX_PACKET_LEN) {
294 recvfrom(sockfd, header, sizeof(header), 0,
295 (struct sockaddr *)&src, &sizeof_src);
300 if (src.ss_family == AF_INET) {
301 struct sockaddr_in *s4;
303 s4 = (struct sockaddr_in *)&src;
304 src_ipaddr->af = AF_INET;
305 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
306 *src_port = ntohs(s4->sin_port);
308 #ifdef HAVE_STRUCT_SOCKADDR_IN6
309 } else if (src.ss_family == AF_INET6) {
310 struct sockaddr_in6 *s6;
312 s6 = (struct sockaddr_in6 *)&src;
313 src_ipaddr->af = AF_INET6;
314 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
315 *src_port = ntohs(s6->sin6_port);
319 recvfrom(sockfd, header, sizeof(header), 0,
320 (struct sockaddr *)&src, &sizeof_src);
327 * The packet says it's this long, but the actual UDP
328 * size could still be smaller.
335 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
336 * possible combinations.
338 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
339 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
340 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
342 struct sockaddr_storage src;
343 struct sockaddr_storage dst;
344 socklen_t sizeof_src = sizeof(src);
345 socklen_t sizeof_dst = sizeof(dst);
351 memset(&src, 0, sizeof_src);
352 memset(&dst, 0, sizeof_dst);
355 * Get address family, etc. first, so we know if we
356 * need to do udpfromto.
358 * FIXME: udpfromto also does this, but it's not
359 * a critical problem.
361 if (getsockname(sockfd, (struct sockaddr *)&dst,
362 &sizeof_dst) < 0) return -1;
365 * Read the length of the packet, from the packet.
366 * This lets us allocate the buffer to use for
367 * reading the rest of the packet.
369 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
370 (struct sockaddr *)&src, &sizeof_src);
372 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
377 * Too little data is available, discard the packet.
380 recvfrom(sockfd, header, sizeof(header), flags,
381 (struct sockaddr *)&src, &sizeof_src);
384 } else { /* we got 4 bytes of data. */
386 * See how long the packet says it is.
388 len = (header[2] * 256) + header[3];
391 * The length in the packet says it's less than
392 * a RADIUS header length: discard it.
394 if (len < AUTH_HDR_LEN) {
395 recvfrom(sockfd, header, sizeof(header), flags,
396 (struct sockaddr *)&src, &sizeof_src);
400 * Enforce RFC requirements, for sanity.
401 * Anything after 4k will be discarded.
403 } else if (len > MAX_PACKET_LEN) {
404 recvfrom(sockfd, header, sizeof(header), flags,
405 (struct sockaddr *)&src, &sizeof_src);
414 * Receive the packet. The OS will discard any data in the
415 * packet after "len" bytes.
417 #ifdef WITH_UDPFROMTO
418 if (dst.ss_family == AF_INET) {
419 data_len = recvfromto(sockfd, buf, len, flags,
420 (struct sockaddr *)&src, &sizeof_src,
421 (struct sockaddr *)&dst, &sizeof_dst);
425 * No udpfromto, OR an IPv6 socket. Fail gracefully.
427 data_len = recvfrom(sockfd, buf, len, flags,
428 (struct sockaddr *)&src, &sizeof_src);
435 * Check address families, and update src/dst ports, etc.
437 if (src.ss_family == AF_INET) {
438 struct sockaddr_in *s4;
440 s4 = (struct sockaddr_in *)&src;
441 src_ipaddr->af = AF_INET;
442 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
443 *src_port = ntohs(s4->sin_port);
445 s4 = (struct sockaddr_in *)&dst;
446 dst_ipaddr->af = AF_INET;
447 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
448 *dst_port = ntohs(s4->sin_port);
450 #ifdef HAVE_STRUCT_SOCKADDR_IN6
451 } else if (src.ss_family == AF_INET6) {
452 struct sockaddr_in6 *s6;
454 s6 = (struct sockaddr_in6 *)&src;
455 src_ipaddr->af = AF_INET6;
456 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
457 *src_port = ntohs(s6->sin6_port);
459 s6 = (struct sockaddr_in6 *)&dst;
460 dst_ipaddr->af = AF_INET6;
461 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
462 *dst_port = ntohs(s6->sin6_port);
466 return -1; /* Unknown address family, Die Die Die! */
470 * Different address families should never happen.
472 if (src.ss_family != dst.ss_family) {
478 * Tell the caller about the data
486 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
487 /*************************************************************************
489 * Function: make_secret
491 * Purpose: Build an encrypted secret value to return in a reply
492 * packet. The secret is hidden by xoring with a MD5 digest
493 * created from the shared secret and the authentication
494 * vector. We put them into MD5 in the reverse order from
495 * that used when encrypting passwords to RADIUS.
497 *************************************************************************/
498 static void make_secret(uint8_t *digest, const uint8_t *vector,
499 const char *secret, const uint8_t *value)
504 fr_MD5Init(&context);
505 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
506 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
507 fr_MD5Final(digest, &context);
509 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
510 digest[i] ^= value[i];
514 #define MAX_PASS_LEN (128)
515 static void make_passwd(uint8_t *output, int *outlen,
516 const uint8_t *input, int inlen,
517 const char *secret, const uint8_t *vector)
519 FR_MD5_CTX context, old;
520 uint8_t digest[AUTH_VECTOR_LEN];
521 uint8_t passwd[MAX_PASS_LEN];
526 * If the length is zero, round it up.
532 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
534 else if ((len & 0x0f) != 0) {
540 memcpy(passwd, input, len);
541 memset(passwd + len, 0, sizeof(passwd) - len);
543 fr_MD5Init(&context);
544 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
550 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
552 for (n = 0; n < len; n += AUTH_PASS_LEN) {
555 fr_MD5Update(&context,
556 passwd + n - AUTH_PASS_LEN,
560 fr_MD5Final(digest, &context);
561 for (i = 0; i < AUTH_PASS_LEN; i++) {
562 passwd[i + n] ^= digest[i];
566 memcpy(output, passwd, len);
569 static void make_tunnel_passwd(uint8_t *output, int *outlen,
570 const uint8_t *input, int inlen, int room,
571 const char *secret, const uint8_t *vector)
573 FR_MD5_CTX context, old;
574 uint8_t digest[AUTH_VECTOR_LEN];
575 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
582 if (room > 253) room = 253;
585 * Account for 2 bytes of the salt, and round the room
586 * available down to the nearest multiple of 16. Then,
587 * subtract one from that to account for the length byte,
588 * and the resulting number is the upper bound on the data
591 * We could short-cut this calculation just be forcing
592 * inlen to be no more than 239. It would work for all
593 * VSA's, as we don't pack multiple VSA's into one
596 * However, this calculation is more general, if a little
597 * complex. And it will work in the future for all possible
598 * kinds of weird attribute packing.
601 room -= (room & 0x0f);
604 if (inlen > room) inlen = room;
607 * Length of the encrypted data is password length plus
608 * one byte for the length of the password.
611 if ((len & 0x0f) != 0) {
615 *outlen = len + 2; /* account for the salt */
618 * Copy the password over.
620 memcpy(passwd + 3, input, inlen);
621 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
624 * Generate salt. The RFC's say:
626 * The high bit of salt[0] must be set, each salt in a
627 * packet should be unique, and they should be random
629 * So, we set the high bit, add in a counter, and then
630 * add in some CSPRNG data. should be OK..
632 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
634 passwd[1] = fr_rand();
635 passwd[2] = inlen; /* length of the password string */
637 fr_MD5Init(&context);
638 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
641 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
642 fr_MD5Update(&context, &passwd[0], 2);
644 for (n = 0; n < len; n += AUTH_PASS_LEN) {
647 fr_MD5Update(&context,
648 passwd + 2 + n - AUTH_PASS_LEN,
652 fr_MD5Final(digest, &context);
653 for (i = 0; i < AUTH_PASS_LEN; i++) {
654 passwd[i + 2 + n] ^= digest[i];
657 memcpy(output, passwd, len + 2);
662 * Parse a data structure into a RADIUS attribute.
664 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
665 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
668 int offset, len, total_length;
670 uint8_t *length_ptr, *vsa_length_ptr;
671 const uint8_t *data = NULL;
674 vendorcode = total_length = 0;
675 length_ptr = vsa_length_ptr = NULL;
678 * For interoperability, always put vendor attributes
679 * into their own VSA.
681 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
682 *(ptr++) = vp->attribute & 0xFF;
690 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
693 * This must be an RFC-format attribute. If it
694 * wasn't, then the "decode" function would have
695 * made a Vendor-Specific attribute (i.e. type
696 * 26), and we would have "vendorcode == 0" here.
700 vsa_llen = dv->length;
704 * Build a VSA header.
706 *ptr++ = PW_VENDOR_SPECIFIC;
707 vsa_length_ptr = ptr;
709 lvalue = htonl(vendorcode);
710 memcpy(ptr, &lvalue, 4);
716 ptr[0] = (vp->attribute & 0xFF);
720 ptr[0] = ((vp->attribute >> 8) & 0xFF);
721 ptr[1] = (vp->attribute & 0xFF);
727 ptr[2] = ((vp->attribute >> 8) & 0xFF);
728 ptr[3] = (vp->attribute & 0xFF);
732 return 0; /* silently discard it */
738 length_ptr = vsa_length_ptr;
739 vsa_length_ptr = NULL;
748 length_ptr = ptr + 1;
752 return 0; /* silently discard it */
756 total_length += vsa_tlen + vsa_llen;
757 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
758 *length_ptr += vsa_tlen + vsa_llen;
762 if (vp->flags.has_tag) {
763 if (TAG_VALID(vp->flags.tag)) {
764 ptr[0] = vp->flags.tag & 0xff;
767 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
769 * Tunnel passwords REQUIRE a tag, even
770 * if don't have a valid tag.
774 } /* else don't write a tag */
775 } /* else the attribute doesn't have a tag */
778 * Set up the default sources for the data.
780 data = vp->vp_octets;
787 case PW_TYPE_IPV6ADDR:
788 case PW_TYPE_IPV6PREFIX:
789 case PW_TYPE_ABINARY:
790 /* nothing more to do */
794 len = 1; /* just in case */
795 array[0] = vp->vp_integer & 0xff;
802 len = 2; /* just in case */
803 array[0] = (vp->vp_integer >> 8) & 0xff;
804 array[1] = vp->vp_integer & 0xff;
809 case PW_TYPE_INTEGER:
810 len = 4; /* just in case */
811 lvalue = htonl(vp->vp_integer);
812 memcpy(array, &lvalue, sizeof(lvalue));
815 * Perhaps discard the first octet.
817 data = &array[offset];
822 data = (const uint8_t *) &vp->vp_ipaddr;
823 len = 4; /* just in case */
827 * There are no tagged date attributes.
830 lvalue = htonl(vp->vp_date);
831 data = (const uint8_t *) &lvalue;
832 len = 4; /* just in case */
835 default: /* unknown type: ignore it */
836 librad_log("ERROR: Unknown attribute type %d", vp->type);
841 * Bound the data to 255 bytes.
843 if (len + offset + total_length > 255) {
844 len = 255 - offset - total_length;
848 * Encrypt the various password styles
850 * Attributes with encrypted values MUST be less than
853 switch (vp->flags.encrypt) {
854 case FLAG_ENCRYPT_USER_PASSWORD:
855 make_passwd(ptr + offset, &len,
857 secret, packet->vector);
860 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
862 * Check if 255 - offset - total_length is less
863 * than 18. If so, we can't fit the data into
864 * the available space, and we discard the
867 * This is ONLY a problem if we have multiple VSA's
868 * in one Vendor-Specific, though.
870 if ((255 - offset - total_length) < 18) return 0;
872 switch (packet->code) {
873 case PW_AUTHENTICATION_ACK:
874 case PW_AUTHENTICATION_REJECT:
875 case PW_ACCESS_CHALLENGE:
878 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
881 make_tunnel_passwd(ptr + offset, &len,
882 data, len, 255 - offset - total_length,
883 secret, original->vector);
885 case PW_ACCOUNTING_REQUEST:
886 case PW_DISCONNECT_REQUEST:
888 make_tunnel_passwd(ptr + offset, &len,
889 data, len, 255 - offset - total_length,
890 secret, packet->vector);
896 * The code above ensures that this attribute
899 case FLAG_ENCRYPT_ASCEND_SECRET:
900 make_secret(ptr + offset, packet->vector,
902 len = AUTH_VECTOR_LEN;
908 * Just copy the data over
910 memcpy(ptr + offset, data, len);
912 } /* switch over encryption flags */
915 * Account for the tag (if any).
920 * RFC 2865 section 5 says that zero-length attributes
923 if (len == 0) return 0;
926 * Update the various lengths.
929 if (vsa_length_ptr) *vsa_length_ptr += len;
933 return total_length; /* of attribute */
940 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
943 radius_packet_t *hdr;
945 uint16_t total_length;
952 * For simplicity in the following logic, we allow
953 * the attributes to "overflow" the 4k maximum
954 * RADIUS packet size, by one attribute.
956 * It's uint32_t, for alignment purposes.
958 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
960 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
961 what = packet_codes[packet->code];
966 DEBUG("Sending %s of id %d to %s port %d\n",
968 inet_ntop(packet->dst_ipaddr.af,
969 &packet->dst_ipaddr.ipaddr,
970 ip_buffer, sizeof(ip_buffer)),
974 * Double-check some things based on packet code.
976 switch (packet->code) {
977 case PW_AUTHENTICATION_ACK:
978 case PW_AUTHENTICATION_REJECT:
979 case PW_ACCESS_CHALLENGE:
981 librad_log("ERROR: Cannot sign response packet without a request packet.");
987 * These packet vectors start off as all zero.
989 case PW_ACCOUNTING_REQUEST:
990 case PW_DISCONNECT_REQUEST:
992 memset(packet->vector, 0, sizeof(packet->vector));
1000 * Use memory on the stack, until we know how
1001 * large the packet will be.
1003 hdr = (radius_packet_t *) data;
1006 * Build standard header
1008 hdr->code = packet->code;
1009 hdr->id = packet->id;
1011 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1013 total_length = AUTH_HDR_LEN;
1016 * Load up the configuration values for the user
1022 * FIXME: Loop twice over the reply list. The first time,
1023 * calculate the total length of data. The second time,
1024 * allocate the memory, and fill in the VP's.
1026 * Hmm... this may be slower than just doing a small
1031 * Loop over the reply attributes for the packet.
1033 for (reply = packet->vps; reply; reply = reply->next) {
1035 * Ignore non-wire attributes
1037 if ((VENDOR(reply->attribute) == 0) &&
1038 ((reply->attribute & 0xFFFF) > 0xff)) {
1041 * Permit the admin to send BADLY formatted
1042 * attributes with a debug build.
1044 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1045 memcpy(ptr, reply->vp_octets, reply->length);
1046 len = reply->length;
1054 * Set the Message-Authenticator to the correct
1055 * length and initial value.
1057 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1058 reply->length = AUTH_VECTOR_LEN;
1059 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1062 * Cache the offset to the
1063 * Message-Authenticator
1065 packet->offset = total_length;
1069 * Print out ONLY the attributes which
1070 * we're sending over the wire, and print
1071 * them out BEFORE they're encrypted.
1075 len = rad_vp2attr(packet, original, secret, reply, ptr);
1077 if (len < 0) return -1;
1080 * Check that the packet is no more than 4k in
1081 * size, AFTER writing the attribute past the 4k
1082 * boundary, but BEFORE deciding to increase the
1083 * size of the packet. Note that the 'data'
1084 * buffer, above, is one attribute longer than
1085 * necessary, in order to permit this overflow.
1087 if ((total_length + len) > MAX_PACKET_LEN) {
1093 total_length += len;
1094 } /* done looping over all attributes */
1097 * Fill in the rest of the fields, and copy the data over
1098 * from the local stack to the newly allocated memory.
1100 * Yes, all this 'memcpy' is slow, but it means
1101 * that we only allocate the minimum amount of
1102 * memory for a request.
1104 packet->data_len = total_length;
1105 packet->data = (uint8_t *) malloc(packet->data_len);
1106 if (!packet->data) {
1107 librad_log("Out of memory");
1111 memcpy(packet->data, data, packet->data_len);
1112 hdr = (radius_packet_t *) packet->data;
1114 total_length = htons(total_length);
1115 memcpy(hdr->length, &total_length, sizeof(total_length));
1122 * Sign a previously encoded packet.
1124 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1127 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1130 * It wasn't assigned an Id, this is bad!
1132 if (packet->id < 0) {
1133 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1137 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1138 (packet->offset < 0)) {
1139 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1144 * If there's a Message-Authenticator, update it
1145 * now, BEFORE updating the authentication vector.
1147 if (packet->offset > 0) {
1148 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1150 switch (packet->code) {
1151 case PW_ACCOUNTING_REQUEST:
1152 case PW_ACCOUNTING_RESPONSE:
1153 case PW_DISCONNECT_REQUEST:
1154 case PW_DISCONNECT_ACK:
1155 case PW_DISCONNECT_NAK:
1156 case PW_COA_REQUEST:
1159 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1162 case PW_AUTHENTICATION_ACK:
1163 case PW_AUTHENTICATION_REJECT:
1164 case PW_ACCESS_CHALLENGE:
1166 librad_log("ERROR: Cannot sign response packet without a request packet.");
1169 memcpy(hdr->vector, original->vector,
1173 default: /* others have vector already set to zero */
1179 * Set the authentication vector to zero,
1180 * calculate the signature, and put it
1181 * into the Message-Authenticator
1184 fr_hmac_md5(packet->data, packet->data_len,
1185 (const uint8_t *) secret, strlen(secret),
1187 memcpy(packet->data + packet->offset + 2,
1188 calc_auth_vector, AUTH_VECTOR_LEN);
1191 * Copy the original request vector back
1192 * to the raw packet.
1194 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1198 * Switch over the packet code, deciding how to
1201 switch (packet->code) {
1203 * Request packets are not signed, bur
1204 * have a random authentication vector.
1206 case PW_AUTHENTICATION_REQUEST:
1207 case PW_STATUS_SERVER:
1211 * Reply packets are signed with the
1212 * authentication vector of the request.
1219 fr_MD5Init(&context);
1220 fr_MD5Update(&context, packet->data, packet->data_len);
1221 fr_MD5Update(&context, (const uint8_t *) secret,
1223 fr_MD5Final(digest, &context);
1225 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1226 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1229 }/* switch over packet codes */
1235 * Reply to the request. Also attach
1236 * reply attribute value pairs and any user message provided.
1238 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1243 char ip_buffer[128];
1246 * Maybe it's a fake packet. Don't send it.
1248 if (!packet || (packet->sockfd < 0)) {
1252 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1253 what = packet_codes[packet->code];
1259 * First time through, allocate room for the packet
1261 if (!packet->data) {
1263 * Encode the packet.
1265 if (rad_encode(packet, original, secret) < 0) {
1270 * Re-sign it, including updating the
1271 * Message-Authenticator.
1273 if (rad_sign(packet, original, secret) < 0) {
1278 * If packet->data points to data, then we print out
1279 * the VP list again only for debugging.
1281 } else if (librad_debug) {
1282 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1283 inet_ntop(packet->dst_ipaddr.af,
1284 &packet->dst_ipaddr.ipaddr,
1285 ip_buffer, sizeof(ip_buffer)),
1288 for (reply = packet->vps; reply; reply = reply->next) {
1289 if ((VENDOR(reply->attribute) == 0) &&
1290 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1296 * And send it on it's way.
1298 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1299 &packet->src_ipaddr, packet->src_port,
1300 &packet->dst_ipaddr, packet->dst_port);
1305 * Validates the requesting client NAS. Calculates the
1306 * signature based on the clients private key.
1308 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1310 uint8_t digest[AUTH_VECTOR_LEN];
1314 * Zero out the auth_vector in the received packet.
1315 * Then append the shared secret to the received packet,
1316 * and calculate the MD5 sum. This must be the same
1317 * as the original MD5 sum (packet->vector).
1319 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1322 * MD5(packet + secret);
1324 fr_MD5Init(&context);
1325 fr_MD5Update(&context, packet->data, packet->data_len);
1326 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1327 fr_MD5Final(digest, &context);
1330 * Return 0 if OK, 2 if not OK.
1332 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1338 * Validates the requesting client NAS. Calculates the
1339 * signature based on the clients private key.
1341 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1344 uint8_t calc_digest[AUTH_VECTOR_LEN];
1350 if (original == NULL) {
1355 * Copy the original vector in place.
1357 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1360 * MD5(packet + secret);
1362 fr_MD5Init(&context);
1363 fr_MD5Update(&context, packet->data, packet->data_len);
1364 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1365 fr_MD5Final(calc_digest, &context);
1368 * Copy the packet's vector back to the packet.
1370 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1373 * Return 0 if OK, 2 if not OK.
1375 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1381 * See if the data pointed to by PTR is a valid RADIUS packet.
1383 * packet is not 'const * const' because we may update data_len,
1384 * if there's more data in the UDP packet than in the RADIUS packet.
1386 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1391 radius_packet_t *hdr;
1392 char host_ipaddr[128];
1398 * Check for packets smaller than the packet header.
1400 * RFC 2865, Section 3., subsection 'length' says:
1402 * "The minimum length is 20 ..."
1404 if (packet->data_len < AUTH_HDR_LEN) {
1405 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1406 inet_ntop(packet->src_ipaddr.af,
1407 &packet->src_ipaddr.ipaddr,
1408 host_ipaddr, sizeof(host_ipaddr)),
1409 packet->data_len, AUTH_HDR_LEN);
1414 * RFC 2865, Section 3., subsection 'length' says:
1416 * " ... and maximum length is 4096."
1418 if (packet->data_len > MAX_PACKET_LEN) {
1419 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1420 inet_ntop(packet->src_ipaddr.af,
1421 &packet->src_ipaddr.ipaddr,
1422 host_ipaddr, sizeof(host_ipaddr)),
1423 packet->data_len, MAX_PACKET_LEN);
1428 * Check for packets with mismatched size.
1429 * i.e. We've received 128 bytes, and the packet header
1430 * says it's 256 bytes long.
1432 totallen = (packet->data[2] << 8) | packet->data[3];
1433 hdr = (radius_packet_t *)packet->data;
1436 * Code of 0 is not understood.
1437 * Code of 16 or greate is not understood.
1439 if ((hdr->code == 0) ||
1440 (hdr->code >= MAX_PACKET_CODE)) {
1441 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1442 inet_ntop(packet->src_ipaddr.af,
1443 &packet->src_ipaddr.ipaddr,
1444 host_ipaddr, sizeof(host_ipaddr)),
1450 * Message-Authenticator is required in Status-Server
1451 * packets, otherwise they can be trivially forged.
1453 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1456 * It's also required if the caller asks for it.
1458 if (flags) require_ma = 1;
1461 * Repeat the length checks. This time, instead of
1462 * looking at the data we received, look at the value
1463 * of the 'length' field inside of the packet.
1465 * Check for packets smaller than the packet header.
1467 * RFC 2865, Section 3., subsection 'length' says:
1469 * "The minimum length is 20 ..."
1471 if (totallen < AUTH_HDR_LEN) {
1472 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1473 inet_ntop(packet->src_ipaddr.af,
1474 &packet->src_ipaddr.ipaddr,
1475 host_ipaddr, sizeof(host_ipaddr)),
1476 totallen, AUTH_HDR_LEN);
1481 * And again, for the value of the 'length' field.
1483 * RFC 2865, Section 3., subsection 'length' says:
1485 * " ... and maximum length is 4096."
1487 if (totallen > MAX_PACKET_LEN) {
1488 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1489 inet_ntop(packet->src_ipaddr.af,
1490 &packet->src_ipaddr.ipaddr,
1491 host_ipaddr, sizeof(host_ipaddr)),
1492 totallen, MAX_PACKET_LEN);
1497 * RFC 2865, Section 3., subsection 'length' says:
1499 * "If the packet is shorter than the Length field
1500 * indicates, it MUST be silently discarded."
1502 * i.e. No response to the NAS.
1504 if (packet->data_len < totallen) {
1505 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1506 inet_ntop(packet->src_ipaddr.af,
1507 &packet->src_ipaddr.ipaddr,
1508 host_ipaddr, sizeof(host_ipaddr)),
1509 packet->data_len, totallen);
1514 * RFC 2865, Section 3., subsection 'length' says:
1516 * "Octets outside the range of the Length field MUST be
1517 * treated as padding and ignored on reception."
1519 if (packet->data_len > totallen) {
1521 * We're shortening the packet below, but just
1522 * to be paranoid, zero out the extra data.
1524 memset(packet->data + totallen, 0, packet->data_len - totallen);
1525 packet->data_len = totallen;
1529 * Walk through the packet's attributes, ensuring that
1530 * they add up EXACTLY to the size of the packet.
1532 * If they don't, then the attributes either under-fill
1533 * or over-fill the packet. Any parsing of the packet
1534 * is impossible, and will result in unknown side effects.
1536 * This would ONLY happen with buggy RADIUS implementations,
1537 * or with an intentional attack. Either way, we do NOT want
1538 * to be vulnerable to this problem.
1541 count = totallen - AUTH_HDR_LEN;
1546 * Attribute number zero is NOT defined.
1549 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1550 inet_ntop(packet->src_ipaddr.af,
1551 &packet->src_ipaddr.ipaddr,
1552 host_ipaddr, sizeof(host_ipaddr)));
1557 * Attributes are at LEAST as long as the ID & length
1558 * fields. Anything shorter is an invalid attribute.
1561 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1562 inet_ntop(packet->src_ipaddr.af,
1563 &packet->src_ipaddr.ipaddr,
1564 host_ipaddr, sizeof(host_ipaddr)),
1570 * Sanity check the attributes for length.
1573 default: /* don't do anything by default */
1577 * If there's an EAP-Message, we require
1578 * a Message-Authenticator.
1580 case PW_EAP_MESSAGE:
1584 case PW_MESSAGE_AUTHENTICATOR:
1585 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1586 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1587 inet_ntop(packet->src_ipaddr.af,
1588 &packet->src_ipaddr.ipaddr,
1589 host_ipaddr, sizeof(host_ipaddr)),
1598 * FIXME: Look up the base 255 attributes in the
1599 * dictionary, and switch over their type. For
1600 * integer/date/ip, the attribute length SHOULD
1603 count -= attr[1]; /* grab the attribute length */
1605 num_attributes++; /* seen one more attribute */
1609 * If the attributes add up to a packet, it's allowed.
1611 * If not, we complain, and throw the packet away.
1614 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1615 inet_ntop(packet->src_ipaddr.af,
1616 &packet->src_ipaddr.ipaddr,
1617 host_ipaddr, sizeof(host_ipaddr)));
1622 * If we're configured to look for a maximum number of
1623 * attributes, and we've seen more than that maximum,
1624 * then throw the packet away, as a possible DoS.
1626 if ((librad_max_attributes > 0) &&
1627 (num_attributes > librad_max_attributes)) {
1628 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1629 inet_ntop(packet->src_ipaddr.af,
1630 &packet->src_ipaddr.ipaddr,
1631 host_ipaddr, sizeof(host_ipaddr)),
1632 num_attributes, librad_max_attributes);
1637 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1639 * A packet with an EAP-Message attribute MUST also have
1640 * a Message-Authenticator attribute.
1642 * A Message-Authenticator all by itself is OK, though.
1644 * Similarly, Status-Server packets MUST contain
1645 * Message-Authenticator attributes.
1647 if (require_ma && ! seen_ma) {
1648 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1649 inet_ntop(packet->src_ipaddr.af,
1650 &packet->src_ipaddr.ipaddr,
1651 host_ipaddr, sizeof(host_ipaddr)));
1656 * Fill RADIUS header fields
1658 packet->code = hdr->code;
1659 packet->id = hdr->id;
1660 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1667 * Receive UDP client requests, and fill in
1668 * the basics of a RADIUS_PACKET structure.
1670 RADIUS_PACKET *rad_recv(int fd, int flags)
1672 RADIUS_PACKET *packet;
1675 * Allocate the new request data structure
1677 if ((packet = malloc(sizeof(*packet))) == NULL) {
1678 librad_log("out of memory");
1681 memset(packet, 0, sizeof(*packet));
1683 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1684 &packet->src_ipaddr, &packet->src_port,
1685 &packet->dst_ipaddr, &packet->dst_port);
1688 * Check for socket errors.
1690 if (packet->data_len < 0) {
1691 librad_log("Error receiving packet: %s", strerror(errno));
1692 /* packet->data is NULL */
1698 * If the packet is too big, then rad_recvfrom did NOT
1699 * allocate memory. Instead, it just discarded the
1702 if (packet->data_len > MAX_PACKET_LEN) {
1703 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1704 /* packet->data is NULL */
1710 * Read no data. Continue.
1711 * This check is AFTER the MAX_PACKET_LEN check above, because
1712 * if the packet is larger than MAX_PACKET_LEN, we also have
1713 * packet->data == NULL
1715 if ((packet->data_len == 0) || !packet->data) {
1716 librad_log("Empty packet: Socket is not ready.");
1722 * See if it's a well-formed RADIUS packet.
1724 if (!rad_packet_ok(packet, flags)) {
1730 * Remember which socket we read the packet from.
1732 packet->sockfd = fd;
1735 * FIXME: Do even more filtering by only permitting
1736 * certain IP's. The problem is that we don't know
1737 * how to do this properly for all possible clients...
1741 * Explicitely set the VP list to empty.
1746 char host_ipaddr[128];
1748 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1749 DEBUG("rad_recv: %s packet from host %s port %d",
1750 packet_codes[packet->code],
1751 inet_ntop(packet->src_ipaddr.af,
1752 &packet->src_ipaddr.ipaddr,
1753 host_ipaddr, sizeof(host_ipaddr)),
1756 DEBUG("rad_recv: Packet from host %s port %d code=%d",
1757 inet_ntop(packet->src_ipaddr.af,
1758 &packet->src_ipaddr.ipaddr,
1759 host_ipaddr, sizeof(host_ipaddr)),
1763 DEBUG(", id=%d, length=%d\n", packet->id, packet->data_len);
1771 * Verify the signature of a packet.
1773 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1780 if (!packet || !packet->data) return -1;
1783 * Before we allocate memory for the attributes, do more
1786 ptr = packet->data + AUTH_HDR_LEN;
1787 length = packet->data_len - AUTH_HDR_LEN;
1788 while (length > 0) {
1789 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1790 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1795 default: /* don't do anything. */
1799 * Note that more than one Message-Authenticator
1800 * attribute is invalid.
1802 case PW_MESSAGE_AUTHENTICATOR:
1803 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1804 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1806 switch (packet->code) {
1810 case PW_ACCOUNTING_REQUEST:
1811 case PW_ACCOUNTING_RESPONSE:
1812 case PW_DISCONNECT_REQUEST:
1813 case PW_DISCONNECT_ACK:
1814 case PW_DISCONNECT_NAK:
1815 case PW_COA_REQUEST:
1818 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1821 case PW_AUTHENTICATION_ACK:
1822 case PW_AUTHENTICATION_REJECT:
1823 case PW_ACCESS_CHALLENGE:
1825 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1828 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1832 fr_hmac_md5(packet->data, packet->data_len,
1833 (const uint8_t *) secret, strlen(secret),
1835 if (memcmp(calc_auth_vector, msg_auth_vector,
1836 sizeof(calc_auth_vector)) != 0) {
1838 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1839 inet_ntop(packet->src_ipaddr.af,
1840 &packet->src_ipaddr.ipaddr,
1841 buffer, sizeof(buffer)));
1842 /* Silently drop packet, according to RFC 3579 */
1844 } /* else the message authenticator was good */
1847 * Reinitialize Authenticators.
1849 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1850 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1852 } /* switch over the attributes */
1856 } /* loop over the packet, sanity checking the attributes */
1859 * It looks like a RADIUS packet, but we can't validate
1862 if ((packet->code == 0) || (packet->code >= MAX_PACKET_CODE)) {
1864 librad_log("Received Unknown packet code %d "
1865 "from client %s port %d: Cannot validate signature.",
1867 inet_ntop(packet->src_ipaddr.af,
1868 &packet->src_ipaddr.ipaddr,
1869 buffer, sizeof(buffer)),
1875 * Calculate and/or verify digest.
1877 switch(packet->code) {
1881 case PW_AUTHENTICATION_REQUEST:
1882 case PW_STATUS_SERVER:
1884 * The authentication vector is random
1885 * nonsense, invented by the client.
1889 case PW_COA_REQUEST:
1890 case PW_DISCONNECT_REQUEST:
1891 case PW_ACCOUNTING_REQUEST:
1892 if (calc_acctdigest(packet, secret) > 1) {
1893 librad_log("Received %s packet "
1894 "from %s with invalid signature! (Shared secret is incorrect.)",
1895 packet_codes[packet->code],
1896 inet_ntop(packet->src_ipaddr.af,
1897 &packet->src_ipaddr.ipaddr,
1898 buffer, sizeof(buffer)));
1903 /* Verify the reply digest */
1904 case PW_AUTHENTICATION_ACK:
1905 case PW_AUTHENTICATION_REJECT:
1906 case PW_ACCESS_CHALLENGE:
1907 case PW_ACCOUNTING_RESPONSE:
1908 case PW_DISCONNECT_ACK:
1909 case PW_DISCONNECT_NAK:
1912 rcode = calc_replydigest(packet, original, secret);
1914 librad_log("Received %s packet "
1915 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1916 packet_codes[packet->code],
1917 inet_ntop(packet->src_ipaddr.af,
1918 &packet->src_ipaddr.ipaddr,
1919 buffer, sizeof(buffer)),
1927 librad_log("Received Unknown packet code %d "
1928 "from client %s port %d: Cannot validate signature",
1930 inet_ntop(packet->src_ipaddr.af,
1931 &packet->src_ipaddr.ipaddr,
1932 buffer, sizeof(buffer)),
1942 * Parse a RADIUS attribute into a data structure.
1944 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1945 const char *secret, int attribute, int length,
1946 const uint8_t *data)
1951 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1956 * If length is greater than 253, something is SERIOUSLY
1959 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1961 vp->length = length;
1962 vp->operator = T_OP_EQ;
1968 if (vp->flags.has_tag) {
1969 if (TAG_VALID(data[0]) ||
1970 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1972 * Tunnel passwords REQUIRE a tag, even
1973 * if don't have a valid tag.
1975 vp->flags.tag = data[0];
1977 if ((vp->type == PW_TYPE_STRING) ||
1978 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1983 * Copy the data to be decrypted
1985 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1986 vp->length -= offset;
1989 * Decrypt the attribute.
1991 switch (vp->flags.encrypt) {
1995 case FLAG_ENCRYPT_USER_PASSWORD:
1997 rad_pwdecode((char *)vp->vp_strvalue,
2001 rad_pwdecode((char *)vp->vp_strvalue,
2005 if (vp->attribute == PW_USER_PASSWORD) {
2006 vp->length = strlen(vp->vp_strvalue);
2011 * Tunnel-Password's may go ONLY
2012 * in response packets.
2014 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2015 if (!original) goto raw;
2017 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2018 secret, original->vector) < 0) {
2024 * Ascend-Send-Secret
2025 * Ascend-Receive-Secret
2027 case FLAG_ENCRYPT_ASCEND_SECRET:
2031 uint8_t my_digest[AUTH_VECTOR_LEN];
2032 make_secret(my_digest,
2035 memcpy(vp->vp_strvalue, my_digest,
2037 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2038 vp->length = strlen(vp->vp_strvalue);
2044 } /* switch over encryption flags */
2048 case PW_TYPE_STRING:
2049 case PW_TYPE_OCTETS:
2050 case PW_TYPE_ABINARY:
2051 /* nothing more to do */
2055 if (vp->length != 1) goto raw;
2057 vp->vp_integer = vp->vp_octets[0];
2062 if (vp->length != 2) goto raw;
2064 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2067 case PW_TYPE_INTEGER:
2068 if (vp->length != 4) goto raw;
2070 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2071 vp->vp_integer = ntohl(vp->vp_integer);
2073 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2076 * Try to get named VALUEs
2080 dval = dict_valbyattr(vp->attribute,
2083 strlcpy(vp->vp_strvalue,
2085 sizeof(vp->vp_strvalue));
2091 if (vp->length != 4) goto raw;
2093 memcpy(&vp->vp_date, vp->vp_octets, 4);
2094 vp->vp_date = ntohl(vp->vp_date);
2098 case PW_TYPE_IPADDR:
2099 if (vp->length != 4) goto raw;
2101 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2105 * IPv6 interface ID is 8 octets long.
2108 if (vp->length != 8) goto raw;
2109 /* vp->vp_ifid == vp->vp_octets */
2113 * IPv6 addresses are 16 octets long
2115 case PW_TYPE_IPV6ADDR:
2116 if (vp->length != 16) goto raw;
2117 /* vp->vp_ipv6addr == vp->vp_octets */
2121 * IPv6 prefixes are 2 to 18 octets long.
2123 * RFC 3162: The first octet is unused.
2124 * The second is the length of the prefix
2125 * the rest are the prefix data.
2127 * The prefix length can have value 0 to 128.
2129 case PW_TYPE_IPV6PREFIX:
2130 if (vp->length < 2 || vp->length > 18) goto raw;
2131 if (vp->vp_octets[1] > 128) goto raw;
2134 * FIXME: double-check that
2135 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2137 if (vp->length < 18) {
2138 memset(vp->vp_octets + vp->length, 0,
2145 vp->type = PW_TYPE_OCTETS;
2146 vp->length = length;
2147 memcpy(vp->vp_octets, data, length);
2151 * Ensure there's no encryption or tag stuff,
2152 * we just pass the attribute as-is.
2154 memset(&vp->flags, 0, sizeof(vp->flags));
2162 * Calculate/check digest, and decode radius attributes.
2164 * -1 on decoding error
2167 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2171 uint32_t vendorcode;
2179 radius_packet_t *hdr;
2180 int vsa_tlen, vsa_llen;
2181 DICT_VENDOR *dv = NULL;
2182 int num_attributes = 0;
2185 * Extract attribute-value pairs
2187 hdr = (radius_packet_t *)packet->data;
2189 packet_length = packet->data_len - AUTH_HDR_LEN;
2192 * There may be VP's already in the packet. Don't
2195 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2201 vsa_tlen = vsa_llen = 1;
2204 * We have to read at least two bytes.
2206 * rad_recv() above ensures that this is OK.
2208 while (packet_length > 0) {
2213 * Normal attribute, handle it like normal.
2215 if (vendorcode == 0) {
2217 * No room to read attr/length,
2218 * or bad attribute, or attribute is
2219 * too short, or attribute is too long,
2220 * stop processing the packet.
2222 if ((packet_length < 2) ||
2223 (ptr[0] == 0) || (ptr[1] < 2) ||
2224 (ptr[1] > packet_length)) break;
2232 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2235 * No vendor code, or ONLY vendor code.
2237 if (attrlen <= 4) goto create_pair;
2243 * Handle Vendor-Specific
2245 if (vendorlen == 0) {
2251 * attrlen was checked above.
2253 memcpy(&lvalue, ptr, 4);
2254 myvendor = ntohl(lvalue);
2257 * Zero isn't allowed.
2259 if (myvendor == 0) goto create_pair;
2262 * This is an implementation issue.
2263 * We currently pack vendor into the upper
2264 * 16 bits of a 32-bit attribute number,
2265 * so we can't handle vendor numbers larger
2268 if (myvendor > 65535) goto create_pair;
2270 vsa_tlen = vsa_llen = 1;
2271 dv = dict_vendorbyvalue(myvendor);
2273 vsa_tlen = dv->type;
2274 vsa_llen = dv->length;
2278 * Sweep through the list of VSA's,
2279 * seeing if they exactly fill the
2280 * outer Vendor-Specific attribute.
2282 * If not, create a raw Vendor-Specific.
2285 sublen = attrlen - 4;
2288 * See if we can parse it.
2294 * Don't have a type, it's bad.
2296 if (sublen < vsa_tlen) goto create_pair;
2299 * Ensure that the attribute number
2308 myattr = (subptr[0] << 8) | subptr[1];
2312 if ((subptr[0] != 0) ||
2313 (subptr[1] != 0)) goto create_pair;
2315 myattr = (subptr[2] << 8) | subptr[3];
2319 * Our dictionary is broken.
2326 * Not enough room for one more
2329 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2332 attribute = (myvendor << 16) | myattr;
2333 ptr += 4 + vsa_tlen;
2334 attrlen -= (4 + vsa_tlen);
2335 packet_length -= 4 + vsa_tlen;
2339 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2342 if (subptr[vsa_tlen] > sublen)
2344 sublen -= subptr[vsa_tlen];
2345 subptr += subptr[vsa_tlen];
2349 if (subptr[vsa_tlen] != 0) goto create_pair;
2350 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2352 if (subptr[vsa_tlen + 1] > sublen)
2354 sublen -= subptr[vsa_tlen + 1];
2355 subptr += subptr[vsa_tlen + 1];
2359 * Our dictionaries are
2365 } while (sublen > 0);
2367 vendorcode = myvendor;
2368 vendorlen = attrlen - 4;
2375 * attrlen is the length of this attribute.
2376 * total_len is the length of the encompassing
2385 attribute = (ptr[0] << 8) | ptr[1];
2388 default: /* can't hit this. */
2391 attribute |= (vendorcode << 16);
2396 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2400 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2403 default: /* can't hit this. */
2407 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2408 if (vendorlen == 0) vendorcode = 0;
2409 packet_length -= (vsa_tlen + vsa_llen);
2412 * Create the attribute, setting the default type
2413 * to 'octets'. If the type in the dictionary
2414 * is different, then the dictionary type will
2415 * over-ride this one.
2417 * If the attribute has no data, then discard it.
2420 if (!attrlen) goto next;
2422 pair = rad_attr2vp(packet, original, secret,
2423 attribute, attrlen, ptr);
2425 pairfree(&packet->vps);
2426 librad_log("out of memory");
2439 * VSA's may not have been counted properly in
2440 * rad_packet_ok() above, as it is hard to count
2441 * then without using the dictionary. We
2442 * therefore enforce the limits here, too.
2444 if ((librad_max_attributes > 0) &&
2445 (num_attributes > librad_max_attributes)) {
2446 char host_ipaddr[128];
2448 pairfree(&packet->vps);
2449 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2450 inet_ntop(packet->src_ipaddr.af,
2451 &packet->src_ipaddr.ipaddr,
2452 host_ipaddr, sizeof(host_ipaddr)),
2453 num_attributes, librad_max_attributes);
2459 packet_length -= attrlen;
2463 * Merge information from the outside world into our
2466 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2475 * We assume that the passwd buffer passed is big enough.
2476 * RFC2138 says the password is max 128 chars, so the size
2477 * of the passwd buffer must be at least 129 characters.
2478 * Preferably it's just MAX_STRING_LEN.
2480 * int *pwlen is updated to the new length of the encrypted
2481 * password - a multiple of 16 bytes.
2483 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
2484 const uint8_t *vector)
2486 FR_MD5_CTX context, old;
2487 uint8_t digest[AUTH_VECTOR_LEN];
2488 int i, n, secretlen;
2492 * RFC maximum is 128 bytes.
2494 * If length is zero, pad it out with zeros.
2496 * If the length isn't aligned to 16 bytes,
2497 * zero out the extra data.
2501 if (len > 128) len = 128;
2504 memset(passwd, 0, AUTH_PASS_LEN);
2505 len = AUTH_PASS_LEN;
2506 } else if ((len % AUTH_PASS_LEN) != 0) {
2507 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2508 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2513 * Use the secret to setup the decryption digest
2515 secretlen = strlen(secret);
2517 fr_MD5Init(&context);
2518 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2519 old = context; /* save intermediate work */
2522 * Encrypt it in place. Don't bother checking
2523 * len, as we've ensured above that it's OK.
2525 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2527 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2528 fr_MD5Final(digest, &context);
2531 fr_MD5Update(&context,
2532 (uint8_t *) passwd + n - AUTH_PASS_LEN,
2534 fr_MD5Final(digest, &context);
2537 for (i = 0; i < AUTH_PASS_LEN; i++) {
2538 passwd[i + n] ^= digest[i];
2548 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
2549 const uint8_t *vector)
2551 FR_MD5_CTX context, old;
2552 uint8_t digest[AUTH_VECTOR_LEN];
2554 size_t n, secretlen;
2557 * The RFC's say that the maximum is 128.
2558 * The buffer we're putting it into above is 254, so
2559 * we don't need to do any length checking.
2561 if (pwlen > 128) pwlen = 128;
2566 if (pwlen == 0) goto done;
2569 * Use the secret to setup the decryption digest
2571 secretlen = strlen(secret);
2573 fr_MD5Init(&context);
2574 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2575 old = context; /* save intermediate work */
2578 * The inverse of the code above.
2580 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2582 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2583 fr_MD5Final(digest, &context);
2586 if (pwlen > AUTH_PASS_LEN) {
2587 fr_MD5Update(&context, (uint8_t *) passwd,
2591 fr_MD5Final(digest, &context);
2594 if (pwlen > (n + AUTH_PASS_LEN)) {
2595 fr_MD5Update(&context, (uint8_t *) passwd + n,
2600 for (i = 0; i < AUTH_PASS_LEN; i++) {
2601 passwd[i + n] ^= digest[i];
2606 passwd[pwlen] = '\0';
2607 return strlen(passwd);
2612 * Encode Tunnel-Password attributes when sending them out on the wire.
2614 * int *pwlen is updated to the new length of the encrypted
2615 * password - a multiple of 16 bytes.
2617 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2620 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
2621 const uint8_t *vector)
2623 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2624 unsigned char digest[AUTH_VECTOR_LEN];
2626 int i, n, secretlen;
2631 if (len > 127) len = 127;
2634 * Shift the password 3 positions right to place a salt and original
2635 * length, tag will be added automatically on packet send
2637 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2641 * save original password length as first password character;
2648 * Generate salt. The RFC's say:
2650 * The high bit of salt[0] must be set, each salt in a
2651 * packet should be unique, and they should be random
2653 * So, we set the high bit, add in a counter, and then
2654 * add in some CSPRNG data. should be OK..
2656 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2657 (fr_rand() & 0x07));
2658 salt[1] = fr_rand();
2661 * Padd password to multiple of AUTH_PASS_LEN bytes.
2663 n = len % AUTH_PASS_LEN;
2665 n = AUTH_PASS_LEN - n;
2666 for (; n > 0; n--, len++)
2669 /* set new password length */
2673 * Use the secret to setup the decryption digest
2675 secretlen = strlen(secret);
2676 memcpy(buffer, secret, secretlen);
2678 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2680 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2681 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2682 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2684 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2685 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2688 for (i = 0; i < AUTH_PASS_LEN; i++) {
2689 passwd[i + n2] ^= digest[i];
2697 * Decode Tunnel-Password encrypted attributes.
2699 * Defined in RFC-2868, this uses a two char SALT along with the
2700 * initial intermediate value, to differentiate it from the
2703 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
2704 const uint8_t *vector)
2706 FR_MD5_CTX context, old;
2707 uint8_t digest[AUTH_VECTOR_LEN];
2709 unsigned i, n, len, reallen;
2714 * We need at least a salt.
2717 librad_log("tunnel password is too short");
2722 * There's a salt, but no password. Or, there's a salt
2723 * and a 'data_len' octet. It's wrong, but at least we
2724 * can figure out what it means: the password is empty.
2726 * Note that this means we ignore the 'data_len' field,
2727 * if the attribute length tells us that there's no
2728 * more data. So the 'data_len' field may be wrong,
2737 len -= 2; /* discount the salt */
2740 * Use the secret to setup the decryption digest
2742 secretlen = strlen(secret);
2744 fr_MD5Init(&context);
2745 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2746 old = context; /* save intermediate work */
2749 * Set up the initial key:
2751 * b(1) = MD5(secret + vector + salt)
2753 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2754 fr_MD5Update(&context, passwd, 2);
2757 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2761 fr_MD5Final(digest, &context);
2766 * A quick check: decrypt the first octet
2767 * of the password, which is the
2768 * 'data_len' field. Ensure it's sane.
2770 reallen = passwd[2] ^ digest[0];
2771 if (reallen >= len) {
2772 librad_log("tunnel password is too long for the attribute");
2776 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2780 fr_MD5Final(digest, &context);
2783 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2786 for (i = base; i < AUTH_PASS_LEN; i++) {
2787 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2792 * See make_tunnel_password, above.
2794 if (reallen > 239) reallen = 239;
2797 passwd[reallen] = 0;
2803 * Encode a CHAP password
2805 * FIXME: might not work with Ascend because
2806 * we use vp->length, and Ascend gear likes
2807 * to send an extra '\0' in the string!
2809 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2810 VALUE_PAIR *password)
2814 uint8_t string[MAX_STRING_LEN * 2 + 1];
2815 VALUE_PAIR *challenge;
2818 * Sanity check the input parameters
2820 if ((packet == NULL) || (password == NULL)) {
2825 * Note that the password VP can be EITHER
2826 * a User-Password attribute (from a check-item list),
2827 * or a CHAP-Password attribute (the client asking
2828 * the library to encode it).
2836 memcpy(ptr, password->vp_strvalue, password->length);
2837 ptr += password->length;
2838 i += password->length;
2841 * Use Chap-Challenge pair if present,
2842 * Request-Authenticator otherwise.
2844 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2846 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2847 i += challenge->length;
2849 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2850 i += AUTH_VECTOR_LEN;
2854 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2861 * Seed the random number generator.
2863 * May be called any number of times.
2865 void fr_rand_seed(const void *data, size_t size)
2870 * Ensure that the pool is initialized.
2872 if (!fr_rand_initialized) {
2875 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2877 fd = open("/dev/urandom", O_RDONLY);
2883 while (total < sizeof(fr_rand_pool.randrsl)) {
2884 this = read(fd, fr_rand_pool.randrsl,
2885 sizeof(fr_rand_pool.randrsl) - total);
2886 if ((this < 0) && (errno != EINTR)) break;
2887 if (this > 0) total += this;
2891 fr_rand_pool.randrsl[0] = fd;
2892 fr_rand_pool.randrsl[1] = time(NULL);
2893 fr_rand_pool.randrsl[2] = errno;
2896 fr_randinit(&fr_rand_pool, 1);
2897 fr_rand_pool.randcnt = 0;
2898 fr_rand_initialized = 1;
2904 * Hash the user data
2907 if (!hash) hash = fr_rand();
2908 hash = fr_hash_update(data, size, hash);
2910 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2915 * Return a 32-bit random number.
2917 uint32_t fr_rand(void)
2922 * Ensure that the pool is initialized.
2924 if (!fr_rand_initialized) {
2925 fr_rand_seed(NULL, 0);
2928 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2929 if (fr_rand_pool.randcnt == 256) {
2930 fr_rand_pool.randcnt = 0;
2931 fr_isaac(&fr_rand_pool);
2939 * Allocate a new RADIUS_PACKET
2941 RADIUS_PACKET *rad_alloc(int newvector)
2945 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2946 librad_log("out of memory");
2949 memset(rp, 0, sizeof(*rp));
2955 uint32_t hash, base;
2958 * Don't expose the actual contents of the random
2962 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2963 hash = fr_rand() ^ base;
2964 memcpy(rp->vector + i, &hash, sizeof(hash));
2967 fr_rand(); /* stir the pool again */
2973 * Free a RADIUS_PACKET
2975 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2977 RADIUS_PACKET *radius_packet;
2979 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2980 radius_packet = *radius_packet_ptr;
2982 free(radius_packet->data);
2984 pairfree(&radius_packet->vps);
2986 free(radius_packet);
2988 *radius_packet_ptr = NULL;