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/autoconf.h>
27 #include <freeradius-devel/md5.h>
39 #include <freeradius-devel/udpfromto.h>
51 #include <freeradius-devel/missing.h>
52 #include <freeradius-devel/libradius.h>
55 * The RFC says 4096 octets max, and most packets are less than 256.
57 #define MAX_PACKET_LEN 4096
60 * The maximum number of attributes which we allow in an incoming
61 * request. If there are more attributes than this, the request
64 * This helps to minimize the potential for a DoS, when an
65 * attacker spoofs Access-Request packets, which don't have a
66 * Message-Authenticator attribute. This means that the packet
67 * is unsigned, and the attacker can use resources on the server,
68 * even if the end request is rejected.
70 int librad_max_attributes = 0;
72 typedef struct radius_packet_t {
76 uint8_t vector[AUTH_VECTOR_LEN];
80 static lrad_randctx lrad_rand_pool; /* across multiple calls */
81 static int lrad_rand_initialized = 0;
82 static unsigned int salt_offset = 0;
85 #define MAX_PACKET_CODE (52)
86 static const char *packet_codes[] = {
92 "Accounting-Response",
108 "Resource-Free-Request",
109 "Resource-Free-Response",
110 "Resource-Query-Request",
111 "Resource-Query-Response",
112 "Alternate-Resource-Reclaim-Request",
113 "NAS-Reboot-Request",
114 "NAS-Reboot-Response",
127 "Disconnect-Request",
137 "IP-Address-Allocate",
143 * Wrapper for sendto which handles sendfromto, IPv6, and all
144 * possible combinations.
146 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
147 lrad_ipaddr_t *src_ipaddr, lrad_ipaddr_t *dst_ipaddr,
150 struct sockaddr_storage dst;
151 socklen_t sizeof_dst = sizeof(dst);
153 #ifdef WITH_UDPFROMTO
154 struct sockaddr_storage src;
155 socklen_t sizeof_src = sizeof(src);
157 memset(&src, 0, sizeof(src));
159 memset(&dst, 0, sizeof(dst));
164 if (dst_ipaddr->af == AF_INET) {
165 struct sockaddr_in *s4;
167 s4 = (struct sockaddr_in *)&dst;
168 sizeof_dst = sizeof(struct sockaddr_in);
170 s4->sin_family = AF_INET;
171 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
172 s4->sin_port = htons(dst_port);
174 #ifdef WITH_UDPFROMTO
175 s4 = (struct sockaddr_in *)&src;
176 sizeof_src = sizeof(struct sockaddr_in);
178 s4->sin_family = AF_INET;
179 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
183 * IPv6 MAY be supported.
185 #ifdef HAVE_STRUCT_SOCKADDR_IN6
186 } else if (dst_ipaddr->af == AF_INET6) {
187 struct sockaddr_in6 *s6;
189 s6 = (struct sockaddr_in6 *)&dst;
190 sizeof_dst = sizeof(struct sockaddr_in6);
192 s6->sin6_family = AF_INET6;
193 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
194 s6->sin6_port = htons(dst_port);
196 #ifdef WITH_UDPFROMTO
197 return -1; /* UDPFROMTO && IPv6 are not supported */
199 s6 = (struct sockaddr_in6 *)&src;
200 sizeof_src = sizeof(struct sockaddr_in6);
202 s6->sin6_family = AF_INET6;
203 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
205 #endif /* WITH_UDPFROMTO */
206 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
207 } else return -1; /* Unknown address family, Die Die Die! */
209 #ifdef WITH_UDPFROMTO
211 * Only IPv4 is supported for udpfromto.
213 * And if they don't specify a source IP address, don't
216 if ((dst_ipaddr->af == AF_INET) ||
217 (src_ipaddr->af != AF_UNSPEC)) {
218 return sendfromto(sockfd, data, data_len, flags,
219 (struct sockaddr *)&src, sizeof_src,
220 (struct sockaddr *)&dst, sizeof_dst);
223 src_ipaddr = src_ipaddr; /* -Wunused */
227 * No udpfromto, OR an IPv6 socket, fail gracefully.
229 return sendto(sockfd, data, data_len, flags,
230 (struct sockaddr *)&dst, sizeof_dst);
235 * Wrapper for recvfrom, which handles recvfromto, IPv6, and all
236 * possible combinations.
238 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
239 lrad_ipaddr_t *src_ipaddr, uint16_t *src_port,
240 lrad_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
242 struct sockaddr_storage src;
243 struct sockaddr_storage dst;
244 socklen_t sizeof_src = sizeof(src);
245 socklen_t sizeof_dst = sizeof(dst);
251 memset(&src, 0, sizeof_src);
252 memset(&dst, 0, sizeof_dst);
255 * Get address family, etc. first, so we know if we
256 * need to do udpfromto.
258 * FIXME: udpfromto also does this, but it's not
259 * a critical problem.
261 if (getsockname(sockfd, (struct sockaddr *)&dst,
262 &sizeof_dst) < 0) return -1;
265 * Read the length of the packet, from the packet.
266 * This lets us allocate the buffer to use for
267 * reading the rest of the packet.
269 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
270 (struct sockaddr *)&src, &sizeof_src);
271 if (data_len < 0) return -1;
274 * Too little data is available, discard the packet.
277 recvfrom(sockfd, header, sizeof(header), flags,
278 (struct sockaddr *)&src, &sizeof_src);
281 } else { /* we got 4 bytes of data. */
283 * See how long the packet says it is.
285 len = (header[2] * 256) + header[3];
288 * The length in the packet says it's less than
289 * a RADIUS header length: discard it.
291 if (len < AUTH_HDR_LEN) {
292 recvfrom(sockfd, header, sizeof(header), flags,
293 (struct sockaddr *)&src, &sizeof_src);
297 * Enforce RFC requirements, for sanity.
298 * Anything after 4k will be discarded.
300 } else if (len > MAX_PACKET_LEN) {
301 recvfrom(sockfd, header, sizeof(header), flags,
302 (struct sockaddr *)&src, &sizeof_src);
311 * Receive the packet. The OS will discard any data in the
312 * packet after "len" bytes.
314 #ifdef WITH_UDPFROMTO
315 if (dst.ss_family == AF_INET) {
316 data_len = recvfromto(sockfd, buf, len, flags,
317 (struct sockaddr *)&src, &sizeof_src,
318 (struct sockaddr *)&dst, &sizeof_dst);
322 * No udpfromto, OR an IPv6 socket. Fail gracefully.
324 data_len = recvfrom(sockfd, buf, len, flags,
325 (struct sockaddr *)&src, &sizeof_src);
332 * Check address families, and update src/dst ports, etc.
334 if (src.ss_family == AF_INET) {
335 struct sockaddr_in *s4;
337 s4 = (struct sockaddr_in *)&src;
338 src_ipaddr->af = AF_INET;
339 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
340 *src_port = ntohs(s4->sin_port);
342 s4 = (struct sockaddr_in *)&dst;
343 dst_ipaddr->af = AF_INET;
344 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
345 *dst_port = ntohs(s4->sin_port);
347 #ifdef HAVE_STRUCT_SOCKADDR_IN6
348 } else if (src.ss_family == AF_INET6) {
349 struct sockaddr_in6 *s6;
351 s6 = (struct sockaddr_in6 *)&src;
352 src_ipaddr->af = AF_INET6;
353 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
354 *src_port = ntohs(s6->sin6_port);
356 s6 = (struct sockaddr_in6 *)&dst;
357 dst_ipaddr->af = AF_INET6;
358 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
359 *dst_port = ntohs(s6->sin6_port);
363 return -1; /* Unknown address family, Die Die Die! */
367 * Different address families should never happen.
369 if (src.ss_family != dst.ss_family) {
375 * Tell the caller about the data
383 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
384 /*************************************************************************
386 * Function: make_secret
388 * Purpose: Build an encrypted secret value to return in a reply
389 * packet. The secret is hidden by xoring with a MD5 digest
390 * created from the shared secret and the authentication
391 * vector. We put them into MD5 in the reverse order from
392 * that used when encrypting passwords to RADIUS.
394 *************************************************************************/
395 static void make_secret(uint8_t *digest, const uint8_t *vector,
396 const char *secret, const uint8_t *value)
398 lrad_MD5_CTX context;
401 lrad_MD5Init(&context);
402 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
403 lrad_MD5Update(&context, secret, strlen(secret));
404 lrad_MD5Final(digest, &context);
406 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
407 digest[i] ^= value[i];
411 #define MAX_PASS_LEN (128)
412 static void make_passwd(uint8_t *output, int *outlen,
413 const uint8_t *input, int inlen,
414 const char *secret, const uint8_t *vector)
416 lrad_MD5_CTX context, old;
417 uint8_t digest[AUTH_VECTOR_LEN];
418 uint8_t passwd[MAX_PASS_LEN];
423 * If the length is zero, round it up.
429 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
431 else if ((len & 0x0f) != 0) {
437 memcpy(passwd, input, len);
438 memset(passwd + len, 0, sizeof(passwd) - len);
440 lrad_MD5Init(&context);
441 lrad_MD5Update(&context, secret, strlen(secret));
447 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
449 for (n = 0; n < len; n += AUTH_PASS_LEN) {
452 lrad_MD5Update(&context,
453 passwd + n - AUTH_PASS_LEN,
457 lrad_MD5Final(digest, &context);
458 for (i = 0; i < AUTH_PASS_LEN; i++) {
459 passwd[i + n] ^= digest[i];
463 memcpy(output, passwd, len);
466 static void make_tunnel_passwd(uint8_t *output, int *outlen,
467 const uint8_t *input, int inlen, int room,
468 const char *secret, const uint8_t *vector)
470 lrad_MD5_CTX context, old;
471 uint8_t digest[AUTH_VECTOR_LEN];
472 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
479 if (room > 253) room = 253;
482 * Account for 2 bytes of the salt, and round the room
483 * available down to the nearest multiple of 16. Then,
484 * subtract one from that to account for the length byte,
485 * and the resulting number is the upper bound on the data
488 * We could short-cut this calculation just be forcing
489 * inlen to be no more than 239. It would work for all
490 * VSA's, as we don't pack multiple VSA's into one
493 * However, this calculation is more general, if a little
494 * complex. And it will work in the future for all possible
495 * kinds of weird attribute packing.
498 room -= (room & 0x0f);
501 if (inlen > room) inlen = room;
504 * Length of the encrypted data is password length plus
505 * one byte for the length of the password.
508 if ((len & 0x0f) != 0) {
512 *outlen = len + 2; /* account for the salt */
515 * Copy the password over.
517 memcpy(passwd + 3, input, inlen);
518 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
521 * Generate salt. The RFC's say:
523 * The high bit of salt[0] must be set, each salt in a
524 * packet should be unique, and they should be random
526 * So, we set the high bit, add in a counter, and then
527 * add in some CSPRNG data. should be OK..
529 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
530 (lrad_rand() & 0x07));
531 passwd[1] = lrad_rand();
532 passwd[2] = inlen; /* length of the password string */
534 lrad_MD5Init(&context);
535 lrad_MD5Update(&context, secret, strlen(secret));
538 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
539 lrad_MD5Update(&context, &passwd[0], 2);
541 for (n = 0; n < len; n += AUTH_PASS_LEN) {
544 lrad_MD5Update(&context,
545 passwd + 2 + n - AUTH_PASS_LEN,
549 lrad_MD5Final(digest, &context);
550 for (i = 0; i < AUTH_PASS_LEN; i++) {
551 passwd[i + 2 + n] ^= digest[i];
554 memcpy(output, passwd, len + 2);
559 * Parse a data structure into a RADIUS attribute.
561 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
562 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
565 int offset, len, total_length;
567 uint8_t *length_ptr, *vsa_length_ptr;
568 const uint8_t *data = NULL;
571 vendorcode = total_length = 0;
572 length_ptr = vsa_length_ptr = NULL;
575 * For interoperability, always put vendor attributes
576 * into their own VSA.
578 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
579 *(ptr++) = vp->attribute & 0xFF;
587 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
590 * This must be an RFC-format attribute. If it
591 * wasn't, then the "decode" function would have
592 * made a Vendor-Specific attribute (i.e. type
593 * 26), and we would have "vendorcode == 0" here.
597 vsa_llen = dv->length;
601 * Build a VSA header.
603 *ptr++ = PW_VENDOR_SPECIFIC;
604 vsa_length_ptr = ptr;
606 lvalue = htonl(vendorcode);
607 memcpy(ptr, &lvalue, 4);
613 ptr[0] = (vp->attribute & 0xFF);
617 ptr[0] = ((vp->attribute >> 8) & 0xFF);
618 ptr[1] = (vp->attribute & 0xFF);
624 ptr[2] = ((vp->attribute >> 8) & 0xFF);
625 ptr[3] = (vp->attribute & 0xFF);
629 return 0; /* silently discard it */
635 length_ptr = vsa_length_ptr;
636 vsa_length_ptr = NULL;
645 length_ptr = ptr + 1;
649 return 0; /* silently discard it */
653 total_length += vsa_tlen + vsa_llen;
654 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
655 *length_ptr += vsa_tlen + vsa_llen;
659 if (vp->flags.has_tag) {
660 if (TAG_VALID(vp->flags.tag)) {
661 ptr[0] = vp->flags.tag & 0xff;
664 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
666 * Tunnel passwords REQUIRE a tag, even
667 * if don't have a valid tag.
671 } /* else don't write a tag */
672 } /* else the attribute doesn't have a tag */
675 * Set up the default sources for the data.
677 data = vp->vp_octets;
684 case PW_TYPE_IPV6ADDR:
685 case PW_TYPE_IPV6PREFIX:
686 case PW_TYPE_ABINARY:
687 /* nothing more to do */
691 len = 1; /* just in case */
692 array[0] = vp->lvalue & 0xff;
699 len = 2; /* just in case */
700 array[0] = (vp->lvalue >> 8) & 0xff;
701 array[1] = vp->lvalue & 0xff;
706 case PW_TYPE_INTEGER:
707 len = 4; /* just in case */
708 lvalue = htonl(vp->lvalue);
709 memcpy(array, &lvalue, sizeof(lvalue));
712 * Perhaps discard the first octet.
714 data = &array[offset];
719 data = (const uint8_t *) &vp->lvalue;
720 len = 4; /* just in case */
724 * There are no tagged date attributes.
727 lvalue = htonl(vp->lvalue);
728 data = (const uint8_t *) &lvalue;
729 len = 4; /* just in case */
732 default: /* unknown type: ignore it */
733 librad_log("ERROR: Unknown attribute type %d", vp->type);
738 * Bound the data to 255 bytes.
740 if (len + offset + total_length > 255) {
741 len = 255 - offset - total_length;
745 * Encrypt the various password styles
747 * Attributes with encrypted values MUST be less than
750 switch (vp->flags.encrypt) {
751 case FLAG_ENCRYPT_USER_PASSWORD:
752 make_passwd(ptr + offset, &len,
754 secret, packet->vector);
757 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
759 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
764 * Check if 255 - offset - total_length is less
765 * than 18. If so, we can't fit the data into
766 * the available space, and we discard the
769 * This is ONLY a problem if we have multiple VSA's
770 * in one Vendor-Specific, though.
772 if ((255 - offset - total_length) < 18) return 0;
774 make_tunnel_passwd(ptr + offset, &len,
775 data, len, 255 - offset - total_length,
776 secret, original->vector);
780 * The code above ensures that this attribute
783 case FLAG_ENCRYPT_ASCEND_SECRET:
784 make_secret(ptr + offset, packet->vector,
786 len = AUTH_VECTOR_LEN;
792 * Just copy the data over
794 memcpy(ptr + offset, data, len);
796 } /* switch over encryption flags */
799 * Account for the tag (if any).
804 * RFC 2865 section 5 says that zero-length attributes
807 if (len == 0) return 0;
810 * Update the various lengths.
813 if (vsa_length_ptr) *vsa_length_ptr += len;
817 return total_length; /* of attribute */
824 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
827 radius_packet_t *hdr;
829 uint16_t total_length;
836 * For simplicity in the following logic, we allow
837 * the attributes to "overflow" the 4k maximum
838 * RADIUS packet size, by one attribute.
840 * It's uint32_t, for alignment purposes.
842 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
844 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
845 what = packet_codes[packet->code];
850 DEBUG("Sending %s of id %d to %s port %d\n",
852 inet_ntop(packet->dst_ipaddr.af,
853 &packet->dst_ipaddr.ipaddr,
854 ip_buffer, sizeof(ip_buffer)),
858 * Double-check some things based on packet code.
860 switch (packet->code) {
861 case PW_AUTHENTICATION_ACK:
862 case PW_AUTHENTICATION_REJECT:
863 case PW_ACCESS_CHALLENGE:
865 librad_log("ERROR: Cannot sign response packet without a request packet.");
871 * These packet vectors start off as all zero.
873 case PW_ACCOUNTING_REQUEST:
874 case PW_DISCONNECT_REQUEST:
876 memset(packet->vector, 0, sizeof(packet->vector));
884 * Use memory on the stack, until we know how
885 * large the packet will be.
887 hdr = (radius_packet_t *) data;
890 * Build standard header
892 hdr->code = packet->code;
893 hdr->id = packet->id;
895 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
897 total_length = AUTH_HDR_LEN;
898 packet->verified = 0;
901 * Load up the configuration values for the user
906 * FIXME: Loop twice over the reply list. The first time,
907 * calculate the total length of data. The second time,
908 * allocate the memory, and fill in the VP's.
910 * Hmm... this may be slower than just doing a small
915 * Loop over the reply attributes for the packet.
917 for (reply = packet->vps; reply; reply = reply->next) {
919 * Ignore non-wire attributes
921 if ((VENDOR(reply->attribute) == 0) &&
922 ((reply->attribute & 0xFFFF) > 0xff)) {
927 * Set the Message-Authenticator to the correct
928 * length and initial value.
930 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
931 reply->length = AUTH_VECTOR_LEN;
932 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
933 packet->verified = total_length; /* HACK! */
937 * Print out ONLY the attributes which
938 * we're sending over the wire, and print
939 * them out BEFORE they're encrypted.
943 len = rad_vp2attr(packet, original, secret, reply, ptr);
945 if (len < 0) return -1;
948 * Check that the packet is no more than 4k in
949 * size, AFTER writing the attribute past the 4k
950 * boundary, but BEFORE deciding to increase the
951 * size of the packet. Note that the 'data'
952 * buffer, above, is one attribute longer than
953 * necessary, in order to permit this overflow.
955 if ((total_length + len) > MAX_PACKET_LEN) {
961 } /* done looping over all attributes */
964 * Fill in the rest of the fields, and copy the data over
965 * from the local stack to the newly allocated memory.
967 * Yes, all this 'memcpy' is slow, but it means
968 * that we only allocate the minimum amount of
969 * memory for a request.
971 packet->data_len = total_length;
972 packet->data = (uint8_t *) malloc(packet->data_len);
974 librad_log("Out of memory");
978 memcpy(packet->data, data, packet->data_len);
979 hdr = (radius_packet_t *) packet->data;
981 total_length = htons(total_length);
982 memcpy(hdr->length, &total_length, sizeof(total_length));
989 * Sign a previously encoded packet.
991 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
994 radius_packet_t *hdr = (radius_packet_t *)packet->data;
997 * It wasn't assigned an Id, this is bad!
999 if (packet->id < 0) {
1000 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1004 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1005 (packet->verified < 0)) {
1006 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1011 * If there's a Message-Authenticator, update it
1012 * now, BEFORE updating the authentication vector.
1016 if (packet->verified > 0) {
1017 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1019 switch (packet->code) {
1020 case PW_ACCOUNTING_REQUEST:
1021 case PW_ACCOUNTING_RESPONSE:
1022 case PW_DISCONNECT_REQUEST:
1023 case PW_DISCONNECT_ACK:
1024 case PW_DISCONNECT_NAK:
1025 case PW_COA_REQUEST:
1028 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1031 case PW_AUTHENTICATION_ACK:
1032 case PW_AUTHENTICATION_REJECT:
1033 case PW_ACCESS_CHALLENGE:
1035 librad_log("ERROR: Cannot sign response packet without a request packet.");
1038 memcpy(hdr->vector, original->vector,
1042 default: /* others have vector already set to zero */
1048 * Set the authentication vector to zero,
1049 * calculate the signature, and put it
1050 * into the Message-Authenticator
1053 lrad_hmac_md5(packet->data, packet->data_len,
1054 secret, strlen(secret),
1056 memcpy(packet->data + packet->verified + 2,
1057 calc_auth_vector, AUTH_VECTOR_LEN);
1060 * Copy the original request vector back
1061 * to the raw packet.
1063 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1067 * Switch over the packet code, deciding how to
1070 switch (packet->code) {
1072 * Request packets are not signed, bur
1073 * have a random authentication vector.
1075 case PW_AUTHENTICATION_REQUEST:
1076 case PW_STATUS_SERVER:
1080 * Reply packets are signed with the
1081 * authentication vector of the request.
1089 MD5Update(&context, packet->data, packet->data_len);
1090 MD5Update(&context, secret, strlen(secret));
1091 MD5Final(digest, &context);
1093 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1094 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1097 }/* switch over packet codes */
1103 * Reply to the request. Also attach
1104 * reply attribute value pairs and any user message provided.
1106 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1111 char ip_buffer[128];
1114 * Maybe it's a fake packet. Don't send it.
1116 if (!packet || (packet->sockfd < 0)) {
1120 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1121 what = packet_codes[packet->code];
1127 * First time through, allocate room for the packet
1129 if (!packet->data) {
1131 * Encode the packet.
1133 if (rad_encode(packet, original, secret) < 0) {
1138 * Re-sign it, including updating the
1139 * Message-Authenticator.
1141 if (rad_sign(packet, original, secret) < 0) {
1146 * If packet->data points to data, then we print out
1147 * the VP list again only for debugging.
1149 } else if (librad_debug) {
1150 DEBUG("Re-sending %s of id %d to %s port %d\n", what, packet->id,
1151 inet_ntop(packet->dst_ipaddr.af,
1152 &packet->dst_ipaddr.ipaddr,
1153 ip_buffer, sizeof(ip_buffer)),
1156 for (reply = packet->vps; reply; reply = reply->next) {
1157 /* FIXME: ignore attributes > 0xff */
1163 * And send it on it's way.
1165 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1166 &packet->src_ipaddr, &packet->dst_ipaddr,
1172 * Validates the requesting client NAS. Calculates the
1173 * signature based on the clients private key.
1175 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1177 uint8_t digest[AUTH_VECTOR_LEN];
1181 * Older clients have the authentication vector set to
1182 * all zeros. Return `1' in that case.
1184 memset(digest, 0, sizeof(digest));
1185 if (memcmp(packet->vector, digest, AUTH_VECTOR_LEN) == 0) {
1186 packet->verified = 1;
1191 * Zero out the auth_vector in the received packet.
1192 * Then append the shared secret to the received packet,
1193 * and calculate the MD5 sum. This must be the same
1194 * as the original MD5 sum (packet->vector).
1196 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1199 * MD5(packet + secret);
1202 MD5Update(&context, packet->data, packet->data_len);
1203 MD5Update(&context, secret, strlen(secret));
1204 MD5Final(digest, &context);
1207 * Return 0 if OK, 2 if not OK.
1210 memcmp(digest, packet->vector, AUTH_VECTOR_LEN) ? 2 : 0;
1212 return packet->verified;
1216 * Validates the requesting client NAS. Calculates the
1217 * signature based on the clients private key.
1219 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1222 uint8_t calc_digest[AUTH_VECTOR_LEN];
1228 if (original == NULL) {
1233 * Copy the original vector in place.
1235 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1238 * MD5(packet + secret);
1241 MD5Update(&context, packet->data, packet->data_len);
1242 MD5Update(&context, secret, strlen(secret));
1243 MD5Final(calc_digest, &context);
1246 * Copy the packet's vector back to the packet.
1248 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1251 * Return 0 if OK, 2 if not OK.
1254 memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) ? 2 : 0;
1255 return packet->verified;
1260 * See if the data pointed to by PTR is a valid RADIUS packet.
1262 * packet is not 'const * const' because we may update data_len,
1263 * if there's more data in the UDP packet than in the RADIUS packet.
1265 int rad_packet_ok(RADIUS_PACKET *packet)
1270 radius_packet_t *hdr;
1271 char host_ipaddr[128];
1277 * Check for packets smaller than the packet header.
1279 * RFC 2865, Section 3., subsection 'length' says:
1281 * "The minimum length is 20 ..."
1283 if (packet->data_len < AUTH_HDR_LEN) {
1284 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1285 inet_ntop(packet->src_ipaddr.af,
1286 &packet->src_ipaddr.ipaddr,
1287 host_ipaddr, sizeof(host_ipaddr)),
1288 packet->data_len, AUTH_HDR_LEN);
1293 * RFC 2865, Section 3., subsection 'length' says:
1295 * " ... and maximum length is 4096."
1297 if (packet->data_len > MAX_PACKET_LEN) {
1298 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1299 inet_ntop(packet->src_ipaddr.af,
1300 &packet->src_ipaddr.ipaddr,
1301 host_ipaddr, sizeof(host_ipaddr)),
1302 packet->data_len, MAX_PACKET_LEN);
1307 * Check for packets with mismatched size.
1308 * i.e. We've received 128 bytes, and the packet header
1309 * says it's 256 bytes long.
1311 totallen = (packet->data[2] << 8) | packet->data[3];
1312 hdr = (radius_packet_t *)packet->data;
1315 * Code of 0 is not understood.
1316 * Code of 16 or greate is not understood.
1318 if ((hdr->code == 0) ||
1319 (hdr->code >= MAX_PACKET_CODE)) {
1320 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1321 inet_ntop(packet->src_ipaddr.af,
1322 &packet->src_ipaddr.ipaddr,
1323 host_ipaddr, sizeof(host_ipaddr)),
1329 * Message-Authenticator is required in Status-Server
1330 * packets, otherwise they can be trivially forged.
1332 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1335 * Repeat the length checks. This time, instead of
1336 * looking at the data we received, look at the value
1337 * of the 'length' field inside of the packet.
1339 * Check for packets smaller than the packet header.
1341 * RFC 2865, Section 3., subsection 'length' says:
1343 * "The minimum length is 20 ..."
1345 if (totallen < AUTH_HDR_LEN) {
1346 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1347 inet_ntop(packet->src_ipaddr.af,
1348 &packet->src_ipaddr.ipaddr,
1349 host_ipaddr, sizeof(host_ipaddr)),
1350 totallen, AUTH_HDR_LEN);
1355 * And again, for the value of the 'length' field.
1357 * RFC 2865, Section 3., subsection 'length' says:
1359 * " ... and maximum length is 4096."
1361 if (totallen > MAX_PACKET_LEN) {
1362 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1363 inet_ntop(packet->src_ipaddr.af,
1364 &packet->src_ipaddr.ipaddr,
1365 host_ipaddr, sizeof(host_ipaddr)),
1366 totallen, MAX_PACKET_LEN);
1371 * RFC 2865, Section 3., subsection 'length' says:
1373 * "If the packet is shorter than the Length field
1374 * indicates, it MUST be silently discarded."
1376 * i.e. No response to the NAS.
1378 if (packet->data_len < totallen) {
1379 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1380 inet_ntop(packet->src_ipaddr.af,
1381 &packet->src_ipaddr.ipaddr,
1382 host_ipaddr, sizeof(host_ipaddr)),
1383 packet->data_len, totallen);
1388 * RFC 2865, Section 3., subsection 'length' says:
1390 * "Octets outside the range of the Length field MUST be
1391 * treated as padding and ignored on reception."
1393 if (packet->data_len > totallen) {
1395 * We're shortening the packet below, but just
1396 * to be paranoid, zero out the extra data.
1398 memset(packet->data + totallen, 0, packet->data_len - totallen);
1399 packet->data_len = totallen;
1403 * Walk through the packet's attributes, ensuring that
1404 * they add up EXACTLY to the size of the packet.
1406 * If they don't, then the attributes either under-fill
1407 * or over-fill the packet. Any parsing of the packet
1408 * is impossible, and will result in unknown side effects.
1410 * This would ONLY happen with buggy RADIUS implementations,
1411 * or with an intentional attack. Either way, we do NOT want
1412 * to be vulnerable to this problem.
1415 count = totallen - AUTH_HDR_LEN;
1420 * Attribute number zero is NOT defined.
1423 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1424 inet_ntop(packet->src_ipaddr.af,
1425 &packet->src_ipaddr.ipaddr,
1426 host_ipaddr, sizeof(host_ipaddr)));
1431 * Attributes are at LEAST as long as the ID & length
1432 * fields. Anything shorter is an invalid attribute.
1435 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1436 inet_ntop(packet->src_ipaddr.af,
1437 &packet->src_ipaddr.ipaddr,
1438 host_ipaddr, sizeof(host_ipaddr)),
1444 * Sanity check the attributes for length.
1447 default: /* don't do anything by default */
1452 * If there's an EAP-Message, we require
1453 * a Message-Authenticator.
1455 case PW_EAP_MESSAGE:
1459 case PW_MESSAGE_AUTHENTICATOR:
1460 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1461 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1462 inet_ntop(packet->src_ipaddr.af,
1463 &packet->src_ipaddr.ipaddr,
1464 host_ipaddr, sizeof(host_ipaddr)),
1473 * FIXME: Look up the base 255 attributes in the
1474 * dictionary, and switch over their type. For
1475 * integer/date/ip, the attribute length SHOULD
1478 count -= attr[1]; /* grab the attribute length */
1480 num_attributes++; /* seen one more attribute */
1484 * If the attributes add up to a packet, it's allowed.
1486 * If not, we complain, and throw the packet away.
1489 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1490 inet_ntop(packet->src_ipaddr.af,
1491 &packet->src_ipaddr.ipaddr,
1492 host_ipaddr, sizeof(host_ipaddr)));
1497 * If we're configured to look for a maximum number of
1498 * attributes, and we've seen more than that maximum,
1499 * then throw the packet away, as a possible DoS.
1501 if ((librad_max_attributes > 0) &&
1502 (num_attributes > librad_max_attributes)) {
1503 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1504 inet_ntop(packet->src_ipaddr.af,
1505 &packet->src_ipaddr.ipaddr,
1506 host_ipaddr, sizeof(host_ipaddr)),
1507 num_attributes, librad_max_attributes);
1512 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1514 * A packet with an EAP-Message attribute MUST also have
1515 * a Message-Authenticator attribute.
1517 * A Message-Authenticator all by itself is OK, though.
1519 * Similarly, Status-Server packets MUST contain
1520 * Message-Authenticator attributes.
1522 if (require_ma && ! seen_ma) {
1523 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1524 inet_ntop(packet->src_ipaddr.af,
1525 &packet->src_ipaddr.ipaddr,
1526 host_ipaddr, sizeof(host_ipaddr)));
1531 * Fill RADIUS header fields
1533 packet->code = hdr->code;
1534 packet->id = hdr->id;
1535 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1542 * Receive UDP client requests, and fill in
1543 * the basics of a RADIUS_PACKET structure.
1545 RADIUS_PACKET *rad_recv(int fd)
1547 RADIUS_PACKET *packet;
1550 * Allocate the new request data structure
1552 if ((packet = malloc(sizeof(*packet))) == NULL) {
1553 librad_log("out of memory");
1556 memset(packet, 0, sizeof(*packet));
1558 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1559 &packet->src_ipaddr, &packet->src_port,
1560 &packet->dst_ipaddr, &packet->dst_port);
1563 * Check for socket errors.
1565 if (packet->data_len < 0) {
1566 librad_log("Error receiving packet: %s", strerror(errno));
1567 /* packet->data is NULL */
1573 * If the packet is too big, then rad_recvfrom did NOT
1574 * allocate memory. Instead, it just discarded the
1577 if (packet->data_len > MAX_PACKET_LEN) {
1578 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1579 /* packet->data is NULL */
1585 * Read no data. Continue.
1586 * This check is AFTER the MAX_PACKET_LEN check above, because
1587 * if the packet is larger than MAX_PACKET_LEN, we also have
1588 * packet->data == NULL
1590 if ((packet->data_len == 0) || !packet->data) {
1591 librad_log("No data.");
1597 * See if it's a well-formed RADIUS packet.
1599 if (!rad_packet_ok(packet)) {
1605 * Remember which socket we read the packet from.
1607 packet->sockfd = fd;
1610 * FIXME: Do even more filtering by only permitting
1611 * certain IP's. The problem is that we don't know
1612 * how to do this properly for all possible clients...
1616 * Explicitely set the VP list to empty.
1621 char host_ipaddr[128];
1623 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1624 printf("rad_recv: %s packet from host %s port %d",
1625 packet_codes[packet->code],
1626 inet_ntop(packet->src_ipaddr.af,
1627 &packet->src_ipaddr.ipaddr,
1628 host_ipaddr, sizeof(host_ipaddr)),
1631 printf("rad_recv: Packet from host %s port %d code=%d",
1632 inet_ntop(packet->src_ipaddr.af,
1633 &packet->src_ipaddr.ipaddr,
1634 host_ipaddr, sizeof(host_ipaddr)),
1638 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1646 * Verify the signature of a packet.
1648 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1655 if (!packet || !packet->data) return -1;
1658 * Before we allocate memory for the attributes, do more
1661 ptr = packet->data + AUTH_HDR_LEN;
1662 length = packet->data_len - AUTH_HDR_LEN;
1663 while (length > 0) {
1664 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1665 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1670 default: /* don't do anything. */
1674 * Note that more than one Message-Authenticator
1675 * attribute is invalid.
1677 case PW_MESSAGE_AUTHENTICATOR:
1678 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1679 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1681 switch (packet->code) {
1685 case PW_ACCOUNTING_REQUEST:
1686 case PW_ACCOUNTING_RESPONSE:
1687 case PW_DISCONNECT_REQUEST:
1688 case PW_DISCONNECT_ACK:
1689 case PW_DISCONNECT_NAK:
1690 case PW_COA_REQUEST:
1693 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1696 case PW_AUTHENTICATION_ACK:
1697 case PW_AUTHENTICATION_REJECT:
1698 case PW_ACCESS_CHALLENGE:
1700 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1703 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1707 lrad_hmac_md5(packet->data, packet->data_len,
1708 secret, strlen(secret), calc_auth_vector);
1709 if (memcmp(calc_auth_vector, msg_auth_vector,
1710 sizeof(calc_auth_vector)) != 0) {
1712 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1713 inet_ntop(packet->src_ipaddr.af,
1714 &packet->src_ipaddr.ipaddr,
1715 buffer, sizeof(buffer)));
1716 /* Silently drop packet, according to RFC 3579 */
1718 } /* else the message authenticator was good */
1721 * Reinitialize Authenticators.
1723 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1724 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1726 } /* switch over the attributes */
1730 } /* loop over the packet, sanity checking the attributes */
1733 * It looks like a RADIUS packet, but we can't validate
1736 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1738 librad_log("Received Unknown packet code %d"
1739 "from client %s port %d: Cannot validate signature",
1741 inet_ntop(packet->src_ipaddr.af,
1742 &packet->src_ipaddr.ipaddr,
1743 buffer, sizeof(buffer)),
1749 * Calculate and/or verify digest.
1751 switch(packet->code) {
1755 case PW_AUTHENTICATION_REQUEST:
1756 case PW_STATUS_SERVER:
1757 case PW_DISCONNECT_REQUEST:
1759 * The authentication vector is random
1760 * nonsense, invented by the client.
1764 case PW_ACCOUNTING_REQUEST:
1765 if (calc_acctdigest(packet, secret) > 1) {
1766 librad_log("Received Accounting-Request packet "
1767 "from %s with invalid signature! (Shared secret is incorrect.)",
1768 inet_ntop(packet->src_ipaddr.af,
1769 &packet->src_ipaddr.ipaddr,
1770 buffer, sizeof(buffer)));
1775 /* Verify the reply digest */
1776 case PW_AUTHENTICATION_ACK:
1777 case PW_AUTHENTICATION_REJECT:
1778 case PW_ACCESS_CHALLENGE:
1779 case PW_ACCOUNTING_RESPONSE:
1780 case PW_DISCONNECT_ACK:
1781 case PW_DISCONNECT_NAK:
1784 rcode = calc_replydigest(packet, original, secret);
1786 librad_log("Received %s packet "
1787 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1788 packet_codes[packet->code],
1789 inet_ntop(packet->src_ipaddr.af,
1790 &packet->src_ipaddr.ipaddr,
1791 buffer, sizeof(buffer)),
1799 librad_log("Received Unknown packet code %d"
1800 "from client %s port %d: Cannot validate signature",
1802 inet_ntop(packet->src_ipaddr.af,
1803 &packet->src_ipaddr.ipaddr,
1804 buffer, sizeof(buffer)),
1814 * Parse a RADIUS attribute into a data structure.
1816 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1817 const char *secret, int attribute, int length,
1818 const uint8_t *data)
1823 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1828 * If length is greater than 253, something is SERIOUSLY
1831 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1833 vp->length = length;
1834 vp->operator = T_OP_EQ;
1840 if (vp->flags.has_tag) {
1841 if (TAG_VALID(data[0]) ||
1842 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1844 * Tunnel passwords REQUIRE a tag, even
1845 * if don't have a valid tag.
1847 vp->flags.tag = data[0];
1849 if ((vp->type == PW_TYPE_STRING) ||
1850 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1855 * Copy the data to be decrypted
1857 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1858 vp->length -= offset;
1861 * Decrypt the attribute.
1863 switch (vp->flags.encrypt) {
1867 case FLAG_ENCRYPT_USER_PASSWORD:
1869 rad_pwdecode((char *)vp->vp_strvalue,
1873 rad_pwdecode((char *)vp->vp_strvalue,
1877 if (vp->attribute == PW_USER_PASSWORD) {
1878 vp->length = strlen(vp->vp_strvalue);
1883 * Tunnel-Password's may go ONLY
1884 * in response packets.
1886 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1887 if (!original) goto raw;
1889 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1890 secret, original->vector) < 0) {
1896 * Ascend-Send-Secret
1897 * Ascend-Receive-Secret
1899 case FLAG_ENCRYPT_ASCEND_SECRET:
1903 uint8_t my_digest[AUTH_VECTOR_LEN];
1904 make_secret(my_digest,
1907 memcpy(vp->vp_strvalue, my_digest,
1909 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1910 vp->length = strlen(vp->vp_strvalue);
1916 } /* switch over encryption flags */
1920 case PW_TYPE_STRING:
1921 case PW_TYPE_OCTETS:
1922 case PW_TYPE_ABINARY:
1923 /* nothing more to do */
1927 if (vp->length != 1) goto raw;
1929 vp->lvalue = vp->vp_octets[0];
1934 if (vp->length != 2) goto raw;
1936 vp->lvalue = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
1939 case PW_TYPE_INTEGER:
1940 if (vp->length != 4) goto raw;
1942 memcpy(&vp->lvalue, vp->vp_octets, 4);
1943 vp->lvalue = ntohl(vp->lvalue);
1945 if (vp->flags.has_tag) vp->lvalue &= 0x00ffffff;
1948 * Try to get named VALUEs
1952 dval = dict_valbyattr(vp->attribute,
1955 strlcpy(vp->vp_strvalue,
1957 sizeof(vp->vp_strvalue));
1963 if (vp->length != 4) goto raw;
1965 memcpy(&vp->lvalue, vp->vp_octets, 4);
1966 vp->lvalue = ntohl(vp->lvalue);
1970 case PW_TYPE_IPADDR:
1971 if (vp->length != 4) goto raw;
1973 memcpy(&vp->lvalue, vp->vp_octets, 4);
1977 * IPv6 interface ID is 8 octets long.
1980 if (vp->length != 8) goto raw;
1981 /* vp->vp_ifid == vp->vp_octets */
1985 * IPv6 addresses are 16 octets long
1987 case PW_TYPE_IPV6ADDR:
1988 if (vp->length != 16) goto raw;
1989 /* vp->vp_ipv6addr == vp->vp_octets */
1993 * IPv6 prefixes are 2 to 18 octets long.
1995 * RFC 3162: The first octet is unused.
1996 * The second is the length of the prefix
1997 * the rest are the prefix data.
1999 * The prefix length can have value 0 to 128.
2001 case PW_TYPE_IPV6PREFIX:
2002 if (vp->length < 2 || vp->length > 18) goto raw;
2003 if (vp->vp_octets[1] > 128) goto raw;
2006 * FIXME: double-check that
2007 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2009 if (vp->length < 18) {
2010 memset(vp->vp_octets + vp->length, 0,
2017 vp->type = PW_TYPE_OCTETS;
2018 vp->length = length;
2019 memcpy(vp->vp_octets, data, length);
2023 * Ensure there's no encryption or tag stuff,
2024 * we just pass the attribute as-is.
2026 memset(&vp->flags, 0, sizeof(vp->flags));
2034 * Calculate/check digest, and decode radius attributes.
2036 * -1 on decoding error
2039 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2043 uint32_t vendorcode;
2051 radius_packet_t *hdr;
2052 int vsa_tlen, vsa_llen;
2053 DICT_VENDOR *dv = NULL;
2056 * Extract attribute-value pairs
2058 hdr = (radius_packet_t *)packet->data;
2060 packet_length = packet->data_len - AUTH_HDR_LEN;
2063 * There may be VP's already in the packet. Don't
2066 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2072 vsa_tlen = vsa_llen = 1;
2075 * We have to read at least two bytes.
2077 * rad_recv() above ensures that this is OK.
2079 while (packet_length > 0) {
2084 * Normal attribute, handle it like normal.
2086 if (vendorcode == 0) {
2088 * No room to read attr/length,
2089 * or bad attribute, or attribute is
2090 * too short, or attribute is too long,
2091 * stop processing the packet.
2093 if ((packet_length < 2) ||
2094 (ptr[0] == 0) || (ptr[1] < 2) ||
2095 (ptr[1] > packet_length)) break;
2103 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2106 * No vendor code, or ONLY vendor code.
2108 if (attrlen <= 4) goto create_pair;
2114 * Handle Vendor-Specific
2116 if (vendorlen == 0) {
2122 * attrlen was checked above.
2124 memcpy(&lvalue, ptr, 4);
2125 myvendor = ntohl(lvalue);
2128 * Zero isn't allowed.
2130 if (myvendor == 0) goto create_pair;
2133 * This is an implementation issue.
2134 * We currently pack vendor into the upper
2135 * 16 bits of a 32-bit attribute number,
2136 * so we can't handle vendor numbers larger
2139 if (myvendor > 65535) goto create_pair;
2141 vsa_tlen = vsa_llen = 1;
2142 dv = dict_vendorbyvalue(myvendor);
2144 vsa_tlen = dv->type;
2145 vsa_llen = dv->length;
2149 * Sweep through the list of VSA's,
2150 * seeing if they exactly fill the
2151 * outer Vendor-Specific attribute.
2153 * If not, create a raw Vendor-Specific.
2156 sublen = attrlen - 4;
2159 * See if we can parse it.
2165 * Don't have a type, it's bad.
2167 if (sublen < vsa_tlen) goto create_pair;
2170 * Ensure that the attribute number
2179 myattr = (subptr[0] << 8) | subptr[1];
2183 if ((subptr[0] != 0) ||
2184 (subptr[1] != 0)) goto create_pair;
2186 myattr = (subptr[2] << 8) | subptr[3];
2190 * Our dictionary is broken.
2197 * Not enough room for one more
2200 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2203 attribute = (myvendor << 16) | myattr;
2204 ptr += 4 + vsa_tlen;
2205 attrlen -= (4 + vsa_tlen);
2206 packet_length -= 4 + vsa_tlen;
2210 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2213 if (subptr[vsa_tlen] > sublen)
2215 sublen -= subptr[vsa_tlen];
2216 subptr += subptr[vsa_tlen];
2220 if (subptr[vsa_tlen] != 0) goto create_pair;
2221 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2223 if (subptr[vsa_tlen + 1] > sublen)
2225 sublen -= subptr[vsa_tlen + 1];
2226 subptr += subptr[vsa_tlen + 1];
2230 * Our dictionaries are
2236 } while (sublen > 0);
2238 vendorcode = myvendor;
2239 vendorlen = attrlen - 4;
2246 * attrlen is the length of this attribute.
2247 * total_len is the length of the encompassing
2256 attribute = (ptr[0] << 8) | ptr[1];
2259 default: /* can't hit this. */
2262 attribute |= (vendorcode << 16);
2267 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2271 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2274 default: /* can't hit this. */
2278 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2279 if (vendorlen == 0) vendorcode = 0;
2280 packet_length -= (vsa_tlen + vsa_llen);
2283 * Create the attribute, setting the default type
2284 * to 'octets'. If the type in the dictionary
2285 * is different, then the dictionary type will
2286 * over-ride this one.
2289 pair = rad_attr2vp(packet, original, secret,
2290 attribute, attrlen, ptr);
2293 pairfree(&packet->vps);
2294 librad_log("out of memory");
2306 packet_length -= attrlen;
2310 * Merge information from the outside world into our
2313 lrad_rand_seed(packet->data, AUTH_HDR_LEN);
2322 * We assume that the passwd buffer passed is big enough.
2323 * RFC2138 says the password is max 128 chars, so the size
2324 * of the passwd buffer must be at least 129 characters.
2325 * Preferably it's just MAX_STRING_LEN.
2327 * int *pwlen is updated to the new length of the encrypted
2328 * password - a multiple of 16 bytes.
2330 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2331 const uint8_t *vector)
2333 lrad_MD5_CTX context, old;
2334 uint8_t digest[AUTH_VECTOR_LEN];
2335 int i, n, secretlen;
2339 * RFC maximum is 128 bytes.
2341 * If length is zero, pad it out with zeros.
2343 * If the length isn't aligned to 16 bytes,
2344 * zero out the extra data.
2348 if (len > 128) len = 128;
2351 memset(passwd, 0, AUTH_PASS_LEN);
2352 len = AUTH_PASS_LEN;
2353 } else if ((len % AUTH_PASS_LEN) != 0) {
2354 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2355 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2360 * Use the secret to setup the decryption digest
2362 secretlen = strlen(secret);
2364 lrad_MD5Init(&context);
2365 lrad_MD5Update(&context, secret, secretlen);
2366 old = context; /* save intermediate work */
2369 * Encrypt it in place. Don't bother checking
2370 * len, as we've ensured above that it's OK.
2372 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2374 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
2375 lrad_MD5Final(digest, &context);
2378 lrad_MD5Update(&context,
2379 passwd + n - AUTH_PASS_LEN,
2381 lrad_MD5Final(digest, &context);
2384 for (i = 0; i < AUTH_PASS_LEN; i++) {
2385 passwd[i + n] ^= digest[i];
2395 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2396 const uint8_t *vector)
2398 lrad_MD5_CTX context, old;
2399 uint8_t digest[AUTH_VECTOR_LEN];
2400 int i, n, secretlen;
2403 * The RFC's say that the maximum is 128.
2404 * The buffer we're putting it into above is 254, so
2405 * we don't need to do any length checking.
2407 if (pwlen > 128) pwlen = 128;
2412 if (pwlen == 0) goto done;
2415 * Use the secret to setup the decryption digest
2417 secretlen = strlen(secret);
2419 lrad_MD5Init(&context);
2420 lrad_MD5Update(&context, secret, secretlen);
2421 old = context; /* save intermediate work */
2424 * The inverse of the code above.
2426 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2428 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2429 lrad_MD5Final(digest, &context);
2432 lrad_MD5Update(&context, passwd, AUTH_PASS_LEN);
2434 lrad_MD5Final(digest, &context);
2437 lrad_MD5Update(&context, passwd + n, AUTH_PASS_LEN);
2440 for (i = 0; i < AUTH_PASS_LEN; i++) {
2441 passwd[i + n] ^= digest[i];
2446 passwd[pwlen] = '\0';
2447 return strlen(passwd);
2452 * Encode Tunnel-Password attributes when sending them out on the wire.
2454 * int *pwlen is updated to the new length of the encrypted
2455 * password - a multiple of 16 bytes.
2457 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2460 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2461 const uint8_t *vector)
2463 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2464 unsigned char digest[AUTH_VECTOR_LEN];
2466 int i, n, secretlen;
2471 if (len > 127) len = 127;
2474 * Shift the password 3 positions right to place a salt and original
2475 * length, tag will be added automatically on packet send
2477 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2481 * save original password length as first password character;
2488 * Generate salt. The RFC's say:
2490 * The high bit of salt[0] must be set, each salt in a
2491 * packet should be unique, and they should be random
2493 * So, we set the high bit, add in a counter, and then
2494 * add in some CSPRNG data. should be OK..
2496 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2497 (lrad_rand() & 0x07));
2498 salt[1] = lrad_rand();
2501 * Padd password to multiple of AUTH_PASS_LEN bytes.
2503 n = len % AUTH_PASS_LEN;
2505 n = AUTH_PASS_LEN - n;
2506 for (; n > 0; n--, len++)
2509 /* set new password length */
2513 * Use the secret to setup the decryption digest
2515 secretlen = strlen(secret);
2516 memcpy(buffer, secret, secretlen);
2518 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2520 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2521 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2522 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2524 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2525 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2528 for (i = 0; i < AUTH_PASS_LEN; i++) {
2529 passwd[i + n2] ^= digest[i];
2537 * Decode Tunnel-Password encrypted attributes.
2539 * Defined in RFC-2868, this uses a two char SALT along with the
2540 * initial intermediate value, to differentiate it from the
2543 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2544 const uint8_t *vector)
2546 lrad_MD5_CTX context, old;
2547 uint8_t digest[AUTH_VECTOR_LEN];
2549 unsigned i, n, len, reallen;
2554 * We need at least a salt.
2557 librad_log("tunnel password is too short");
2562 * There's a salt, but no password. Or, there's a salt
2563 * and a 'data_len' octet. It's wrong, but at least we
2564 * can figure out what it means: the password is empty.
2566 * Note that this means we ignore the 'data_len' field,
2567 * if the attribute length tells us that there's no
2568 * more data. So the 'data_len' field may be wrong,
2577 len -= 2; /* discount the salt */
2580 * Use the secret to setup the decryption digest
2582 secretlen = strlen(secret);
2584 lrad_MD5Init(&context);
2585 lrad_MD5Update(&context, secret, secretlen);
2586 old = context; /* save intermediate work */
2589 * Set up the initial key:
2591 * b(1) = MD5(secret + vector + salt)
2593 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2594 lrad_MD5Update(&context, passwd, 2);
2597 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2601 lrad_MD5Final(digest, &context);
2606 * A quick check: decrypt the first octet
2607 * of the password, which is the
2608 * 'data_len' field. Ensure it's sane.
2610 reallen = passwd[2] ^ digest[0];
2611 if (reallen >= len) {
2612 librad_log("tunnel password is too long for the attribute");
2616 lrad_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2620 lrad_MD5Final(digest, &context);
2623 lrad_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2626 for (i = base; i < AUTH_PASS_LEN; i++) {
2627 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2632 * See make_tunnel_password, above.
2634 if (reallen > 239) reallen = 239;
2637 passwd[reallen] = 0;
2643 * Encode a CHAP password
2645 * FIXME: might not work with Ascend because
2646 * we use vp->length, and Ascend gear likes
2647 * to send an extra '\0' in the string!
2649 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2650 VALUE_PAIR *password)
2654 uint8_t string[MAX_STRING_LEN * 2 + 1];
2655 VALUE_PAIR *challenge;
2658 * Sanity check the input parameters
2660 if ((packet == NULL) || (password == NULL)) {
2665 * Note that the password VP can be EITHER
2666 * a User-Password attribute (from a check-item list),
2667 * or a CHAP-Password attribute (the client asking
2668 * the library to encode it).
2676 memcpy(ptr, password->vp_strvalue, password->length);
2677 ptr += password->length;
2678 i += password->length;
2681 * Use Chap-Challenge pair if present,
2682 * Request-Authenticator otherwise.
2684 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2686 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2687 i += challenge->length;
2689 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2690 i += AUTH_VECTOR_LEN;
2694 librad_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2701 * Seed the random number generator.
2703 * May be called any number of times.
2705 void lrad_rand_seed(const void *data, size_t size)
2710 * Ensure that the pool is initialized.
2712 if (!lrad_rand_initialized) {
2715 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2717 fd = open("/dev/urandom", O_RDONLY);
2723 while (total < sizeof(lrad_rand_pool.randrsl)) {
2724 this = read(fd, lrad_rand_pool.randrsl,
2725 sizeof(lrad_rand_pool.randrsl) - total);
2726 if ((this < 0) && (errno != EINTR)) break;
2727 if (this > 0) total += this;
2731 lrad_rand_pool.randrsl[0] = fd;
2732 lrad_rand_pool.randrsl[1] = time(NULL);
2733 lrad_rand_pool.randrsl[2] = errno;
2736 lrad_randinit(&lrad_rand_pool, 1);
2737 lrad_rand_pool.randcnt = 0;
2738 lrad_rand_initialized = 1;
2744 * Hash the user data
2747 if (!hash) hash = lrad_rand();
2748 hash = lrad_hash_update(data, size, hash);
2750 lrad_rand_pool.randmem[lrad_rand_pool.randcnt] ^= hash;
2755 * Return a 32-bit random number.
2757 uint32_t lrad_rand(void)
2762 * Ensure that the pool is initialized.
2764 if (!lrad_rand_initialized) {
2765 lrad_rand_seed(NULL, 0);
2768 num = lrad_rand_pool.randrsl[lrad_rand_pool.randcnt++];
2769 if (lrad_rand_pool.randcnt == 256) {
2770 lrad_isaac(&lrad_rand_pool);
2771 lrad_rand_pool.randcnt = 0;
2779 * Allocate a new RADIUS_PACKET
2781 RADIUS_PACKET *rad_alloc(int newvector)
2785 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2786 librad_log("out of memory");
2789 memset(rp, 0, sizeof(*rp));
2795 uint32_t hash, base;
2798 * Don't expose the actual contents of the random
2802 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2803 hash = lrad_rand() ^ base;
2804 memcpy(rp->vector + i, &hash, sizeof(hash));
2807 lrad_rand(); /* stir the pool again */
2813 * Free a RADIUS_PACKET
2815 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2817 RADIUS_PACKET *radius_packet;
2819 if (!radius_packet_ptr) return;
2820 radius_packet = *radius_packet_ptr;
2822 free(radius_packet->data);
2823 pairfree(&radius_packet->vps);
2825 free(radius_packet);
2827 *radius_packet_ptr = NULL;