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 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
850 * Check if 255 - offset - total_length is less
851 * than 18. If so, we can't fit the data into
852 * the available space, and we discard the
855 * This is ONLY a problem if we have multiple VSA's
856 * in one Vendor-Specific, though.
858 if ((255 - offset - total_length) < 18) return 0;
860 make_tunnel_passwd(ptr + offset, &len,
861 data, len, 255 - offset - total_length,
862 secret, original->vector);
866 * The code above ensures that this attribute
869 case FLAG_ENCRYPT_ASCEND_SECRET:
870 make_secret(ptr + offset, packet->vector,
872 len = AUTH_VECTOR_LEN;
878 * Just copy the data over
880 memcpy(ptr + offset, data, len);
882 } /* switch over encryption flags */
885 * Account for the tag (if any).
890 * RFC 2865 section 5 says that zero-length attributes
893 if (len == 0) return 0;
896 * Update the various lengths.
899 if (vsa_length_ptr) *vsa_length_ptr += len;
903 return total_length; /* of attribute */
910 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
913 radius_packet_t *hdr;
915 uint16_t total_length;
922 * For simplicity in the following logic, we allow
923 * the attributes to "overflow" the 4k maximum
924 * RADIUS packet size, by one attribute.
926 * It's uint32_t, for alignment purposes.
928 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
930 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
931 what = packet_codes[packet->code];
936 DEBUG("Sending %s of id %d to %s port %d\n",
938 inet_ntop(packet->dst_ipaddr.af,
939 &packet->dst_ipaddr.ipaddr,
940 ip_buffer, sizeof(ip_buffer)),
944 * Double-check some things based on packet code.
946 switch (packet->code) {
947 case PW_AUTHENTICATION_ACK:
948 case PW_AUTHENTICATION_REJECT:
949 case PW_ACCESS_CHALLENGE:
951 librad_log("ERROR: Cannot sign response packet without a request packet.");
957 * These packet vectors start off as all zero.
959 case PW_ACCOUNTING_REQUEST:
960 case PW_DISCONNECT_REQUEST:
962 memset(packet->vector, 0, sizeof(packet->vector));
970 * Use memory on the stack, until we know how
971 * large the packet will be.
973 hdr = (radius_packet_t *) data;
976 * Build standard header
978 hdr->code = packet->code;
979 hdr->id = packet->id;
981 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
983 total_length = AUTH_HDR_LEN;
986 * Load up the configuration values for the user
992 * FIXME: Loop twice over the reply list. The first time,
993 * calculate the total length of data. The second time,
994 * allocate the memory, and fill in the VP's.
996 * Hmm... this may be slower than just doing a small
1001 * Loop over the reply attributes for the packet.
1003 for (reply = packet->vps; reply; reply = reply->next) {
1005 * Ignore non-wire attributes
1007 if ((VENDOR(reply->attribute) == 0) &&
1008 ((reply->attribute & 0xFFFF) > 0xff)) {
1013 * Set the Message-Authenticator to the correct
1014 * length and initial value.
1016 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1017 reply->length = AUTH_VECTOR_LEN;
1018 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1021 * Cache the offset to the
1022 * Message-Authenticator
1024 packet->offset = total_length;
1028 * Print out ONLY the attributes which
1029 * we're sending over the wire, and print
1030 * them out BEFORE they're encrypted.
1034 len = rad_vp2attr(packet, original, secret, reply, ptr);
1036 if (len < 0) return -1;
1039 * Check that the packet is no more than 4k in
1040 * size, AFTER writing the attribute past the 4k
1041 * boundary, but BEFORE deciding to increase the
1042 * size of the packet. Note that the 'data'
1043 * buffer, above, is one attribute longer than
1044 * necessary, in order to permit this overflow.
1046 if ((total_length + len) > MAX_PACKET_LEN) {
1051 total_length += len;
1052 } /* done looping over all attributes */
1055 * Fill in the rest of the fields, and copy the data over
1056 * from the local stack to the newly allocated memory.
1058 * Yes, all this 'memcpy' is slow, but it means
1059 * that we only allocate the minimum amount of
1060 * memory for a request.
1062 packet->data_len = total_length;
1063 packet->data = (uint8_t *) malloc(packet->data_len);
1064 if (!packet->data) {
1065 librad_log("Out of memory");
1069 memcpy(packet->data, data, packet->data_len);
1070 hdr = (radius_packet_t *) packet->data;
1072 total_length = htons(total_length);
1073 memcpy(hdr->length, &total_length, sizeof(total_length));
1080 * Sign a previously encoded packet.
1082 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1085 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1088 * It wasn't assigned an Id, this is bad!
1090 if (packet->id < 0) {
1091 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1095 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1096 (packet->offset < 0)) {
1097 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1102 * If there's a Message-Authenticator, update it
1103 * now, BEFORE updating the authentication vector.
1105 if (packet->offset > 0) {
1106 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1108 switch (packet->code) {
1109 case PW_ACCOUNTING_REQUEST:
1110 case PW_ACCOUNTING_RESPONSE:
1111 case PW_DISCONNECT_REQUEST:
1112 case PW_DISCONNECT_ACK:
1113 case PW_DISCONNECT_NAK:
1114 case PW_COA_REQUEST:
1117 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1120 case PW_AUTHENTICATION_ACK:
1121 case PW_AUTHENTICATION_REJECT:
1122 case PW_ACCESS_CHALLENGE:
1124 librad_log("ERROR: Cannot sign response packet without a request packet.");
1127 memcpy(hdr->vector, original->vector,
1131 default: /* others have vector already set to zero */
1137 * Set the authentication vector to zero,
1138 * calculate the signature, and put it
1139 * into the Message-Authenticator
1142 fr_hmac_md5(packet->data, packet->data_len,
1143 (const uint8_t *) secret, strlen(secret),
1145 memcpy(packet->data + packet->offset + 2,
1146 calc_auth_vector, AUTH_VECTOR_LEN);
1149 * Copy the original request vector back
1150 * to the raw packet.
1152 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1156 * Switch over the packet code, deciding how to
1159 switch (packet->code) {
1161 * Request packets are not signed, bur
1162 * have a random authentication vector.
1164 case PW_AUTHENTICATION_REQUEST:
1165 case PW_STATUS_SERVER:
1169 * Reply packets are signed with the
1170 * authentication vector of the request.
1177 fr_MD5Init(&context);
1178 fr_MD5Update(&context, packet->data, packet->data_len);
1179 fr_MD5Update(&context, (const uint8_t *) secret,
1181 fr_MD5Final(digest, &context);
1183 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1184 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1187 }/* switch over packet codes */
1193 * Reply to the request. Also attach
1194 * reply attribute value pairs and any user message provided.
1196 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1201 char ip_buffer[128];
1204 * Maybe it's a fake packet. Don't send it.
1206 if (!packet || (packet->sockfd < 0)) {
1210 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1211 what = packet_codes[packet->code];
1217 * First time through, allocate room for the packet
1219 if (!packet->data) {
1221 * Encode the packet.
1223 if (rad_encode(packet, original, secret) < 0) {
1228 * Re-sign it, including updating the
1229 * Message-Authenticator.
1231 if (rad_sign(packet, original, secret) < 0) {
1236 * If packet->data points to data, then we print out
1237 * the VP list again only for debugging.
1239 } else if (librad_debug) {
1240 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1241 inet_ntop(packet->dst_ipaddr.af,
1242 &packet->dst_ipaddr.ipaddr,
1243 ip_buffer, sizeof(ip_buffer)),
1246 for (reply = packet->vps; reply; reply = reply->next) {
1247 /* FIXME: ignore attributes > 0xff */
1253 * And send it on it's way.
1255 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1256 &packet->src_ipaddr, packet->src_port,
1257 &packet->dst_ipaddr, packet->dst_port);
1262 * Validates the requesting client NAS. Calculates the
1263 * signature based on the clients private key.
1265 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1267 uint8_t digest[AUTH_VECTOR_LEN];
1271 * Zero out the auth_vector in the received packet.
1272 * Then append the shared secret to the received packet,
1273 * and calculate the MD5 sum. This must be the same
1274 * as the original MD5 sum (packet->vector).
1276 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1279 * MD5(packet + secret);
1281 fr_MD5Init(&context);
1282 fr_MD5Update(&context, packet->data, packet->data_len);
1283 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1284 fr_MD5Final(digest, &context);
1287 * Return 0 if OK, 2 if not OK.
1289 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1295 * Validates the requesting client NAS. Calculates the
1296 * signature based on the clients private key.
1298 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1301 uint8_t calc_digest[AUTH_VECTOR_LEN];
1307 if (original == NULL) {
1312 * Copy the original vector in place.
1314 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1317 * MD5(packet + secret);
1319 fr_MD5Init(&context);
1320 fr_MD5Update(&context, packet->data, packet->data_len);
1321 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1322 fr_MD5Final(calc_digest, &context);
1325 * Copy the packet's vector back to the packet.
1327 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1330 * Return 0 if OK, 2 if not OK.
1332 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1338 * See if the data pointed to by PTR is a valid RADIUS packet.
1340 * packet is not 'const * const' because we may update data_len,
1341 * if there's more data in the UDP packet than in the RADIUS packet.
1343 int rad_packet_ok(RADIUS_PACKET *packet)
1348 radius_packet_t *hdr;
1349 char host_ipaddr[128];
1355 * Check for packets smaller than the packet header.
1357 * RFC 2865, Section 3., subsection 'length' says:
1359 * "The minimum length is 20 ..."
1361 if (packet->data_len < AUTH_HDR_LEN) {
1362 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1363 inet_ntop(packet->src_ipaddr.af,
1364 &packet->src_ipaddr.ipaddr,
1365 host_ipaddr, sizeof(host_ipaddr)),
1366 packet->data_len, AUTH_HDR_LEN);
1371 * RFC 2865, Section 3., subsection 'length' says:
1373 * " ... and maximum length is 4096."
1375 if (packet->data_len > MAX_PACKET_LEN) {
1376 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1377 inet_ntop(packet->src_ipaddr.af,
1378 &packet->src_ipaddr.ipaddr,
1379 host_ipaddr, sizeof(host_ipaddr)),
1380 packet->data_len, MAX_PACKET_LEN);
1385 * Check for packets with mismatched size.
1386 * i.e. We've received 128 bytes, and the packet header
1387 * says it's 256 bytes long.
1389 totallen = (packet->data[2] << 8) | packet->data[3];
1390 hdr = (radius_packet_t *)packet->data;
1393 * Code of 0 is not understood.
1394 * Code of 16 or greate is not understood.
1396 if ((hdr->code == 0) ||
1397 (hdr->code >= MAX_PACKET_CODE)) {
1398 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1399 inet_ntop(packet->src_ipaddr.af,
1400 &packet->src_ipaddr.ipaddr,
1401 host_ipaddr, sizeof(host_ipaddr)),
1407 * Message-Authenticator is required in Status-Server
1408 * packets, otherwise they can be trivially forged.
1410 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1413 * Repeat the length checks. This time, instead of
1414 * looking at the data we received, look at the value
1415 * of the 'length' field inside of the packet.
1417 * Check for packets smaller than the packet header.
1419 * RFC 2865, Section 3., subsection 'length' says:
1421 * "The minimum length is 20 ..."
1423 if (totallen < AUTH_HDR_LEN) {
1424 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1425 inet_ntop(packet->src_ipaddr.af,
1426 &packet->src_ipaddr.ipaddr,
1427 host_ipaddr, sizeof(host_ipaddr)),
1428 totallen, AUTH_HDR_LEN);
1433 * And again, for the value of the 'length' field.
1435 * RFC 2865, Section 3., subsection 'length' says:
1437 * " ... and maximum length is 4096."
1439 if (totallen > MAX_PACKET_LEN) {
1440 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1441 inet_ntop(packet->src_ipaddr.af,
1442 &packet->src_ipaddr.ipaddr,
1443 host_ipaddr, sizeof(host_ipaddr)),
1444 totallen, MAX_PACKET_LEN);
1449 * RFC 2865, Section 3., subsection 'length' says:
1451 * "If the packet is shorter than the Length field
1452 * indicates, it MUST be silently discarded."
1454 * i.e. No response to the NAS.
1456 if (packet->data_len < totallen) {
1457 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1458 inet_ntop(packet->src_ipaddr.af,
1459 &packet->src_ipaddr.ipaddr,
1460 host_ipaddr, sizeof(host_ipaddr)),
1461 packet->data_len, totallen);
1466 * RFC 2865, Section 3., subsection 'length' says:
1468 * "Octets outside the range of the Length field MUST be
1469 * treated as padding and ignored on reception."
1471 if (packet->data_len > totallen) {
1473 * We're shortening the packet below, but just
1474 * to be paranoid, zero out the extra data.
1476 memset(packet->data + totallen, 0, packet->data_len - totallen);
1477 packet->data_len = totallen;
1481 * Walk through the packet's attributes, ensuring that
1482 * they add up EXACTLY to the size of the packet.
1484 * If they don't, then the attributes either under-fill
1485 * or over-fill the packet. Any parsing of the packet
1486 * is impossible, and will result in unknown side effects.
1488 * This would ONLY happen with buggy RADIUS implementations,
1489 * or with an intentional attack. Either way, we do NOT want
1490 * to be vulnerable to this problem.
1493 count = totallen - AUTH_HDR_LEN;
1498 * Attribute number zero is NOT defined.
1501 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1502 inet_ntop(packet->src_ipaddr.af,
1503 &packet->src_ipaddr.ipaddr,
1504 host_ipaddr, sizeof(host_ipaddr)));
1509 * Attributes are at LEAST as long as the ID & length
1510 * fields. Anything shorter is an invalid attribute.
1513 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1514 inet_ntop(packet->src_ipaddr.af,
1515 &packet->src_ipaddr.ipaddr,
1516 host_ipaddr, sizeof(host_ipaddr)),
1522 * Sanity check the attributes for length.
1525 default: /* don't do anything by default */
1529 * If there's an EAP-Message, we require
1530 * a Message-Authenticator.
1532 case PW_EAP_MESSAGE:
1536 case PW_MESSAGE_AUTHENTICATOR:
1537 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1538 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1539 inet_ntop(packet->src_ipaddr.af,
1540 &packet->src_ipaddr.ipaddr,
1541 host_ipaddr, sizeof(host_ipaddr)),
1550 * FIXME: Look up the base 255 attributes in the
1551 * dictionary, and switch over their type. For
1552 * integer/date/ip, the attribute length SHOULD
1555 count -= attr[1]; /* grab the attribute length */
1557 num_attributes++; /* seen one more attribute */
1561 * If the attributes add up to a packet, it's allowed.
1563 * If not, we complain, and throw the packet away.
1566 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1567 inet_ntop(packet->src_ipaddr.af,
1568 &packet->src_ipaddr.ipaddr,
1569 host_ipaddr, sizeof(host_ipaddr)));
1574 * If we're configured to look for a maximum number of
1575 * attributes, and we've seen more than that maximum,
1576 * then throw the packet away, as a possible DoS.
1578 if ((librad_max_attributes > 0) &&
1579 (num_attributes > librad_max_attributes)) {
1580 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1581 inet_ntop(packet->src_ipaddr.af,
1582 &packet->src_ipaddr.ipaddr,
1583 host_ipaddr, sizeof(host_ipaddr)),
1584 num_attributes, librad_max_attributes);
1589 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1591 * A packet with an EAP-Message attribute MUST also have
1592 * a Message-Authenticator attribute.
1594 * A Message-Authenticator all by itself is OK, though.
1596 * Similarly, Status-Server packets MUST contain
1597 * Message-Authenticator attributes.
1599 if (require_ma && ! seen_ma) {
1600 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1601 inet_ntop(packet->src_ipaddr.af,
1602 &packet->src_ipaddr.ipaddr,
1603 host_ipaddr, sizeof(host_ipaddr)));
1608 * Fill RADIUS header fields
1610 packet->code = hdr->code;
1611 packet->id = hdr->id;
1612 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1619 * Receive UDP client requests, and fill in
1620 * the basics of a RADIUS_PACKET structure.
1622 RADIUS_PACKET *rad_recv(int fd)
1624 RADIUS_PACKET *packet;
1627 * Allocate the new request data structure
1629 if ((packet = malloc(sizeof(*packet))) == NULL) {
1630 librad_log("out of memory");
1633 memset(packet, 0, sizeof(*packet));
1635 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1636 &packet->src_ipaddr, &packet->src_port,
1637 &packet->dst_ipaddr, &packet->dst_port);
1640 * Check for socket errors.
1642 if (packet->data_len < 0) {
1643 librad_log("Error receiving packet: %s", strerror(errno));
1644 /* packet->data is NULL */
1650 * If the packet is too big, then rad_recvfrom did NOT
1651 * allocate memory. Instead, it just discarded the
1654 if (packet->data_len > MAX_PACKET_LEN) {
1655 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1656 /* packet->data is NULL */
1662 * Read no data. Continue.
1663 * This check is AFTER the MAX_PACKET_LEN check above, because
1664 * if the packet is larger than MAX_PACKET_LEN, we also have
1665 * packet->data == NULL
1667 if ((packet->data_len == 0) || !packet->data) {
1668 librad_log("No data.");
1674 * See if it's a well-formed RADIUS packet.
1676 if (!rad_packet_ok(packet)) {
1682 * Remember which socket we read the packet from.
1684 packet->sockfd = fd;
1687 * FIXME: Do even more filtering by only permitting
1688 * certain IP's. The problem is that we don't know
1689 * how to do this properly for all possible clients...
1693 * Explicitely set the VP list to empty.
1698 char host_ipaddr[128];
1700 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1701 printf("rad_recv: %s packet from host %s port %d",
1702 packet_codes[packet->code],
1703 inet_ntop(packet->src_ipaddr.af,
1704 &packet->src_ipaddr.ipaddr,
1705 host_ipaddr, sizeof(host_ipaddr)),
1708 printf("rad_recv: Packet from host %s port %d code=%d",
1709 inet_ntop(packet->src_ipaddr.af,
1710 &packet->src_ipaddr.ipaddr,
1711 host_ipaddr, sizeof(host_ipaddr)),
1715 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1723 * Verify the signature of a packet.
1725 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1732 if (!packet || !packet->data) return -1;
1735 * Before we allocate memory for the attributes, do more
1738 ptr = packet->data + AUTH_HDR_LEN;
1739 length = packet->data_len - AUTH_HDR_LEN;
1740 while (length > 0) {
1741 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1742 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1747 default: /* don't do anything. */
1751 * Note that more than one Message-Authenticator
1752 * attribute is invalid.
1754 case PW_MESSAGE_AUTHENTICATOR:
1755 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1756 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1758 switch (packet->code) {
1762 case PW_ACCOUNTING_REQUEST:
1763 case PW_ACCOUNTING_RESPONSE:
1764 case PW_DISCONNECT_REQUEST:
1765 case PW_DISCONNECT_ACK:
1766 case PW_DISCONNECT_NAK:
1767 case PW_COA_REQUEST:
1770 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1773 case PW_AUTHENTICATION_ACK:
1774 case PW_AUTHENTICATION_REJECT:
1775 case PW_ACCESS_CHALLENGE:
1777 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1780 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1784 fr_hmac_md5(packet->data, packet->data_len,
1785 (const uint8_t *) secret, strlen(secret),
1787 if (memcmp(calc_auth_vector, msg_auth_vector,
1788 sizeof(calc_auth_vector)) != 0) {
1790 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1791 inet_ntop(packet->src_ipaddr.af,
1792 &packet->src_ipaddr.ipaddr,
1793 buffer, sizeof(buffer)));
1794 /* Silently drop packet, according to RFC 3579 */
1796 } /* else the message authenticator was good */
1799 * Reinitialize Authenticators.
1801 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1802 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1804 } /* switch over the attributes */
1808 } /* loop over the packet, sanity checking the attributes */
1811 * It looks like a RADIUS packet, but we can't validate
1814 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1816 librad_log("Received Unknown packet code %d"
1817 "from client %s port %d: Cannot validate signature",
1819 inet_ntop(packet->src_ipaddr.af,
1820 &packet->src_ipaddr.ipaddr,
1821 buffer, sizeof(buffer)),
1827 * Calculate and/or verify digest.
1829 switch(packet->code) {
1833 case PW_AUTHENTICATION_REQUEST:
1834 case PW_STATUS_SERVER:
1835 case PW_DISCONNECT_REQUEST:
1837 * The authentication vector is random
1838 * nonsense, invented by the client.
1842 case PW_ACCOUNTING_REQUEST:
1843 if (calc_acctdigest(packet, secret) > 1) {
1844 librad_log("Received Accounting-Request packet "
1845 "from %s with invalid signature! (Shared secret is incorrect.)",
1846 inet_ntop(packet->src_ipaddr.af,
1847 &packet->src_ipaddr.ipaddr,
1848 buffer, sizeof(buffer)));
1853 /* Verify the reply digest */
1854 case PW_AUTHENTICATION_ACK:
1855 case PW_AUTHENTICATION_REJECT:
1856 case PW_ACCESS_CHALLENGE:
1857 case PW_ACCOUNTING_RESPONSE:
1858 case PW_DISCONNECT_ACK:
1859 case PW_DISCONNECT_NAK:
1862 rcode = calc_replydigest(packet, original, secret);
1864 librad_log("Received %s packet "
1865 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1866 packet_codes[packet->code],
1867 inet_ntop(packet->src_ipaddr.af,
1868 &packet->src_ipaddr.ipaddr,
1869 buffer, sizeof(buffer)),
1877 librad_log("Received Unknown packet code %d"
1878 "from client %s port %d: Cannot validate signature",
1880 inet_ntop(packet->src_ipaddr.af,
1881 &packet->src_ipaddr.ipaddr,
1882 buffer, sizeof(buffer)),
1892 * Parse a RADIUS attribute into a data structure.
1894 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1895 const char *secret, int attribute, int length,
1896 const uint8_t *data)
1901 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1906 * If length is greater than 253, something is SERIOUSLY
1909 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1911 vp->length = length;
1912 vp->operator = T_OP_EQ;
1918 if (vp->flags.has_tag) {
1919 if (TAG_VALID(data[0]) ||
1920 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1922 * Tunnel passwords REQUIRE a tag, even
1923 * if don't have a valid tag.
1925 vp->flags.tag = data[0];
1927 if ((vp->type == PW_TYPE_STRING) ||
1928 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1933 * Copy the data to be decrypted
1935 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1936 vp->length -= offset;
1939 * Decrypt the attribute.
1941 switch (vp->flags.encrypt) {
1945 case FLAG_ENCRYPT_USER_PASSWORD:
1947 rad_pwdecode((char *)vp->vp_strvalue,
1951 rad_pwdecode((char *)vp->vp_strvalue,
1955 if (vp->attribute == PW_USER_PASSWORD) {
1956 vp->length = strlen(vp->vp_strvalue);
1961 * Tunnel-Password's may go ONLY
1962 * in response packets.
1964 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1965 if (!original) goto raw;
1967 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1968 secret, original->vector) < 0) {
1974 * Ascend-Send-Secret
1975 * Ascend-Receive-Secret
1977 case FLAG_ENCRYPT_ASCEND_SECRET:
1981 uint8_t my_digest[AUTH_VECTOR_LEN];
1982 make_secret(my_digest,
1985 memcpy(vp->vp_strvalue, my_digest,
1987 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1988 vp->length = strlen(vp->vp_strvalue);
1994 } /* switch over encryption flags */
1998 case PW_TYPE_STRING:
1999 case PW_TYPE_OCTETS:
2000 case PW_TYPE_ABINARY:
2001 /* nothing more to do */
2005 if (vp->length != 1) goto raw;
2007 vp->vp_integer = vp->vp_octets[0];
2012 if (vp->length != 2) goto raw;
2014 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2017 case PW_TYPE_INTEGER:
2018 if (vp->length != 4) goto raw;
2020 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2021 vp->vp_integer = ntohl(vp->vp_integer);
2023 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2026 * Try to get named VALUEs
2030 dval = dict_valbyattr(vp->attribute,
2033 strlcpy(vp->vp_strvalue,
2035 sizeof(vp->vp_strvalue));
2041 if (vp->length != 4) goto raw;
2043 memcpy(&vp->vp_date, vp->vp_octets, 4);
2044 vp->vp_date = ntohl(vp->vp_date);
2048 case PW_TYPE_IPADDR:
2049 if (vp->length != 4) goto raw;
2051 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2055 * IPv6 interface ID is 8 octets long.
2058 if (vp->length != 8) goto raw;
2059 /* vp->vp_ifid == vp->vp_octets */
2063 * IPv6 addresses are 16 octets long
2065 case PW_TYPE_IPV6ADDR:
2066 if (vp->length != 16) goto raw;
2067 /* vp->vp_ipv6addr == vp->vp_octets */
2071 * IPv6 prefixes are 2 to 18 octets long.
2073 * RFC 3162: The first octet is unused.
2074 * The second is the length of the prefix
2075 * the rest are the prefix data.
2077 * The prefix length can have value 0 to 128.
2079 case PW_TYPE_IPV6PREFIX:
2080 if (vp->length < 2 || vp->length > 18) goto raw;
2081 if (vp->vp_octets[1] > 128) goto raw;
2084 * FIXME: double-check that
2085 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2087 if (vp->length < 18) {
2088 memset(vp->vp_octets + vp->length, 0,
2095 vp->type = PW_TYPE_OCTETS;
2096 vp->length = length;
2097 memcpy(vp->vp_octets, data, length);
2101 * Ensure there's no encryption or tag stuff,
2102 * we just pass the attribute as-is.
2104 memset(&vp->flags, 0, sizeof(vp->flags));
2112 * Calculate/check digest, and decode radius attributes.
2114 * -1 on decoding error
2117 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2121 uint32_t vendorcode;
2129 radius_packet_t *hdr;
2130 int vsa_tlen, vsa_llen;
2131 DICT_VENDOR *dv = NULL;
2132 int num_attributes = 0;
2135 * Extract attribute-value pairs
2137 hdr = (radius_packet_t *)packet->data;
2139 packet_length = packet->data_len - AUTH_HDR_LEN;
2142 * There may be VP's already in the packet. Don't
2145 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2151 vsa_tlen = vsa_llen = 1;
2154 * We have to read at least two bytes.
2156 * rad_recv() above ensures that this is OK.
2158 while (packet_length > 0) {
2163 * Normal attribute, handle it like normal.
2165 if (vendorcode == 0) {
2167 * No room to read attr/length,
2168 * or bad attribute, or attribute is
2169 * too short, or attribute is too long,
2170 * stop processing the packet.
2172 if ((packet_length < 2) ||
2173 (ptr[0] == 0) || (ptr[1] < 2) ||
2174 (ptr[1] > packet_length)) break;
2182 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2185 * No vendor code, or ONLY vendor code.
2187 if (attrlen <= 4) goto create_pair;
2193 * Handle Vendor-Specific
2195 if (vendorlen == 0) {
2201 * attrlen was checked above.
2203 memcpy(&lvalue, ptr, 4);
2204 myvendor = ntohl(lvalue);
2207 * Zero isn't allowed.
2209 if (myvendor == 0) goto create_pair;
2212 * This is an implementation issue.
2213 * We currently pack vendor into the upper
2214 * 16 bits of a 32-bit attribute number,
2215 * so we can't handle vendor numbers larger
2218 if (myvendor > 65535) goto create_pair;
2220 vsa_tlen = vsa_llen = 1;
2221 dv = dict_vendorbyvalue(myvendor);
2223 vsa_tlen = dv->type;
2224 vsa_llen = dv->length;
2228 * Sweep through the list of VSA's,
2229 * seeing if they exactly fill the
2230 * outer Vendor-Specific attribute.
2232 * If not, create a raw Vendor-Specific.
2235 sublen = attrlen - 4;
2238 * See if we can parse it.
2244 * Don't have a type, it's bad.
2246 if (sublen < vsa_tlen) goto create_pair;
2249 * Ensure that the attribute number
2258 myattr = (subptr[0] << 8) | subptr[1];
2262 if ((subptr[0] != 0) ||
2263 (subptr[1] != 0)) goto create_pair;
2265 myattr = (subptr[2] << 8) | subptr[3];
2269 * Our dictionary is broken.
2276 * Not enough room for one more
2279 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2282 attribute = (myvendor << 16) | myattr;
2283 ptr += 4 + vsa_tlen;
2284 attrlen -= (4 + vsa_tlen);
2285 packet_length -= 4 + vsa_tlen;
2289 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2292 if (subptr[vsa_tlen] > sublen)
2294 sublen -= subptr[vsa_tlen];
2295 subptr += subptr[vsa_tlen];
2299 if (subptr[vsa_tlen] != 0) goto create_pair;
2300 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2302 if (subptr[vsa_tlen + 1] > sublen)
2304 sublen -= subptr[vsa_tlen + 1];
2305 subptr += subptr[vsa_tlen + 1];
2309 * Our dictionaries are
2315 } while (sublen > 0);
2317 vendorcode = myvendor;
2318 vendorlen = attrlen - 4;
2325 * attrlen is the length of this attribute.
2326 * total_len is the length of the encompassing
2335 attribute = (ptr[0] << 8) | ptr[1];
2338 default: /* can't hit this. */
2341 attribute |= (vendorcode << 16);
2346 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2350 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2353 default: /* can't hit this. */
2357 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2358 if (vendorlen == 0) vendorcode = 0;
2359 packet_length -= (vsa_tlen + vsa_llen);
2362 * Create the attribute, setting the default type
2363 * to 'octets'. If the type in the dictionary
2364 * is different, then the dictionary type will
2365 * over-ride this one.
2368 pair = rad_attr2vp(packet, original, secret,
2369 attribute, attrlen, ptr);
2371 pairfree(&packet->vps);
2372 librad_log("out of memory");
2385 * VSA's may not have been counted properly in
2386 * rad_packet_ok() above, as it is hard to count
2387 * then without using the dictionary. We
2388 * therefore enforce the limits here, too.
2390 if ((librad_max_attributes > 0) &&
2391 (num_attributes > librad_max_attributes)) {
2392 char host_ipaddr[128];
2394 pairfree(&packet->vps);
2395 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2396 inet_ntop(packet->src_ipaddr.af,
2397 &packet->src_ipaddr.ipaddr,
2398 host_ipaddr, sizeof(host_ipaddr)),
2399 num_attributes, librad_max_attributes);
2404 packet_length -= attrlen;
2408 * Merge information from the outside world into our
2411 fr_rand_seed(packet->data, AUTH_HDR_LEN);
2420 * We assume that the passwd buffer passed is big enough.
2421 * RFC2138 says the password is max 128 chars, so the size
2422 * of the passwd buffer must be at least 129 characters.
2423 * Preferably it's just MAX_STRING_LEN.
2425 * int *pwlen is updated to the new length of the encrypted
2426 * password - a multiple of 16 bytes.
2428 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2429 const uint8_t *vector)
2431 FR_MD5_CTX context, old;
2432 uint8_t digest[AUTH_VECTOR_LEN];
2433 int i, n, secretlen;
2437 * RFC maximum is 128 bytes.
2439 * If length is zero, pad it out with zeros.
2441 * If the length isn't aligned to 16 bytes,
2442 * zero out the extra data.
2446 if (len > 128) len = 128;
2449 memset(passwd, 0, AUTH_PASS_LEN);
2450 len = AUTH_PASS_LEN;
2451 } else if ((len % AUTH_PASS_LEN) != 0) {
2452 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2453 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2458 * Use the secret to setup the decryption digest
2460 secretlen = strlen(secret);
2462 fr_MD5Init(&context);
2463 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2464 old = context; /* save intermediate work */
2467 * Encrypt it in place. Don't bother checking
2468 * len, as we've ensured above that it's OK.
2470 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2472 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
2473 fr_MD5Final(digest, &context);
2476 fr_MD5Update(&context,
2477 (uint8_t *) passwd + n - AUTH_PASS_LEN,
2479 fr_MD5Final(digest, &context);
2482 for (i = 0; i < AUTH_PASS_LEN; i++) {
2483 passwd[i + n] ^= digest[i];
2493 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2494 const uint8_t *vector)
2496 FR_MD5_CTX context, old;
2497 uint8_t digest[AUTH_VECTOR_LEN];
2498 int i, n, secretlen;
2501 * The RFC's say that the maximum is 128.
2502 * The buffer we're putting it into above is 254, so
2503 * we don't need to do any length checking.
2505 if (pwlen > 128) pwlen = 128;
2510 if (pwlen == 0) goto done;
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 * The inverse of the code above.
2524 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2526 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2527 fr_MD5Final(digest, &context);
2530 if (pwlen > AUTH_PASS_LEN) {
2531 fr_MD5Update(&context, (uint8_t *) passwd,
2535 fr_MD5Final(digest, &context);
2538 if (pwlen > (n + AUTH_PASS_LEN)) {
2539 fr_MD5Update(&context, (uint8_t *) passwd + n,
2544 for (i = 0; i < AUTH_PASS_LEN; i++) {
2545 passwd[i + n] ^= digest[i];
2550 passwd[pwlen] = '\0';
2551 return strlen(passwd);
2556 * Encode Tunnel-Password attributes when sending them out on the wire.
2558 * int *pwlen is updated to the new length of the encrypted
2559 * password - a multiple of 16 bytes.
2561 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2564 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2565 const uint8_t *vector)
2567 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2568 unsigned char digest[AUTH_VECTOR_LEN];
2570 int i, n, secretlen;
2575 if (len > 127) len = 127;
2578 * Shift the password 3 positions right to place a salt and original
2579 * length, tag will be added automatically on packet send
2581 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2585 * save original password length as first password character;
2592 * Generate salt. The RFC's say:
2594 * The high bit of salt[0] must be set, each salt in a
2595 * packet should be unique, and they should be random
2597 * So, we set the high bit, add in a counter, and then
2598 * add in some CSPRNG data. should be OK..
2600 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2601 (fr_rand() & 0x07));
2602 salt[1] = fr_rand();
2605 * Padd password to multiple of AUTH_PASS_LEN bytes.
2607 n = len % AUTH_PASS_LEN;
2609 n = AUTH_PASS_LEN - n;
2610 for (; n > 0; n--, len++)
2613 /* set new password length */
2617 * Use the secret to setup the decryption digest
2619 secretlen = strlen(secret);
2620 memcpy(buffer, secret, secretlen);
2622 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2624 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2625 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2626 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2628 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2629 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2632 for (i = 0; i < AUTH_PASS_LEN; i++) {
2633 passwd[i + n2] ^= digest[i];
2641 * Decode Tunnel-Password encrypted attributes.
2643 * Defined in RFC-2868, this uses a two char SALT along with the
2644 * initial intermediate value, to differentiate it from the
2647 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2648 const uint8_t *vector)
2650 FR_MD5_CTX context, old;
2651 uint8_t digest[AUTH_VECTOR_LEN];
2653 unsigned i, n, len, reallen;
2658 * We need at least a salt.
2661 librad_log("tunnel password is too short");
2666 * There's a salt, but no password. Or, there's a salt
2667 * and a 'data_len' octet. It's wrong, but at least we
2668 * can figure out what it means: the password is empty.
2670 * Note that this means we ignore the 'data_len' field,
2671 * if the attribute length tells us that there's no
2672 * more data. So the 'data_len' field may be wrong,
2681 len -= 2; /* discount the salt */
2684 * Use the secret to setup the decryption digest
2686 secretlen = strlen(secret);
2688 fr_MD5Init(&context);
2689 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
2690 old = context; /* save intermediate work */
2693 * Set up the initial key:
2695 * b(1) = MD5(secret + vector + salt)
2697 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2698 fr_MD5Update(&context, passwd, 2);
2701 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2705 fr_MD5Final(digest, &context);
2710 * A quick check: decrypt the first octet
2711 * of the password, which is the
2712 * 'data_len' field. Ensure it's sane.
2714 reallen = passwd[2] ^ digest[0];
2715 if (reallen >= len) {
2716 librad_log("tunnel password is too long for the attribute");
2720 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2724 fr_MD5Final(digest, &context);
2727 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2730 for (i = base; i < AUTH_PASS_LEN; i++) {
2731 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2736 * See make_tunnel_password, above.
2738 if (reallen > 239) reallen = 239;
2741 passwd[reallen] = 0;
2747 * Encode a CHAP password
2749 * FIXME: might not work with Ascend because
2750 * we use vp->length, and Ascend gear likes
2751 * to send an extra '\0' in the string!
2753 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2754 VALUE_PAIR *password)
2758 uint8_t string[MAX_STRING_LEN * 2 + 1];
2759 VALUE_PAIR *challenge;
2762 * Sanity check the input parameters
2764 if ((packet == NULL) || (password == NULL)) {
2769 * Note that the password VP can be EITHER
2770 * a User-Password attribute (from a check-item list),
2771 * or a CHAP-Password attribute (the client asking
2772 * the library to encode it).
2780 memcpy(ptr, password->vp_strvalue, password->length);
2781 ptr += password->length;
2782 i += password->length;
2785 * Use Chap-Challenge pair if present,
2786 * Request-Authenticator otherwise.
2788 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2790 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2791 i += challenge->length;
2793 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2794 i += AUTH_VECTOR_LEN;
2798 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2805 * Seed the random number generator.
2807 * May be called any number of times.
2809 void fr_rand_seed(const void *data, size_t size)
2814 * Ensure that the pool is initialized.
2816 if (!fr_rand_initialized) {
2819 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
2821 fd = open("/dev/urandom", O_RDONLY);
2827 while (total < sizeof(fr_rand_pool.randrsl)) {
2828 this = read(fd, fr_rand_pool.randrsl,
2829 sizeof(fr_rand_pool.randrsl) - total);
2830 if ((this < 0) && (errno != EINTR)) break;
2831 if (this > 0) total += this;
2835 fr_rand_pool.randrsl[0] = fd;
2836 fr_rand_pool.randrsl[1] = time(NULL);
2837 fr_rand_pool.randrsl[2] = errno;
2840 fr_randinit(&fr_rand_pool, 1);
2841 fr_rand_pool.randcnt = 0;
2842 fr_rand_initialized = 1;
2848 * Hash the user data
2851 if (!hash) hash = fr_rand();
2852 hash = fr_hash_update(data, size, hash);
2854 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
2859 * Return a 32-bit random number.
2861 uint32_t fr_rand(void)
2866 * Ensure that the pool is initialized.
2868 if (!fr_rand_initialized) {
2869 fr_rand_seed(NULL, 0);
2872 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
2873 if (fr_rand_pool.randcnt == 256) {
2874 fr_rand_pool.randcnt = 0;
2875 fr_isaac(&fr_rand_pool);
2883 * Allocate a new RADIUS_PACKET
2885 RADIUS_PACKET *rad_alloc(int newvector)
2889 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2890 librad_log("out of memory");
2893 memset(rp, 0, sizeof(*rp));
2899 uint32_t hash, base;
2902 * Don't expose the actual contents of the random
2906 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2907 hash = fr_rand() ^ base;
2908 memcpy(rp->vector + i, &hash, sizeof(hash));
2911 fr_rand(); /* stir the pool again */
2917 * Free a RADIUS_PACKET
2919 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2921 RADIUS_PACKET *radius_packet;
2923 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2924 radius_packet = *radius_packet_ptr;
2926 free(radius_packet->data);
2928 pairfree(&radius_packet->vps);
2930 free(radius_packet);
2932 *radius_packet_ptr = NULL;