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 The FreeRADIUS server project
23 static const char rcsid[] = "$Id$";
38 #include "libradius.h"
40 #include "udpfromto.h"
43 #ifdef HAVE_NETINET_IN_H
44 #include <netinet/in.h>
47 #include <sys/socket.h>
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
62 * The RFC says 4096 octets max, and most packets are less than 256.
64 #define MAX_PACKET_LEN 4096
67 * The maximum number of attributes which we allow in an incoming
68 * request. If there are more attributes than this, the request
71 * This helps to minimize the potential for a DoS, when an
72 * attacker spoofs Access-Request packets, which don't have a
73 * Message-Authenticator attribute. This means that the packet
74 * is unsigned, and the attacker can use resources on the server,
75 * even if the end request is rejected.
77 int librad_max_attributes = 0;
79 typedef struct radius_packet_t {
83 uint8_t vector[AUTH_VECTOR_LEN];
87 static lrad_randctx lrad_rand_pool; /* across multiple calls */
88 static volatile int lrad_rand_index = -1;
89 static unsigned int salt_offset = 0;
91 static const char *packet_codes[] = {
97 "Accounting-Response",
102 "Accounting-Message",
113 "Resource-Free-Request",
114 "Resource-Free-Response",
115 "Resource-Query-Request",
116 "Resource-Query-Response",
117 "Alternate-Resource-Reclaim-Request",
118 "NAS-Reboot-Request",
119 "NAS-Reboot-Response",
132 "Disconnect-Request",
142 "IP-Address-Allocate",
147 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
148 /*************************************************************************
150 * Function: make_secret
152 * Purpose: Build an encrypted secret value to return in a reply
153 * packet. The secret is hidden by xoring with a MD5 digest
154 * created from the shared secret and the authentication
155 * vector. We put them into MD5 in the reverse order from
156 * that used when encrypting passwords to RADIUS.
158 *************************************************************************/
159 static void make_secret(uint8_t *digest, const uint8_t *vector,
160 const char *secret, const uint8_t *value)
166 MD5Update(&context, vector, AUTH_VECTOR_LEN);
167 MD5Update(&context, secret, strlen(secret));
168 MD5Final(digest, &context);
170 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
171 digest[i] ^= value[i];
175 #define MAX_PASS_LEN (128)
176 static void make_passwd(uint8_t *output, int *outlen,
177 const uint8_t *input, int inlen,
178 const char *secret, const uint8_t *vector)
180 MD5_CTX context, old;
181 uint8_t digest[AUTH_VECTOR_LEN];
182 uint8_t passwd[MAX_PASS_LEN];
187 * If the length is zero, round it up.
193 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
195 else if ((len & 0x0f) != 0) {
201 memcpy(passwd, input, len);
202 memset(passwd + len, 0, sizeof(passwd) - len);
205 MD5Update(&context, secret, strlen(secret));
211 MD5Update(&context, vector, AUTH_PASS_LEN);
213 for (n = 0; n < len; n += AUTH_PASS_LEN) {
217 passwd + n - AUTH_PASS_LEN,
221 MD5Final(digest, &context);
222 for (i = 0; i < AUTH_PASS_LEN; i++) {
223 passwd[i + n] ^= digest[i];
227 memcpy(output, passwd, len);
230 static void make_tunnel_passwd(uint8_t *output, int *outlen,
231 const uint8_t *input, int inlen, int room,
232 const char *secret, const uint8_t *vector)
234 MD5_CTX context, old;
235 uint8_t digest[AUTH_VECTOR_LEN];
236 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
241 * Account for 2 bytes of the salt, and round the room
242 * available down to the nearest multiple of 16. Then,
243 * subtract one from that to account for the length byte,
244 * and the resulting number is the upper bound on the data
247 * We could short-cut this calculation just be forcing
248 * inlen to be no more than 239. It would work for all
249 * VSA's, as we don't pack multiple VSA's into one
252 * However, this calculation is more general, if a little
253 * complex. And it will work in the future for all possible
254 * kinds of weird attribute packing.
257 room -= (room & 0x0f);
260 if (inlen > room) inlen = room;
263 * Length of the encrypted data is password length plus
264 * one byte for the length of the password.
267 if ((len & 0x0f) != 0) {
271 *outlen = len + 2; /* account for the salt */
274 * Copy the password over.
276 memcpy(passwd + 3, input, inlen);
277 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
280 * Generate salt. The RFC's say:
282 * The high bit of salt[0] must be set, each salt in a
283 * packet should be unique, and they should be random
285 * So, we set the high bit, add in a counter, and then
286 * add in some CSPRNG data. should be OK..
288 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
289 (lrad_rand() & 0x07));
290 passwd[1] = lrad_rand();
291 passwd[2] = inlen; /* length of the password string */
294 MD5Update(&context, secret, strlen(secret));
297 MD5Update(&context, vector, AUTH_VECTOR_LEN);
298 MD5Update(&context, &passwd[0], 2);
300 for (n = 0; n < len; n += AUTH_PASS_LEN) {
304 passwd + 2 + n - AUTH_PASS_LEN,
308 MD5Final(digest, &context);
309 for (i = 0; i < AUTH_PASS_LEN; i++) {
310 passwd[i + 2 + n] ^= digest[i];
313 memcpy(output, passwd, len + 2);
318 * Parse a data structure into a RADIUS attribute.
320 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
321 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
324 int offset, len, total_length;
326 uint8_t *length_ptr, *vsa_length_ptr;
327 const uint8_t *data = NULL;
330 vendorcode = total_length = 0;
331 length_ptr = vsa_length_ptr = NULL;
334 * For interoperability, always put vendor attributes
335 * into their own VSA.
337 if ((vendorcode = VENDOR(vp->attribute)) != 0) {
339 * Build a VSA header.
341 *ptr++ = PW_VENDOR_SPECIFIC;
342 vsa_length_ptr = ptr;
344 lvalue = htonl(vendorcode);
345 memcpy(ptr, &lvalue, 4);
349 if (vendorcode == VENDORPEC_USR) {
350 lvalue = htonl(vp->attribute & 0xFFFF);
351 memcpy(ptr, &lvalue, 4);
353 length_ptr = vsa_length_ptr;
360 * We don't have two different lengths.
362 vsa_length_ptr = NULL;
364 } else if (vendorcode == VENDORPEC_LUCENT) {
366 * 16-bit attribute, 8-bit length
368 *ptr++ = ((vp->attribute >> 8) & 0xFF);
369 *ptr++ = (vp->attribute & 0xFF);
371 *vsa_length_ptr += 3;
375 } else if (vendorcode == VENDORPEC_STARENT) {
377 * 16-bit attribute, 16-bit length
378 * with the upper 8 bits of the length
381 *ptr++ = ((vp->attribute >> 8) & 0xFF);
382 *ptr++ = (vp->attribute & 0xFF);
385 *vsa_length_ptr += 4;
390 * All other VSA's are encoded the same
393 *vsa_length_ptr += 2;
399 * All other attributes are encoded as
402 *ptr++ = (vp->attribute & 0xFF);
409 if (vp->flags.has_tag) {
410 if (TAG_VALID(vp->flags.tag)) {
411 ptr[0] = vp->flags.tag & 0xff;
414 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
416 * Tunnel passwords REQUIRE a tag, even
417 * if don't have a valid tag.
421 } /* else don't write a tag */
422 } /* else the attribute doesn't have a tag */
425 * Set up the default sources for the data.
431 * Encrypted passwords can't be very long.
432 * This check also ensures that the hashed version
433 * of the password + attribute header fits into one
436 * FIXME: Print a warning message if it's too long?
438 if (vp->flags.encrypt && (len > MAX_PASS_LEN)) {
446 case PW_TYPE_IPV6ADDR:
447 case PW_TYPE_IPV6PREFIX:
448 case PW_TYPE_ABINARY:
449 /* nothing more to do */
452 case PW_TYPE_INTEGER:
453 len = 4; /* just in case */
454 lvalue = htonl(vp->lvalue);
455 memcpy(array, &lvalue, sizeof(lvalue));
458 * Perhaps discard the first octet.
460 data = &array[offset];
465 data = (const uint8_t *) &vp->lvalue;
466 len = 4; /* just in case */
470 * There are no tagged date attributes.
473 lvalue = htonl(vp->lvalue);
474 data = (const uint8_t *) &lvalue;
475 len = 4; /* just in case */
478 default: /* unknown type: ignore it */
479 librad_log("ERROR: Unknown attribute type %d", vp->type);
484 * Bound the data to 255 bytes.
486 if (len + offset + total_length > 255) {
487 len = 255 - offset - total_length;
491 * Encrypt the various password styles
493 * Attributes with encrypted values MUST be less than
496 switch (vp->flags.encrypt) {
497 case FLAG_ENCRYPT_USER_PASSWORD:
498 make_passwd(ptr + offset, &len,
500 secret, packet->vector);
503 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
505 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
510 * Check if 255 - offset - total_length is less
511 * than 18. If so, we can't fit the data into
512 * the available space, and we discard the
515 * This is ONLY a problem if we have multiple VSA's
516 * in one Vendor-Specific, though.
518 if ((255 - offset - total_length) < 18) return 0;
521 * Can't make the password, suppress it.
523 make_tunnel_passwd(ptr + offset, &len,
524 data, len, 255 - offset - total_length,
525 secret, original->vector);
529 * The code above ensures that this attribute
532 case FLAG_ENCRYPT_ASCEND_SECRET:
533 make_secret(ptr + offset, packet->vector,
535 len = AUTH_VECTOR_LEN;
541 * Just copy the data over
543 memcpy(ptr + offset, data, len);
545 } /* switch over encryption flags */
548 * Account for the tag (if any).
553 * RFC 2865 section 5 says that zero-length attributes
556 if (len == 0) return 0;
559 * Update the various lengths.
562 if (vsa_length_ptr) *vsa_length_ptr += len;
566 return total_length; /* of attribute */
573 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
576 radius_packet_t *hdr;
578 uint16_t total_length;
583 * For simplicity in the following logic, we allow
584 * the attributes to "overflow" the 4k maximum
585 * RADIUS packet size, by one attribute.
587 * It's uint32_t, for alignment purposes.
589 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
592 * Double-check some things based on packet code.
594 switch (packet->code) {
595 case PW_AUTHENTICATION_ACK:
596 case PW_AUTHENTICATION_REJECT:
597 case PW_ACCESS_CHALLENGE:
599 librad_log("ERROR: Cannot sign response packet without a request packet.");
605 * These packet vectors start off as all zero.
607 case PW_ACCOUNTING_REQUEST:
608 case PW_DISCONNECT_REQUEST:
610 memset(packet->vector, 0, sizeof(packet->vector));
618 * Use memory on the stack, until we know how
619 * large the packet will be.
621 hdr = (radius_packet_t *) data;
624 * Build standard header
626 hdr->code = packet->code;
627 hdr->id = packet->id;
629 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
631 total_length = AUTH_HDR_LEN;
632 packet->verified = 0;
635 * Load up the configuration values for the user
640 * FIXME: Loop twice over the reply list. The first time,
641 * calculate the total length of data. The second time,
642 * allocate the memory, and fill in the VP's.
644 * Hmm... this may be slower than just doing a small
649 * Loop over the reply attributes for the packet.
651 for (reply = packet->vps; reply; reply = reply->next) {
653 * Ignore non-wire attributes
655 if ((VENDOR(reply->attribute) == 0) &&
656 ((reply->attribute & 0xFFFF) > 0xff)) {
661 * Set the Message-Authenticator to the correct
662 * length and initial value.
664 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
665 reply->length = AUTH_VECTOR_LEN;
666 memset(reply->strvalue, 0, AUTH_VECTOR_LEN);
667 packet->verified = total_length; /* HACK! */
671 * Print out ONLY the attributes which
672 * we're sending over the wire, and print
673 * them out BEFORE they're encrypted.
677 len = rad_vp2attr(packet, original, secret, reply, ptr);
678 if (len < 0) return -1;
681 * Check that the packet is no more than 4k in
682 * size, AFTER writing the attribute past the 4k
683 * boundary, but BEFORE deciding to increase the
684 * size of the packet. Note that the 'data'
685 * buffer, above, is one attribute longer than
686 * necessary, in order to permit this overflow.
688 if ((total_length + len) > MAX_PACKET_LEN) {
694 } /* done looping over all attributes */
697 * Fill in the rest of the fields, and copy the data over
698 * from the local stack to the newly allocated memory.
700 * Yes, all this 'memcpy' is slow, but it means
701 * that we only allocate the minimum amount of
702 * memory for a request.
704 packet->data_len = total_length;
705 packet->data = (uint8_t *) malloc(packet->data_len);
707 librad_log("Out of memory");
711 memcpy(packet->data, data, packet->data_len);
712 hdr = (radius_packet_t *) packet->data;
714 total_length = htons(total_length);
715 memcpy(hdr->length, &total_length, sizeof(total_length));
722 * Sign a previously encoded packet.
724 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
727 radius_packet_t *hdr = (radius_packet_t *)packet->data;
730 * It wasn't assigned an Id, this is bad!
732 if (packet->id < 0) {
733 librad_log("ERROR: RADIUS packets must be assigned an Id.");
737 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
738 (packet->verified < 0)) {
739 librad_log("ERROR: You must call rad_encode() before rad_sign()");
744 * If there's a Message-Authenticator, update it
745 * now, BEFORE updating the authentication vector.
749 if (packet->verified > 0) {
750 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
752 switch (packet->code) {
753 case PW_ACCOUNTING_REQUEST:
754 case PW_ACCOUNTING_RESPONSE:
755 case PW_DISCONNECT_REQUEST:
756 case PW_DISCONNECT_ACK:
757 case PW_DISCONNECT_NAK:
761 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
764 case PW_AUTHENTICATION_ACK:
765 case PW_AUTHENTICATION_REJECT:
766 case PW_ACCESS_CHALLENGE:
768 librad_log("ERROR: Cannot sign response packet without a request packet.");
771 memcpy(hdr->vector, original->vector,
775 default: /* others have vector already set to zero */
781 * Set the authentication vector to zero,
782 * calculate the signature, and put it
783 * into the Message-Authenticator
786 lrad_hmac_md5(packet->data, packet->data_len,
787 secret, strlen(secret),
789 memcpy(packet->data + packet->verified + 2,
790 calc_auth_vector, AUTH_VECTOR_LEN);
793 * Copy the original request vector back
796 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
800 * Switch over the packet code, deciding how to
803 switch (packet->code) {
805 * Request packets are not signed, bur
806 * have a random authentication vector.
808 case PW_AUTHENTICATION_REQUEST:
809 case PW_STATUS_SERVER:
813 * Reply packets are signed with the
814 * authentication vector of the request.
822 MD5Update(&context, packet->data, packet->data_len);
823 MD5Update(&context, secret, strlen(secret));
824 MD5Final(digest, &context);
826 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
827 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
830 }/* switch over packet codes */
836 * Reply to the request. Also attach
837 * reply attribute value pairs and any user message provided.
839 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
845 struct sockaddr_in saremote;
846 struct sockaddr_in *sa;
849 * Maybe it's a fake packet. Don't send it.
851 if (!packet || (packet->sockfd < 0)) {
855 if ((packet->code > 0) && (packet->code < 52)) {
856 what = packet_codes[packet->code];
862 * First time through, allocate room for the packet
865 DEBUG("Sending %s of id %d to %s port %d\n",
867 ip_ntoa(ip_buffer, packet->dst_ipaddr),
873 if (rad_encode(packet, original, secret) < 0) {
878 * Re-sign it, including updating the
879 * Message-Authenticator.
881 if (rad_sign(packet, original, secret) < 0) {
886 * If packet->data points to data, then we print out
887 * the VP list again only for debugging.
889 } else if (librad_debug) {
890 DEBUG("Re-sending %s of id %d to %s port %d\n", what, packet->id,
891 ip_ntoa(ip_buffer, packet->dst_ipaddr),
894 for (reply = packet->vps; reply; reply = reply->next) {
895 /* FIXME: ignore attributes > 0xff */
901 * And send it on it's way.
903 sa = (struct sockaddr_in *) &saremote;
904 memset ((char *) sa, '\0', sizeof (saremote));
905 sa->sin_family = AF_INET;
906 sa->sin_addr.s_addr = packet->dst_ipaddr;
907 sa->sin_port = htons(packet->dst_port);
908 #ifndef WITH_UDPFROMTO
909 return sendto(packet->sockfd, packet->data, (int)packet->data_len, 0,
910 (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
913 struct sockaddr_in salocal;
914 memset ((char *) &salocal, '\0', sizeof (salocal));
915 salocal.sin_family = AF_INET;
916 salocal.sin_addr.s_addr = packet->src_ipaddr;
918 return sendfromto(packet->sockfd, packet->data, (int)packet->data_len, 0,
919 (struct sockaddr *)&salocal, sizeof(struct sockaddr_in),
920 (struct sockaddr *)&saremote, sizeof(struct sockaddr_in));
927 * Validates the requesting client NAS. Calculates the
928 * signature based on the clients private key.
930 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
932 u_char digest[AUTH_VECTOR_LEN];
936 * Older clients have the authentication vector set to
937 * all zeros. Return `1' in that case.
939 memset(digest, 0, sizeof(digest));
940 if (memcmp(packet->vector, digest, AUTH_VECTOR_LEN) == 0) {
941 packet->verified = 1;
946 * Zero out the auth_vector in the received packet.
947 * Then append the shared secret to the received packet,
948 * and calculate the MD5 sum. This must be the same
949 * as the original MD5 sum (packet->vector).
951 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
954 * MD5(packet + secret);
957 MD5Update(&context, packet->data, packet->data_len);
958 MD5Update(&context, secret, strlen(secret));
959 MD5Final(digest, &context);
962 * Return 0 if OK, 2 if not OK.
965 memcmp(digest, packet->vector, AUTH_VECTOR_LEN) ? 2 : 0;
967 return packet->verified;
971 * Validates the requesting client NAS. Calculates the
972 * signature based on the clients private key.
974 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
977 uint8_t calc_digest[AUTH_VECTOR_LEN];
983 if (original == NULL) {
988 * Copy the original vector in place.
990 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
993 * MD5(packet + secret);
996 MD5Update(&context, packet->data, packet->data_len);
997 MD5Update(&context, secret, strlen(secret));
998 MD5Final(calc_digest, &context);
1001 * Copy the packet's vector back to the packet.
1003 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1006 * Return 0 if OK, 2 if not OK.
1009 memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) ? 2 : 0;
1010 return packet->verified;
1014 * Receive UDP client requests, and fill in
1015 * the basics of a RADIUS_PACKET structure.
1017 RADIUS_PACKET *rad_recv(int fd)
1019 RADIUS_PACKET *packet;
1020 struct sockaddr_in saremote;
1025 radius_packet_t *hdr;
1026 char host_ipaddr[16];
1029 uint8_t data[MAX_PACKET_LEN];
1033 * Allocate the new request data structure
1035 if ((packet = malloc(sizeof(RADIUS_PACKET))) == NULL) {
1036 librad_log("out of memory");
1039 memset(packet, 0, sizeof(RADIUS_PACKET));
1042 * Receive the packet.
1044 salen = sizeof(saremote);
1045 memset(&saremote, 0, sizeof(saremote));
1046 #ifndef WITH_UDPFROMTO
1047 packet->data_len = recvfrom(fd, data, sizeof(data),
1048 0, (struct sockaddr *)&saremote, &salen);
1049 packet->dst_ipaddr = htonl(INADDR_ANY); /* i.e. unknown */
1052 socklen_t salen_local;
1053 struct sockaddr_in salocal;
1054 salen_local = sizeof(salocal);
1055 memset(&salocal, 0, sizeof(salocal));
1056 packet->data_len = recvfromto(fd, data, sizeof(data), 0,
1057 (struct sockaddr *)&saremote, &salen,
1058 (struct sockaddr *)&salocal, &salen_local);
1059 packet->dst_ipaddr = salocal.sin_addr.s_addr;
1064 * Check for socket errors.
1066 if (packet->data_len < 0) {
1067 librad_log("Error receiving packet: %s", strerror(errno));
1073 * Fill IP header fields. We need these for the error
1074 * messages which may come later.
1076 packet->sockfd = fd;
1077 packet->src_ipaddr = saremote.sin_addr.s_addr;
1078 packet->src_port = ntohs(saremote.sin_port);
1081 * FIXME: Do even more filtering by only permitting
1082 * certain IP's. The problem is that we don't know
1083 * how to do this properly for all possible clients...
1087 * Explicitely set the VP list to empty.
1092 * Check for packets smaller than the packet header.
1094 * RFC 2865, Section 3., subsection 'length' says:
1096 * "The minimum length is 20 ..."
1098 if (packet->data_len < AUTH_HDR_LEN) {
1099 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1100 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1101 packet->data_len, AUTH_HDR_LEN);
1107 * RFC 2865, Section 3., subsection 'length' says:
1109 * " ... and maximum length is 4096."
1111 if (packet->data_len > MAX_PACKET_LEN) {
1112 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1113 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1114 packet->data_len, MAX_PACKET_LEN);
1120 * Check for packets with mismatched size.
1121 * i.e. We've received 128 bytes, and the packet header
1122 * says it's 256 bytes long.
1124 totallen = (data[2] << 8) | data[3];
1125 hdr = (radius_packet_t *)data;
1128 * Code of 0 is not understood.
1129 * Code of 16 or greate is not understood.
1131 if ((hdr->code == 0) ||
1132 (hdr->code >= 52)) {
1133 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1134 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1141 * Message-Authenticator is required in Status-Server
1142 * packets, otherwise they can be trivially forged.
1144 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1147 * Repeat the length checks. This time, instead of
1148 * looking at the data we received, look at the value
1149 * of the 'length' field inside of the packet.
1151 * Check for packets smaller than the packet header.
1153 * RFC 2865, Section 3., subsection 'length' says:
1155 * "The minimum length is 20 ..."
1157 if (totallen < AUTH_HDR_LEN) {
1158 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1159 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1160 totallen, AUTH_HDR_LEN);
1166 * And again, for the value of the 'length' field.
1168 * RFC 2865, Section 3., subsection 'length' says:
1170 * " ... and maximum length is 4096."
1172 if (totallen > MAX_PACKET_LEN) {
1173 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1174 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1175 totallen, MAX_PACKET_LEN);
1181 * RFC 2865, Section 3., subsection 'length' says:
1183 * "If the packet is shorter than the Length field
1184 * indicates, it MUST be silently discarded."
1186 * i.e. No response to the NAS.
1188 if (packet->data_len < totallen) {
1189 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1190 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1191 packet->data_len, totallen);
1197 * RFC 2865, Section 3., subsection 'length' says:
1199 * "Octets outside the range of the Length field MUST be
1200 * treated as padding and ignored on reception."
1202 if (packet->data_len > totallen) {
1204 * We're shortening the packet below, but just
1205 * to be paranoid, zero out the extra data.
1207 memset(data + totallen, 0, packet->data_len - totallen);
1208 packet->data_len = totallen;
1212 * Walk through the packet's attributes, ensuring that
1213 * they add up EXACTLY to the size of the packet.
1215 * If they don't, then the attributes either under-fill
1216 * or over-fill the packet. Any parsing of the packet
1217 * is impossible, and will result in unknown side effects.
1219 * This would ONLY happen with buggy RADIUS implementations,
1220 * or with an intentional attack. Either way, we do NOT want
1221 * to be vulnerable to this problem.
1224 count = totallen - AUTH_HDR_LEN;
1229 * Attribute number zero is NOT defined.
1232 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1233 ip_ntoa(host_ipaddr, packet->src_ipaddr));
1239 * Attributes are at LEAST as long as the ID & length
1240 * fields. Anything shorter is an invalid attribute.
1243 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1244 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1251 * Sanity check the attributes for length.
1254 default: /* don't do anything by default */
1259 * If there's an EAP-Message, we require
1260 * a Message-Authenticator.
1262 case PW_EAP_MESSAGE:
1266 case PW_MESSAGE_AUTHENTICATOR:
1267 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1268 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1269 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1279 * FIXME: Look up the base 255 attributes in the
1280 * dictionary, and switch over their type. For
1281 * integer/date/ip, the attribute length SHOULD
1284 count -= attr[1]; /* grab the attribute length */
1286 num_attributes++; /* seen one more attribute */
1290 * If the attributes add up to a packet, it's allowed.
1292 * If not, we complain, and throw the packet away.
1295 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1296 ip_ntoa(host_ipaddr, packet->src_ipaddr));
1302 * If we're configured to look for a maximum number of
1303 * attributes, and we've seen more than that maximum,
1304 * then throw the packet away, as a possible DoS.
1306 if ((librad_max_attributes > 0) &&
1307 (num_attributes > librad_max_attributes)) {
1308 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1309 ip_ntoa(host_ipaddr, packet->src_ipaddr),
1310 num_attributes, librad_max_attributes);
1316 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1318 * A packet with an EAP-Message attribute MUST also have
1319 * a Message-Authenticator attribute.
1321 * A Message-Authenticator all by itself is OK, though.
1323 * Similarly, Status-Server packets MUST contain
1324 * Message-Authenticator attributes.
1326 if (require_ma && ! seen_ma) {
1327 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1328 ip_ntoa(host_ipaddr, packet->src_ipaddr));
1334 if ((hdr->code > 0) && (hdr->code < 52)) {
1335 printf("rad_recv: %s packet from host %s:%d",
1336 packet_codes[hdr->code],
1337 ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port);
1339 printf("rad_recv: Packet from host %s:%d code=%d",
1340 ip_ntoa(host_ipaddr, packet->src_ipaddr), packet->src_port,
1343 printf(", id=%d, length=%d\n", hdr->id, totallen);
1347 * Fill RADIUS header fields
1349 packet->code = hdr->code;
1350 packet->id = hdr->id;
1351 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1354 * Now that we've sanity checked the packet, we can allocate
1355 * memory for it, and copy the data from the local area to
1356 * the packet buffer.
1358 if ((packet->data = malloc(packet->data_len)) == NULL) {
1360 librad_log("out of memory");
1363 memcpy(packet->data, data, packet->data_len);
1370 * Verify the signature of a packet.
1372 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1379 if (!packet || !packet->data) return -1;
1382 * Before we allocate memory for the attributes, do more
1385 ptr = packet->data + AUTH_HDR_LEN;
1386 length = packet->data_len - AUTH_HDR_LEN;
1387 while (length > 0) {
1388 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1389 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1394 default: /* don't do anything. */
1398 * Note that more than one Message-Authenticator
1399 * attribute is invalid.
1401 case PW_MESSAGE_AUTHENTICATOR:
1402 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1403 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1405 switch (packet->code) {
1409 case PW_ACCOUNTING_REQUEST:
1410 case PW_ACCOUNTING_RESPONSE:
1411 case PW_DISCONNECT_REQUEST:
1412 case PW_DISCONNECT_ACK:
1413 case PW_DISCONNECT_NAK:
1414 case PW_COA_REQUEST:
1417 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1420 case PW_AUTHENTICATION_ACK:
1421 case PW_AUTHENTICATION_REJECT:
1422 case PW_ACCESS_CHALLENGE:
1424 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1427 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1431 lrad_hmac_md5(packet->data, packet->data_len,
1432 secret, strlen(secret), calc_auth_vector);
1433 if (memcmp(calc_auth_vector, msg_auth_vector,
1434 sizeof(calc_auth_vector)) != 0) {
1436 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1437 ip_ntoa(buffer, packet->src_ipaddr));
1438 /* Silently drop packet, according to RFC 3579 */
1440 } /* else the message authenticator was good */
1443 * Reinitialize Authenticators.
1445 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1446 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1448 } /* switch over the attributes */
1452 } /* loop over the packet, sanity checking the attributes */
1455 * Calculate and/or verify digest.
1457 switch(packet->code) {
1460 case PW_AUTHENTICATION_REQUEST:
1461 case PW_STATUS_SERVER:
1462 case PW_DISCONNECT_REQUEST:
1464 * The authentication vector is random
1465 * nonsense, invented by the client.
1469 case PW_ACCOUNTING_REQUEST:
1470 if (calc_acctdigest(packet, secret) > 1) {
1472 librad_log("Received Accounting-Request packet "
1473 "from %s with invalid signature! (Shared secret is incorrect.)",
1474 ip_ntoa(buffer, packet->src_ipaddr));
1479 /* Verify the reply digest */
1480 case PW_AUTHENTICATION_ACK:
1481 case PW_AUTHENTICATION_REJECT:
1482 case PW_ACCESS_CHALLENGE:
1483 case PW_ACCOUNTING_RESPONSE:
1484 rcode = calc_replydigest(packet, original, secret);
1487 librad_log("Received %s packet "
1488 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1489 packet_codes[packet->code],
1490 ip_ntoa(buffer, packet->src_ipaddr),
1503 * Parse a RADIUS attribute into a data structure.
1505 static VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1506 const char *secret, int attribute, int length,
1507 const uint8_t *data)
1512 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1517 * If length is greater than 253, something is SERIOUSLY
1520 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1522 vp->length = length;
1523 vp->operator = T_OP_EQ;
1529 if (vp->flags.has_tag) {
1530 if (TAG_VALID(data[0]) ||
1531 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1533 * Tunnel passwords REQUIRE a tag, even
1534 * if don't have a valid tag.
1536 vp->flags.tag = data[0];
1538 if ((vp->type == PW_TYPE_STRING) ||
1539 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1544 * Copy the data to be decrypted
1546 memcpy(&vp->strvalue[0], data + offset, length - offset);
1547 vp->length -= offset;
1550 * Decrypt the attribute.
1552 switch (vp->flags.encrypt) {
1556 case FLAG_ENCRYPT_USER_PASSWORD:
1558 rad_pwdecode((char *)vp->strvalue,
1562 rad_pwdecode((char *)vp->strvalue,
1566 if (vp->attribute == PW_USER_PASSWORD) {
1567 vp->length = strlen(vp->strvalue);
1572 * Tunnel-Password's may go ONLY
1573 * in response packets.
1575 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1576 if (!original) goto raw;
1578 if (rad_tunnel_pwdecode(vp->strvalue, &vp->length,
1579 secret, original->vector) < 0) {
1585 * Ascend-Send-Secret
1586 * Ascend-Receive-Secret
1588 case FLAG_ENCRYPT_ASCEND_SECRET:
1592 uint8_t my_digest[AUTH_VECTOR_LEN];
1593 make_secret(my_digest,
1596 memcpy(vp->strvalue, my_digest,
1598 vp->strvalue[AUTH_VECTOR_LEN] = '\0';
1599 vp->length = strlen(vp->strvalue);
1605 } /* switch over encryption flags */
1609 case PW_TYPE_STRING:
1610 case PW_TYPE_OCTETS:
1611 case PW_TYPE_ABINARY:
1612 /* nothing more to do */
1615 case PW_TYPE_INTEGER:
1616 if (vp->length != 4) goto raw;
1618 memcpy(&vp->lvalue, vp->strvalue, 4);
1619 vp->lvalue = ntohl(vp->lvalue);
1621 if (vp->flags.has_tag) vp->lvalue &= 0x00ffffff;
1624 * Try to get named VALUEs
1628 dval = dict_valbyattr(vp->attribute,
1631 strNcpy(vp->strvalue,
1633 sizeof(vp->strvalue));
1639 if (vp->length != 4) goto raw;
1641 memcpy(&vp->lvalue, vp->strvalue, 4);
1642 vp->lvalue = ntohl(vp->lvalue);
1646 * IPv4 address. Keep it in network byte order in
1647 * vp->lvalue and put ASCII IP address in standard
1648 * dot notation into vp->strvalue.
1650 case PW_TYPE_IPADDR:
1651 if (vp->length != 4) goto raw;
1653 memcpy(&vp->lvalue, vp->strvalue, 4);
1654 ip_ntoa(vp->strvalue, vp->lvalue);
1658 * IPv6 interface ID is 8 octets long.
1661 if (vp->length != 8) goto raw;
1662 /* vp->vp_ifid == vp->strvalue */
1666 * IPv6 addresses are 16 octets long
1668 case PW_TYPE_IPV6ADDR:
1669 if (vp->length != 16) goto raw;
1670 /* vp->vp_ipv6addr == vp->strvalue */
1674 * IPv6 prefixes are 2 to 18 octets long.
1676 * RFC 3162: The first octet is unused.
1677 * The second is the length of the prefix
1678 * the rest are the prefix data.
1680 * The prefix length can have value 0 to 128.
1682 case PW_TYPE_IPV6PREFIX:
1683 if (vp->length < 2 || vp->length > 18) goto raw;
1684 if (vp->strvalue[1] > 128) goto raw;
1687 * FIXME: double-check that
1688 * (vp->strvalue[1] >> 3) matches vp->length + 2
1690 if (vp->length < 18) {
1691 memset(vp->strvalue + vp->length, 0,
1698 vp->type = PW_TYPE_OCTETS;
1699 vp->length = length;
1700 memcpy(vp->strvalue, data, length);
1704 * Ensure there's no encryption or tag stuff,
1705 * we just pass the attribute as-is.
1707 memset(&vp->flags, 0, sizeof(vp->flags));
1715 * Calculate/check digest, and decode radius attributes.
1717 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1721 uint32_t vendorcode;
1729 radius_packet_t *hdr;
1730 int vsa_tlen, vsa_llen;
1731 DICT_VENDOR *dv = NULL;
1734 * Extract attribute-value pairs
1736 hdr = (radius_packet_t *)packet->data;
1738 packet_length = packet->data_len - AUTH_HDR_LEN;
1741 * There may be VP's already in the packet. Don't
1744 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
1750 vsa_tlen = vsa_llen = 1;
1753 * We have to read at least two bytes.
1755 * rad_recv() above ensures that this is OK.
1757 while (packet_length > 0) {
1762 * Normal attribute, handle it like normal.
1764 if (vendorcode == 0) {
1766 * No room to read attr/length,
1767 * or bad attribute, or attribute is
1768 * too short, or attribute is too long,
1769 * stop processing the packet.
1771 if ((packet_length < 2) ||
1772 (ptr[0] == 0) || (ptr[1] < 2) ||
1773 (ptr[1] > packet_length)) break;
1781 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
1784 * No vendor code, or ONLY vendor code.
1786 if (attrlen <= 4) goto create_pair;
1792 * Handle Vendor-Specific
1794 if (vendorlen == 0) {
1800 * attrlen was checked above.
1802 memcpy(&lvalue, ptr, 4);
1803 myvendor = ntohl(lvalue);
1806 * Zero isn't allowed.
1808 if (myvendor == 0) goto create_pair;
1811 * This is an implementation issue.
1812 * We currently pack vendor into the upper
1813 * 16 bits of a 32-bit attribute number,
1814 * so we can't handle vendor numbers larger
1817 if (myvendor > 65535) goto create_pair;
1819 vsa_tlen = vsa_llen = 1;
1820 dv = dict_vendorbyvalue(myvendor);
1822 vsa_tlen = dv->type;
1823 vsa_llen = dv->length;
1827 * Sweep through the list of VSA's,
1828 * seeing if they exactly fill the
1829 * outer Vendor-Specific attribute.
1831 * If not, create a raw Vendor-Specific.
1834 sublen = attrlen - 4;
1837 * See if we can parse it.
1843 * Don't have a type, it's bad.
1845 if (sublen < vsa_tlen) goto create_pair;
1848 * Ensure that the attribute number
1857 myattr = (subptr[0] << 8) | subptr[1];
1861 if ((subptr[0] != 0) ||
1862 (subptr[1] != 0)) goto create_pair;
1864 myattr = (subptr[2] << 8) | subptr[3];
1868 * Our dictionary is broken.
1875 * Not enough room for one more
1878 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
1881 attribute = (myvendor << 16) | myattr;
1882 ptr += 4 + vsa_tlen;
1883 attrlen -= (4 + vsa_tlen);
1884 packet_length -= 4 + vsa_tlen;
1888 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
1891 if (subptr[vsa_tlen] > sublen)
1893 sublen -= subptr[vsa_tlen];
1894 subptr += subptr[vsa_tlen];
1898 if (subptr[vsa_tlen] != 0) goto create_pair;
1899 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
1901 if (subptr[vsa_tlen + 1] > sublen)
1903 sublen -= subptr[vsa_tlen + 1];
1904 subptr += subptr[vsa_tlen + 1];
1908 * Our dictionaries are
1914 } while (sublen > 0);
1916 vendorcode = myvendor;
1917 vendorlen = attrlen - 4;
1924 * attrlen is the length of this attribute.
1925 * total_len is the length of the encompassing
1934 attribute = (ptr[0] << 8) | ptr[1];
1937 default: /* can't hit this. */
1940 attribute |= (vendorcode << 16);
1945 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
1949 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
1952 default: /* can't hit this. */
1956 vendorlen -= vsa_tlen + vsa_llen + attrlen;
1957 if (vendorlen == 0) vendorcode = 0;
1958 packet_length -= (vsa_tlen + vsa_llen);
1961 * Create the attribute, setting the default type
1962 * to 'octects'. If the type in the dictionary
1963 * is different, then the dictionary type will
1964 * over-ride this one.
1967 pair = rad_attr2vp(packet, original, secret,
1968 attribute, attrlen, ptr);
1970 pairfree(&packet->vps);
1971 librad_log("out of memory");
1980 packet_length -= attrlen;
1984 * Merge information from the outside world into our
1987 lrad_rand_seed(packet->data, AUTH_HDR_LEN);
1996 * We assume that the passwd buffer passed is big enough.
1997 * RFC2138 says the password is max 128 chars, so the size
1998 * of the passwd buffer must be at least 129 characters.
1999 * Preferably it's just MAX_STRING_LEN.
2001 * int *pwlen is updated to the new length of the encrypted
2002 * password - a multiple of 16 bytes.
2004 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2007 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
2008 char digest[AUTH_VECTOR_LEN];
2009 int i, n, secretlen;
2013 * Pad password to multiple of AUTH_PASS_LEN bytes.
2016 if (len > 128) len = 128;
2018 if (len % AUTH_PASS_LEN != 0) {
2019 n = AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2020 for (i = len; n > 0; n--, i++)
2024 } else if (len == 0) {
2025 memset(passwd, 0, AUTH_PASS_LEN);
2026 *pwlen = len = AUTH_PASS_LEN;
2030 * Use the secret to setup the decryption digest
2032 secretlen = strlen(secret);
2033 memcpy(buffer, secret, secretlen);
2034 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2035 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
2038 * Now we can encode the password *in place*
2040 for (i = 0; i < AUTH_PASS_LEN; i++)
2041 passwd[i] ^= digest[i];
2043 if (len <= AUTH_PASS_LEN) return 0;
2046 * Length > AUTH_PASS_LEN, so we need to use the extended
2049 for (n = 0; n < 128 && n <= (len - AUTH_PASS_LEN); n += AUTH_PASS_LEN) {
2050 memcpy(buffer + secretlen, passwd + n, AUTH_PASS_LEN);
2051 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
2052 for (i = 0; i < AUTH_PASS_LEN; i++)
2053 passwd[i + n + AUTH_PASS_LEN] ^= digest[i];
2062 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2065 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 1];
2066 char digest[AUTH_VECTOR_LEN];
2067 char r[AUTH_VECTOR_LEN];
2069 int i, n, secretlen;
2073 * Use the secret to setup the decryption digest
2075 secretlen = strlen(secret);
2076 memcpy(buffer, secret, secretlen);
2077 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2078 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_VECTOR_LEN);
2081 * Now we can decode the password *in place*
2083 memcpy(r, passwd, AUTH_PASS_LEN);
2084 for (i = 0; i < AUTH_PASS_LEN && i < pwlen; i++)
2085 passwd[i] ^= digest[i];
2087 if (pwlen <= AUTH_PASS_LEN) {
2088 passwd[pwlen+1] = 0;
2093 * Length > AUTH_PASS_LEN, so we need to use the extended
2096 rlen = ((pwlen - 1) / AUTH_PASS_LEN) * AUTH_PASS_LEN;
2098 for (n = rlen; n > 0; n -= AUTH_PASS_LEN ) {
2099 s = (n == AUTH_PASS_LEN) ? r : (passwd + n - AUTH_PASS_LEN);
2100 memcpy(buffer + secretlen, s, AUTH_PASS_LEN);
2101 librad_md5_calc((u_char *)digest, buffer, secretlen + AUTH_PASS_LEN);
2102 for (i = 0; i < AUTH_PASS_LEN && (i + n) < pwlen; i++)
2103 passwd[i + n] ^= digest[i];
2112 * Encode Tunnel-Password attributes when sending them out on the wire.
2114 * int *pwlen is updated to the new length of the encrypted
2115 * password - a multiple of 16 bytes.
2117 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2120 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2123 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2124 unsigned char digest[AUTH_VECTOR_LEN];
2126 int i, n, secretlen;
2131 if (len > 127) len = 127;
2133 * Shift the password 3 positions right to place a salt and original
2134 * length, tag will be added automatically on packet send
2136 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2140 * save original password length as first password character;
2147 * Generate salt. The RFC's say:
2149 * The high bit of salt[0] must be set, each salt in a
2150 * packet should be unique, and they should be random
2152 * So, we set the high bit, add in a counter, and then
2153 * add in some CSPRNG data. should be OK..
2155 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2156 (lrad_rand() & 0x07));
2157 salt[1] = lrad_rand();
2160 * Padd password to multiple of AUTH_PASS_LEN bytes.
2162 n = len % AUTH_PASS_LEN;
2164 n = AUTH_PASS_LEN - n;
2165 for (; n > 0; n--, len++)
2168 /* set new password length */
2172 * Use the secret to setup the decryption digest
2174 secretlen = strlen(secret);
2175 memcpy(buffer, secret, secretlen);
2177 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2179 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2180 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2181 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2183 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2184 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2187 for (i = 0; i < AUTH_PASS_LEN; i++) {
2188 passwd[i + n2] ^= digest[i];
2196 * Decode Tunnel-Password encrypted attributes.
2198 * Defined in RFC-2868, this uses a two char SALT along with the
2199 * initial intermediate value, to differentiate it from the
2202 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2205 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2206 uint8_t digest[AUTH_VECTOR_LEN];
2207 uint8_t decrypted[MAX_STRING_LEN + 1];
2214 * We need at least a salt.
2217 librad_log("tunnel password is too short");
2222 * There's a salt, but no password. Or, there's a salt
2223 * and a 'data_len' octet. It's wrong, but at least we
2224 * can figure out what it means: the password is empty.
2226 * Note that this means we ignore the 'data_len' field,
2227 * if the attribute length tells us that there's no
2228 * more data. So the 'data_len' field may be wrong,
2237 len -= 2; /* discount the salt */
2240 * Use the secret to setup the decryption digest
2242 secretlen = strlen(secret);
2245 * Set up the initial key:
2247 * b(1) = MD5(secret + vector + salt)
2249 memcpy(buffer, secret, secretlen);
2250 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2251 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, passwd, 2);
2252 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2255 * A quick check: decrypt the first octet of the password,
2256 * which is the 'data_len' field. Ensure it's sane.
2258 * 'n' doesn't include the 'data_len' octet
2261 n = passwd[2] ^ digest[0];
2263 librad_log("tunnel password is too long for the attribute");
2268 * Loop over the data, decrypting it, and generating
2269 * the key for the next round of decryption.
2271 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2272 for (i = 0; i < AUTH_PASS_LEN; i++) {
2273 decrypted[n + i] = passwd[n + i + 2] ^ digest[i];
2276 * Encrypted password may not be aligned
2277 * on 16 octets, so we catch that here...
2279 if ((n + i) == len) break;
2283 * Update the digest, based on
2285 * b(n) = MD5(secret + cleartext(n-1)
2287 * but only if there's more data...
2289 memcpy(buffer + secretlen, passwd + n + 2, AUTH_PASS_LEN);
2290 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2294 * We've already validated the length of the decrypted
2295 * password. Copy it back to the caller.
2297 memcpy(passwd, decrypted + 1, decrypted[0]);
2298 passwd[decrypted[0]] = 0;
2299 *pwlen = decrypted[0];
2301 return decrypted[0];
2305 * Encode a CHAP password
2307 * FIXME: might not work with Ascend because
2308 * we use vp->length, and Ascend gear likes
2309 * to send an extra '\0' in the string!
2311 int rad_chap_encode(RADIUS_PACKET *packet, char *output, int id,
2312 VALUE_PAIR *password)
2316 char string[MAX_STRING_LEN * 2 + 1];
2317 VALUE_PAIR *challenge;
2320 * Sanity check the input parameters
2322 if ((packet == NULL) || (password == NULL)) {
2327 * Note that the password VP can be EITHER
2328 * a User-Password attribute (from a check-item list),
2329 * or a CHAP-Password attribute (the client asking
2330 * the library to encode it).
2338 memcpy(ptr, password->strvalue, password->length);
2339 ptr += password->length;
2340 i += password->length;
2343 * Use Chap-Challenge pair if present,
2344 * Request-Authenticator otherwise.
2346 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2348 memcpy(ptr, challenge->strvalue, challenge->length);
2349 i += challenge->length;
2351 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2352 i += AUTH_VECTOR_LEN;
2356 librad_md5_calc((u_char *)output + 1, (u_char *)string, i);
2363 * Seed the random number generator.
2365 * May be called any number of times.
2367 void lrad_rand_seed(const void *data, size_t size)
2372 * Ensure that the pool is initialized.
2374 if (lrad_rand_index < 0) {
2377 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2379 fd = open("/dev/urandom", O_RDONLY);
2385 while (total < sizeof(lrad_rand_pool.randrsl)) {
2386 this = read(fd, lrad_rand_pool.randrsl,
2387 sizeof(lrad_rand_pool.randrsl) - total);
2388 if ((this < 0) && (errno != EINTR)) break;
2389 if (this > 0) total += this;
2393 lrad_rand_pool.randrsl[0] = fd;
2394 lrad_rand_pool.randrsl[1] = time(NULL);
2395 lrad_rand_pool.randrsl[2] = errno;
2398 lrad_randinit(&lrad_rand_pool, 1);
2399 lrad_rand_index = 0;
2405 * Hash the user data
2407 hash = lrad_hash(data, size);
2409 lrad_rand_pool.randrsl[lrad_rand_index & 0xff] ^= hash;
2411 lrad_rand_index &= 0xff;
2414 * Churn the pool every so often after seeding it.
2416 if (((int) (hash & 0xff)) == lrad_rand_index) {
2417 lrad_isaac(&lrad_rand_pool);
2423 * Return a 32-bit random number.
2425 uint32_t lrad_rand(void)
2430 * Ensure that the pool is initialized.
2432 if (lrad_rand_index < 0) {
2433 lrad_rand_seed(NULL, 0);
2437 * We don't return data directly from the pool.
2438 * Rather, we return a summary of the data.
2440 num = lrad_rand_pool.randrsl[lrad_rand_index & 0xff];
2442 lrad_rand_index &= 0xff;
2445 * Every so often, churn the pool.
2447 if (((int) (num & 0xff)) == lrad_rand_index) {
2448 lrad_isaac(&lrad_rand_pool);
2455 * Allocate a new RADIUS_PACKET
2457 RADIUS_PACKET *rad_alloc(int newvector)
2461 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2462 librad_log("out of memory");
2465 memset(rp, 0, sizeof(RADIUS_PACKET));
2468 uint32_t hash, base;
2471 * Don't expose the actual contents of the random
2475 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2476 hash = lrad_rand() ^ base;
2477 memcpy(rp->vector + i, &hash, sizeof(hash));
2486 * Free a RADIUS_PACKET
2488 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2490 RADIUS_PACKET *radius_packet;
2492 if (!radius_packet_ptr) return;
2493 radius_packet = *radius_packet_ptr;
2495 if (radius_packet->data) free(radius_packet->data);
2496 if (radius_packet->vps) pairfree(&radius_packet->vps);
2498 free(radius_packet);
2500 *radius_packet_ptr = NULL;