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, int src_port,
134 lrad_ipaddr_t *dst_ipaddr, int dst_port)
136 struct sockaddr_storage dst;
137 socklen_t sizeof_dst = sizeof(dst);
139 #ifdef WITH_UDPFROMTO
140 struct sockaddr_storage src;
141 socklen_t sizeof_src = sizeof(src);
143 memset(&src, 0, sizeof(src));
145 memset(&dst, 0, sizeof(dst));
150 if (dst_ipaddr->af == AF_INET) {
151 struct sockaddr_in *s4;
153 s4 = (struct sockaddr_in *)&dst;
154 sizeof_dst = sizeof(struct sockaddr_in);
156 s4->sin_family = AF_INET;
157 s4->sin_addr = dst_ipaddr->ipaddr.ip4addr;
158 s4->sin_port = htons(dst_port);
160 #ifdef WITH_UDPFROMTO
161 s4 = (struct sockaddr_in *)&src;
162 sizeof_src = sizeof(struct sockaddr_in);
164 s4->sin_family = AF_INET;
165 s4->sin_addr = src_ipaddr->ipaddr.ip4addr;
166 s4->sin_port = htons(src_port);
170 * IPv6 MAY be supported.
172 #ifdef HAVE_STRUCT_SOCKADDR_IN6
173 } else if (dst_ipaddr->af == AF_INET6) {
174 struct sockaddr_in6 *s6;
176 s6 = (struct sockaddr_in6 *)&dst;
177 sizeof_dst = sizeof(struct sockaddr_in6);
179 s6->sin6_family = AF_INET6;
180 s6->sin6_addr = dst_ipaddr->ipaddr.ip6addr;
181 s6->sin6_port = htons(dst_port);
183 #ifdef WITH_UDPFROMTO
184 return -1; /* UDPFROMTO && IPv6 are not supported */
186 s6 = (struct sockaddr_in6 *)&src;
187 sizeof_src = sizeof(struct sockaddr_in6);
189 s6->sin6_family = AF_INET6;
190 s6->sin6_addr = src_ipaddr->ipaddr.ip6addr;
192 #endif /* WITH_UDPFROMTO */
193 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
194 } else return -1; /* Unknown address family, Die Die Die! */
196 #ifdef WITH_UDPFROMTO
198 * Only IPv4 is supported for udpfromto.
200 * And if they don't specify a source IP address, don't
203 if ((dst_ipaddr->af == AF_INET) ||
204 (src_ipaddr->af != AF_UNSPEC)) {
205 return sendfromto(sockfd, data, data_len, flags,
206 (struct sockaddr *)&src, sizeof_src,
207 (struct sockaddr *)&dst, sizeof_dst);
210 src_ipaddr = src_ipaddr; /* -Wunused */
214 * No udpfromto, OR an IPv6 socket, fail gracefully.
216 return sendto(sockfd, data, data_len, flags,
217 (struct sockaddr *)&dst, sizeof_dst);
221 void rad_recv_discard(int sockfd)
224 struct sockaddr_storage src;
225 socklen_t sizeof_src = sizeof(src);
227 recvfrom(sockfd, header, sizeof(header), 0,
228 (struct sockaddr *)&src, &sizeof_src);
232 ssize_t rad_recv_header(int sockfd, lrad_ipaddr_t *src_ipaddr, int *src_port,
235 ssize_t data_len, packet_len;
237 struct sockaddr_storage src;
238 socklen_t sizeof_src = sizeof(src);
240 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
241 (struct sockaddr *)&src, &sizeof_src);
242 if (data_len < 0) return -1;
245 * Too little data is available, discard the packet.
248 recvfrom(sockfd, header, sizeof(header), 0,
249 (struct sockaddr *)&src, &sizeof_src);
252 } else { /* we got 4 bytes of data. */
254 * See how long the packet says it is.
256 packet_len = (header[2] * 256) + header[3];
259 * The length in the packet says it's less than
260 * a RADIUS header length: discard it.
262 if (packet_len < AUTH_HDR_LEN) {
263 recvfrom(sockfd, header, sizeof(header), 0,
264 (struct sockaddr *)&src, &sizeof_src);
268 * Enforce RFC requirements, for sanity.
269 * Anything after 4k will be discarded.
271 } else if (packet_len > MAX_PACKET_LEN) {
272 recvfrom(sockfd, header, sizeof(header), 0,
273 (struct sockaddr *)&src, &sizeof_src);
278 if (src.ss_family == AF_INET) {
279 struct sockaddr_in *s4;
281 s4 = (struct sockaddr_in *)&src;
282 src_ipaddr->af = AF_INET;
283 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
284 *src_port = ntohs(s4->sin_port);
286 #ifdef HAVE_STRUCT_SOCKADDR_IN6
287 } else if (src.ss_family == AF_INET6) {
288 struct sockaddr_in6 *s6;
290 s6 = (struct sockaddr_in6 *)&src;
291 src_ipaddr->af = AF_INET6;
292 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
293 *src_port = ntohs(s6->sin6_port);
297 recvfrom(sockfd, header, sizeof(header), 0,
298 (struct sockaddr *)&src, &sizeof_src);
305 * The packet says it's this long, but the actual UDP
306 * size could still be smaller.
313 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
314 * possible combinations.
316 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
317 lrad_ipaddr_t *src_ipaddr, uint16_t *src_port,
318 lrad_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
320 struct sockaddr_storage src;
321 struct sockaddr_storage dst;
322 socklen_t sizeof_src = sizeof(src);
323 socklen_t sizeof_dst = sizeof(dst);
329 memset(&src, 0, sizeof_src);
330 memset(&dst, 0, sizeof_dst);
333 * Get address family, etc. first, so we know if we
334 * need to do udpfromto.
336 * FIXME: udpfromto also does this, but it's not
337 * a critical problem.
339 if (getsockname(sockfd, (struct sockaddr *)&dst,
340 &sizeof_dst) < 0) return -1;
343 * Read the length of the packet, from the packet.
344 * This lets us allocate the buffer to use for
345 * reading the rest of the packet.
347 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
348 (struct sockaddr *)&src, &sizeof_src);
349 if (data_len < 0) return -1;
352 * Too little data is available, discard the packet.
355 recvfrom(sockfd, header, sizeof(header), flags,
356 (struct sockaddr *)&src, &sizeof_src);
359 } else { /* we got 4 bytes of data. */
361 * See how long the packet says it is.
363 len = (header[2] * 256) + header[3];
366 * The length in the packet says it's less than
367 * a RADIUS header length: discard it.
369 if (len < AUTH_HDR_LEN) {
370 recvfrom(sockfd, header, sizeof(header), flags,
371 (struct sockaddr *)&src, &sizeof_src);
375 * Enforce RFC requirements, for sanity.
376 * Anything after 4k will be discarded.
378 } else if (len > MAX_PACKET_LEN) {
379 recvfrom(sockfd, header, sizeof(header), flags,
380 (struct sockaddr *)&src, &sizeof_src);
389 * Receive the packet. The OS will discard any data in the
390 * packet after "len" bytes.
392 #ifdef WITH_UDPFROMTO
393 if (dst.ss_family == AF_INET) {
394 data_len = recvfromto(sockfd, buf, len, flags,
395 (struct sockaddr *)&src, &sizeof_src,
396 (struct sockaddr *)&dst, &sizeof_dst);
400 * No udpfromto, OR an IPv6 socket. Fail gracefully.
402 data_len = recvfrom(sockfd, buf, len, flags,
403 (struct sockaddr *)&src, &sizeof_src);
410 * Check address families, and update src/dst ports, etc.
412 if (src.ss_family == AF_INET) {
413 struct sockaddr_in *s4;
415 s4 = (struct sockaddr_in *)&src;
416 src_ipaddr->af = AF_INET;
417 src_ipaddr->ipaddr.ip4addr = s4->sin_addr;
418 *src_port = ntohs(s4->sin_port);
420 s4 = (struct sockaddr_in *)&dst;
421 dst_ipaddr->af = AF_INET;
422 dst_ipaddr->ipaddr.ip4addr = s4->sin_addr;
423 *dst_port = ntohs(s4->sin_port);
425 #ifdef HAVE_STRUCT_SOCKADDR_IN6
426 } else if (src.ss_family == AF_INET6) {
427 struct sockaddr_in6 *s6;
429 s6 = (struct sockaddr_in6 *)&src;
430 src_ipaddr->af = AF_INET6;
431 src_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
432 *src_port = ntohs(s6->sin6_port);
434 s6 = (struct sockaddr_in6 *)&dst;
435 dst_ipaddr->af = AF_INET6;
436 dst_ipaddr->ipaddr.ip6addr = s6->sin6_addr;
437 *dst_port = ntohs(s6->sin6_port);
441 return -1; /* Unknown address family, Die Die Die! */
445 * Different address families should never happen.
447 if (src.ss_family != dst.ss_family) {
453 * Tell the caller about the data
461 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
462 /*************************************************************************
464 * Function: make_secret
466 * Purpose: Build an encrypted secret value to return in a reply
467 * packet. The secret is hidden by xoring with a MD5 digest
468 * created from the shared secret and the authentication
469 * vector. We put them into MD5 in the reverse order from
470 * that used when encrypting passwords to RADIUS.
472 *************************************************************************/
473 static void make_secret(uint8_t *digest, const uint8_t *vector,
474 const char *secret, const uint8_t *value)
476 lrad_MD5_CTX context;
479 lrad_MD5Init(&context);
480 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
481 lrad_MD5Update(&context, secret, strlen(secret));
482 lrad_MD5Final(digest, &context);
484 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
485 digest[i] ^= value[i];
489 #define MAX_PASS_LEN (128)
490 static void make_passwd(uint8_t *output, int *outlen,
491 const uint8_t *input, int inlen,
492 const char *secret, const uint8_t *vector)
494 lrad_MD5_CTX context, old;
495 uint8_t digest[AUTH_VECTOR_LEN];
496 uint8_t passwd[MAX_PASS_LEN];
501 * If the length is zero, round it up.
507 else if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
509 else if ((len & 0x0f) != 0) {
515 memcpy(passwd, input, len);
516 memset(passwd + len, 0, sizeof(passwd) - len);
518 lrad_MD5Init(&context);
519 lrad_MD5Update(&context, secret, strlen(secret));
525 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
527 for (n = 0; n < len; n += AUTH_PASS_LEN) {
530 lrad_MD5Update(&context,
531 passwd + n - AUTH_PASS_LEN,
535 lrad_MD5Final(digest, &context);
536 for (i = 0; i < AUTH_PASS_LEN; i++) {
537 passwd[i + n] ^= digest[i];
541 memcpy(output, passwd, len);
544 static void make_tunnel_passwd(uint8_t *output, int *outlen,
545 const uint8_t *input, int inlen, int room,
546 const char *secret, const uint8_t *vector)
548 lrad_MD5_CTX context, old;
549 uint8_t digest[AUTH_VECTOR_LEN];
550 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
557 if (room > 253) room = 253;
560 * Account for 2 bytes of the salt, and round the room
561 * available down to the nearest multiple of 16. Then,
562 * subtract one from that to account for the length byte,
563 * and the resulting number is the upper bound on the data
566 * We could short-cut this calculation just be forcing
567 * inlen to be no more than 239. It would work for all
568 * VSA's, as we don't pack multiple VSA's into one
571 * However, this calculation is more general, if a little
572 * complex. And it will work in the future for all possible
573 * kinds of weird attribute packing.
576 room -= (room & 0x0f);
579 if (inlen > room) inlen = room;
582 * Length of the encrypted data is password length plus
583 * one byte for the length of the password.
586 if ((len & 0x0f) != 0) {
590 *outlen = len + 2; /* account for the salt */
593 * Copy the password over.
595 memcpy(passwd + 3, input, inlen);
596 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
599 * Generate salt. The RFC's say:
601 * The high bit of salt[0] must be set, each salt in a
602 * packet should be unique, and they should be random
604 * So, we set the high bit, add in a counter, and then
605 * add in some CSPRNG data. should be OK..
607 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
608 (lrad_rand() & 0x07));
609 passwd[1] = lrad_rand();
610 passwd[2] = inlen; /* length of the password string */
612 lrad_MD5Init(&context);
613 lrad_MD5Update(&context, secret, strlen(secret));
616 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
617 lrad_MD5Update(&context, &passwd[0], 2);
619 for (n = 0; n < len; n += AUTH_PASS_LEN) {
622 lrad_MD5Update(&context,
623 passwd + 2 + n - AUTH_PASS_LEN,
627 lrad_MD5Final(digest, &context);
628 for (i = 0; i < AUTH_PASS_LEN; i++) {
629 passwd[i + 2 + n] ^= digest[i];
632 memcpy(output, passwd, len + 2);
637 * Parse a data structure into a RADIUS attribute.
639 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
640 const char *secret, const VALUE_PAIR *vp, uint8_t *ptr)
643 int offset, len, total_length;
645 uint8_t *length_ptr, *vsa_length_ptr;
646 const uint8_t *data = NULL;
649 vendorcode = total_length = 0;
650 length_ptr = vsa_length_ptr = NULL;
653 * For interoperability, always put vendor attributes
654 * into their own VSA.
656 if ((vendorcode = VENDOR(vp->attribute)) == 0) {
657 *(ptr++) = vp->attribute & 0xFF;
665 DICT_VENDOR *dv = dict_vendorbyvalue(vendorcode);
668 * This must be an RFC-format attribute. If it
669 * wasn't, then the "decode" function would have
670 * made a Vendor-Specific attribute (i.e. type
671 * 26), and we would have "vendorcode == 0" here.
675 vsa_llen = dv->length;
679 * Build a VSA header.
681 *ptr++ = PW_VENDOR_SPECIFIC;
682 vsa_length_ptr = ptr;
684 lvalue = htonl(vendorcode);
685 memcpy(ptr, &lvalue, 4);
691 ptr[0] = (vp->attribute & 0xFF);
695 ptr[0] = ((vp->attribute >> 8) & 0xFF);
696 ptr[1] = (vp->attribute & 0xFF);
702 ptr[2] = ((vp->attribute >> 8) & 0xFF);
703 ptr[3] = (vp->attribute & 0xFF);
707 return 0; /* silently discard it */
713 length_ptr = vsa_length_ptr;
714 vsa_length_ptr = NULL;
723 length_ptr = ptr + 1;
727 return 0; /* silently discard it */
731 total_length += vsa_tlen + vsa_llen;
732 if (vsa_length_ptr) *vsa_length_ptr += vsa_tlen + vsa_llen;
733 *length_ptr += vsa_tlen + vsa_llen;
737 if (vp->flags.has_tag) {
738 if (TAG_VALID(vp->flags.tag)) {
739 ptr[0] = vp->flags.tag & 0xff;
742 } else if (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD) {
744 * Tunnel passwords REQUIRE a tag, even
745 * if don't have a valid tag.
749 } /* else don't write a tag */
750 } /* else the attribute doesn't have a tag */
753 * Set up the default sources for the data.
755 data = vp->vp_octets;
762 case PW_TYPE_IPV6ADDR:
763 case PW_TYPE_IPV6PREFIX:
764 case PW_TYPE_ABINARY:
765 /* nothing more to do */
769 len = 1; /* just in case */
770 array[0] = vp->vp_integer & 0xff;
777 len = 2; /* just in case */
778 array[0] = (vp->vp_integer >> 8) & 0xff;
779 array[1] = vp->vp_integer & 0xff;
784 case PW_TYPE_INTEGER:
785 len = 4; /* just in case */
786 lvalue = htonl(vp->vp_integer);
787 memcpy(array, &lvalue, sizeof(lvalue));
790 * Perhaps discard the first octet.
792 data = &array[offset];
797 data = (const uint8_t *) &vp->vp_ipaddr;
798 len = 4; /* just in case */
802 * There are no tagged date attributes.
805 lvalue = htonl(vp->vp_date);
806 data = (const uint8_t *) &lvalue;
807 len = 4; /* just in case */
810 default: /* unknown type: ignore it */
811 librad_log("ERROR: Unknown attribute type %d", vp->type);
816 * Bound the data to 255 bytes.
818 if (len + offset + total_length > 255) {
819 len = 255 - offset - total_length;
823 * Encrypt the various password styles
825 * Attributes with encrypted values MUST be less than
828 switch (vp->flags.encrypt) {
829 case FLAG_ENCRYPT_USER_PASSWORD:
830 make_passwd(ptr + offset, &len,
832 secret, packet->vector);
835 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
837 librad_log("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
842 * Check if 255 - offset - total_length is less
843 * than 18. If so, we can't fit the data into
844 * the available space, and we discard the
847 * This is ONLY a problem if we have multiple VSA's
848 * in one Vendor-Specific, though.
850 if ((255 - offset - total_length) < 18) return 0;
852 make_tunnel_passwd(ptr + offset, &len,
853 data, len, 255 - offset - total_length,
854 secret, original->vector);
858 * The code above ensures that this attribute
861 case FLAG_ENCRYPT_ASCEND_SECRET:
862 make_secret(ptr + offset, packet->vector,
864 len = AUTH_VECTOR_LEN;
870 * Just copy the data over
872 memcpy(ptr + offset, data, len);
874 } /* switch over encryption flags */
877 * Account for the tag (if any).
882 * RFC 2865 section 5 says that zero-length attributes
885 if (len == 0) return 0;
888 * Update the various lengths.
891 if (vsa_length_ptr) *vsa_length_ptr += len;
895 return total_length; /* of attribute */
902 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
905 radius_packet_t *hdr;
907 uint16_t total_length;
914 * For simplicity in the following logic, we allow
915 * the attributes to "overflow" the 4k maximum
916 * RADIUS packet size, by one attribute.
918 * It's uint32_t, for alignment purposes.
920 uint32_t data[(MAX_PACKET_LEN + 256) / 4];
922 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
923 what = packet_codes[packet->code];
928 DEBUG("Sending %s of id %d to %s port %d\n",
930 inet_ntop(packet->dst_ipaddr.af,
931 &packet->dst_ipaddr.ipaddr,
932 ip_buffer, sizeof(ip_buffer)),
936 * Double-check some things based on packet code.
938 switch (packet->code) {
939 case PW_AUTHENTICATION_ACK:
940 case PW_AUTHENTICATION_REJECT:
941 case PW_ACCESS_CHALLENGE:
943 librad_log("ERROR: Cannot sign response packet without a request packet.");
949 * These packet vectors start off as all zero.
951 case PW_ACCOUNTING_REQUEST:
952 case PW_DISCONNECT_REQUEST:
954 memset(packet->vector, 0, sizeof(packet->vector));
962 * Use memory on the stack, until we know how
963 * large the packet will be.
965 hdr = (radius_packet_t *) data;
968 * Build standard header
970 hdr->code = packet->code;
971 hdr->id = packet->id;
973 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
975 total_length = AUTH_HDR_LEN;
978 * Load up the configuration values for the user
984 * FIXME: Loop twice over the reply list. The first time,
985 * calculate the total length of data. The second time,
986 * allocate the memory, and fill in the VP's.
988 * Hmm... this may be slower than just doing a small
993 * Loop over the reply attributes for the packet.
995 for (reply = packet->vps; reply; reply = reply->next) {
997 * Ignore non-wire attributes
999 if ((VENDOR(reply->attribute) == 0) &&
1000 ((reply->attribute & 0xFFFF) > 0xff)) {
1005 * Set the Message-Authenticator to the correct
1006 * length and initial value.
1008 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1009 reply->length = AUTH_VECTOR_LEN;
1010 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1013 * Cache the offset to the
1014 * Message-Authenticator
1016 packet->offset = total_length;
1020 * Print out ONLY the attributes which
1021 * we're sending over the wire, and print
1022 * them out BEFORE they're encrypted.
1026 len = rad_vp2attr(packet, original, secret, reply, ptr);
1028 if (len < 0) return -1;
1031 * Check that the packet is no more than 4k in
1032 * size, AFTER writing the attribute past the 4k
1033 * boundary, but BEFORE deciding to increase the
1034 * size of the packet. Note that the 'data'
1035 * buffer, above, is one attribute longer than
1036 * necessary, in order to permit this overflow.
1038 if ((total_length + len) > MAX_PACKET_LEN) {
1043 total_length += len;
1044 } /* done looping over all attributes */
1047 * Fill in the rest of the fields, and copy the data over
1048 * from the local stack to the newly allocated memory.
1050 * Yes, all this 'memcpy' is slow, but it means
1051 * that we only allocate the minimum amount of
1052 * memory for a request.
1054 packet->data_len = total_length;
1055 packet->data = (uint8_t *) malloc(packet->data_len);
1056 if (!packet->data) {
1057 librad_log("Out of memory");
1061 memcpy(packet->data, data, packet->data_len);
1062 hdr = (radius_packet_t *) packet->data;
1064 total_length = htons(total_length);
1065 memcpy(hdr->length, &total_length, sizeof(total_length));
1072 * Sign a previously encoded packet.
1074 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1077 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1080 * It wasn't assigned an Id, this is bad!
1082 if (packet->id < 0) {
1083 librad_log("ERROR: RADIUS packets must be assigned an Id.");
1087 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1088 (packet->offset < 0)) {
1089 librad_log("ERROR: You must call rad_encode() before rad_sign()");
1094 * If there's a Message-Authenticator, update it
1095 * now, BEFORE updating the authentication vector.
1097 if (packet->offset > 0) {
1098 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1100 switch (packet->code) {
1101 case PW_ACCOUNTING_REQUEST:
1102 case PW_ACCOUNTING_RESPONSE:
1103 case PW_DISCONNECT_REQUEST:
1104 case PW_DISCONNECT_ACK:
1105 case PW_DISCONNECT_NAK:
1106 case PW_COA_REQUEST:
1109 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1112 case PW_AUTHENTICATION_ACK:
1113 case PW_AUTHENTICATION_REJECT:
1114 case PW_ACCESS_CHALLENGE:
1116 librad_log("ERROR: Cannot sign response packet without a request packet.");
1119 memcpy(hdr->vector, original->vector,
1123 default: /* others have vector already set to zero */
1129 * Set the authentication vector to zero,
1130 * calculate the signature, and put it
1131 * into the Message-Authenticator
1134 lrad_hmac_md5(packet->data, packet->data_len,
1135 secret, strlen(secret),
1137 memcpy(packet->data + packet->offset + 2,
1138 calc_auth_vector, AUTH_VECTOR_LEN);
1141 * Copy the original request vector back
1142 * to the raw packet.
1144 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1148 * Switch over the packet code, deciding how to
1151 switch (packet->code) {
1153 * Request packets are not signed, bur
1154 * have a random authentication vector.
1156 case PW_AUTHENTICATION_REQUEST:
1157 case PW_STATUS_SERVER:
1161 * Reply packets are signed with the
1162 * authentication vector of the request.
1170 MD5Update(&context, packet->data, packet->data_len);
1171 MD5Update(&context, secret, strlen(secret));
1172 MD5Final(digest, &context);
1174 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1175 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1178 }/* switch over packet codes */
1184 * Reply to the request. Also attach
1185 * reply attribute value pairs and any user message provided.
1187 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1192 char ip_buffer[128];
1195 * Maybe it's a fake packet. Don't send it.
1197 if (!packet || (packet->sockfd < 0)) {
1201 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1202 what = packet_codes[packet->code];
1208 * First time through, allocate room for the packet
1210 if (!packet->data) {
1212 * Encode the packet.
1214 if (rad_encode(packet, original, secret) < 0) {
1219 * Re-sign it, including updating the
1220 * Message-Authenticator.
1222 if (rad_sign(packet, original, secret) < 0) {
1227 * If packet->data points to data, then we print out
1228 * the VP list again only for debugging.
1230 } else if (librad_debug) {
1231 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1232 inet_ntop(packet->dst_ipaddr.af,
1233 &packet->dst_ipaddr.ipaddr,
1234 ip_buffer, sizeof(ip_buffer)),
1237 for (reply = packet->vps; reply; reply = reply->next) {
1238 /* FIXME: ignore attributes > 0xff */
1244 * And send it on it's way.
1246 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1247 &packet->src_ipaddr, packet->src_port,
1248 &packet->dst_ipaddr, packet->dst_port);
1253 * Validates the requesting client NAS. Calculates the
1254 * signature based on the clients private key.
1256 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1258 uint8_t digest[AUTH_VECTOR_LEN];
1262 * Zero out the auth_vector in the received packet.
1263 * Then append the shared secret to the received packet,
1264 * and calculate the MD5 sum. This must be the same
1265 * as the original MD5 sum (packet->vector).
1267 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1270 * MD5(packet + secret);
1273 MD5Update(&context, packet->data, packet->data_len);
1274 MD5Update(&context, secret, strlen(secret));
1275 MD5Final(digest, &context);
1278 * Return 0 if OK, 2 if not OK.
1280 if (memcmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1286 * Validates the requesting client NAS. Calculates the
1287 * signature based on the clients private key.
1289 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1292 uint8_t calc_digest[AUTH_VECTOR_LEN];
1298 if (original == NULL) {
1303 * Copy the original vector in place.
1305 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1308 * MD5(packet + secret);
1311 MD5Update(&context, packet->data, packet->data_len);
1312 MD5Update(&context, secret, strlen(secret));
1313 MD5Final(calc_digest, &context);
1316 * Copy the packet's vector back to the packet.
1318 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1321 * Return 0 if OK, 2 if not OK.
1323 if (memcmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1329 * See if the data pointed to by PTR is a valid RADIUS packet.
1331 * packet is not 'const * const' because we may update data_len,
1332 * if there's more data in the UDP packet than in the RADIUS packet.
1334 int rad_packet_ok(RADIUS_PACKET *packet)
1339 radius_packet_t *hdr;
1340 char host_ipaddr[128];
1346 * Check for packets smaller than the packet header.
1348 * RFC 2865, Section 3., subsection 'length' says:
1350 * "The minimum length is 20 ..."
1352 if (packet->data_len < AUTH_HDR_LEN) {
1353 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1354 inet_ntop(packet->src_ipaddr.af,
1355 &packet->src_ipaddr.ipaddr,
1356 host_ipaddr, sizeof(host_ipaddr)),
1357 packet->data_len, AUTH_HDR_LEN);
1362 * RFC 2865, Section 3., subsection 'length' says:
1364 * " ... and maximum length is 4096."
1366 if (packet->data_len > MAX_PACKET_LEN) {
1367 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1368 inet_ntop(packet->src_ipaddr.af,
1369 &packet->src_ipaddr.ipaddr,
1370 host_ipaddr, sizeof(host_ipaddr)),
1371 packet->data_len, MAX_PACKET_LEN);
1376 * Check for packets with mismatched size.
1377 * i.e. We've received 128 bytes, and the packet header
1378 * says it's 256 bytes long.
1380 totallen = (packet->data[2] << 8) | packet->data[3];
1381 hdr = (radius_packet_t *)packet->data;
1384 * Code of 0 is not understood.
1385 * Code of 16 or greate is not understood.
1387 if ((hdr->code == 0) ||
1388 (hdr->code >= MAX_PACKET_CODE)) {
1389 librad_log("WARNING: Bad RADIUS packet from host %s: unknown packet code %d",
1390 inet_ntop(packet->src_ipaddr.af,
1391 &packet->src_ipaddr.ipaddr,
1392 host_ipaddr, sizeof(host_ipaddr)),
1398 * Message-Authenticator is required in Status-Server
1399 * packets, otherwise they can be trivially forged.
1401 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1404 * Repeat the length checks. This time, instead of
1405 * looking at the data we received, look at the value
1406 * of the 'length' field inside of the packet.
1408 * Check for packets smaller than the packet header.
1410 * RFC 2865, Section 3., subsection 'length' says:
1412 * "The minimum length is 20 ..."
1414 if (totallen < AUTH_HDR_LEN) {
1415 librad_log("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1416 inet_ntop(packet->src_ipaddr.af,
1417 &packet->src_ipaddr.ipaddr,
1418 host_ipaddr, sizeof(host_ipaddr)),
1419 totallen, AUTH_HDR_LEN);
1424 * And again, for the value of the 'length' field.
1426 * RFC 2865, Section 3., subsection 'length' says:
1428 * " ... and maximum length is 4096."
1430 if (totallen > MAX_PACKET_LEN) {
1431 librad_log("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1432 inet_ntop(packet->src_ipaddr.af,
1433 &packet->src_ipaddr.ipaddr,
1434 host_ipaddr, sizeof(host_ipaddr)),
1435 totallen, MAX_PACKET_LEN);
1440 * RFC 2865, Section 3., subsection 'length' says:
1442 * "If the packet is shorter than the Length field
1443 * indicates, it MUST be silently discarded."
1445 * i.e. No response to the NAS.
1447 if (packet->data_len < totallen) {
1448 librad_log("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1449 inet_ntop(packet->src_ipaddr.af,
1450 &packet->src_ipaddr.ipaddr,
1451 host_ipaddr, sizeof(host_ipaddr)),
1452 packet->data_len, totallen);
1457 * RFC 2865, Section 3., subsection 'length' says:
1459 * "Octets outside the range of the Length field MUST be
1460 * treated as padding and ignored on reception."
1462 if (packet->data_len > totallen) {
1464 * We're shortening the packet below, but just
1465 * to be paranoid, zero out the extra data.
1467 memset(packet->data + totallen, 0, packet->data_len - totallen);
1468 packet->data_len = totallen;
1472 * Walk through the packet's attributes, ensuring that
1473 * they add up EXACTLY to the size of the packet.
1475 * If they don't, then the attributes either under-fill
1476 * or over-fill the packet. Any parsing of the packet
1477 * is impossible, and will result in unknown side effects.
1479 * This would ONLY happen with buggy RADIUS implementations,
1480 * or with an intentional attack. Either way, we do NOT want
1481 * to be vulnerable to this problem.
1484 count = totallen - AUTH_HDR_LEN;
1489 * Attribute number zero is NOT defined.
1492 librad_log("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1493 inet_ntop(packet->src_ipaddr.af,
1494 &packet->src_ipaddr.ipaddr,
1495 host_ipaddr, sizeof(host_ipaddr)));
1500 * Attributes are at LEAST as long as the ID & length
1501 * fields. Anything shorter is an invalid attribute.
1504 librad_log("WARNING: Malformed RADIUS packet from host %s: attribute %d too short",
1505 inet_ntop(packet->src_ipaddr.af,
1506 &packet->src_ipaddr.ipaddr,
1507 host_ipaddr, sizeof(host_ipaddr)),
1513 * Sanity check the attributes for length.
1516 default: /* don't do anything by default */
1520 * If there's an EAP-Message, we require
1521 * a Message-Authenticator.
1523 case PW_EAP_MESSAGE:
1527 case PW_MESSAGE_AUTHENTICATOR:
1528 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1529 librad_log("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1530 inet_ntop(packet->src_ipaddr.af,
1531 &packet->src_ipaddr.ipaddr,
1532 host_ipaddr, sizeof(host_ipaddr)),
1541 * FIXME: Look up the base 255 attributes in the
1542 * dictionary, and switch over their type. For
1543 * integer/date/ip, the attribute length SHOULD
1546 count -= attr[1]; /* grab the attribute length */
1548 num_attributes++; /* seen one more attribute */
1552 * If the attributes add up to a packet, it's allowed.
1554 * If not, we complain, and throw the packet away.
1557 librad_log("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1558 inet_ntop(packet->src_ipaddr.af,
1559 &packet->src_ipaddr.ipaddr,
1560 host_ipaddr, sizeof(host_ipaddr)));
1565 * If we're configured to look for a maximum number of
1566 * attributes, and we've seen more than that maximum,
1567 * then throw the packet away, as a possible DoS.
1569 if ((librad_max_attributes > 0) &&
1570 (num_attributes > librad_max_attributes)) {
1571 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1572 inet_ntop(packet->src_ipaddr.af,
1573 &packet->src_ipaddr.ipaddr,
1574 host_ipaddr, sizeof(host_ipaddr)),
1575 num_attributes, librad_max_attributes);
1580 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1582 * A packet with an EAP-Message attribute MUST also have
1583 * a Message-Authenticator attribute.
1585 * A Message-Authenticator all by itself is OK, though.
1587 * Similarly, Status-Server packets MUST contain
1588 * Message-Authenticator attributes.
1590 if (require_ma && ! seen_ma) {
1591 librad_log("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1592 inet_ntop(packet->src_ipaddr.af,
1593 &packet->src_ipaddr.ipaddr,
1594 host_ipaddr, sizeof(host_ipaddr)));
1599 * Fill RADIUS header fields
1601 packet->code = hdr->code;
1602 packet->id = hdr->id;
1603 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1610 * Receive UDP client requests, and fill in
1611 * the basics of a RADIUS_PACKET structure.
1613 RADIUS_PACKET *rad_recv(int fd)
1615 RADIUS_PACKET *packet;
1618 * Allocate the new request data structure
1620 if ((packet = malloc(sizeof(*packet))) == NULL) {
1621 librad_log("out of memory");
1624 memset(packet, 0, sizeof(*packet));
1626 packet->data_len = rad_recvfrom(fd, &packet->data, 0,
1627 &packet->src_ipaddr, &packet->src_port,
1628 &packet->dst_ipaddr, &packet->dst_port);
1631 * Check for socket errors.
1633 if (packet->data_len < 0) {
1634 librad_log("Error receiving packet: %s", strerror(errno));
1635 /* packet->data is NULL */
1641 * If the packet is too big, then rad_recvfrom did NOT
1642 * allocate memory. Instead, it just discarded the
1645 if (packet->data_len > MAX_PACKET_LEN) {
1646 librad_log("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1647 /* packet->data is NULL */
1653 * Read no data. Continue.
1654 * This check is AFTER the MAX_PACKET_LEN check above, because
1655 * if the packet is larger than MAX_PACKET_LEN, we also have
1656 * packet->data == NULL
1658 if ((packet->data_len == 0) || !packet->data) {
1659 librad_log("No data.");
1665 * See if it's a well-formed RADIUS packet.
1667 if (!rad_packet_ok(packet)) {
1673 * Remember which socket we read the packet from.
1675 packet->sockfd = fd;
1678 * FIXME: Do even more filtering by only permitting
1679 * certain IP's. The problem is that we don't know
1680 * how to do this properly for all possible clients...
1684 * Explicitely set the VP list to empty.
1689 char host_ipaddr[128];
1691 if ((packet->code > 0) && (packet->code < MAX_PACKET_CODE)) {
1692 printf("rad_recv: %s packet from host %s port %d",
1693 packet_codes[packet->code],
1694 inet_ntop(packet->src_ipaddr.af,
1695 &packet->src_ipaddr.ipaddr,
1696 host_ipaddr, sizeof(host_ipaddr)),
1699 printf("rad_recv: Packet from host %s port %d code=%d",
1700 inet_ntop(packet->src_ipaddr.af,
1701 &packet->src_ipaddr.ipaddr,
1702 host_ipaddr, sizeof(host_ipaddr)),
1706 printf(", id=%d, length=%d\n", packet->id, packet->data_len);
1714 * Verify the signature of a packet.
1716 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1723 if (!packet || !packet->data) return -1;
1726 * Before we allocate memory for the attributes, do more
1729 ptr = packet->data + AUTH_HDR_LEN;
1730 length = packet->data_len - AUTH_HDR_LEN;
1731 while (length > 0) {
1732 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
1733 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1738 default: /* don't do anything. */
1742 * Note that more than one Message-Authenticator
1743 * attribute is invalid.
1745 case PW_MESSAGE_AUTHENTICATOR:
1746 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
1747 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
1749 switch (packet->code) {
1753 case PW_ACCOUNTING_REQUEST:
1754 case PW_ACCOUNTING_RESPONSE:
1755 case PW_DISCONNECT_REQUEST:
1756 case PW_DISCONNECT_ACK:
1757 case PW_DISCONNECT_NAK:
1758 case PW_COA_REQUEST:
1761 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1764 case PW_AUTHENTICATION_ACK:
1765 case PW_AUTHENTICATION_REJECT:
1766 case PW_ACCESS_CHALLENGE:
1768 librad_log("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
1771 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1775 lrad_hmac_md5(packet->data, packet->data_len,
1776 secret, strlen(secret), calc_auth_vector);
1777 if (memcmp(calc_auth_vector, msg_auth_vector,
1778 sizeof(calc_auth_vector)) != 0) {
1780 librad_log("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
1781 inet_ntop(packet->src_ipaddr.af,
1782 &packet->src_ipaddr.ipaddr,
1783 buffer, sizeof(buffer)));
1784 /* Silently drop packet, according to RFC 3579 */
1786 } /* else the message authenticator was good */
1789 * Reinitialize Authenticators.
1791 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
1792 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1794 } /* switch over the attributes */
1798 } /* loop over the packet, sanity checking the attributes */
1801 * It looks like a RADIUS packet, but we can't validate
1804 if ((packet->code == 0) || packet->code >= MAX_PACKET_CODE) {
1806 librad_log("Received Unknown packet code %d"
1807 "from client %s port %d: Cannot validate signature",
1809 inet_ntop(packet->src_ipaddr.af,
1810 &packet->src_ipaddr.ipaddr,
1811 buffer, sizeof(buffer)),
1817 * Calculate and/or verify digest.
1819 switch(packet->code) {
1823 case PW_AUTHENTICATION_REQUEST:
1824 case PW_STATUS_SERVER:
1825 case PW_DISCONNECT_REQUEST:
1827 * The authentication vector is random
1828 * nonsense, invented by the client.
1832 case PW_ACCOUNTING_REQUEST:
1833 if (calc_acctdigest(packet, secret) > 1) {
1834 librad_log("Received Accounting-Request packet "
1835 "from %s with invalid signature! (Shared secret is incorrect.)",
1836 inet_ntop(packet->src_ipaddr.af,
1837 &packet->src_ipaddr.ipaddr,
1838 buffer, sizeof(buffer)));
1843 /* Verify the reply digest */
1844 case PW_AUTHENTICATION_ACK:
1845 case PW_AUTHENTICATION_REJECT:
1846 case PW_ACCESS_CHALLENGE:
1847 case PW_ACCOUNTING_RESPONSE:
1848 case PW_DISCONNECT_ACK:
1849 case PW_DISCONNECT_NAK:
1852 rcode = calc_replydigest(packet, original, secret);
1854 librad_log("Received %s packet "
1855 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
1856 packet_codes[packet->code],
1857 inet_ntop(packet->src_ipaddr.af,
1858 &packet->src_ipaddr.ipaddr,
1859 buffer, sizeof(buffer)),
1867 librad_log("Received Unknown packet code %d"
1868 "from client %s port %d: Cannot validate signature",
1870 inet_ntop(packet->src_ipaddr.af,
1871 &packet->src_ipaddr.ipaddr,
1872 buffer, sizeof(buffer)),
1882 * Parse a RADIUS attribute into a data structure.
1884 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1885 const char *secret, int attribute, int length,
1886 const uint8_t *data)
1891 if ((vp = paircreate(attribute, PW_TYPE_OCTETS)) == NULL) {
1896 * If length is greater than 253, something is SERIOUSLY
1899 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
1901 vp->length = length;
1902 vp->operator = T_OP_EQ;
1908 if (vp->flags.has_tag) {
1909 if (TAG_VALID(data[0]) ||
1910 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
1912 * Tunnel passwords REQUIRE a tag, even
1913 * if don't have a valid tag.
1915 vp->flags.tag = data[0];
1917 if ((vp->type == PW_TYPE_STRING) ||
1918 (vp->type == PW_TYPE_OCTETS)) offset = 1;
1923 * Copy the data to be decrypted
1925 memcpy(&vp->vp_octets[0], data + offset, length - offset);
1926 vp->length -= offset;
1929 * Decrypt the attribute.
1931 switch (vp->flags.encrypt) {
1935 case FLAG_ENCRYPT_USER_PASSWORD:
1937 rad_pwdecode((char *)vp->vp_strvalue,
1941 rad_pwdecode((char *)vp->vp_strvalue,
1945 if (vp->attribute == PW_USER_PASSWORD) {
1946 vp->length = strlen(vp->vp_strvalue);
1951 * Tunnel-Password's may go ONLY
1952 * in response packets.
1954 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
1955 if (!original) goto raw;
1957 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
1958 secret, original->vector) < 0) {
1964 * Ascend-Send-Secret
1965 * Ascend-Receive-Secret
1967 case FLAG_ENCRYPT_ASCEND_SECRET:
1971 uint8_t my_digest[AUTH_VECTOR_LEN];
1972 make_secret(my_digest,
1975 memcpy(vp->vp_strvalue, my_digest,
1977 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
1978 vp->length = strlen(vp->vp_strvalue);
1984 } /* switch over encryption flags */
1988 case PW_TYPE_STRING:
1989 case PW_TYPE_OCTETS:
1990 case PW_TYPE_ABINARY:
1991 /* nothing more to do */
1995 if (vp->length != 1) goto raw;
1997 vp->vp_integer = vp->vp_octets[0];
2002 if (vp->length != 2) goto raw;
2004 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2007 case PW_TYPE_INTEGER:
2008 if (vp->length != 4) goto raw;
2010 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2011 vp->vp_integer = ntohl(vp->vp_integer);
2013 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2016 * Try to get named VALUEs
2020 dval = dict_valbyattr(vp->attribute,
2023 strlcpy(vp->vp_strvalue,
2025 sizeof(vp->vp_strvalue));
2031 if (vp->length != 4) goto raw;
2033 memcpy(&vp->vp_date, vp->vp_octets, 4);
2034 vp->vp_date = ntohl(vp->vp_date);
2038 case PW_TYPE_IPADDR:
2039 if (vp->length != 4) goto raw;
2041 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2045 * IPv6 interface ID is 8 octets long.
2048 if (vp->length != 8) goto raw;
2049 /* vp->vp_ifid == vp->vp_octets */
2053 * IPv6 addresses are 16 octets long
2055 case PW_TYPE_IPV6ADDR:
2056 if (vp->length != 16) goto raw;
2057 /* vp->vp_ipv6addr == vp->vp_octets */
2061 * IPv6 prefixes are 2 to 18 octets long.
2063 * RFC 3162: The first octet is unused.
2064 * The second is the length of the prefix
2065 * the rest are the prefix data.
2067 * The prefix length can have value 0 to 128.
2069 case PW_TYPE_IPV6PREFIX:
2070 if (vp->length < 2 || vp->length > 18) goto raw;
2071 if (vp->vp_octets[1] > 128) goto raw;
2074 * FIXME: double-check that
2075 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2077 if (vp->length < 18) {
2078 memset(vp->vp_octets + vp->length, 0,
2085 vp->type = PW_TYPE_OCTETS;
2086 vp->length = length;
2087 memcpy(vp->vp_octets, data, length);
2091 * Ensure there's no encryption or tag stuff,
2092 * we just pass the attribute as-is.
2094 memset(&vp->flags, 0, sizeof(vp->flags));
2102 * Calculate/check digest, and decode radius attributes.
2104 * -1 on decoding error
2107 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2111 uint32_t vendorcode;
2119 radius_packet_t *hdr;
2120 int vsa_tlen, vsa_llen;
2121 DICT_VENDOR *dv = NULL;
2122 int num_attributes = 0;
2125 * Extract attribute-value pairs
2127 hdr = (radius_packet_t *)packet->data;
2129 packet_length = packet->data_len - AUTH_HDR_LEN;
2132 * There may be VP's already in the packet. Don't
2135 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2141 vsa_tlen = vsa_llen = 1;
2144 * We have to read at least two bytes.
2146 * rad_recv() above ensures that this is OK.
2148 while (packet_length > 0) {
2153 * Normal attribute, handle it like normal.
2155 if (vendorcode == 0) {
2157 * No room to read attr/length,
2158 * or bad attribute, or attribute is
2159 * too short, or attribute is too long,
2160 * stop processing the packet.
2162 if ((packet_length < 2) ||
2163 (ptr[0] == 0) || (ptr[1] < 2) ||
2164 (ptr[1] > packet_length)) break;
2172 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2175 * No vendor code, or ONLY vendor code.
2177 if (attrlen <= 4) goto create_pair;
2183 * Handle Vendor-Specific
2185 if (vendorlen == 0) {
2191 * attrlen was checked above.
2193 memcpy(&lvalue, ptr, 4);
2194 myvendor = ntohl(lvalue);
2197 * Zero isn't allowed.
2199 if (myvendor == 0) goto create_pair;
2202 * This is an implementation issue.
2203 * We currently pack vendor into the upper
2204 * 16 bits of a 32-bit attribute number,
2205 * so we can't handle vendor numbers larger
2208 if (myvendor > 65535) goto create_pair;
2210 vsa_tlen = vsa_llen = 1;
2211 dv = dict_vendorbyvalue(myvendor);
2213 vsa_tlen = dv->type;
2214 vsa_llen = dv->length;
2218 * Sweep through the list of VSA's,
2219 * seeing if they exactly fill the
2220 * outer Vendor-Specific attribute.
2222 * If not, create a raw Vendor-Specific.
2225 sublen = attrlen - 4;
2228 * See if we can parse it.
2234 * Don't have a type, it's bad.
2236 if (sublen < vsa_tlen) goto create_pair;
2239 * Ensure that the attribute number
2248 myattr = (subptr[0] << 8) | subptr[1];
2252 if ((subptr[0] != 0) ||
2253 (subptr[1] != 0)) goto create_pair;
2255 myattr = (subptr[2] << 8) | subptr[3];
2259 * Our dictionary is broken.
2266 * Not enough room for one more
2269 if (sublen < vsa_tlen + vsa_llen) goto create_pair;
2272 attribute = (myvendor << 16) | myattr;
2273 ptr += 4 + vsa_tlen;
2274 attrlen -= (4 + vsa_tlen);
2275 packet_length -= 4 + vsa_tlen;
2279 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen))
2282 if (subptr[vsa_tlen] > sublen)
2284 sublen -= subptr[vsa_tlen];
2285 subptr += subptr[vsa_tlen];
2289 if (subptr[vsa_tlen] != 0) goto create_pair;
2290 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2292 if (subptr[vsa_tlen + 1] > sublen)
2294 sublen -= subptr[vsa_tlen + 1];
2295 subptr += subptr[vsa_tlen + 1];
2299 * Our dictionaries are
2305 } while (sublen > 0);
2307 vendorcode = myvendor;
2308 vendorlen = attrlen - 4;
2315 * attrlen is the length of this attribute.
2316 * total_len is the length of the encompassing
2325 attribute = (ptr[0] << 8) | ptr[1];
2328 default: /* can't hit this. */
2331 attribute |= (vendorcode << 16);
2336 attrlen = ptr[0] - (vsa_tlen + vsa_llen);
2340 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
2343 default: /* can't hit this. */
2347 vendorlen -= vsa_tlen + vsa_llen + attrlen;
2348 if (vendorlen == 0) vendorcode = 0;
2349 packet_length -= (vsa_tlen + vsa_llen);
2352 * Create the attribute, setting the default type
2353 * to 'octets'. If the type in the dictionary
2354 * is different, then the dictionary type will
2355 * over-ride this one.
2358 pair = rad_attr2vp(packet, original, secret,
2359 attribute, attrlen, ptr);
2361 pairfree(&packet->vps);
2362 librad_log("out of memory");
2375 * VSA's may not have been counted properly in
2376 * rad_packet_ok() above, as it is hard to count
2377 * then without using the dictionary. We
2378 * therefore enforce the limits here, too.
2380 if ((librad_max_attributes > 0) &&
2381 (num_attributes > librad_max_attributes)) {
2382 char host_ipaddr[128];
2384 pairfree(&packet->vps);
2385 librad_log("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
2386 inet_ntop(packet->src_ipaddr.af,
2387 &packet->src_ipaddr.ipaddr,
2388 host_ipaddr, sizeof(host_ipaddr)),
2389 num_attributes, librad_max_attributes);
2394 packet_length -= attrlen;
2398 * Merge information from the outside world into our
2401 lrad_rand_seed(packet->data, AUTH_HDR_LEN);
2410 * We assume that the passwd buffer passed is big enough.
2411 * RFC2138 says the password is max 128 chars, so the size
2412 * of the passwd buffer must be at least 129 characters.
2413 * Preferably it's just MAX_STRING_LEN.
2415 * int *pwlen is updated to the new length of the encrypted
2416 * password - a multiple of 16 bytes.
2418 int rad_pwencode(char *passwd, int *pwlen, const char *secret,
2419 const uint8_t *vector)
2421 lrad_MD5_CTX context, old;
2422 uint8_t digest[AUTH_VECTOR_LEN];
2423 int i, n, secretlen;
2427 * RFC maximum is 128 bytes.
2429 * If length is zero, pad it out with zeros.
2431 * If the length isn't aligned to 16 bytes,
2432 * zero out the extra data.
2436 if (len > 128) len = 128;
2439 memset(passwd, 0, AUTH_PASS_LEN);
2440 len = AUTH_PASS_LEN;
2441 } else if ((len % AUTH_PASS_LEN) != 0) {
2442 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
2443 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
2448 * Use the secret to setup the decryption digest
2450 secretlen = strlen(secret);
2452 lrad_MD5Init(&context);
2453 lrad_MD5Update(&context, secret, secretlen);
2454 old = context; /* save intermediate work */
2457 * Encrypt it in place. Don't bother checking
2458 * len, as we've ensured above that it's OK.
2460 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2462 lrad_MD5Update(&context, vector, AUTH_PASS_LEN);
2463 lrad_MD5Final(digest, &context);
2466 lrad_MD5Update(&context,
2467 passwd + n - AUTH_PASS_LEN,
2469 lrad_MD5Final(digest, &context);
2472 for (i = 0; i < AUTH_PASS_LEN; i++) {
2473 passwd[i + n] ^= digest[i];
2483 int rad_pwdecode(char *passwd, int pwlen, const char *secret,
2484 const uint8_t *vector)
2486 lrad_MD5_CTX context, old;
2487 uint8_t digest[AUTH_VECTOR_LEN];
2488 int i, n, secretlen;
2491 * The RFC's say that the maximum is 128.
2492 * The buffer we're putting it into above is 254, so
2493 * we don't need to do any length checking.
2495 if (pwlen > 128) pwlen = 128;
2500 if (pwlen == 0) goto done;
2503 * Use the secret to setup the decryption digest
2505 secretlen = strlen(secret);
2507 lrad_MD5Init(&context);
2508 lrad_MD5Update(&context, secret, secretlen);
2509 old = context; /* save intermediate work */
2512 * The inverse of the code above.
2514 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
2516 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2517 lrad_MD5Final(digest, &context);
2520 if (pwlen > AUTH_PASS_LEN) lrad_MD5Update(&context, passwd, AUTH_PASS_LEN);
2522 lrad_MD5Final(digest, &context);
2525 if (pwlen > (n + AUTH_PASS_LEN)) lrad_MD5Update(&context, passwd + n, AUTH_PASS_LEN);
2528 for (i = 0; i < AUTH_PASS_LEN; i++) {
2529 passwd[i + n] ^= digest[i];
2534 passwd[pwlen] = '\0';
2535 return strlen(passwd);
2540 * Encode Tunnel-Password attributes when sending them out on the wire.
2542 * int *pwlen is updated to the new length of the encrypted
2543 * password - a multiple of 16 bytes.
2545 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
2548 int rad_tunnel_pwencode(char *passwd, int *pwlen, const char *secret,
2549 const uint8_t *vector)
2551 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
2552 unsigned char digest[AUTH_VECTOR_LEN];
2554 int i, n, secretlen;
2559 if (len > 127) len = 127;
2562 * Shift the password 3 positions right to place a salt and original
2563 * length, tag will be added automatically on packet send
2565 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
2569 * save original password length as first password character;
2576 * Generate salt. The RFC's say:
2578 * The high bit of salt[0] must be set, each salt in a
2579 * packet should be unique, and they should be random
2581 * So, we set the high bit, add in a counter, and then
2582 * add in some CSPRNG data. should be OK..
2584 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
2585 (lrad_rand() & 0x07));
2586 salt[1] = lrad_rand();
2589 * Padd password to multiple of AUTH_PASS_LEN bytes.
2591 n = len % AUTH_PASS_LEN;
2593 n = AUTH_PASS_LEN - n;
2594 for (; n > 0; n--, len++)
2597 /* set new password length */
2601 * Use the secret to setup the decryption digest
2603 secretlen = strlen(secret);
2604 memcpy(buffer, secret, secretlen);
2606 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
2608 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
2609 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
2610 librad_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
2612 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
2613 librad_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
2616 for (i = 0; i < AUTH_PASS_LEN; i++) {
2617 passwd[i + n2] ^= digest[i];
2625 * Decode Tunnel-Password encrypted attributes.
2627 * Defined in RFC-2868, this uses a two char SALT along with the
2628 * initial intermediate value, to differentiate it from the
2631 int rad_tunnel_pwdecode(uint8_t *passwd, int *pwlen, const char *secret,
2632 const uint8_t *vector)
2634 lrad_MD5_CTX context, old;
2635 uint8_t digest[AUTH_VECTOR_LEN];
2637 unsigned i, n, len, reallen;
2642 * We need at least a salt.
2645 librad_log("tunnel password is too short");
2650 * There's a salt, but no password. Or, there's a salt
2651 * and a 'data_len' octet. It's wrong, but at least we
2652 * can figure out what it means: the password is empty.
2654 * Note that this means we ignore the 'data_len' field,
2655 * if the attribute length tells us that there's no
2656 * more data. So the 'data_len' field may be wrong,
2665 len -= 2; /* discount the salt */
2668 * Use the secret to setup the decryption digest
2670 secretlen = strlen(secret);
2672 lrad_MD5Init(&context);
2673 lrad_MD5Update(&context, secret, secretlen);
2674 old = context; /* save intermediate work */
2677 * Set up the initial key:
2679 * b(1) = MD5(secret + vector + salt)
2681 lrad_MD5Update(&context, vector, AUTH_VECTOR_LEN);
2682 lrad_MD5Update(&context, passwd, 2);
2685 for (n = 0; n < len; n += AUTH_PASS_LEN) {
2689 lrad_MD5Final(digest, &context);
2694 * A quick check: decrypt the first octet
2695 * of the password, which is the
2696 * 'data_len' field. Ensure it's sane.
2698 reallen = passwd[2] ^ digest[0];
2699 if (reallen >= len) {
2700 librad_log("tunnel password is too long for the attribute");
2704 lrad_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
2708 lrad_MD5Final(digest, &context);
2711 lrad_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
2714 for (i = base; i < AUTH_PASS_LEN; i++) {
2715 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
2720 * See make_tunnel_password, above.
2722 if (reallen > 239) reallen = 239;
2725 passwd[reallen] = 0;
2731 * Encode a CHAP password
2733 * FIXME: might not work with Ascend because
2734 * we use vp->length, and Ascend gear likes
2735 * to send an extra '\0' in the string!
2737 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
2738 VALUE_PAIR *password)
2742 uint8_t string[MAX_STRING_LEN * 2 + 1];
2743 VALUE_PAIR *challenge;
2746 * Sanity check the input parameters
2748 if ((packet == NULL) || (password == NULL)) {
2753 * Note that the password VP can be EITHER
2754 * a User-Password attribute (from a check-item list),
2755 * or a CHAP-Password attribute (the client asking
2756 * the library to encode it).
2764 memcpy(ptr, password->vp_strvalue, password->length);
2765 ptr += password->length;
2766 i += password->length;
2769 * Use Chap-Challenge pair if present,
2770 * Request-Authenticator otherwise.
2772 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE);
2774 memcpy(ptr, challenge->vp_strvalue, challenge->length);
2775 i += challenge->length;
2777 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
2778 i += AUTH_VECTOR_LEN;
2782 librad_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
2789 * Seed the random number generator.
2791 * May be called any number of times.
2793 void lrad_rand_seed(const void *data, size_t size)
2798 * Ensure that the pool is initialized.
2800 if (!lrad_rand_initialized) {
2803 memset(&lrad_rand_pool, 0, sizeof(lrad_rand_pool));
2805 fd = open("/dev/urandom", O_RDONLY);
2811 while (total < sizeof(lrad_rand_pool.randrsl)) {
2812 this = read(fd, lrad_rand_pool.randrsl,
2813 sizeof(lrad_rand_pool.randrsl) - total);
2814 if ((this < 0) && (errno != EINTR)) break;
2815 if (this > 0) total += this;
2819 lrad_rand_pool.randrsl[0] = fd;
2820 lrad_rand_pool.randrsl[1] = time(NULL);
2821 lrad_rand_pool.randrsl[2] = errno;
2824 lrad_randinit(&lrad_rand_pool, 1);
2825 lrad_rand_pool.randcnt = 0;
2826 lrad_rand_initialized = 1;
2832 * Hash the user data
2835 if (!hash) hash = lrad_rand();
2836 hash = lrad_hash_update(data, size, hash);
2838 lrad_rand_pool.randmem[lrad_rand_pool.randcnt] ^= hash;
2843 * Return a 32-bit random number.
2845 uint32_t lrad_rand(void)
2850 * Ensure that the pool is initialized.
2852 if (!lrad_rand_initialized) {
2853 lrad_rand_seed(NULL, 0);
2856 num = lrad_rand_pool.randrsl[lrad_rand_pool.randcnt++];
2857 if (lrad_rand_pool.randcnt == 256) {
2858 lrad_rand_pool.randcnt = 0;
2859 lrad_isaac(&lrad_rand_pool);
2867 * Allocate a new RADIUS_PACKET
2869 RADIUS_PACKET *rad_alloc(int newvector)
2873 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
2874 librad_log("out of memory");
2877 memset(rp, 0, sizeof(*rp));
2883 uint32_t hash, base;
2886 * Don't expose the actual contents of the random
2890 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
2891 hash = lrad_rand() ^ base;
2892 memcpy(rp->vector + i, &hash, sizeof(hash));
2895 lrad_rand(); /* stir the pool again */
2901 * Free a RADIUS_PACKET
2903 void rad_free(RADIUS_PACKET **radius_packet_ptr)
2905 RADIUS_PACKET *radius_packet;
2907 if (!radius_packet_ptr || !*radius_packet_ptr) return;
2908 radius_packet = *radius_packet_ptr;
2910 free(radius_packet->data);
2912 pairfree(&radius_packet->vps);
2914 free(radius_packet);
2916 *radius_packet_ptr = NULL;