2 * radius.c Functions to send/receive radius packets.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000-2003,2006 The FreeRADIUS server project
23 #include <freeradius-devel/ident.h>
26 #include <freeradius-devel/libradius.h>
27 #include <freeradius-devel/md5.h>
33 #include <freeradius-devel/udpfromto.h>
41 * The RFC says 4096 octets max, and most packets are less than 256.
43 #define MAX_PACKET_LEN 4096
46 * The maximum number of attributes which we allow in an incoming
47 * request. If there are more attributes than this, the request
50 * This helps to minimize the potential for a DoS, when an
51 * attacker spoofs Access-Request packets, which don't have a
52 * Message-Authenticator attribute. This means that the packet
53 * is unsigned, and the attacker can use resources on the server,
54 * even if the end request is rejected.
56 int librad_max_attributes = 0;
58 typedef struct radius_packet_t {
62 uint8_t vector[AUTH_VECTOR_LEN];
66 static lrad_randctx lrad_rand_pool; /* across multiple calls */
67 static int lrad_rand_initialized = 0;
68 static unsigned int salt_offset = 0;
71 #define MAX_PACKET_CODE (52)
72 static const char *packet_codes[] = {
78 "Accounting-Response",
94 "Resource-Free-Request",
95 "Resource-Free-Response",
96 "Resource-Query-Request",
97 "Resource-Query-Response",
98 "Alternate-Resource-Reclaim-Request",
100 "NAS-Reboot-Response",
113 "Disconnect-Request",
123 "IP-Address-Allocate",
129 * Wrapper for sendto which handles sendfromto, IPv6, and all
130 * possible combinations.
132 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
133 lrad_ipaddr_t *src_ipaddr, lrad_ipaddr_t *dst_ipaddr,
136 struct sockaddr_storage dst;
137 socklen_t sizeof_dst = sizeof(dst);
139 #ifdef WITH_UDPFROMTO
140 struct sockaddr_storage src;
141 socklen_t sizeof_src = sizeof(src);
143 memset(&src, 0, sizeof(src));
145 memset(&dst, 0, sizeof(dst));
150 if (dst_ipaddr->af == AF_INET) {
151 struct sockaddr_in *s4;
153 s4 = (struct sockaddr_in *)&dst;
154 sizeof_dst = sizeof(struct sockaddr_in);
156 s4->sin_family = AF_INET;
157 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
158 s4->sin_port = htons(dst_port);
160 #ifdef WITH_UDPFROMTO
161 s4 = (struct sockaddr_in *)&src;
162 sizeof_src = sizeof(struct sockaddr_in);
164 s4->sin_family = AF_INET;
165 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
169 * IPv6 MAY be supported.
171 #ifdef HAVE_STRUCT_SOCKADDR_IN6
172 } else if (dst_ipaddr->af == AF_INET6) {
173 struct sockaddr_in6 *s6;
175 s6 = (struct sockaddr_in6 *)&dst;
176 sizeof_dst = sizeof(struct sockaddr_in6);
178 s6->sin6_family = AF_INET6;
179 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
180 s6->sin6_port = htons(dst_port);
182 #ifdef WITH_UDPFROMTO
183 return -1; /* UDPFROMTO && IPv6 are not supported */
185 s6 = (struct sockaddr_in6 *)&src;
186 sizeof_src = sizeof(struct sockaddr_in6);
188 s6->sin6_family = AF_INET6;
189 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
191 #endif /* WITH_UDPFROMTO */
192 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
193 } else return -1; /* Unknown address family, Die Die Die! */
195 #ifdef WITH_UDPFROMTO
197 * Only IPv4 is supported for udpfromto.
199 * And if they don't specify a source IP address, don't
202 if ((dst_ipaddr->af == AF_INET) ||
203 (src_ipaddr->af != AF_UNSPEC)) {
204 return sendfromto(sockfd, data, data_len, flags,
205 (struct sockaddr *)&src, sizeof_src,
206 (struct sockaddr *)&dst, sizeof_dst);
209 src_ipaddr = src_ipaddr; /* -Wunused */
213 * No udpfromto, OR an IPv6 socket, fail gracefully.
215 return sendto(sockfd, data, data_len, flags,
216 (struct sockaddr *)&dst, sizeof_dst);
221 * Wrapper for recvfrom, which handles recvfromto, IPv6, and all
222 * possible combinations.
224 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
225 lrad_ipaddr_t *src_ipaddr, uint16_t *src_port,
226 lrad_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
228 struct sockaddr_storage src;
229 struct sockaddr_storage dst;
230 socklen_t sizeof_src = sizeof(src);
231 socklen_t sizeof_dst = sizeof(dst);
237 memset(&src, 0, sizeof_src);
238 memset(&dst, 0, sizeof_dst);
241 * Get address family, etc. first, so we know if we
242 * need to do udpfromto.
244 * FIXME: udpfromto also does this, but it's not
245 * a critical problem.
247 if (getsockname(sockfd, (struct sockaddr *)&dst,
248 &sizeof_dst) < 0) return -1;
251 * Read the length of the packet, from the packet.
252 * This lets us allocate the buffer to use for
253 * reading the rest of the packet.
255 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
256 (struct sockaddr *)&src, &sizeof_src);
257 if (data_len < 0) return -1;
260 * Too little data is available, discard the packet.
263 recvfrom(sockfd, header, sizeof(header), flags,
264 (struct sockaddr *)&src, &sizeof_src);
267 } else { /* we got 4 bytes of data. */
269 * See how long the packet says it is.
271 len = (header[2] * 256) + header[3];
274 * The length in the packet says it's less than
275 * a RADIUS header length: discard it.
277 if (len < AUTH_HDR_LEN) {
278 recvfrom(sockfd, header, sizeof(header), flags,
279 (struct sockaddr *)&src, &sizeof_src);
283 * Enforce RFC requirements, for sanity.
284 * Anything after 4k will be discarded.
286 } else if (len > MAX_PACKET_LEN) {
287 recvfrom(sockfd, header, sizeof(header), flags,
288 (struct sockaddr *)&src, &sizeof_src);
297 * Receive the packet. The OS will discard any data in the
298 * packet after "len" bytes.
300 #ifdef WITH_UDPFROMTO
301 if (dst.ss_family == AF_INET) {
302 data_len = recvfromto(sockfd, buf, len, flags,
303 (struct sockaddr *)&src, &sizeof_src,
304 (struct sockaddr *)&dst, &sizeof_dst);
308 * No udpfromto, OR an IPv6 socket. Fail gracefully.
310 data_len = recvfrom(sockfd, buf, len, flags,
311 (struct sockaddr *)&src, &sizeof_src);
318 * Check address families, and update src/dst ports, etc.
320 if (src.ss_family == AF_INET) {
321 struct sockaddr_in *s4;
323 s4 = (struct sockaddr_in *)&src;
324 src_ipaddr->af = AF_INET;
325 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
326 *src_port = ntohs(s4->sin_port);
328 s4 = (struct sockaddr_in *)&dst;
329 dst_ipaddr->af = AF_INET;
330 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
331 *dst_port = ntohs(s4->sin_port);
333 #ifdef HAVE_STRUCT_SOCKADDR_IN6
334 } else if (src.ss_family == AF_INET6) {
335 struct sockaddr_in6 *s6;
337 s6 = (struct sockaddr_in6 *)&src;
338 src_ipaddr->af = AF_INET6;
339 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
340 *src_port = ntohs(s6->sin6_port);
342 s6 = (struct sockaddr_in6 *)&dst;
343 dst_ipaddr->af = AF_INET6;
344 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
345 *dst_port = ntohs(s6->sin6_port);
349 return -1; /* Unknown address family, Die Die Die! */
353 * Different address families should never happen.
355 if (src.ss_family != dst.ss_family) {
361 * Tell the caller about the data
369 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
370 /*************************************************************************
372 * Function: make_secret
374 * Purpose: Build an encrypted secret value to return in a reply
375 * packet. The secret is hidden by xoring with a MD5 digest
376 * created from the shared secret and the authentication
377 * vector. We put them into MD5 in the reverse order from
378 * that used when encrypting passwords to RADIUS.
380 *************************************************************************/
381 static void make_secret(uint8_t *digest, const uint8_t *vector,
382 const char *secret, const uint8_t *value)
384 lrad_MD5_CTX context;
387 lrad_MD5Init(&context);
388 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
389 lrad_MD5Update(&context, secret, strlen(secret));
390 lrad_MD5Final(digest, &context);
392 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
393 digest[i] ^= value[i];
397 #define MAX_PASS_LEN (128)
398 static void make_passwd(uint8_t *output, int *outlen,
399 const uint8_t *input, int inlen,
400 const char *secret, const uint8_t *vector)
402 lrad_MD5_CTX context, old;
403 uint8_t digest[AUTH_VECTOR_LEN];
404 uint8_t passwd[MAX_PASS_LEN];
409 * If the length is zero, round it up.
415 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
417 else if ((len & 0x0f) != 0) {
423 memcpy(passwd, input, len);
424 memset(passwd + len, 0, sizeof(passwd) - len);
426 lrad_MD5Init(&context);
427 lrad_MD5Update(&context, secret, strlen(secret));
433 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
435 for (n = 0; n < len; n += AUTH_PASS_LEN) {
438 lrad_MD5Update(&context,
439 passwd + n - AUTH_PASS_LEN,
443 lrad_MD5Final(digest, &context);
444 for (i = 0; i < AUTH_PASS_LEN; i++) {
445 passwd[i + n] ^= digest[i];
449 memcpy(output, passwd, len);
452 static void make_tunnel_passwd(uint8_t *output, int *outlen,
453 const uint8_t *input, int inlen, int room,
454 const char *secret, const uint8_t *vector)
456 lrad_MD5_CTX context, old;
457 uint8_t digest[AUTH_VECTOR_LEN];
458 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
465 if (room > 253) room = 253;
468 * Account for 2 bytes of the salt, and round the room
469 * available down to the nearest multiple of 16. Then,
470 * subtract one from that to account for the length byte,
471 * and the resulting number is the upper bound on the data
474 * We could short-cut this calculation just be forcing
475 * inlen to be no more than 239. It would work for all
476 * VSA's, as we don't pack multiple VSA's into one
479 * However, this calculation is more general, if a little
480 * complex. And it will work in the future for all possible
481 * kinds of weird attribute packing.
484 room -= (room & 0x0f);
487 if (inlen > room) inlen = room;
490 * Length of the encrypted data is password length plus
491 * one byte for the length of the password.
494 if ((len & 0x0f) != 0) {
498 *outlen = len + 2; /* account for the salt */
501 * Copy the password over.
503 memcpy(passwd + 3, input, inlen);
504 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
507 * Generate salt. The RFC's say:
509 * The high bit of salt[0] must be set, each salt in a
510 * packet should be unique, and they should be random
512 * So, we set the high bit, add in a counter, and then
513 * add in some CSPRNG data. should be OK..
515 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
516 (lrad_rand() & 0x07));
517 passwd[1] = lrad_rand();
518 passwd[2] = inlen; /* length of the password string */
520 lrad_MD5Init(&context);
521 lrad_MD5Update(&context, secret, strlen(secret));
524 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
525 lrad_MD5Update(&context, &passwd[0], 2);
527 for (n = 0; n < len; n += AUTH_PASS_LEN) {
530 lrad_MD5Update(&context,
531 passwd + 2 + n - AUTH_PASS_LEN,
535 lrad_MD5Final(digest, &context);
536 for (i = 0; i < AUTH_PASS_LEN; i++) {
537 passwd[i + 2 + n] ^= digest[i];
540 memcpy(output, passwd, len + 2);
545 * Parse a data structure into a RADIUS attribute.
547 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
548 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
551 int offset, len, total_length;
553 uint8_t *length_ptr, *vsa_length_ptr;
554 const uint8_t *data = NULL;
557 vendorcode = total_length = 0;
558 length_ptr = vsa_length_ptr = NULL;
561 * For interoperability, always put vendor attributes
562 * into their own VSA.
564 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
565 *(ptr++) = vp->attribute & 0xFF;
573 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
576 * This must be an RFC-format attribute. If it
577 * wasn't, then the "decode" function would have
578 * made a Vendor-Specific attribute (i.e. type
579 * 26), and we would have "vendorcode == 0" here.
583 vsa_llen = dv->length;
587 * Build a VSA header.
589 *ptr++ = PW_VENDOR_SPECIFIC;
590 vsa_length_ptr = ptr;
592 lvalue = htonl(vendorcode);
593 memcpy(ptr, &lvalue, 4);
599 ptr[0] = (vp->attribute & 0xFF);
603 ptr[0] = ((vp->attribute >> 8) & 0xFF);
604 ptr[1] = (vp->attribute & 0xFF);
610 ptr[2] = ((vp->attribute >> 8) & 0xFF);
611 ptr[3] = (vp->attribute & 0xFF);
615 return 0; /* silently discard it */
621 length_ptr = vsa_length_ptr;
622 vsa_length_ptr = NULL;
631 length_ptr = ptr + 1;
635 return 0; /* silently discard it */
639 total_length += vsa_tlen + vsa_llen;
640 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
641 *length_ptr += vsa_tlen + vsa_llen;
645 if (vp->flags.has_tag) {
646 if (TAG_VALID(vp->flags.tag)) {
647 ptr[0] = vp->flags.tag & 0xff;
650 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
652 * Tunnel passwords REQUIRE a tag, even
653 * if don't have a valid tag.
657 } /* else don't write a tag */
658 } /* else the attribute doesn't have a tag */
661 * Set up the default sources for the data.
663 data = vp->vp_octets;
670 case PW_TYPE_IPV6ADDR:
671 case PW_TYPE_IPV6PREFIX:
672 case PW_TYPE_ABINARY:
673 /* nothing more to do */
677 len = 1; /* just in case */
678 array[0] = vp->lvalue & 0xff;
685 len = 2; /* just in case */
686 array[0] = (vp->lvalue >> 8) & 0xff;
687 array[1] = vp->lvalue & 0xff;
692 case PW_TYPE_INTEGER:
693 len = 4; /* just in case */
694 lvalue = htonl(vp->lvalue);
695 memcpy(array, &lvalue, sizeof(lvalue));
698 * Perhaps discard the first octet.
700 data = &array[offset];
705 data = (const uint8_t *) &vp->lvalue;
706 len = 4; /* just in case */
710 * There are no tagged date attributes.
713 lvalue = htonl(vp->lvalue);
714 data = (const uint8_t *) &lvalue;
715 len = 4; /* just in case */
718 default: /* unknown type: ignore it */
719 librad_log("ERROR: Unknown attribute type %d", vp->type);
724 * Bound the data to 255 bytes.
726 if (len + offset + total_length > 255) {
727 len = 255 - offset - total_length;
731 * Encrypt the various password styles
733 * Attributes with encrypted values MUST be less than
736 switch (vp->flags.encrypt) {
737 case FLAG_ENCRYPT_USER_PASSWORD:
738 make_passwd(ptr + offset, &len,
740 secret, packet->vector);
743 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
745 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
750 * Check if 255 - offset - total_length is less
751 * than 18. If so, we can't fit the data into
752 * the available space, and we discard the
755 * This is ONLY a problem if we have multiple VSA's
756 * in one Vendor-Specific, though.
758 if ((255 - offset - total_length) < 18) return 0;
760 make_tunnel_passwd(ptr + offset, &len,
761 data, len, 255 - offset - total_length,
762 secret, original->vector);
766 * The code above ensures that this attribute
769 case FLAG_ENCRYPT_ASCEND_SECRET:
770 make_secret(ptr + offset, packet->vector,
772 len = AUTH_VECTOR_LEN;
778 * Just copy the data over
780 memcpy(ptr + offset, data, len);
782 } /* switch over encryption flags */
785 * Account for the tag (if any).
790 * RFC 2865 section 5 says that zero-length attributes
793 if (len == 0) return 0;
796 * Update the various lengths.
799 if (vsa_length_ptr) *vsa_length_ptr += len;
803 return total_length; /* of attribute */
810 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
813 radius_packet_t *hdr;
815 uint16_t total_length;
822 * For simplicity in the following logic, we allow
823 * the attributes to "overflow" the 4k maximum
824 * RADIUS packet size, by one attribute.
826 * It's uint32_t, for alignment purposes.
828 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
830 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
831 what = packet_codes[packet->code];
836 DEBUG("Sending %s of id %d to %s port %d\n",
838 inet_ntop(packet->dst_ipaddr.af,
839 &packet->dst_ipaddr.ipaddr,
840 ip_buffer, sizeof(ip_buffer)),
844 * Double-check some things based on packet code.
846 switch (packet->code) {
847 case PW_AUTHENTICATION_ACK:
848 case PW_AUTHENTICATION_REJECT:
849 case PW_ACCESS_CHALLENGE:
851 librad_log("ERROR: Cannot sign response packet without a request packet.");
857 * These packet vectors start off as all zero.
859 case PW_ACCOUNTING_REQUEST:
860 case PW_DISCONNECT_REQUEST:
862 memset(packet->vector, 0, sizeof(packet->vector));
870 * Use memory on the stack, until we know how
871 * large the packet will be.
873 hdr = (radius_packet_t *) data;
876 * Build standard header
878 hdr->code = packet->code;
879 hdr->id = packet->id;
881 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
883 total_length = AUTH_HDR_LEN;
884 packet->verified = 0;
887 * Load up the configuration values for the user
892 * FIXME: Loop twice over the reply list. The first time,
893 * calculate the total length of data. The second time,
894 * allocate the memory, and fill in the VP's.
896 * Hmm... this may be slower than just doing a small
901 * Loop over the reply attributes for the packet.
903 for (reply = packet->vps; reply; reply = reply->next) {
905 * Ignore non-wire attributes
907 if ((VENDOR(reply->attribute) == 0) &&
908 ((reply->attribute & 0xFFFF) > 0xff)) {
913 * Set the Message-Authenticator to the correct
914 * length and initial value.
916 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
917 reply->length = AUTH_VECTOR_LEN;
918 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
919 packet->verified = total_length; /* HACK! */
923 * Print out ONLY the attributes which
924 * we're sending over the wire, and print
925 * them out BEFORE they're encrypted.
929 len = rad_vp2attr(packet, original, secret, reply, ptr);
931 if (len < 0) return -1;
934 * Check that the packet is no more than 4k in
935 * size, AFTER writing the attribute past the 4k
936 * boundary, but BEFORE deciding to increase the
937 * size of the packet. Note that the 'data'
938 * buffer, above, is one attribute longer than
939 * necessary, in order to permit this overflow.
941 if ((total_length + len) > MAX_PACKET_LEN) {
947 } /* done looping over all attributes */
950 * Fill in the rest of the fields, and copy the data over
951 * from the local stack to the newly allocated memory.
953 * Yes, all this 'memcpy' is slow, but it means
954 * that we only allocate the minimum amount of
955 * memory for a request.
957 packet->data_len = total_length;
958 packet->data = (uint8_t *) malloc(packet->data_len);
960 librad_log("Out of memory");
964 memcpy(packet->data, data, packet->data_len);
965 hdr = (radius_packet_t *) packet->data;
967 total_length = htons(total_length);
968 memcpy(hdr->length, &total_length, sizeof(total_length));
975 * Sign a previously encoded packet.
977 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
980 radius_packet_t *hdr = (radius_packet_t *)packet->data;
983 * It wasn't assigned an Id, this is bad!
985 if (packet->id < 0) {
986 librad_log("ERROR: RADIUS packets must be assigned an Id.");
990 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
991 (packet->verified < 0)) {
992 librad_log("ERROR: You must call rad_encode() before rad_sign()");
997 * If there's a Message-Authenticator, update it
998 * now, BEFORE updating the authentication vector.
1002 if (packet->verified > 0) {
1003 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1005 switch (packet->code) {
1006 case PW_ACCOUNTING_REQUEST:
1007 case PW_ACCOUNTING_RESPONSE:
1008 case PW_DISCONNECT_REQUEST:
1009 case PW_DISCONNECT_ACK:
1010 case PW_DISCONNECT_NAK:
1011 case PW_COA_REQUEST:
1014 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1017 case PW_AUTHENTICATION_ACK:
1018 case PW_AUTHENTICATION_REJECT:
1019 case PW_ACCESS_CHALLENGE:
1021 librad_log("ERROR: Cannot sign response packet without a request packet.");
1024 memcpy(hdr->vector, original->vector,
1028 default: /* others have vector already set to zero */
1034 * Set the authentication vector to zero,
1035 * calculate the signature, and put it
1036 * into the Message-Authenticator
1039 lrad_hmac_md5(packet->data, packet->data_len,
1040 secret, strlen(secret),
1042 memcpy(packet->data + packet->verified + 2,
1043 calc_auth_vector, AUTH_VECTOR_LEN);
1046 * Copy the original request vector back
1047 * to the raw packet.
1049 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1053 * Switch over the packet code, deciding how to
1056 switch (packet->code) {
1058 * Request packets are not signed, bur
1059 * have a random authentication vector.
1061 case PW_AUTHENTICATION_REQUEST:
1062 case PW_STATUS_SERVER:
1066 * Reply packets are signed with the
1067 * authentication vector of the request.
1075 MD5Update(&context, packet->data, packet->data_len);
1076 MD5Update(&context, secret, strlen(secret));
1077 MD5Final(digest, &context);
1079 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1080 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1083 }/* switch over packet codes */
1089 * Reply to the request. Also attach
1090 * reply attribute value pairs and any user message provided.
1092 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1097 char ip_buffer[128];
1100 * Maybe it's a fake packet. Don't send it.
1102 if (!packet || (packet->sockfd < 0)) {
1106 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1107 what = packet_codes[packet->code];
1113 * First time through, allocate room for the packet
1115 if (!packet->data) {
1117 * Encode the packet.
1119 if (rad_encode(packet, original, secret) < 0) {
1124 * Re-sign it, including updating the
1125 * Message-Authenticator.
1127 if (rad_sign(packet, original, secret) < 0) {
1132 * If packet->data points to data, then we print out
1133 * the VP list again only for debugging.
1135 } else if (librad_debug) {
1136 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1137 inet_ntop(packet->dst_ipaddr.af,
1138 &packet->dst_ipaddr.ipaddr,
1139 ip_buffer, sizeof(ip_buffer)),
1142 for (reply = packet->vps; reply; reply = reply->next) {
1143 /* FIXME: ignore attributes > 0xff */
1149 * And send it on it's way.
1151 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1152 &packet->src_ipaddr, &packet->dst_ipaddr,
1158 * Validates the requesting client NAS. Calculates the
1159 * signature based on the clients private key.
1161 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1163 uint8_t digest[AUTH_VECTOR_LEN];
1167 * Older clients have the authentication vector set to
1168 * all zeros. Return `1' in that case.
1170 memset(digest, 0, sizeof(digest));
1171 if (memcmp(packet->vector, digest, AUTH_VECTOR_LEN) == 0) {
1172 packet->verified = 1;
1177 * Zero out the auth_vector in the received packet.
1178 * Then append the shared secret to the received packet,
1179 * and calculate the MD5 sum. This must be the same
1180 * as the original MD5 sum (packet->vector).
1182 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1185 * MD5(packet + secret);
1188 MD5Update(&context, packet->data, packet->data_len);
1189 MD5Update(&context, secret, strlen(secret));
1190 MD5Final(digest, &context);
1193 * Return 0 if OK, 2 if not OK.
1196 memcmp(digest, packet->vector, AUTH_VECTOR_LEN) ? 2 : 0;
1198 return packet->verified;
1202 * Validates the requesting client NAS. Calculates the
1203 * signature based on the clients private key.
1205 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1208 uint8_t calc_digest[AUTH_VECTOR_LEN];
1214 if (original == NULL) {
1219 * Copy the original vector in place.
1221 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1224 * MD5(packet + secret);
1227 MD5Update(&context, packet->data, packet->data_len);
1228 MD5Update(&context, secret, strlen(secret));
1229 MD5Final(calc_digest, &context);
1232 * Copy the packet's vector back to the packet.
1234 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1237 * Return 0 if OK, 2 if not OK.
1240 memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) ? 2 : 0;
1241 return packet->verified;
1246 * See if the data pointed to by PTR is a valid RADIUS packet.
1248 * packet is not 'const * const' because we may update data_len,
1249 * if there's more data in the UDP packet than in the RADIUS packet.
1251 int rad_packet_ok(RADIUS_PACKET *packet)
1256 radius_packet_t *hdr;
1257 char host_ipaddr[128];
1263 * Check for packets smaller than the packet header.
1265 * RFC 2865, Section 3., subsection 'length' says:
1267 * "The minimum length is 20 ..."
1269 if (packet->data_len < AUTH_HDR_LEN) {
1270 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1271 inet_ntop(packet->src_ipaddr.af,
1272 &packet->src_ipaddr.ipaddr,
1273 host_ipaddr, sizeof(host_ipaddr)),
1274 packet->data_len, AUTH_HDR_LEN);
1279 * RFC 2865, Section 3., subsection 'length' says:
1281 * " ... and maximum length is 4096."
1283 if (packet->data_len > MAX_PACKET_LEN) {
1284 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1285 inet_ntop(packet->src_ipaddr.af,
1286 &packet->src_ipaddr.ipaddr,
1287 host_ipaddr, sizeof(host_ipaddr)),
1288 packet->data_len, MAX_PACKET_LEN);
1293 * Check for packets with mismatched size.
1294 * i.e. We've received 128 bytes, and the packet header
1295 * says it's 256 bytes long.
1297 totallen = (packet->data[2] << 8) | packet->data[3];
1298 hdr = (radius_packet_t *)packet->data;
1301 * Code of 0 is not understood.
1302 * Code of 16 or greate is not understood.
1304 if ((hdr->code == 0) ||
1305 (hdr->code >= MAX_PACKET_CODE)) {
1306 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1307 inet_ntop(packet->src_ipaddr.af,
1308 &packet->src_ipaddr.ipaddr,
1309 host_ipaddr, sizeof(host_ipaddr)),
1315 * Message-Authenticator is required in Status-Server
1316 * packets, otherwise they can be trivially forged.
1318 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1321 * Repeat the length checks. This time, instead of
1322 * looking at the data we received, look at the value
1323 * of the 'length' field inside of the packet.
1325 * Check for packets smaller than the packet header.
1327 * RFC 2865, Section 3., subsection 'length' says:
1329 * "The minimum length is 20 ..."
1331 if (totallen < AUTH_HDR_LEN) {
1332 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1333 inet_ntop(packet->src_ipaddr.af,
1334 &packet->src_ipaddr.ipaddr,
1335 host_ipaddr, sizeof(host_ipaddr)),
1336 totallen, AUTH_HDR_LEN);
1341 * And again, for the value of the 'length' field.
1343 * RFC 2865, Section 3., subsection 'length' says:
1345 * " ... and maximum length is 4096."
1347 if (totallen > MAX_PACKET_LEN) {
1348 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1349 inet_ntop(packet->src_ipaddr.af,
1350 &packet->src_ipaddr.ipaddr,
1351 host_ipaddr, sizeof(host_ipaddr)),
1352 totallen, MAX_PACKET_LEN);
1357 * RFC 2865, Section 3., subsection 'length' says:
1359 * "If the packet is shorter than the Length field
1360 * indicates, it MUST be silently discarded."
1362 * i.e. No response to the NAS.
1364 if (packet->data_len < totallen) {
1365 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1366 inet_ntop(packet->src_ipaddr.af,
1367 &packet->src_ipaddr.ipaddr,
1368 host_ipaddr, sizeof(host_ipaddr)),
1369 packet->data_len, totallen);
1374 * RFC 2865, Section 3., subsection 'length' says:
1376 * "Octets outside the range of the Length field MUST be
1377 * treated as padding and ignored on reception."
1379 if (packet->data_len > totallen) {
1381 * We're shortening the packet below, but just
1382 * to be paranoid, zero out the extra data.
1384 memset(packet->data + totallen, 0, packet->data_len - totallen);
1385 packet->data_len = totallen;
1389 * Walk through the packet's attributes, ensuring that
1390 * they add up EXACTLY to the size of the packet.
1392 * If they don't, then the attributes either under-fill
1393 * or over-fill the packet. Any parsing of the packet
1394 * is impossible, and will result in unknown side effects.
1396 * This would ONLY happen with buggy RADIUS implementations,
1397 * or with an intentional attack. Either way, we do NOT want
1398 * to be vulnerable to this problem.
1401 count = totallen - AUTH_HDR_LEN;
1406 * Attribute number zero is NOT defined.
1409 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1410 inet_ntop(packet->src_ipaddr.af,
1411 &packet->src_ipaddr.ipaddr,
1412 host_ipaddr, sizeof(host_ipaddr)));
1417 * Attributes are at LEAST as long as the ID & length
1418 * fields. Anything shorter is an invalid attribute.
1421 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1422 inet_ntop(packet->src_ipaddr.af,
1423 &packet->src_ipaddr.ipaddr,
1424 host_ipaddr, sizeof(host_ipaddr)),
1430 * Sanity check the attributes for length.
1433 default: /* don't do anything by default */
1438 * If there's an EAP-Message, we require
1439 * a Message-Authenticator.
1441 case PW_EAP_MESSAGE:
1445 case PW_MESSAGE_AUTHENTICATOR:
1446 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1447 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1448 inet_ntop(packet->src_ipaddr.af,
1449 &packet->src_ipaddr.ipaddr,
1450 host_ipaddr, sizeof(host_ipaddr)),
1459 * FIXME: Look up the base 255 attributes in the
1460 * dictionary, and switch over their type. For
1461 * integer/date/ip, the attribute length SHOULD
1464 count -= attr[1]; /* grab the attribute length */
1466 num_attributes++; /* seen one more attribute */
1470 * If the attributes add up to a packet, it's allowed.
1472 * If not, we complain, and throw the packet away.
1475 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1476 inet_ntop(packet->src_ipaddr.af,
1477 &packet->src_ipaddr.ipaddr,
1478 host_ipaddr, sizeof(host_ipaddr)));
1483 * If we're configured to look for a maximum number of
1484 * attributes, and we've seen more than that maximum,
1485 * then throw the packet away, as a possible DoS.
1487 if ((librad_max_attributes > 0) &&
1488 (num_attributes > librad_max_attributes)) {
1489 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1490 inet_ntop(packet->src_ipaddr.af,
1491 &packet->src_ipaddr.ipaddr,
1492 host_ipaddr, sizeof(host_ipaddr)),
1493 num_attributes, librad_max_attributes);
1498 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1500 * A packet with an EAP-Message attribute MUST also have
1501 * a Message-Authenticator attribute.
1503 * A Message-Authenticator all by itself is OK, though.
1505 * Similarly, Status-Server packets MUST contain
1506 * Message-Authenticator attributes.
1508 if (require_ma && ! seen_ma) {
1509 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1510 inet_ntop(packet->src_ipaddr.af,
1511 &packet->src_ipaddr.ipaddr,
1512 host_ipaddr, sizeof(host_ipaddr)));
1517 * Fill RADIUS header fields
1519 packet->code = hdr->code;
1520 packet->id = hdr->id;
1521 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1528 * Receive UDP client requests, and fill in
1529 * the basics of a RADIUS_PACKET structure.
1531 RADIUS_PACKET *rad_recv(int fd)
1533 RADIUS_PACKET *packet;
1536 * Allocate the new request data structure
1538 if ((packet = malloc(sizeof(*packet))) == NULL) {
1539 librad_log("out of memory");
1542 memset(packet, 0, sizeof(*packet));
1544 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1545 &packet->src_ipaddr, &packet->src_port,
1546 &packet->dst_ipaddr, &packet->dst_port);
1549 * Check for socket errors.
1551 if (packet->data_len < 0) {
1552 librad_log("Error receiving packet: %s", strerror(errno));
1553 /* packet->data is NULL */
1559 * If the packet is too big, then rad_recvfrom did NOT
1560 * allocate memory. Instead, it just discarded the
1563 if (packet->data_len > MAX_PACKET_LEN) {
1564 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1565 /* packet->data is NULL */
1571 * Read no data. Continue.
1572 * This check is AFTER the MAX_PACKET_LEN check above, because
1573 * if the packet is larger than MAX_PACKET_LEN, we also have
1574 * packet->data == NULL
1576 if ((packet->data_len == 0) || !packet->data) {
1577 librad_log("No data.");
1583 * See if it's a well-formed RADIUS packet.
1585 if (!rad_packet_ok(packet)) {
1591 * Remember which socket we read the packet from.
1593 packet->sockfd = fd;
1596 * FIXME: Do even more filtering by only permitting
1597 * certain IP's. The problem is that we don't know
1598 * how to do this properly for all possible clients...
1602 * Explicitely set the VP list to empty.
1607 char host_ipaddr[128];
1609 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1610 printf("rad_recv: %s packet from host %s port %d",
1611 packet_codes[packet->code],
1612 inet_ntop(packet->src_ipaddr.af,
1613 &packet->src_ipaddr.ipaddr,
1614 host_ipaddr, sizeof(host_ipaddr)),
1617 printf("rad_recv: Packet from host %s port %d code=%d",
1618 inet_ntop(packet->src_ipaddr.af,
1619 &packet->src_ipaddr.ipaddr,
1620 host_ipaddr, sizeof(host_ipaddr)),
1624 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1632 * Verify the signature of a packet.
1634 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1641 if (!packet || !packet->data) return -1;
1644 * Before we allocate memory for the attributes, do more
1647 ptr = packet->data + AUTH_HDR_LEN;
1648 length = packet->data_len - AUTH_HDR_LEN;
1649 while (length > 0) {
1650 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1651 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1656 default: /* don't do anything. */
1660 * Note that more than one Message-Authenticator
1661 * attribute is invalid.
1663 case PW_MESSAGE_AUTHENTICATOR:
1664 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1665 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1667 switch (packet->code) {
1671 case PW_ACCOUNTING_REQUEST:
1672 case PW_ACCOUNTING_RESPONSE:
1673 case PW_DISCONNECT_REQUEST:
1674 case PW_DISCONNECT_ACK:
1675 case PW_DISCONNECT_NAK:
1676 case PW_COA_REQUEST:
1679 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1682 case PW_AUTHENTICATION_ACK:
1683 case PW_AUTHENTICATION_REJECT:
1684 case PW_ACCESS_CHALLENGE:
1686 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1689 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1693 lrad_hmac_md5(packet->data, packet->data_len,
1694 secret, strlen(secret), calc_auth_vector);
1695 if (memcmp(calc_auth_vector, msg_auth_vector,
1696 sizeof(calc_auth_vector)) != 0) {
1698 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1699 inet_ntop(packet->src_ipaddr.af,
1700 &packet->src_ipaddr.ipaddr,
1701 buffer, sizeof(buffer)));
1702 /* Silently drop packet, according to RFC 3579 */
1704 } /* else the message authenticator was good */
1707 * Reinitialize Authenticators.
1709 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1710 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1712 } /* switch over the attributes */
1716 } /* loop over the packet, sanity checking the attributes */
1719 * It looks like a RADIUS packet, but we can't validate
1722 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1724 librad_log("Received Unknown packet code %d"
1725 "from client %s port %d: Cannot validate signature",
1727 inet_ntop(packet->src_ipaddr.af,
1728 &packet->src_ipaddr.ipaddr,
1729 buffer, sizeof(buffer)),
1735 * Calculate and/or verify digest.
1737 switch(packet->code) {
1741 case PW_AUTHENTICATION_REQUEST:
1742 case PW_STATUS_SERVER:
1743 case PW_DISCONNECT_REQUEST:
1745 * The authentication vector is random
1746 * nonsense, invented by the client.
1750 case PW_ACCOUNTING_REQUEST:
1751 if (calc_acctdigest(packet, secret) > 1) {
1752 librad_log("Received Accounting-Request packet "
1753 "from %s with invalid signature! (Shared secret is incorrect.)",
1754 inet_ntop(packet->src_ipaddr.af,
1755 &packet->src_ipaddr.ipaddr,
1756 buffer, sizeof(buffer)));
1761 /* Verify the reply digest */
1762 case PW_AUTHENTICATION_ACK:
1763 case PW_AUTHENTICATION_REJECT:
1764 case PW_ACCESS_CHALLENGE:
1765 case PW_ACCOUNTING_RESPONSE:
1766 case PW_DISCONNECT_ACK:
1767 case PW_DISCONNECT_NAK:
1770 rcode = calc_replydigest(packet, original, secret);
1772 librad_log("Received %s packet "
1773 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1774 packet_codes[packet->code],
1775 inet_ntop(packet->src_ipaddr.af,
1776 &packet->src_ipaddr.ipaddr,
1777 buffer, sizeof(buffer)),
1785 librad_log("Received Unknown packet code %d"
1786 "from client %s port %d: Cannot validate signature",
1788 inet_ntop(packet->src_ipaddr.af,
1789 &packet->src_ipaddr.ipaddr,
1790 buffer, sizeof(buffer)),
1800 * Parse a RADIUS attribute into a data structure.
1802 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1803 const char *secret, int attribute, int length,
1804 const uint8_t *data)
1809 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1814 * If length is greater than 253, something is SERIOUSLY
1817 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1819 vp->length = length;
1820 vp->operator = T_OP_EQ;
1826 if (vp->flags.has_tag) {
1827 if (TAG_VALID(data[0]) ||
1828 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1830 * Tunnel passwords REQUIRE a tag, even
1831 * if don't have a valid tag.
1833 vp->flags.tag = data[0];
1835 if ((vp->type == PW_TYPE_STRING) ||
1836 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1841 * Copy the data to be decrypted
1843 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1844 vp->length -= offset;
1847 * Decrypt the attribute.
1849 switch (vp->flags.encrypt) {
1853 case FLAG_ENCRYPT_USER_PASSWORD:
1855 rad_pwdecode((char *)vp->vp_strvalue,
1859 rad_pwdecode((char *)vp->vp_strvalue,
1863 if (vp->attribute == PW_USER_PASSWORD) {
1864 vp->length = strlen(vp->vp_strvalue);
1869 * Tunnel-Password's may go ONLY
1870 * in response packets.
1872 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1873 if (!original) goto raw;
1875 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1876 secret, original->vector) < 0) {
1882 * Ascend-Send-Secret
1883 * Ascend-Receive-Secret
1885 case FLAG_ENCRYPT_ASCEND_SECRET:
1889 uint8_t my_digest[AUTH_VECTOR_LEN];
1890 make_secret(my_digest,
1893 memcpy(vp->vp_strvalue, my_digest,
1895 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1896 vp->length = strlen(vp->vp_strvalue);
1902 } /* switch over encryption flags */
1906 case PW_TYPE_STRING:
1907 case PW_TYPE_OCTETS:
1908 case PW_TYPE_ABINARY:
1909 /* nothing more to do */
1913 if (vp->length != 1) goto raw;
1915 vp->lvalue = vp->vp_octets[0];
1920 if (vp->length != 2) goto raw;
1922 vp->lvalue = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
1925 case PW_TYPE_INTEGER:
1926 if (vp->length != 4) goto raw;
1928 memcpy(&vp->lvalue, vp->vp_octets, 4);
1929 vp->lvalue = ntohl(vp->lvalue);
1931 if (vp->flags.has_tag) vp->lvalue &= 0x00ffffff;
1934 * Try to get named VALUEs
1938 dval = dict_valbyattr(vp->attribute,
1941 strlcpy(vp->vp_strvalue,
1943 sizeof(vp->vp_strvalue));
1949 if (vp->length != 4) goto raw;
1951 memcpy(&vp->lvalue, vp->vp_octets, 4);
1952 vp->lvalue = ntohl(vp->lvalue);
1956 case PW_TYPE_IPADDR:
1957 if (vp->length != 4) goto raw;
1959 memcpy(&vp->lvalue, vp->vp_octets, 4);
1963 * IPv6 interface ID is 8 octets long.
1966 if (vp->length != 8) goto raw;
1967 /* vp->vp_ifid == vp->vp_octets */
1971 * IPv6 addresses are 16 octets long
1973 case PW_TYPE_IPV6ADDR:
1974 if (vp->length != 16) goto raw;
1975 /* vp->vp_ipv6addr == vp->vp_octets */
1979 * IPv6 prefixes are 2 to 18 octets long.
1981 * RFC 3162: The first octet is unused.
1982 * The second is the length of the prefix
1983 * the rest are the prefix data.
1985 * The prefix length can have value 0 to 128.
1987 case PW_TYPE_IPV6PREFIX:
1988 if (vp->length < 2 || vp->length > 18) goto raw;
1989 if (vp->vp_octets[1] > 128) goto raw;
1992 * FIXME: double-check that
1993 * (vp->vp_octets[1] >> 3) matches vp->length + 2
1995 if (vp->length < 18) {
1996 memset(vp->vp_octets + vp->length, 0,
2003 vp->type = PW_TYPE_OCTETS;
2004 vp->length = length;
2005 memcpy(vp->vp_octets, data, length);
2009 * Ensure there's no encryption or tag stuff,
2010 * we just pass the attribute as-is.
2012 memset(&vp->flags, 0, sizeof(vp->flags));
2020 * Calculate/check digest, and decode radius attributes.
2022 * -1 on decoding error
2025 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2029 uint32_t vendorcode;
2037 radius_packet_t *hdr;
2038 int vsa_tlen, vsa_llen;
2039 DICT_VENDOR *dv = NULL;
2042 * Extract attribute-value pairs
2044 hdr = (radius_packet_t *)packet->data;
2046 packet_length = packet->data_len - AUTH_HDR_LEN;
2049 * There may be VP's already in the packet. Don't
2052 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2058 vsa_tlen = vsa_llen = 1;
2061 * We have to read at least two bytes.
2063 * rad_recv() above ensures that this is OK.
2065 while (packet_length > 0) {
2070 * Normal attribute, handle it like normal.
2072 if (vendorcode == 0) {
2074 * No room to read attr/length,
2075 * or bad attribute, or attribute is
2076 * too short, or attribute is too long,
2077 * stop processing the packet.
2079 if ((packet_length < 2) ||
2080 (ptr[0] == 0) || (ptr[1] < 2) ||
2081 (ptr[1] > packet_length)) break;
2089 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2092 * No vendor code, or ONLY vendor code.
2094 if (attrlen <= 4) goto create_pair;
2100 * Handle Vendor-Specific
2102 if (vendorlen == 0) {
2108 * attrlen was checked above.
2110 memcpy(&lvalue, ptr, 4);
2111 myvendor = ntohl(lvalue);
2114 * Zero isn't allowed.
2116 if (myvendor == 0) goto create_pair;
2119 * This is an implementation issue.
2120 * We currently pack vendor into the upper
2121 * 16 bits of a 32-bit attribute number,
2122 * so we can't handle vendor numbers larger
2125 if (myvendor > 65535) goto create_pair;
2127 vsa_tlen = vsa_llen = 1;
2128 dv = dict_vendorbyvalue(myvendor);
2130 vsa_tlen = dv->type;
2131 vsa_llen = dv->length;
2135 * Sweep through the list of VSA's,
2136 * seeing if they exactly fill the
2137 * outer Vendor-Specific attribute.
2139 * If not, create a raw Vendor-Specific.
2142 sublen = attrlen - 4;
2145 * See if we can parse it.
2151 * Don't have a type, it's bad.
2153 if (sublen < vsa_tlen) goto create_pair;
2156 * Ensure that the attribute number
2165 myattr = (subptr[0] << 8) | subptr[1];
2169 if ((subptr[0] != 0) ||
2170 (subptr[1] != 0)) goto create_pair;
2172 myattr = (subptr[2] << 8) | subptr[3];
2176 * Our dictionary is broken.
2183 * Not enough room for one more
2186 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2189 attribute = (myvendor << 16) | myattr;
2190 ptr += 4 + vsa_tlen;
2191 attrlen -= (4 + vsa_tlen);
2192 packet_length -= 4 + vsa_tlen;
2196 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2199 if (subptr[vsa_tlen] > sublen)
2201 sublen -= subptr[vsa_tlen];
2202 subptr += subptr[vsa_tlen];
2206 if (subptr[vsa_tlen] != 0) goto create_pair;
2207 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2209 if (subptr[vsa_tlen + 1] > sublen)
2211 sublen -= subptr[vsa_tlen + 1];
2212 subptr += subptr[vsa_tlen + 1];
2216 * Our dictionaries are
2222 } while (sublen > 0);
2224 vendorcode = myvendor;
2225 vendorlen = attrlen - 4;
2232 * attrlen is the length of this attribute.
2233 * total_len is the length of the encompassing
2242 attribute = (ptr[0] << 8) | ptr[1];
2245 default: /* can't hit this. */
2248 attribute |= (vendorcode << 16);
2253 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2257 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2260 default: /* can't hit this. */
2264 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2265 if (vendorlen == 0) vendorcode = 0;
2266 packet_length -= (vsa_tlen + vsa_llen);
2269 * Create the attribute, setting the default type
2270 * to 'octets'. If the type in the dictionary
2271 * is different, then the dictionary type will
2272 * over-ride this one.
2275 pair = rad_attr2vp(packet, original, secret,
2276 attribute, attrlen, ptr);
2279 pairfree(&packet->vps);
2280 librad_log("out of memory");
2292 packet_length -= attrlen;
2296 * Merge information from the outside world into our
2299 lrad_rand_seed(packet->data, AUTH_HDR_LEN);
2308 * We assume that the passwd buffer passed is big enough.
2309 * RFC2138 says the password is max 128 chars, so the size
2310 * of the passwd buffer must be at least 129 characters.
2311 * Preferably it's just MAX_STRING_LEN.
2313 * int *pwlen is updated to the new length of the encrypted
2314 * password - a multiple of 16 bytes.
2316 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2317 const uint8_t *vector)
2319 lrad_MD5_CTX context, old;
2320 uint8_t digest[AUTH_VECTOR_LEN];
2321 int i, n, secretlen;
2325 * RFC maximum is 128 bytes.
2327 * If length is zero, pad it out with zeros.
2329 * If the length isn't aligned to 16 bytes,
2330 * zero out the extra data.
2334 if (len > 128) len = 128;
2337 memset(passwd, 0, AUTH_PASS_LEN);
2338 len = AUTH_PASS_LEN;
2339 } else if ((len % AUTH_PASS_LEN) != 0) {
2340 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2341 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2346 * Use the secret to setup the decryption digest
2348 secretlen = strlen(secret);
2350 lrad_MD5Init(&context);
2351 lrad_MD5Update(&context, secret, secretlen);
2352 old = context; /* save intermediate work */
2355 * Encrypt it in place. Don't bother checking
2356 * len, as we've ensured above that it's OK.
2358 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2360 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
2361 lrad_MD5Final(digest, &context);
2364 lrad_MD5Update(&context,
2365 passwd + n - AUTH_PASS_LEN,
2367 lrad_MD5Final(digest, &context);
2370 for (i = 0; i < AUTH_PASS_LEN; i++) {
2371 passwd[i + n] ^= digest[i];
2381 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2382 const uint8_t *vector)
2384 lrad_MD5_CTX context, old;
2385 uint8_t digest[AUTH_VECTOR_LEN];
2386 int i, n, secretlen;
2389 * The RFC's say that the maximum is 128.
2390 * The buffer we're putting it into above is 254, so
2391 * we don't need to do any length checking.
2393 if (pwlen > 128) pwlen = 128;
2398 if (pwlen == 0) goto done;
2401 * Use the secret to setup the decryption digest
2403 secretlen = strlen(secret);
2405 lrad_MD5Init(&context);
2406 lrad_MD5Update(&context, secret, secretlen);
2407 old = context; /* save intermediate work */
2410 * The inverse of the code above.
2412 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2414 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2415 lrad_MD5Final(digest, &context);
2418 lrad_MD5Update(&context, passwd, AUTH_PASS_LEN);
2420 lrad_MD5Final(digest, &context);
2423 lrad_MD5Update(&context, passwd + n, AUTH_PASS_LEN);
2426 for (i = 0; i < AUTH_PASS_LEN; i++) {
2427 passwd[i + n] ^= digest[i];
2432 passwd[pwlen] = '\0';
2433 return strlen(passwd);
2438 * Encode Tunnel-Password attributes when sending them out on the wire.
2440 * int *pwlen is updated to the new length of the encrypted
2441 * password - a multiple of 16 bytes.
2443 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2446 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2447 const uint8_t *vector)
2449 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2450 unsigned char digest[AUTH_VECTOR_LEN];
2452 int i, n, secretlen;
2457 if (len > 127) len = 127;
2460 * Shift the password 3 positions right to place a salt and original
2461 * length, tag will be added automatically on packet send
2463 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2467 * save original password length as first password character;
2474 * Generate salt. The RFC's say:
2476 * The high bit of salt[0] must be set, each salt in a
2477 * packet should be unique, and they should be random
2479 * So, we set the high bit, add in a counter, and then
2480 * add in some CSPRNG data. should be OK..
2482 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2483 (lrad_rand() & 0x07));
2484 salt[1] = lrad_rand();
2487 * Padd password to multiple of AUTH_PASS_LEN bytes.
2489 n = len % AUTH_PASS_LEN;
2491 n = AUTH_PASS_LEN - n;
2492 for (; n > 0; n--, len++)
2495 /* set new password length */
2499 * Use the secret to setup the decryption digest
2501 secretlen = strlen(secret);
2502 memcpy(buffer, secret, secretlen);
2504 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2506 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2507 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2508 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2510 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2511 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2514 for (i = 0; i < AUTH_PASS_LEN; i++) {
2515 passwd[i + n2] ^= digest[i];
2523 * Decode Tunnel-Password encrypted attributes.
2525 * Defined in RFC-2868, this uses a two char SALT along with the
2526 * initial intermediate value, to differentiate it from the
2529 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2530 const uint8_t *vector)
2532 lrad_MD5_CTX context, old;
2533 uint8_t digest[AUTH_VECTOR_LEN];
2535 unsigned i, n, len, reallen;
2540 * We need at least a salt.
2543 librad_log("tunnel password is too short");
2548 * There's a salt, but no password. Or, there's a salt
2549 * and a 'data_len' octet. It's wrong, but at least we
2550 * can figure out what it means: the password is empty.
2552 * Note that this means we ignore the 'data_len' field,
2553 * if the attribute length tells us that there's no
2554 * more data. So the 'data_len' field may be wrong,
2563 len -= 2; /* discount the salt */
2566 * Use the secret to setup the decryption digest
2568 secretlen = strlen(secret);
2570 lrad_MD5Init(&context);
2571 lrad_MD5Update(&context, secret, secretlen);
2572 old = context; /* save intermediate work */
2575 * Set up the initial key:
2577 * b(1) = MD5(secret + vector + salt)
2579 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2580 lrad_MD5Update(&context, passwd, 2);
2583 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2587 lrad_MD5Final(digest, &context);
2592 * A quick check: decrypt the first octet
2593 * of the password, which is the
2594 * 'data_len' field. Ensure it's sane.
2596 reallen = passwd[2] ^ digest[0];
2597 if (reallen >= len) {
2598 librad_log("tunnel password is too long for the attribute");
2602 lrad_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2606 lrad_MD5Final(digest, &context);
2609 lrad_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2612 for (i = base; i < AUTH_PASS_LEN; i++) {
2613 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2618 * See make_tunnel_password, above.
2620 if (reallen > 239) reallen = 239;
2623 passwd[reallen] = 0;
2629 * Encode a CHAP password
2631 * FIXME: might not work with Ascend because
2632 * we use vp->length, and Ascend gear likes
2633 * to send an extra '\0' in the string!
2635 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2636 VALUE_PAIR *password)
2640 uint8_t string[MAX_STRING_LEN * 2 + 1];
2641 VALUE_PAIR *challenge;
2644 * Sanity check the input parameters
2646 if ((packet == NULL) || (password == NULL)) {
2651 * Note that the password VP can be EITHER
2652 * a User-Password attribute (from a check-item list),
2653 * or a CHAP-Password attribute (the client asking
2654 * the library to encode it).
2662 memcpy(ptr, password->vp_strvalue, password->length);
2663 ptr += password->length;
2664 i += password->length;
2667 * Use Chap-Challenge pair if present,
2668 * Request-Authenticator otherwise.
2670 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2672 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2673 i += challenge->length;
2675 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2676 i += AUTH_VECTOR_LEN;
2680 librad_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2687 * Seed the random number generator.
2689 * May be called any number of times.
2691 void lrad_rand_seed(const void *data, size_t size)
2696 * Ensure that the pool is initialized.
2698 if (!lrad_rand_initialized) {
2701 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2703 fd = open("/dev/urandom", O_RDONLY);
2709 while (total < sizeof(lrad_rand_pool.randrsl)) {
2710 this = read(fd, lrad_rand_pool.randrsl,
2711 sizeof(lrad_rand_pool.randrsl) - total);
2712 if ((this < 0) && (errno != EINTR)) break;
2713 if (this > 0) total += this;
2717 lrad_rand_pool.randrsl[0] = fd;
2718 lrad_rand_pool.randrsl[1] = time(NULL);
2719 lrad_rand_pool.randrsl[2] = errno;
2722 lrad_randinit(&lrad_rand_pool, 1);
2723 lrad_rand_pool.randcnt = 0;
2724 lrad_rand_initialized = 1;
2730 * Hash the user data
2733 if (!hash) hash = lrad_rand();
2734 hash = lrad_hash_update(data, size, hash);
2736 lrad_rand_pool.randmem[lrad_rand_pool.randcnt] ^= hash;
2741 * Return a 32-bit random number.
2743 uint32_t lrad_rand(void)
2748 * Ensure that the pool is initialized.
2750 if (!lrad_rand_initialized) {
2751 lrad_rand_seed(NULL, 0);
2754 num = lrad_rand_pool.randrsl[lrad_rand_pool.randcnt++];
2755 if (lrad_rand_pool.randcnt == 256) {
2756 lrad_isaac(&lrad_rand_pool);
2757 lrad_rand_pool.randcnt = 0;
2765 * Allocate a new RADIUS_PACKET
2767 RADIUS_PACKET *rad_alloc(int newvector)
2771 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2772 librad_log("out of memory");
2775 memset(rp, 0, sizeof(*rp));
2781 uint32_t hash, base;
2784 * Don't expose the actual contents of the random
2788 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2789 hash = lrad_rand() ^ base;
2790 memcpy(rp->vector + i, &hash, sizeof(hash));
2793 lrad_rand(); /* stir the pool again */
2799 * Free a RADIUS_PACKET
2801 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2803 RADIUS_PACKET *radius_packet;
2805 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2806 radius_packet = *radius_packet_ptr;
2808 free(radius_packet->data);
2809 pairfree(&radius_packet->vps);
2811 free(radius_packet);
2813 *radius_packet_ptr = NULL;