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 lrad_randctx lrad_rand_pool; /* across multiple calls */
67 static int lrad_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 lrad_ipaddr_t *src_ipaddr, lrad_ipaddr_t *dst_ipaddr,
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;
169 * IPv6 MAY be supported.
171 #ifdef HAVE_STRUCT_SOCKADDR_IN6
172 } else if (dst_ipaddr->af == AF_INET6) {
173 struct sockaddr_in6 *s6;
175 s6 = (struct sockaddr_in6 *)&dst;
176 sizeof_dst = sizeof(struct sockaddr_in6);
178 s6->sin6_family = AF_INET6;
179 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
180 s6->sin6_port = htons(dst_port);
182 #ifdef WITH_UDPFROMTO
183 return -1; /* UDPFROMTO && IPv6 are not supported */
185 s6 = (struct sockaddr_in6 *)&src;
186 sizeof_src = sizeof(struct sockaddr_in6);
188 s6->sin6_family = AF_INET6;
189 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
191 #endif /* WITH_UDPFROMTO */
192 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
193 } else return -1; /* Unknown address family, Die Die Die! */
195 #ifdef WITH_UDPFROMTO
197 * Only IPv4 is supported for udpfromto.
199 * And if they don't specify a source IP address, don't
202 if ((dst_ipaddr->af == AF_INET) ||
203 (src_ipaddr->af != AF_UNSPEC)) {
204 return sendfromto(sockfd, data, data_len, flags,
205 (struct sockaddr *)&src, sizeof_src,
206 (struct sockaddr *)&dst, sizeof_dst);
209 src_ipaddr = src_ipaddr; /* -Wunused */
213 * No udpfromto, OR an IPv6 socket, fail gracefully.
215 return sendto(sockfd, data, data_len, flags,
216 (struct sockaddr *)&dst, sizeof_dst);
220 void rad_recv_discard(int sockfd)
223 struct sockaddr_storage src;
224 socklen_t sizeof_src = sizeof(src);
226 recvfrom(sockfd, header, sizeof(header), 0,
227 (struct sockaddr *)&src, &sizeof_src);
231 ssize_t rad_recv_header(int sockfd, lrad_ipaddr_t *src_ipaddr, int *src_port,
234 ssize_t data_len, packet_len;
236 struct sockaddr_storage src;
237 socklen_t sizeof_src = sizeof(src);
239 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
240 (struct sockaddr *)&src, &sizeof_src);
241 if (data_len < 0) return -1;
244 * Too little data is available, discard the packet.
247 recvfrom(sockfd, header, sizeof(header), 0,
248 (struct sockaddr *)&src, &sizeof_src);
251 } else { /* we got 4 bytes of data. */
253 * See how long the packet says it is.
255 packet_len = (header[2] * 256) + header[3];
258 * The length in the packet says it's less than
259 * a RADIUS header length: discard it.
261 if (packet_len < AUTH_HDR_LEN) {
262 recvfrom(sockfd, header, sizeof(header), 0,
263 (struct sockaddr *)&src, &sizeof_src);
267 * Enforce RFC requirements, for sanity.
268 * Anything after 4k will be discarded.
270 } else if (packet_len > MAX_PACKET_LEN) {
271 recvfrom(sockfd, header, sizeof(header), 0,
272 (struct sockaddr *)&src, &sizeof_src);
277 if (src.ss_family == AF_INET) {
278 struct sockaddr_in *s4;
280 s4 = (struct sockaddr_in *)&src;
281 src_ipaddr->af = AF_INET;
282 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
283 *src_port = ntohs(s4->sin_port);
285 #ifdef HAVE_STRUCT_SOCKADDR_IN6
286 } else if (src.ss_family == AF_INET6) {
287 struct sockaddr_in6 *s6;
289 s6 = (struct sockaddr_in6 *)&src;
290 src_ipaddr->af = AF_INET6;
291 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
292 *src_port = ntohs(s6->sin6_port);
296 recvfrom(sockfd, header, sizeof(header), 0,
297 (struct sockaddr *)&src, &sizeof_src);
304 * The packet says it's this long, but the actual UDP
305 * size could still be smaller.
312 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
313 * possible combinations.
315 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
316 lrad_ipaddr_t *src_ipaddr, uint16_t *src_port,
317 lrad_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
319 struct sockaddr_storage src;
320 struct sockaddr_storage dst;
321 socklen_t sizeof_src = sizeof(src);
322 socklen_t sizeof_dst = sizeof(dst);
328 memset(&src, 0, sizeof_src);
329 memset(&dst, 0, sizeof_dst);
332 * Get address family, etc. first, so we know if we
333 * need to do udpfromto.
335 * FIXME: udpfromto also does this, but it's not
336 * a critical problem.
338 if (getsockname(sockfd, (struct sockaddr *)&dst,
339 &sizeof_dst) < 0) return -1;
342 * Read the length of the packet, from the packet.
343 * This lets us allocate the buffer to use for
344 * reading the rest of the packet.
346 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
347 (struct sockaddr *)&src, &sizeof_src);
348 if (data_len < 0) return -1;
351 * Too little data is available, discard the packet.
354 recvfrom(sockfd, header, sizeof(header), flags,
355 (struct sockaddr *)&src, &sizeof_src);
358 } else { /* we got 4 bytes of data. */
360 * See how long the packet says it is.
362 len = (header[2] * 256) + header[3];
365 * The length in the packet says it's less than
366 * a RADIUS header length: discard it.
368 if (len < AUTH_HDR_LEN) {
369 recvfrom(sockfd, header, sizeof(header), flags,
370 (struct sockaddr *)&src, &sizeof_src);
374 * Enforce RFC requirements, for sanity.
375 * Anything after 4k will be discarded.
377 } else if (len > MAX_PACKET_LEN) {
378 recvfrom(sockfd, header, sizeof(header), flags,
379 (struct sockaddr *)&src, &sizeof_src);
388 * Receive the packet. The OS will discard any data in the
389 * packet after "len" bytes.
391 #ifdef WITH_UDPFROMTO
392 if (dst.ss_family == AF_INET) {
393 data_len = recvfromto(sockfd, buf, len, flags,
394 (struct sockaddr *)&src, &sizeof_src,
395 (struct sockaddr *)&dst, &sizeof_dst);
399 * No udpfromto, OR an IPv6 socket. Fail gracefully.
401 data_len = recvfrom(sockfd, buf, len, flags,
402 (struct sockaddr *)&src, &sizeof_src);
409 * Check address families, and update src/dst ports, etc.
411 if (src.ss_family == AF_INET) {
412 struct sockaddr_in *s4;
414 s4 = (struct sockaddr_in *)&src;
415 src_ipaddr->af = AF_INET;
416 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
417 *src_port = ntohs(s4->sin_port);
419 s4 = (struct sockaddr_in *)&dst;
420 dst_ipaddr->af = AF_INET;
421 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
422 *dst_port = ntohs(s4->sin_port);
424 #ifdef HAVE_STRUCT_SOCKADDR_IN6
425 } else if (src.ss_family == AF_INET6) {
426 struct sockaddr_in6 *s6;
428 s6 = (struct sockaddr_in6 *)&src;
429 src_ipaddr->af = AF_INET6;
430 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
431 *src_port = ntohs(s6->sin6_port);
433 s6 = (struct sockaddr_in6 *)&dst;
434 dst_ipaddr->af = AF_INET6;
435 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
436 *dst_port = ntohs(s6->sin6_port);
440 return -1; /* Unknown address family, Die Die Die! */
444 * Different address families should never happen.
446 if (src.ss_family != dst.ss_family) {
452 * Tell the caller about the data
460 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
461 /*************************************************************************
463 * Function: make_secret
465 * Purpose: Build an encrypted secret value to return in a reply
466 * packet. The secret is hidden by xoring with a MD5 digest
467 * created from the shared secret and the authentication
468 * vector. We put them into MD5 in the reverse order from
469 * that used when encrypting passwords to RADIUS.
471 *************************************************************************/
472 static void make_secret(uint8_t *digest, const uint8_t *vector,
473 const char *secret, const uint8_t *value)
475 lrad_MD5_CTX context;
478 lrad_MD5Init(&context);
479 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
480 lrad_MD5Update(&context, secret, strlen(secret));
481 lrad_MD5Final(digest, &context);
483 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
484 digest[i] ^= value[i];
488 #define MAX_PASS_LEN (128)
489 static void make_passwd(uint8_t *output, int *outlen,
490 const uint8_t *input, int inlen,
491 const char *secret, const uint8_t *vector)
493 lrad_MD5_CTX context, old;
494 uint8_t digest[AUTH_VECTOR_LEN];
495 uint8_t passwd[MAX_PASS_LEN];
500 * If the length is zero, round it up.
506 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
508 else if ((len & 0x0f) != 0) {
514 memcpy(passwd, input, len);
515 memset(passwd + len, 0, sizeof(passwd) - len);
517 lrad_MD5Init(&context);
518 lrad_MD5Update(&context, secret, strlen(secret));
524 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
526 for (n = 0; n < len; n += AUTH_PASS_LEN) {
529 lrad_MD5Update(&context,
530 passwd + n - AUTH_PASS_LEN,
534 lrad_MD5Final(digest, &context);
535 for (i = 0; i < AUTH_PASS_LEN; i++) {
536 passwd[i + n] ^= digest[i];
540 memcpy(output, passwd, len);
543 static void make_tunnel_passwd(uint8_t *output, int *outlen,
544 const uint8_t *input, int inlen, int room,
545 const char *secret, const uint8_t *vector)
547 lrad_MD5_CTX context, old;
548 uint8_t digest[AUTH_VECTOR_LEN];
549 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
556 if (room > 253) room = 253;
559 * Account for 2 bytes of the salt, and round the room
560 * available down to the nearest multiple of 16. Then,
561 * subtract one from that to account for the length byte,
562 * and the resulting number is the upper bound on the data
565 * We could short-cut this calculation just be forcing
566 * inlen to be no more than 239. It would work for all
567 * VSA's, as we don't pack multiple VSA's into one
570 * However, this calculation is more general, if a little
571 * complex. And it will work in the future for all possible
572 * kinds of weird attribute packing.
575 room -= (room & 0x0f);
578 if (inlen > room) inlen = room;
581 * Length of the encrypted data is password length plus
582 * one byte for the length of the password.
585 if ((len & 0x0f) != 0) {
589 *outlen = len + 2; /* account for the salt */
592 * Copy the password over.
594 memcpy(passwd + 3, input, inlen);
595 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
598 * Generate salt. The RFC's say:
600 * The high bit of salt[0] must be set, each salt in a
601 * packet should be unique, and they should be random
603 * So, we set the high bit, add in a counter, and then
604 * add in some CSPRNG data. should be OK..
606 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
607 (lrad_rand() & 0x07));
608 passwd[1] = lrad_rand();
609 passwd[2] = inlen; /* length of the password string */
611 lrad_MD5Init(&context);
612 lrad_MD5Update(&context, secret, strlen(secret));
615 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
616 lrad_MD5Update(&context, &passwd[0], 2);
618 for (n = 0; n < len; n += AUTH_PASS_LEN) {
621 lrad_MD5Update(&context,
622 passwd + 2 + n - AUTH_PASS_LEN,
626 lrad_MD5Final(digest, &context);
627 for (i = 0; i < AUTH_PASS_LEN; i++) {
628 passwd[i + 2 + n] ^= digest[i];
631 memcpy(output, passwd, len + 2);
636 * Parse a data structure into a RADIUS attribute.
638 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
639 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
642 int offset, len, total_length;
644 uint8_t *length_ptr, *vsa_length_ptr;
645 const uint8_t *data = NULL;
648 vendorcode = total_length = 0;
649 length_ptr = vsa_length_ptr = NULL;
652 * For interoperability, always put vendor attributes
653 * into their own VSA.
655 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
656 *(ptr++) = vp->attribute & 0xFF;
664 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
667 * This must be an RFC-format attribute. If it
668 * wasn't, then the "decode" function would have
669 * made a Vendor-Specific attribute (i.e. type
670 * 26), and we would have "vendorcode == 0" here.
674 vsa_llen = dv->length;
678 * Build a VSA header.
680 *ptr++ = PW_VENDOR_SPECIFIC;
681 vsa_length_ptr = ptr;
683 lvalue = htonl(vendorcode);
684 memcpy(ptr, &lvalue, 4);
690 ptr[0] = (vp->attribute & 0xFF);
694 ptr[0] = ((vp->attribute >> 8) & 0xFF);
695 ptr[1] = (vp->attribute & 0xFF);
701 ptr[2] = ((vp->attribute >> 8) & 0xFF);
702 ptr[3] = (vp->attribute & 0xFF);
706 return 0; /* silently discard it */
712 length_ptr = vsa_length_ptr;
713 vsa_length_ptr = NULL;
722 length_ptr = ptr + 1;
726 return 0; /* silently discard it */
730 total_length += vsa_tlen + vsa_llen;
731 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
732 *length_ptr += vsa_tlen + vsa_llen;
736 if (vp->flags.has_tag) {
737 if (TAG_VALID(vp->flags.tag)) {
738 ptr[0] = vp->flags.tag & 0xff;
741 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
743 * Tunnel passwords REQUIRE a tag, even
744 * if don't have a valid tag.
748 } /* else don't write a tag */
749 } /* else the attribute doesn't have a tag */
752 * Set up the default sources for the data.
754 data = vp->vp_octets;
761 case PW_TYPE_IPV6ADDR:
762 case PW_TYPE_IPV6PREFIX:
763 case PW_TYPE_ABINARY:
764 /* nothing more to do */
768 len = 1; /* just in case */
769 array[0] = vp->vp_integer & 0xff;
776 len = 2; /* just in case */
777 array[0] = (vp->vp_integer >> 8) & 0xff;
778 array[1] = vp->vp_integer & 0xff;
783 case PW_TYPE_INTEGER:
784 len = 4; /* just in case */
785 lvalue = htonl(vp->vp_integer);
786 memcpy(array, &lvalue, sizeof(lvalue));
789 * Perhaps discard the first octet.
791 data = &array[offset];
796 data = (const uint8_t *) &vp->vp_ipaddr;
797 len = 4; /* just in case */
801 * There are no tagged date attributes.
804 lvalue = htonl(vp->vp_date);
805 data = (const uint8_t *) &lvalue;
806 len = 4; /* just in case */
809 default: /* unknown type: ignore it */
810 librad_log("ERROR: Unknown attribute type %d", vp->type);
815 * Bound the data to 255 bytes.
817 if (len + offset + total_length > 255) {
818 len = 255 - offset - total_length;
822 * Encrypt the various password styles
824 * Attributes with encrypted values MUST be less than
827 switch (vp->flags.encrypt) {
828 case FLAG_ENCRYPT_USER_PASSWORD:
829 make_passwd(ptr + offset, &len,
831 secret, packet->vector);
834 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
836 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
841 * Check if 255 - offset - total_length is less
842 * than 18. If so, we can't fit the data into
843 * the available space, and we discard the
846 * This is ONLY a problem if we have multiple VSA's
847 * in one Vendor-Specific, though.
849 if ((255 - offset - total_length) < 18) return 0;
851 make_tunnel_passwd(ptr + offset, &len,
852 data, len, 255 - offset - total_length,
853 secret, original->vector);
857 * The code above ensures that this attribute
860 case FLAG_ENCRYPT_ASCEND_SECRET:
861 make_secret(ptr + offset, packet->vector,
863 len = AUTH_VECTOR_LEN;
869 * Just copy the data over
871 memcpy(ptr + offset, data, len);
873 } /* switch over encryption flags */
876 * Account for the tag (if any).
881 * RFC 2865 section 5 says that zero-length attributes
884 if (len == 0) return 0;
887 * Update the various lengths.
890 if (vsa_length_ptr) *vsa_length_ptr += len;
894 return total_length; /* of attribute */
901 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
904 radius_packet_t *hdr;
906 uint16_t total_length;
913 * For simplicity in the following logic, we allow
914 * the attributes to "overflow" the 4k maximum
915 * RADIUS packet size, by one attribute.
917 * It's uint32_t, for alignment purposes.
919 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
921 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
922 what = packet_codes[packet->code];
927 DEBUG("Sending %s of id %d to %s port %d\n",
929 inet_ntop(packet->dst_ipaddr.af,
930 &packet->dst_ipaddr.ipaddr,
931 ip_buffer, sizeof(ip_buffer)),
935 * Double-check some things based on packet code.
937 switch (packet->code) {
938 case PW_AUTHENTICATION_ACK:
939 case PW_AUTHENTICATION_REJECT:
940 case PW_ACCESS_CHALLENGE:
942 librad_log("ERROR: Cannot sign response packet without a request packet.");
948 * These packet vectors start off as all zero.
950 case PW_ACCOUNTING_REQUEST:
951 case PW_DISCONNECT_REQUEST:
953 memset(packet->vector, 0, sizeof(packet->vector));
961 * Use memory on the stack, until we know how
962 * large the packet will be.
964 hdr = (radius_packet_t *) data;
967 * Build standard header
969 hdr->code = packet->code;
970 hdr->id = packet->id;
972 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
974 total_length = AUTH_HDR_LEN;
977 * Load up the configuration values for the user
983 * FIXME: Loop twice over the reply list. The first time,
984 * calculate the total length of data. The second time,
985 * allocate the memory, and fill in the VP's.
987 * Hmm... this may be slower than just doing a small
992 * Loop over the reply attributes for the packet.
994 for (reply = packet->vps; reply; reply = reply->next) {
996 * Ignore non-wire attributes
998 if ((VENDOR(reply->attribute) == 0) &&
999 ((reply->attribute & 0xFFFF) > 0xff)) {
1004 * Set the Message-Authenticator to the correct
1005 * length and initial value.
1007 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1008 reply->length = AUTH_VECTOR_LEN;
1009 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1012 * Cache the offset to the
1013 * Message-Authenticator
1015 packet->offset = total_length;
1019 * Print out ONLY the attributes which
1020 * we're sending over the wire, and print
1021 * them out BEFORE they're encrypted.
1025 len = rad_vp2attr(packet, original, secret, reply, ptr);
1027 if (len < 0) return -1;
1030 * Check that the packet is no more than 4k in
1031 * size, AFTER writing the attribute past the 4k
1032 * boundary, but BEFORE deciding to increase the
1033 * size of the packet. Note that the 'data'
1034 * buffer, above, is one attribute longer than
1035 * necessary, in order to permit this overflow.
1037 if ((total_length + len) > MAX_PACKET_LEN) {
1042 total_length += len;
1043 } /* done looping over all attributes */
1046 * Fill in the rest of the fields, and copy the data over
1047 * from the local stack to the newly allocated memory.
1049 * Yes, all this 'memcpy' is slow, but it means
1050 * that we only allocate the minimum amount of
1051 * memory for a request.
1053 packet->data_len = total_length;
1054 packet->data = (uint8_t *) malloc(packet->data_len);
1055 if (!packet->data) {
1056 librad_log("Out of memory");
1060 memcpy(packet->data, data, packet->data_len);
1061 hdr = (radius_packet_t *) packet->data;
1063 total_length = htons(total_length);
1064 memcpy(hdr->length, &total_length, sizeof(total_length));
1071 * Sign a previously encoded packet.
1073 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1076 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1079 * It wasn't assigned an Id, this is bad!
1081 if (packet->id < 0) {
1082 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1086 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1087 (packet->offset < 0)) {
1088 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1093 * If there's a Message-Authenticator, update it
1094 * now, BEFORE updating the authentication vector.
1096 if (packet->offset > 0) {
1097 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1099 switch (packet->code) {
1100 case PW_ACCOUNTING_REQUEST:
1101 case PW_ACCOUNTING_RESPONSE:
1102 case PW_DISCONNECT_REQUEST:
1103 case PW_DISCONNECT_ACK:
1104 case PW_DISCONNECT_NAK:
1105 case PW_COA_REQUEST:
1108 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1111 case PW_AUTHENTICATION_ACK:
1112 case PW_AUTHENTICATION_REJECT:
1113 case PW_ACCESS_CHALLENGE:
1115 librad_log("ERROR: Cannot sign response packet without a request packet.");
1118 memcpy(hdr->vector, original->vector,
1122 default: /* others have vector already set to zero */
1128 * Set the authentication vector to zero,
1129 * calculate the signature, and put it
1130 * into the Message-Authenticator
1133 lrad_hmac_md5(packet->data, packet->data_len,
1134 secret, strlen(secret),
1136 memcpy(packet->data + packet->offset + 2,
1137 calc_auth_vector, AUTH_VECTOR_LEN);
1140 * Copy the original request vector back
1141 * to the raw packet.
1143 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1147 * Switch over the packet code, deciding how to
1150 switch (packet->code) {
1152 * Request packets are not signed, bur
1153 * have a random authentication vector.
1155 case PW_AUTHENTICATION_REQUEST:
1156 case PW_STATUS_SERVER:
1160 * Reply packets are signed with the
1161 * authentication vector of the request.
1169 MD5Update(&context, packet->data, packet->data_len);
1170 MD5Update(&context, secret, strlen(secret));
1171 MD5Final(digest, &context);
1173 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1174 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1177 }/* switch over packet codes */
1183 * Reply to the request. Also attach
1184 * reply attribute value pairs and any user message provided.
1186 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1191 char ip_buffer[128];
1194 * Maybe it's a fake packet. Don't send it.
1196 if (!packet || (packet->sockfd < 0)) {
1200 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1201 what = packet_codes[packet->code];
1207 * First time through, allocate room for the packet
1209 if (!packet->data) {
1211 * Encode the packet.
1213 if (rad_encode(packet, original, secret) < 0) {
1218 * Re-sign it, including updating the
1219 * Message-Authenticator.
1221 if (rad_sign(packet, original, secret) < 0) {
1226 * If packet->data points to data, then we print out
1227 * the VP list again only for debugging.
1229 } else if (librad_debug) {
1230 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1231 inet_ntop(packet->dst_ipaddr.af,
1232 &packet->dst_ipaddr.ipaddr,
1233 ip_buffer, sizeof(ip_buffer)),
1236 for (reply = packet->vps; reply; reply = reply->next) {
1237 /* FIXME: ignore attributes > 0xff */
1243 * And send it on it's way.
1245 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1246 &packet->src_ipaddr, &packet->dst_ipaddr,
1252 * Validates the requesting client NAS. Calculates the
1253 * signature based on the clients private key.
1255 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1257 uint8_t digest[AUTH_VECTOR_LEN];
1261 * Zero out the auth_vector in the received packet.
1262 * Then append the shared secret to the received packet,
1263 * and calculate the MD5 sum. This must be the same
1264 * as the original MD5 sum (packet->vector).
1266 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1269 * MD5(packet + secret);
1272 MD5Update(&context, packet->data, packet->data_len);
1273 MD5Update(&context, secret, strlen(secret));
1274 MD5Final(digest, &context);
1277 * Return 0 if OK, 2 if not OK.
1279 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1285 * Validates the requesting client NAS. Calculates the
1286 * signature based on the clients private key.
1288 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1291 uint8_t calc_digest[AUTH_VECTOR_LEN];
1297 if (original == NULL) {
1302 * Copy the original vector in place.
1304 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1307 * MD5(packet + secret);
1310 MD5Update(&context, packet->data, packet->data_len);
1311 MD5Update(&context, secret, strlen(secret));
1312 MD5Final(calc_digest, &context);
1315 * Copy the packet's vector back to the packet.
1317 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1320 * Return 0 if OK, 2 if not OK.
1322 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1328 * See if the data pointed to by PTR is a valid RADIUS packet.
1330 * packet is not 'const * const' because we may update data_len,
1331 * if there's more data in the UDP packet than in the RADIUS packet.
1333 int rad_packet_ok(RADIUS_PACKET *packet)
1338 radius_packet_t *hdr;
1339 char host_ipaddr[128];
1345 * Check for packets smaller than the packet header.
1347 * RFC 2865, Section 3., subsection 'length' says:
1349 * "The minimum length is 20 ..."
1351 if (packet->data_len < AUTH_HDR_LEN) {
1352 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1353 inet_ntop(packet->src_ipaddr.af,
1354 &packet->src_ipaddr.ipaddr,
1355 host_ipaddr, sizeof(host_ipaddr)),
1356 packet->data_len, AUTH_HDR_LEN);
1361 * RFC 2865, Section 3., subsection 'length' says:
1363 * " ... and maximum length is 4096."
1365 if (packet->data_len > MAX_PACKET_LEN) {
1366 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1367 inet_ntop(packet->src_ipaddr.af,
1368 &packet->src_ipaddr.ipaddr,
1369 host_ipaddr, sizeof(host_ipaddr)),
1370 packet->data_len, MAX_PACKET_LEN);
1375 * Check for packets with mismatched size.
1376 * i.e. We've received 128 bytes, and the packet header
1377 * says it's 256 bytes long.
1379 totallen = (packet->data[2] << 8) | packet->data[3];
1380 hdr = (radius_packet_t *)packet->data;
1383 * Code of 0 is not understood.
1384 * Code of 16 or greate is not understood.
1386 if ((hdr->code == 0) ||
1387 (hdr->code >= MAX_PACKET_CODE)) {
1388 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1389 inet_ntop(packet->src_ipaddr.af,
1390 &packet->src_ipaddr.ipaddr,
1391 host_ipaddr, sizeof(host_ipaddr)),
1397 * Message-Authenticator is required in Status-Server
1398 * packets, otherwise they can be trivially forged.
1400 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1403 * Repeat the length checks. This time, instead of
1404 * looking at the data we received, look at the value
1405 * of the 'length' field inside of the packet.
1407 * Check for packets smaller than the packet header.
1409 * RFC 2865, Section 3., subsection 'length' says:
1411 * "The minimum length is 20 ..."
1413 if (totallen < AUTH_HDR_LEN) {
1414 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1415 inet_ntop(packet->src_ipaddr.af,
1416 &packet->src_ipaddr.ipaddr,
1417 host_ipaddr, sizeof(host_ipaddr)),
1418 totallen, AUTH_HDR_LEN);
1423 * And again, for the value of the 'length' field.
1425 * RFC 2865, Section 3., subsection 'length' says:
1427 * " ... and maximum length is 4096."
1429 if (totallen > MAX_PACKET_LEN) {
1430 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1431 inet_ntop(packet->src_ipaddr.af,
1432 &packet->src_ipaddr.ipaddr,
1433 host_ipaddr, sizeof(host_ipaddr)),
1434 totallen, MAX_PACKET_LEN);
1439 * RFC 2865, Section 3., subsection 'length' says:
1441 * "If the packet is shorter than the Length field
1442 * indicates, it MUST be silently discarded."
1444 * i.e. No response to the NAS.
1446 if (packet->data_len < totallen) {
1447 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1448 inet_ntop(packet->src_ipaddr.af,
1449 &packet->src_ipaddr.ipaddr,
1450 host_ipaddr, sizeof(host_ipaddr)),
1451 packet->data_len, totallen);
1456 * RFC 2865, Section 3., subsection 'length' says:
1458 * "Octets outside the range of the Length field MUST be
1459 * treated as padding and ignored on reception."
1461 if (packet->data_len > totallen) {
1463 * We're shortening the packet below, but just
1464 * to be paranoid, zero out the extra data.
1466 memset(packet->data + totallen, 0, packet->data_len - totallen);
1467 packet->data_len = totallen;
1471 * Walk through the packet's attributes, ensuring that
1472 * they add up EXACTLY to the size of the packet.
1474 * If they don't, then the attributes either under-fill
1475 * or over-fill the packet. Any parsing of the packet
1476 * is impossible, and will result in unknown side effects.
1478 * This would ONLY happen with buggy RADIUS implementations,
1479 * or with an intentional attack. Either way, we do NOT want
1480 * to be vulnerable to this problem.
1483 count = totallen - AUTH_HDR_LEN;
1488 * Attribute number zero is NOT defined.
1491 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1492 inet_ntop(packet->src_ipaddr.af,
1493 &packet->src_ipaddr.ipaddr,
1494 host_ipaddr, sizeof(host_ipaddr)));
1499 * Attributes are at LEAST as long as the ID & length
1500 * fields. Anything shorter is an invalid attribute.
1503 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1504 inet_ntop(packet->src_ipaddr.af,
1505 &packet->src_ipaddr.ipaddr,
1506 host_ipaddr, sizeof(host_ipaddr)),
1512 * Sanity check the attributes for length.
1515 default: /* don't do anything by default */
1519 * If there's an EAP-Message, we require
1520 * a Message-Authenticator.
1522 case PW_EAP_MESSAGE:
1526 case PW_MESSAGE_AUTHENTICATOR:
1527 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1528 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1529 inet_ntop(packet->src_ipaddr.af,
1530 &packet->src_ipaddr.ipaddr,
1531 host_ipaddr, sizeof(host_ipaddr)),
1540 * FIXME: Look up the base 255 attributes in the
1541 * dictionary, and switch over their type. For
1542 * integer/date/ip, the attribute length SHOULD
1545 count -= attr[1]; /* grab the attribute length */
1547 num_attributes++; /* seen one more attribute */
1551 * If the attributes add up to a packet, it's allowed.
1553 * If not, we complain, and throw the packet away.
1556 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1557 inet_ntop(packet->src_ipaddr.af,
1558 &packet->src_ipaddr.ipaddr,
1559 host_ipaddr, sizeof(host_ipaddr)));
1564 * If we're configured to look for a maximum number of
1565 * attributes, and we've seen more than that maximum,
1566 * then throw the packet away, as a possible DoS.
1568 if ((librad_max_attributes > 0) &&
1569 (num_attributes > librad_max_attributes)) {
1570 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1571 inet_ntop(packet->src_ipaddr.af,
1572 &packet->src_ipaddr.ipaddr,
1573 host_ipaddr, sizeof(host_ipaddr)),
1574 num_attributes, librad_max_attributes);
1579 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1581 * A packet with an EAP-Message attribute MUST also have
1582 * a Message-Authenticator attribute.
1584 * A Message-Authenticator all by itself is OK, though.
1586 * Similarly, Status-Server packets MUST contain
1587 * Message-Authenticator attributes.
1589 if (require_ma && ! seen_ma) {
1590 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1591 inet_ntop(packet->src_ipaddr.af,
1592 &packet->src_ipaddr.ipaddr,
1593 host_ipaddr, sizeof(host_ipaddr)));
1598 * Fill RADIUS header fields
1600 packet->code = hdr->code;
1601 packet->id = hdr->id;
1602 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1609 * Receive UDP client requests, and fill in
1610 * the basics of a RADIUS_PACKET structure.
1612 RADIUS_PACKET *rad_recv(int fd)
1614 RADIUS_PACKET *packet;
1617 * Allocate the new request data structure
1619 if ((packet = malloc(sizeof(*packet))) == NULL) {
1620 librad_log("out of memory");
1623 memset(packet, 0, sizeof(*packet));
1625 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1626 &packet->src_ipaddr, &packet->src_port,
1627 &packet->dst_ipaddr, &packet->dst_port);
1630 * Check for socket errors.
1632 if (packet->data_len < 0) {
1633 librad_log("Error receiving packet: %s", strerror(errno));
1634 /* packet->data is NULL */
1640 * If the packet is too big, then rad_recvfrom did NOT
1641 * allocate memory. Instead, it just discarded the
1644 if (packet->data_len > MAX_PACKET_LEN) {
1645 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1646 /* packet->data is NULL */
1652 * Read no data. Continue.
1653 * This check is AFTER the MAX_PACKET_LEN check above, because
1654 * if the packet is larger than MAX_PACKET_LEN, we also have
1655 * packet->data == NULL
1657 if ((packet->data_len == 0) || !packet->data) {
1658 librad_log("No data.");
1664 * See if it's a well-formed RADIUS packet.
1666 if (!rad_packet_ok(packet)) {
1672 * Remember which socket we read the packet from.
1674 packet->sockfd = fd;
1677 * FIXME: Do even more filtering by only permitting
1678 * certain IP's. The problem is that we don't know
1679 * how to do this properly for all possible clients...
1683 * Explicitely set the VP list to empty.
1688 char host_ipaddr[128];
1690 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1691 printf("rad_recv: %s packet from host %s port %d",
1692 packet_codes[packet->code],
1693 inet_ntop(packet->src_ipaddr.af,
1694 &packet->src_ipaddr.ipaddr,
1695 host_ipaddr, sizeof(host_ipaddr)),
1698 printf("rad_recv: Packet from host %s port %d code=%d",
1699 inet_ntop(packet->src_ipaddr.af,
1700 &packet->src_ipaddr.ipaddr,
1701 host_ipaddr, sizeof(host_ipaddr)),
1705 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1713 * Verify the signature of a packet.
1715 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1722 if (!packet || !packet->data) return -1;
1725 * Before we allocate memory for the attributes, do more
1728 ptr = packet->data + AUTH_HDR_LEN;
1729 length = packet->data_len - AUTH_HDR_LEN;
1730 while (length > 0) {
1731 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1732 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1737 default: /* don't do anything. */
1741 * Note that more than one Message-Authenticator
1742 * attribute is invalid.
1744 case PW_MESSAGE_AUTHENTICATOR:
1745 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1746 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1748 switch (packet->code) {
1752 case PW_ACCOUNTING_REQUEST:
1753 case PW_ACCOUNTING_RESPONSE:
1754 case PW_DISCONNECT_REQUEST:
1755 case PW_DISCONNECT_ACK:
1756 case PW_DISCONNECT_NAK:
1757 case PW_COA_REQUEST:
1760 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1763 case PW_AUTHENTICATION_ACK:
1764 case PW_AUTHENTICATION_REJECT:
1765 case PW_ACCESS_CHALLENGE:
1767 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1770 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1774 lrad_hmac_md5(packet->data, packet->data_len,
1775 secret, strlen(secret), calc_auth_vector);
1776 if (memcmp(calc_auth_vector, msg_auth_vector,
1777 sizeof(calc_auth_vector)) != 0) {
1779 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1780 inet_ntop(packet->src_ipaddr.af,
1781 &packet->src_ipaddr.ipaddr,
1782 buffer, sizeof(buffer)));
1783 /* Silently drop packet, according to RFC 3579 */
1785 } /* else the message authenticator was good */
1788 * Reinitialize Authenticators.
1790 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1791 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1793 } /* switch over the attributes */
1797 } /* loop over the packet, sanity checking the attributes */
1800 * It looks like a RADIUS packet, but we can't validate
1803 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1805 librad_log("Received Unknown packet code %d"
1806 "from client %s port %d: Cannot validate signature",
1808 inet_ntop(packet->src_ipaddr.af,
1809 &packet->src_ipaddr.ipaddr,
1810 buffer, sizeof(buffer)),
1816 * Calculate and/or verify digest.
1818 switch(packet->code) {
1822 case PW_AUTHENTICATION_REQUEST:
1823 case PW_STATUS_SERVER:
1824 case PW_DISCONNECT_REQUEST:
1826 * The authentication vector is random
1827 * nonsense, invented by the client.
1831 case PW_ACCOUNTING_REQUEST:
1832 if (calc_acctdigest(packet, secret) > 1) {
1833 librad_log("Received Accounting-Request packet "
1834 "from %s with invalid signature! (Shared secret is incorrect.)",
1835 inet_ntop(packet->src_ipaddr.af,
1836 &packet->src_ipaddr.ipaddr,
1837 buffer, sizeof(buffer)));
1842 /* Verify the reply digest */
1843 case PW_AUTHENTICATION_ACK:
1844 case PW_AUTHENTICATION_REJECT:
1845 case PW_ACCESS_CHALLENGE:
1846 case PW_ACCOUNTING_RESPONSE:
1847 case PW_DISCONNECT_ACK:
1848 case PW_DISCONNECT_NAK:
1851 rcode = calc_replydigest(packet, original, secret);
1853 librad_log("Received %s packet "
1854 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1855 packet_codes[packet->code],
1856 inet_ntop(packet->src_ipaddr.af,
1857 &packet->src_ipaddr.ipaddr,
1858 buffer, sizeof(buffer)),
1866 librad_log("Received Unknown packet code %d"
1867 "from client %s port %d: Cannot validate signature",
1869 inet_ntop(packet->src_ipaddr.af,
1870 &packet->src_ipaddr.ipaddr,
1871 buffer, sizeof(buffer)),
1881 * Parse a RADIUS attribute into a data structure.
1883 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1884 const char *secret, int attribute, int length,
1885 const uint8_t *data)
1890 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1895 * If length is greater than 253, something is SERIOUSLY
1898 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1900 vp->length = length;
1901 vp->operator = T_OP_EQ;
1907 if (vp->flags.has_tag) {
1908 if (TAG_VALID(data[0]) ||
1909 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1911 * Tunnel passwords REQUIRE a tag, even
1912 * if don't have a valid tag.
1914 vp->flags.tag = data[0];
1916 if ((vp->type == PW_TYPE_STRING) ||
1917 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1922 * Copy the data to be decrypted
1924 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1925 vp->length -= offset;
1928 * Decrypt the attribute.
1930 switch (vp->flags.encrypt) {
1934 case FLAG_ENCRYPT_USER_PASSWORD:
1936 rad_pwdecode((char *)vp->vp_strvalue,
1940 rad_pwdecode((char *)vp->vp_strvalue,
1944 if (vp->attribute == PW_USER_PASSWORD) {
1945 vp->length = strlen(vp->vp_strvalue);
1950 * Tunnel-Password's may go ONLY
1951 * in response packets.
1953 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1954 if (!original) goto raw;
1956 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1957 secret, original->vector) < 0) {
1963 * Ascend-Send-Secret
1964 * Ascend-Receive-Secret
1966 case FLAG_ENCRYPT_ASCEND_SECRET:
1970 uint8_t my_digest[AUTH_VECTOR_LEN];
1971 make_secret(my_digest,
1974 memcpy(vp->vp_strvalue, my_digest,
1976 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1977 vp->length = strlen(vp->vp_strvalue);
1983 } /* switch over encryption flags */
1987 case PW_TYPE_STRING:
1988 case PW_TYPE_OCTETS:
1989 case PW_TYPE_ABINARY:
1990 /* nothing more to do */
1994 if (vp->length != 1) goto raw;
1996 vp->vp_integer = vp->vp_octets[0];
2001 if (vp->length != 2) goto raw;
2003 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2006 case PW_TYPE_INTEGER:
2007 if (vp->length != 4) goto raw;
2009 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2010 vp->vp_integer = ntohl(vp->vp_integer);
2012 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2015 * Try to get named VALUEs
2019 dval = dict_valbyattr(vp->attribute,
2022 strlcpy(vp->vp_strvalue,
2024 sizeof(vp->vp_strvalue));
2030 if (vp->length != 4) goto raw;
2032 memcpy(&vp->vp_date, vp->vp_octets, 4);
2033 vp->vp_date = ntohl(vp->vp_date);
2037 case PW_TYPE_IPADDR:
2038 if (vp->length != 4) goto raw;
2040 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2044 * IPv6 interface ID is 8 octets long.
2047 if (vp->length != 8) goto raw;
2048 /* vp->vp_ifid == vp->vp_octets */
2052 * IPv6 addresses are 16 octets long
2054 case PW_TYPE_IPV6ADDR:
2055 if (vp->length != 16) goto raw;
2056 /* vp->vp_ipv6addr == vp->vp_octets */
2060 * IPv6 prefixes are 2 to 18 octets long.
2062 * RFC 3162: The first octet is unused.
2063 * The second is the length of the prefix
2064 * the rest are the prefix data.
2066 * The prefix length can have value 0 to 128.
2068 case PW_TYPE_IPV6PREFIX:
2069 if (vp->length < 2 || vp->length > 18) goto raw;
2070 if (vp->vp_octets[1] > 128) goto raw;
2073 * FIXME: double-check that
2074 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2076 if (vp->length < 18) {
2077 memset(vp->vp_octets + vp->length, 0,
2084 vp->type = PW_TYPE_OCTETS;
2085 vp->length = length;
2086 memcpy(vp->vp_octets, data, length);
2090 * Ensure there's no encryption or tag stuff,
2091 * we just pass the attribute as-is.
2093 memset(&vp->flags, 0, sizeof(vp->flags));
2101 * Calculate/check digest, and decode radius attributes.
2103 * -1 on decoding error
2106 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2110 uint32_t vendorcode;
2118 radius_packet_t *hdr;
2119 int vsa_tlen, vsa_llen;
2120 DICT_VENDOR *dv = NULL;
2121 int num_attributes = 0;
2124 * Extract attribute-value pairs
2126 hdr = (radius_packet_t *)packet->data;
2128 packet_length = packet->data_len - AUTH_HDR_LEN;
2131 * There may be VP's already in the packet. Don't
2134 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2140 vsa_tlen = vsa_llen = 1;
2143 * We have to read at least two bytes.
2145 * rad_recv() above ensures that this is OK.
2147 while (packet_length > 0) {
2152 * Normal attribute, handle it like normal.
2154 if (vendorcode == 0) {
2156 * No room to read attr/length,
2157 * or bad attribute, or attribute is
2158 * too short, or attribute is too long,
2159 * stop processing the packet.
2161 if ((packet_length < 2) ||
2162 (ptr[0] == 0) || (ptr[1] < 2) ||
2163 (ptr[1] > packet_length)) break;
2171 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2174 * No vendor code, or ONLY vendor code.
2176 if (attrlen <= 4) goto create_pair;
2182 * Handle Vendor-Specific
2184 if (vendorlen == 0) {
2190 * attrlen was checked above.
2192 memcpy(&lvalue, ptr, 4);
2193 myvendor = ntohl(lvalue);
2196 * Zero isn't allowed.
2198 if (myvendor == 0) goto create_pair;
2201 * This is an implementation issue.
2202 * We currently pack vendor into the upper
2203 * 16 bits of a 32-bit attribute number,
2204 * so we can't handle vendor numbers larger
2207 if (myvendor > 65535) goto create_pair;
2209 vsa_tlen = vsa_llen = 1;
2210 dv = dict_vendorbyvalue(myvendor);
2212 vsa_tlen = dv->type;
2213 vsa_llen = dv->length;
2217 * Sweep through the list of VSA's,
2218 * seeing if they exactly fill the
2219 * outer Vendor-Specific attribute.
2221 * If not, create a raw Vendor-Specific.
2224 sublen = attrlen - 4;
2227 * See if we can parse it.
2233 * Don't have a type, it's bad.
2235 if (sublen < vsa_tlen) goto create_pair;
2238 * Ensure that the attribute number
2247 myattr = (subptr[0] << 8) | subptr[1];
2251 if ((subptr[0] != 0) ||
2252 (subptr[1] != 0)) goto create_pair;
2254 myattr = (subptr[2] << 8) | subptr[3];
2258 * Our dictionary is broken.
2265 * Not enough room for one more
2268 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2271 attribute = (myvendor << 16) | myattr;
2272 ptr += 4 + vsa_tlen;
2273 attrlen -= (4 + vsa_tlen);
2274 packet_length -= 4 + vsa_tlen;
2278 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2281 if (subptr[vsa_tlen] > sublen)
2283 sublen -= subptr[vsa_tlen];
2284 subptr += subptr[vsa_tlen];
2288 if (subptr[vsa_tlen] != 0) goto create_pair;
2289 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2291 if (subptr[vsa_tlen + 1] > sublen)
2293 sublen -= subptr[vsa_tlen + 1];
2294 subptr += subptr[vsa_tlen + 1];
2298 * Our dictionaries are
2304 } while (sublen > 0);
2306 vendorcode = myvendor;
2307 vendorlen = attrlen - 4;
2314 * attrlen is the length of this attribute.
2315 * total_len is the length of the encompassing
2324 attribute = (ptr[0] << 8) | ptr[1];
2327 default: /* can't hit this. */
2330 attribute |= (vendorcode << 16);
2335 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2339 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2342 default: /* can't hit this. */
2346 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2347 if (vendorlen == 0) vendorcode = 0;
2348 packet_length -= (vsa_tlen + vsa_llen);
2351 * Create the attribute, setting the default type
2352 * to 'octets'. If the type in the dictionary
2353 * is different, then the dictionary type will
2354 * over-ride this one.
2357 pair = rad_attr2vp(packet, original, secret,
2358 attribute, attrlen, ptr);
2360 pairfree(&packet->vps);
2361 librad_log("out of memory");
2374 * VSA's may not have been counted properly in
2375 * rad_packet_ok() above, as it is hard to count
2376 * then without using the dictionary. We
2377 * therefore enforce the limits here, too.
2379 if ((librad_max_attributes > 0) &&
2380 (num_attributes > librad_max_attributes)) {
2381 char host_ipaddr[128];
2383 pairfree(&packet->vps);
2384 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2385 inet_ntop(packet->src_ipaddr.af,
2386 &packet->src_ipaddr.ipaddr,
2387 host_ipaddr, sizeof(host_ipaddr)),
2388 num_attributes, librad_max_attributes);
2393 packet_length -= attrlen;
2397 * Merge information from the outside world into our
2400 lrad_rand_seed(packet->data, AUTH_HDR_LEN);
2409 * We assume that the passwd buffer passed is big enough.
2410 * RFC2138 says the password is max 128 chars, so the size
2411 * of the passwd buffer must be at least 129 characters.
2412 * Preferably it's just MAX_STRING_LEN.
2414 * int *pwlen is updated to the new length of the encrypted
2415 * password - a multiple of 16 bytes.
2417 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2418 const uint8_t *vector)
2420 lrad_MD5_CTX context, old;
2421 uint8_t digest[AUTH_VECTOR_LEN];
2422 int i, n, secretlen;
2426 * RFC maximum is 128 bytes.
2428 * If length is zero, pad it out with zeros.
2430 * If the length isn't aligned to 16 bytes,
2431 * zero out the extra data.
2435 if (len > 128) len = 128;
2438 memset(passwd, 0, AUTH_PASS_LEN);
2439 len = AUTH_PASS_LEN;
2440 } else if ((len % AUTH_PASS_LEN) != 0) {
2441 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2442 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2447 * Use the secret to setup the decryption digest
2449 secretlen = strlen(secret);
2451 lrad_MD5Init(&context);
2452 lrad_MD5Update(&context, secret, secretlen);
2453 old = context; /* save intermediate work */
2456 * Encrypt it in place. Don't bother checking
2457 * len, as we've ensured above that it's OK.
2459 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2461 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
2462 lrad_MD5Final(digest, &context);
2465 lrad_MD5Update(&context,
2466 passwd + n - AUTH_PASS_LEN,
2468 lrad_MD5Final(digest, &context);
2471 for (i = 0; i < AUTH_PASS_LEN; i++) {
2472 passwd[i + n] ^= digest[i];
2482 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2483 const uint8_t *vector)
2485 lrad_MD5_CTX context, old;
2486 uint8_t digest[AUTH_VECTOR_LEN];
2487 int i, n, secretlen;
2490 * The RFC's say that the maximum is 128.
2491 * The buffer we're putting it into above is 254, so
2492 * we don't need to do any length checking.
2494 if (pwlen > 128) pwlen = 128;
2499 if (pwlen == 0) goto done;
2502 * Use the secret to setup the decryption digest
2504 secretlen = strlen(secret);
2506 lrad_MD5Init(&context);
2507 lrad_MD5Update(&context, secret, secretlen);
2508 old = context; /* save intermediate work */
2511 * The inverse of the code above.
2513 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2515 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2516 lrad_MD5Final(digest, &context);
2519 if (pwlen > AUTH_PASS_LEN) lrad_MD5Update(&context, passwd, AUTH_PASS_LEN);
2521 lrad_MD5Final(digest, &context);
2524 if (pwlen > (n + AUTH_PASS_LEN)) lrad_MD5Update(&context, passwd + n, AUTH_PASS_LEN);
2527 for (i = 0; i < AUTH_PASS_LEN; i++) {
2528 passwd[i + n] ^= digest[i];
2533 passwd[pwlen] = '\0';
2534 return strlen(passwd);
2539 * Encode Tunnel-Password attributes when sending them out on the wire.
2541 * int *pwlen is updated to the new length of the encrypted
2542 * password - a multiple of 16 bytes.
2544 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2547 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2548 const uint8_t *vector)
2550 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2551 unsigned char digest[AUTH_VECTOR_LEN];
2553 int i, n, secretlen;
2558 if (len > 127) len = 127;
2561 * Shift the password 3 positions right to place a salt and original
2562 * length, tag will be added automatically on packet send
2564 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2568 * save original password length as first password character;
2575 * Generate salt. The RFC's say:
2577 * The high bit of salt[0] must be set, each salt in a
2578 * packet should be unique, and they should be random
2580 * So, we set the high bit, add in a counter, and then
2581 * add in some CSPRNG data. should be OK..
2583 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2584 (lrad_rand() & 0x07));
2585 salt[1] = lrad_rand();
2588 * Padd password to multiple of AUTH_PASS_LEN bytes.
2590 n = len % AUTH_PASS_LEN;
2592 n = AUTH_PASS_LEN - n;
2593 for (; n > 0; n--, len++)
2596 /* set new password length */
2600 * Use the secret to setup the decryption digest
2602 secretlen = strlen(secret);
2603 memcpy(buffer, secret, secretlen);
2605 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2607 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2608 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2609 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2611 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2612 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2615 for (i = 0; i < AUTH_PASS_LEN; i++) {
2616 passwd[i + n2] ^= digest[i];
2624 * Decode Tunnel-Password encrypted attributes.
2626 * Defined in RFC-2868, this uses a two char SALT along with the
2627 * initial intermediate value, to differentiate it from the
2630 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2631 const uint8_t *vector)
2633 lrad_MD5_CTX context, old;
2634 uint8_t digest[AUTH_VECTOR_LEN];
2636 unsigned i, n, len, reallen;
2641 * We need at least a salt.
2644 librad_log("tunnel password is too short");
2649 * There's a salt, but no password. Or, there's a salt
2650 * and a 'data_len' octet. It's wrong, but at least we
2651 * can figure out what it means: the password is empty.
2653 * Note that this means we ignore the 'data_len' field,
2654 * if the attribute length tells us that there's no
2655 * more data. So the 'data_len' field may be wrong,
2664 len -= 2; /* discount the salt */
2667 * Use the secret to setup the decryption digest
2669 secretlen = strlen(secret);
2671 lrad_MD5Init(&context);
2672 lrad_MD5Update(&context, secret, secretlen);
2673 old = context; /* save intermediate work */
2676 * Set up the initial key:
2678 * b(1) = MD5(secret + vector + salt)
2680 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2681 lrad_MD5Update(&context, passwd, 2);
2684 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2688 lrad_MD5Final(digest, &context);
2693 * A quick check: decrypt the first octet
2694 * of the password, which is the
2695 * 'data_len' field. Ensure it's sane.
2697 reallen = passwd[2] ^ digest[0];
2698 if (reallen >= len) {
2699 librad_log("tunnel password is too long for the attribute");
2703 lrad_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2707 lrad_MD5Final(digest, &context);
2710 lrad_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2713 for (i = base; i < AUTH_PASS_LEN; i++) {
2714 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2719 * See make_tunnel_password, above.
2721 if (reallen > 239) reallen = 239;
2724 passwd[reallen] = 0;
2730 * Encode a CHAP password
2732 * FIXME: might not work with Ascend because
2733 * we use vp->length, and Ascend gear likes
2734 * to send an extra '\0' in the string!
2736 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2737 VALUE_PAIR *password)
2741 uint8_t string[MAX_STRING_LEN * 2 + 1];
2742 VALUE_PAIR *challenge;
2745 * Sanity check the input parameters
2747 if ((packet == NULL) || (password == NULL)) {
2752 * Note that the password VP can be EITHER
2753 * a User-Password attribute (from a check-item list),
2754 * or a CHAP-Password attribute (the client asking
2755 * the library to encode it).
2763 memcpy(ptr, password->vp_strvalue, password->length);
2764 ptr += password->length;
2765 i += password->length;
2768 * Use Chap-Challenge pair if present,
2769 * Request-Authenticator otherwise.
2771 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2773 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2774 i += challenge->length;
2776 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2777 i += AUTH_VECTOR_LEN;
2781 librad_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2788 * Seed the random number generator.
2790 * May be called any number of times.
2792 void lrad_rand_seed(const void *data, size_t size)
2797 * Ensure that the pool is initialized.
2799 if (!lrad_rand_initialized) {
2802 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2804 fd = open("/dev/urandom", O_RDONLY);
2810 while (total < sizeof(lrad_rand_pool.randrsl)) {
2811 this = read(fd, lrad_rand_pool.randrsl,
2812 sizeof(lrad_rand_pool.randrsl) - total);
2813 if ((this < 0) && (errno != EINTR)) break;
2814 if (this > 0) total += this;
2818 lrad_rand_pool.randrsl[0] = fd;
2819 lrad_rand_pool.randrsl[1] = time(NULL);
2820 lrad_rand_pool.randrsl[2] = errno;
2823 lrad_randinit(&lrad_rand_pool, 1);
2824 lrad_rand_pool.randcnt = 0;
2825 lrad_rand_initialized = 1;
2831 * Hash the user data
2834 if (!hash) hash = lrad_rand();
2835 hash = lrad_hash_update(data, size, hash);
2837 lrad_rand_pool.randmem[lrad_rand_pool.randcnt] ^= hash;
2842 * Return a 32-bit random number.
2844 uint32_t lrad_rand(void)
2849 * Ensure that the pool is initialized.
2851 if (!lrad_rand_initialized) {
2852 lrad_rand_seed(NULL, 0);
2855 num = lrad_rand_pool.randrsl[lrad_rand_pool.randcnt++];
2856 if (lrad_rand_pool.randcnt == 256) {
2857 lrad_isaac(&lrad_rand_pool);
2858 lrad_rand_pool.randcnt = 0;
2866 * Allocate a new RADIUS_PACKET
2868 RADIUS_PACKET *rad_alloc(int newvector)
2872 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2873 librad_log("out of memory");
2876 memset(rp, 0, sizeof(*rp));
2882 uint32_t hash, base;
2885 * Don't expose the actual contents of the random
2889 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2890 hash = lrad_rand() ^ base;
2891 memcpy(rp->vector + i, &hash, sizeof(hash));
2894 lrad_rand(); /* stir the pool again */
2900 * Free a RADIUS_PACKET
2902 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2904 RADIUS_PACKET *radius_packet;
2906 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2907 radius_packet = *radius_packet_ptr;
2909 free(radius_packet->data);
2911 pairfree(&radius_packet->vps);
2913 free(radius_packet);
2915 *radius_packet_ptr = NULL;