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 fr_max_attributes = 0;
57 FILE *fr_log_fp = NULL;
59 typedef struct radius_packet_t {
63 uint8_t vector[AUTH_VECTOR_LEN];
67 static fr_randctx fr_rand_pool; /* across multiple calls */
68 static int fr_rand_initialized = 0;
69 static unsigned int salt_offset = 0;
71 const char *fr_packet_codes[FR_MAX_PACKET_CODE] = {
77 "Accounting-Response",
93 "Resource-Free-Request",
94 "Resource-Free-Response",
95 "Resource-Query-Request",
96 "Resource-Query-Response",
97 "Alternate-Resource-Reclaim-Request",
99 "NAS-Reboot-Response",
112 "Disconnect-Request",
122 "IP-Address-Allocate",
127 void fr_printf_log(const char *fmt, ...)
132 if ((fr_debug_flag == 0) || !fr_log_fp) {
137 vfprintf(fr_log_fp, fmt, ap);
143 static void print_hex(RADIUS_PACKET *packet)
147 if (!packet->data) return;
149 printf(" Code:\t\t%u\n", packet->data[0]);
150 printf(" Id:\t\t%u\n", packet->data[1]);
151 printf(" Length:\t%u\n", ((packet->data[2] << 8) |
153 printf(" Vector:\t");
154 for (i = 4; i < 20; i++) {
155 printf("%02x", packet->data[i]);
159 if (packet->data_len > 20) {
164 total = packet->data_len - 20;
165 ptr = packet->data + 20;
171 if (total < 2) { /* too short */
172 printf("%02x\n", *ptr);
176 if (ptr[1] > total) { /* too long */
177 for (i = 0; i < total; i++) {
178 printf("%02x ", ptr[i]);
183 printf("%02x %02x ", ptr[0], ptr[1]);
184 attrlen = ptr[1] - 2;
188 for (i = 0; i < attrlen; i++) {
189 if ((i > 0) && ((i & 0x0f) == 0x00))
191 printf("%02x ", ptr[i]);
192 if ((i & 0x0f) == 0x0f) printf("\n");
195 if ((attrlen & 0x0f) != 0x00) printf("\n");
206 * Wrapper for sendto which handles sendfromto, IPv6, and all
207 * possible combinations.
209 static int rad_sendto(int sockfd, void *data, size_t data_len, int flags,
210 fr_ipaddr_t *src_ipaddr, int src_port,
211 fr_ipaddr_t *dst_ipaddr, int dst_port)
213 struct sockaddr_storage dst;
214 socklen_t sizeof_dst;
216 #ifdef WITH_UDPFROMTO
217 struct sockaddr_storage src;
218 socklen_t sizeof_src;
220 fr_ipaddr2sockaddr(src_ipaddr, src_port, &src, &sizeof_src);
222 src_port = src_port; /* -Wunused */
225 if (!fr_ipaddr2sockaddr(dst_ipaddr, dst_port, &dst, &sizeof_dst)) {
229 #ifdef WITH_UDPFROMTO
231 * Only IPv4 is supported for udpfromto.
233 * And if they don't specify a source IP address, don't
236 if ((dst_ipaddr->af == AF_INET) ||
237 (src_ipaddr->af != AF_UNSPEC)) {
238 return sendfromto(sockfd, data, data_len, flags,
239 (struct sockaddr *)&src, sizeof_src,
240 (struct sockaddr *)&dst, sizeof_dst);
243 src_ipaddr = src_ipaddr; /* -Wunused */
247 * No udpfromto, OR an IPv6 socket, fail gracefully.
249 return sendto(sockfd, data, data_len, flags,
250 (struct sockaddr *) &dst, sizeof_dst);
254 void rad_recv_discard(int sockfd)
257 struct sockaddr_storage src;
258 socklen_t sizeof_src = sizeof(src);
260 recvfrom(sockfd, header, sizeof(header), 0,
261 (struct sockaddr *)&src, &sizeof_src);
265 ssize_t rad_recv_header(int sockfd, fr_ipaddr_t *src_ipaddr, int *src_port,
268 ssize_t data_len, packet_len;
270 struct sockaddr_storage src;
271 socklen_t sizeof_src = sizeof(src);
273 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
274 (struct sockaddr *)&src, &sizeof_src);
276 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
281 * Too little data is available, discard the packet.
284 recvfrom(sockfd, header, sizeof(header), 0,
285 (struct sockaddr *)&src, &sizeof_src);
288 } else { /* we got 4 bytes of data. */
290 * See how long the packet says it is.
292 packet_len = (header[2] * 256) + header[3];
295 * The length in the packet says it's less than
296 * a RADIUS header length: discard it.
298 if (packet_len < AUTH_HDR_LEN) {
299 recvfrom(sockfd, header, sizeof(header), 0,
300 (struct sockaddr *)&src, &sizeof_src);
304 * Enforce RFC requirements, for sanity.
305 * Anything after 4k will be discarded.
307 } else if (packet_len > MAX_PACKET_LEN) {
308 recvfrom(sockfd, header, sizeof(header), 0,
309 (struct sockaddr *)&src, &sizeof_src);
315 * Convert AF. If unknown, discard packet.
317 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, src_port)) {
318 recvfrom(sockfd, header, sizeof(header), 0,
319 (struct sockaddr *)&src, &sizeof_src);
326 * The packet says it's this long, but the actual UDP
327 * size could still be smaller.
334 * wrapper for recvfrom, which handles recvfromto, IPv6, and all
335 * possible combinations.
337 static ssize_t rad_recvfrom(int sockfd, uint8_t **pbuf, int flags,
338 fr_ipaddr_t *src_ipaddr, uint16_t *src_port,
339 fr_ipaddr_t *dst_ipaddr, uint16_t *dst_port)
341 struct sockaddr_storage src;
342 struct sockaddr_storage dst;
343 socklen_t sizeof_src = sizeof(src);
344 socklen_t sizeof_dst = sizeof(dst);
351 memset(&src, 0, sizeof_src);
352 memset(&dst, 0, sizeof_dst);
355 * Get address family, etc. first, so we know if we
356 * need to do udpfromto.
358 * FIXME: udpfromto also does this, but it's not
359 * a critical problem.
361 if (getsockname(sockfd, (struct sockaddr *)&dst,
362 &sizeof_dst) < 0) return -1;
365 * Read the length of the packet, from the packet.
366 * This lets us allocate the buffer to use for
367 * reading the rest of the packet.
369 data_len = recvfrom(sockfd, header, sizeof(header), MSG_PEEK,
370 (struct sockaddr *)&src, &sizeof_src);
372 if ((errno == EAGAIN) || (errno == EINTR)) return 0;
377 * Too little data is available, discard the packet.
380 recvfrom(sockfd, header, sizeof(header), flags,
381 (struct sockaddr *)&src, &sizeof_src);
384 } else { /* we got 4 bytes of data. */
386 * See how long the packet says it is.
388 len = (header[2] * 256) + header[3];
391 * The length in the packet says it's less than
392 * a RADIUS header length: discard it.
394 if (len < AUTH_HDR_LEN) {
395 recvfrom(sockfd, header, sizeof(header), flags,
396 (struct sockaddr *)&src, &sizeof_src);
400 * Enforce RFC requirements, for sanity.
401 * Anything after 4k will be discarded.
403 } else if (len > MAX_PACKET_LEN) {
404 recvfrom(sockfd, header, sizeof(header), flags,
405 (struct sockaddr *)&src, &sizeof_src);
414 * Receive the packet. The OS will discard any data in the
415 * packet after "len" bytes.
417 #ifdef WITH_UDPFROMTO
418 if (dst.ss_family == AF_INET) {
419 data_len = recvfromto(sockfd, buf, len, flags,
420 (struct sockaddr *)&src, &sizeof_src,
421 (struct sockaddr *)&dst, &sizeof_dst);
425 * No udpfromto, OR an IPv6 socket. Fail gracefully.
427 data_len = recvfrom(sockfd, buf, len, flags,
428 (struct sockaddr *)&src, &sizeof_src);
434 if (!fr_sockaddr2ipaddr(&src, sizeof_src, src_ipaddr, &port)) {
436 return -1; /* Unknown address family, Die Die Die! */
440 fr_sockaddr2ipaddr(&dst, sizeof_dst, dst_ipaddr, &port);
444 * Different address families should never happen.
446 if (src.ss_family != dst.ss_family) {
452 * Tell the caller about the data
460 #define AUTH_PASS_LEN (AUTH_VECTOR_LEN)
461 /*************************************************************************
463 * Function: make_secret
465 * Purpose: Build an encrypted secret value to return in a reply
466 * packet. The secret is hidden by xoring with a MD5 digest
467 * created from the shared secret and the authentication
468 * vector. We put them into MD5 in the reverse order from
469 * that used when encrypting passwords to RADIUS.
471 *************************************************************************/
472 static void make_secret(uint8_t *digest, const uint8_t *vector,
473 const char *secret, const uint8_t *value)
478 fr_MD5Init(&context);
479 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
480 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
481 fr_MD5Final(digest, &context);
483 for ( i = 0; i < AUTH_VECTOR_LEN; i++ ) {
484 digest[i] ^= value[i];
488 #define MAX_PASS_LEN (128)
489 static void make_passwd(uint8_t *output, size_t *outlen,
490 const uint8_t *input, size_t inlen,
491 const char *secret, const uint8_t *vector)
493 FR_MD5_CTX context, old;
494 uint8_t digest[AUTH_VECTOR_LEN];
495 uint8_t passwd[MAX_PASS_LEN];
500 * If the length is zero, round it up.
504 if (len > MAX_PASS_LEN) len = MAX_PASS_LEN;
506 memcpy(passwd, input, len);
507 memset(passwd + len, 0, sizeof(passwd) - len);
513 else if ((len & 0x0f) != 0) {
519 fr_MD5Init(&context);
520 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
526 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
528 for (n = 0; n < len; n += AUTH_PASS_LEN) {
531 fr_MD5Update(&context,
532 passwd + n - AUTH_PASS_LEN,
536 fr_MD5Final(digest, &context);
537 for (i = 0; i < AUTH_PASS_LEN; i++) {
538 passwd[i + n] ^= digest[i];
542 memcpy(output, passwd, len);
545 static void make_tunnel_passwd(uint8_t *output, size_t *outlen,
546 const uint8_t *input, size_t inlen, size_t room,
547 const char *secret, const uint8_t *vector)
549 FR_MD5_CTX context, old;
550 uint8_t digest[AUTH_VECTOR_LEN];
551 uint8_t passwd[MAX_STRING_LEN + AUTH_VECTOR_LEN];
558 if (room > 253) room = 253;
561 * Account for 2 bytes of the salt, and round the room
562 * available down to the nearest multiple of 16. Then,
563 * subtract one from that to account for the length byte,
564 * and the resulting number is the upper bound on the data
567 * We could short-cut this calculation just be forcing
568 * inlen to be no more than 239. It would work for all
569 * VSA's, as we don't pack multiple VSA's into one
572 * However, this calculation is more general, if a little
573 * complex. And it will work in the future for all possible
574 * kinds of weird attribute packing.
577 room -= (room & 0x0f);
580 if (inlen > room) inlen = room;
583 * Length of the encrypted data is password length plus
584 * one byte for the length of the password.
587 if ((len & 0x0f) != 0) {
591 *outlen = len + 2; /* account for the salt */
594 * Copy the password over.
596 memcpy(passwd + 3, input, inlen);
597 memset(passwd + 3 + inlen, 0, sizeof(passwd) - 3 - inlen);
600 * Generate salt. The RFC's say:
602 * The high bit of salt[0] must be set, each salt in a
603 * packet should be unique, and they should be random
605 * So, we set the high bit, add in a counter, and then
606 * add in some CSPRNG data. should be OK..
608 passwd[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
610 passwd[1] = fr_rand();
611 passwd[2] = inlen; /* length of the password string */
613 fr_MD5Init(&context);
614 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
617 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
618 fr_MD5Update(&context, &passwd[0], 2);
620 for (n = 0; n < len; n += AUTH_PASS_LEN) {
623 fr_MD5Update(&context,
624 passwd + 2 + n - AUTH_PASS_LEN,
628 fr_MD5Final(digest, &context);
630 for (i = 0; i < AUTH_PASS_LEN; i++) {
631 passwd[i + 2 + n] ^= digest[i];
634 memcpy(output, passwd, len + 2);
638 * Returns the end of the data.
640 static int vp2data(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
641 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
647 uint8_t *ptr = start;
651 * Set up the default sources for the data.
653 data = vp->vp_octets;
660 case PW_TYPE_IPV6ADDR:
661 case PW_TYPE_IPV6PREFIX:
662 case PW_TYPE_ABINARY:
663 /* nothing more to do */
667 len = 1; /* just in case */
668 array[0] = vp->vp_integer & 0xff;
673 len = 2; /* just in case */
674 array[0] = (vp->vp_integer >> 8) & 0xff;
675 array[1] = vp->vp_integer & 0xff;
679 case PW_TYPE_INTEGER:
680 len = 4; /* just in case */
681 lvalue = htonl(vp->vp_integer);
682 memcpy(array, &lvalue, sizeof(lvalue));
687 data = (const uint8_t *) &vp->vp_ipaddr;
688 len = 4; /* just in case */
692 * There are no tagged date attributes.
695 lvalue = htonl(vp->vp_date);
696 data = (const uint8_t *) &lvalue;
697 len = 4; /* just in case */
704 len = 4; /* just in case */
705 slvalue = htonl(vp->vp_signed);
706 memcpy(array, &slvalue, sizeof(slvalue));
713 fr_strerror_printf("ERROR: Cannot encode NULL TLV");
716 if (vp->length > room) return 0; /* can't chop TLVs to fit */
719 default: /* unknown type: ignore it */
720 fr_strerror_printf("ERROR: Unknown attribute type %d", vp->type);
725 * Bound the data to the calling size
727 if (len > room) len = room;
730 * Encrypt the various password styles
732 * Attributes with encrypted values MUST be less than
735 switch (vp->flags.encrypt) {
736 case FLAG_ENCRYPT_USER_PASSWORD:
737 make_passwd(ptr, &len, data, len,
738 secret, packet->vector);
741 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
743 if (vp->flags.has_tag) lvalue = 1;
746 * Check if there's enough room. If there isn't,
747 * we discard the attribute.
749 * This is ONLY a problem if we have multiple VSA's
750 * in one Vendor-Specific, though.
752 if (room < (18 + lvalue)) return 0;
754 switch (packet->code) {
755 case PW_AUTHENTICATION_ACK:
756 case PW_AUTHENTICATION_REJECT:
757 case PW_ACCESS_CHALLENGE:
760 fr_strerror_printf("ERROR: No request packet, cannot encrypt %s attribute in the vp.", vp->name);
764 if (lvalue) ptr[0] = vp->flags.tag;
765 make_tunnel_passwd(ptr + lvalue, &len, data, len,
767 secret, original->vector);
769 case PW_ACCOUNTING_REQUEST:
770 case PW_DISCONNECT_REQUEST:
772 ptr[0] = vp->flags.tag;
773 make_tunnel_passwd(ptr + 1, &len, data, len - 1, room,
774 secret, packet->vector);
780 * The code above ensures that this attribute
783 case FLAG_ENCRYPT_ASCEND_SECRET:
784 make_secret(ptr, packet->vector, secret, data);
785 len = AUTH_VECTOR_LEN;
790 if (vp->flags.has_tag && TAG_VALID(vp->flags.tag)) {
791 if (vp->type == PW_TYPE_STRING) {
792 if (len > (room - 1)) len = room - 1;
793 ptr[0] = vp->flags.tag;
795 } else if (vp->type == PW_TYPE_INTEGER) {
796 array[0] = vp->flags.tag;
797 } /* else it can't be any other type */
799 memcpy(ptr, data, len);
801 } /* switch over encryption flags */
803 return len + (ptr - start);;
807 static int rad_vp2rfc(const RADIUS_PACKET *packet,
808 const RADIUS_PACKET *original,
809 const char *secret, const VALUE_PAIR *vp,
810 unsigned int attribute, uint8_t *ptr, size_t room)
814 if (room < 2) return 0;
816 ptr[0] = attribute & 0xff; /* NOT vp->attribute */
819 len = vp2data(packet, original, secret, vp, ptr + 2, room - 2);
820 if (len < 0) return len;
827 extern int fr_wimax_max_tlv;
828 extern int fr_wimax_shift[];
829 extern int fr_wimax_mask[];
831 static int tlv2data(const RADIUS_PACKET *packet,
832 const RADIUS_PACKET *original,
833 const char *secret, const VALUE_PAIR *vp,
834 uint8_t *ptr, size_t room, int nest)
838 if (nest > fr_wimax_max_tlv) return -1;
840 if (room < 2) return 0;
843 ptr[0] = (vp->attribute >> fr_wimax_shift[nest]) & fr_wimax_mask[nest];
847 * No more nested TLVs: pack the data.
849 if ((nest == fr_wimax_max_tlv) ||
850 ((vp->attribute >> fr_wimax_shift[nest + 1]) == 0)) {
851 len = vp2data(packet, original, secret, vp, ptr + 2, room);
853 len = tlv2data(packet, original, secret, vp, ptr + 2, room,
856 if (len <= 0) return len;
863 static int wimax2data(const RADIUS_PACKET *packet,
864 const RADIUS_PACKET *original,
865 const char *secret, const VALUE_PAIR *vp,
866 uint8_t *start, size_t room, uint8_t *ptr)
871 * Offsets to Vendor-Specific length, and to length of
877 if (room < 1) return 0;
881 * Account for continuation bytes. The caller has
882 * already accounting for the continuation byte in the
883 * Vendor-Specific "length" field.
889 * Chop everything to fit in one attribute.
891 if (room > (255 - 9)) room = (255 - 9);
894 * The attribute contains TLVs that we have NOT decoded
895 * properly, OR it contains TLV that the user has encoded
896 * manually. If it has no data, OR it's too long,
897 * discard it. We're not going to walk through its
898 * contents trying to figure out how to chop it across
899 * multiple continuations.
901 if (vp->flags.has_tlv && (!vp->vp_tlv || (vp->length > room))) {
906 * The attribute is a top-level integer, ipaddr, etc.
909 if (!vp->flags.is_tlv) {
910 len = vp2data(packet, original, secret, vp, ptr, room);
912 len = tlv2data(packet, original, secret, vp, ptr, room, 1);
915 if (len <= 0) return len;
917 start[VS_OFF] += len;
918 start[WM_OFF] += len;
920 return start[VS_OFF];
925 * Parse a data structure into a RADIUS attribute.
927 int rad_vp2attr(const RADIUS_PACKET *packet, const RADIUS_PACKET *original,
928 const char *secret, const VALUE_PAIR *vp, uint8_t *start,
937 * RFC format attributes take the fast path.
939 if (vp->vendor == 0) {
940 len = rad_vp2rfc(packet, original, secret, vp,
941 vp->attribute, start, room);
942 if (len < 0) return -1;
945 * RFC 2865 section 5 says that zero-length
946 * attributes MUST NOT be sent.
948 * ... and the WiMAX forum ignores
949 * this... because of one vendor. Don't they
950 * have anything better to do with their time?
953 (vp->attribute != PW_CHARGEABLE_USER_IDENTITY)) return 0;
960 * Not enough room for:
961 * attr, len, vendor-id, vsa, vsalen
963 if (room < 8) return 0;
966 * Build the Vendor-Specific header
969 *ptr++ = PW_VENDOR_SPECIFIC;
972 lvalue = htonl(vp->vendor);
973 memcpy(ptr, &lvalue, 4);
977 * Unknown vendors, and type=1,length=1,no-continuation
978 * are RFC format attributes.
980 dv = dict_vendorbyvalue(vp->vendor);
982 ((dv->type == 1) && (dv->length = 1) && !dv->flags)) {
983 len = rad_vp2rfc(packet, original, secret, vp,
984 vp->attribute, ptr, room);
985 if (len <= 0) return len;
991 if (room < (dv->type + dv->length + dv->flags)) return 0;
992 room -= (dv->type + dv->length + dv->flags);
993 start[1] += (dv->type + dv->length + dv->flags);
997 ptr[0] = (vp->attribute & 0xFF);
1001 ptr[0] = ((vp->attribute >> 8) & 0xFF);
1002 ptr[1] = (vp->attribute & 0xFF);
1007 ptr[1] = ((vp->attribute >> 16) & 0xFF);
1008 ptr[2] = ((vp->attribute >> 8) & 0xFF);
1009 ptr[3] = (vp->attribute & 0xFF);
1013 return 0; /* silently discard it */
1017 switch (dv->length) {
1021 ptr[0] = dv->type + 1;
1025 ptr[1] = dv->type + 2;
1029 return 0; /* silently discard it */
1034 * WiMAX attributes take their own path through the
1037 if (dv->flags) return wimax2data(packet, original, secret, vp,
1040 len = vp2data(packet, original, secret, vp, ptr, room);
1041 if (len <= 0) return len;
1043 if (dv->length != 0) ptr[-1] += len;
1053 #define REORDER(x) ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000 >> 24))
1057 * Encode a WiMAX sub-TLV. It must NOT be called for WiMAX
1058 * attributes that are of type integer, string, etc.
1060 static int rad_encode_wimax(const RADIUS_PACKET *packet,
1061 const RADIUS_PACKET *original,
1062 const char *secret, VALUE_PAIR *reply,
1063 uint8_t *start, size_t room)
1067 uint8_t *ptr = start, *vsa = start;
1069 VALUE_PAIR *vp = reply;
1072 * Swap the order of the WiMAX hacks, to make later
1073 * comparisons easier.
1075 maxattr = REORDER(vp->attribute);
1078 * Build the Vendor-Specific header
1086 if (room < 9) return 0;
1087 *ptr++ = PW_VENDOR_SPECIFIC;
1090 lvalue = htonl(vp->vendor);
1091 memcpy(ptr, &lvalue, 4);
1093 *(ptr++) = vp->attribute & 0xff;
1095 *(ptr++) = 0; /* continuation */
1099 len = tlv2data(packet, original, secret, vp, ptr, room, 1);
1100 if (len < 0) return len;
1103 * Not enough room. Do a continuation.
1105 if ((len == 0) || ((vsa[VS_OFF] + len) > 255)) {
1106 if (redo) return (start - vsa);
1118 vp->flags.encoded = 1;
1122 * Look at the NEXT tlv. Ensure that we encode
1123 * attributes into a common VSA *only* if they are for
1124 * the same WiMAX VSA, AND if the TLVs are in numerically
1127 if (vp && vp->flags.is_tlv && (reply->vendor == vp->vendor) &&
1128 ((reply->attribute & 0xff) == (vp->attribute & 0xff))) {
1131 attr = REORDER(vp->attribute);
1132 if (attr >= maxattr) {
1145 int rad_encode(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1148 radius_packet_t *hdr;
1150 uint16_t total_length;
1154 char ip_buffer[128];
1157 * A 4K packet, aligned on 64-bits.
1159 uint64_t data[MAX_PACKET_LEN / sizeof(uint64_t)];
1161 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1162 what = fr_packet_codes[packet->code];
1167 DEBUG("Sending %s of id %d to %s port %d\n",
1169 inet_ntop(packet->dst_ipaddr.af,
1170 &packet->dst_ipaddr.ipaddr,
1171 ip_buffer, sizeof(ip_buffer)),
1175 * Double-check some things based on packet code.
1177 switch (packet->code) {
1178 case PW_AUTHENTICATION_ACK:
1179 case PW_AUTHENTICATION_REJECT:
1180 case PW_ACCESS_CHALLENGE:
1182 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1188 * These packet vectors start off as all zero.
1190 case PW_ACCOUNTING_REQUEST:
1191 case PW_DISCONNECT_REQUEST:
1192 case PW_COA_REQUEST:
1193 memset(packet->vector, 0, sizeof(packet->vector));
1201 * Use memory on the stack, until we know how
1202 * large the packet will be.
1204 hdr = (radius_packet_t *) data;
1207 * Build standard header
1209 hdr->code = packet->code;
1210 hdr->id = packet->id;
1212 memcpy(hdr->vector, packet->vector, sizeof(hdr->vector));
1214 total_length = AUTH_HDR_LEN;
1217 * Load up the configuration values for the user
1223 * FIXME: Loop twice over the reply list. The first time,
1224 * calculate the total length of data. The second time,
1225 * allocate the memory, and fill in the VP's.
1227 * Hmm... this may be slower than just doing a small
1232 * Loop over the reply attributes for the packet.
1234 for (reply = packet->vps; reply; reply = reply->next) {
1236 * Ignore non-wire attributes
1238 if ((reply->vendor == 0) &&
1239 ((reply->attribute & 0xFFFF) > 0xff)) {
1242 * Permit the admin to send BADLY formatted
1243 * attributes with a debug build.
1245 if (reply->attribute == PW_RAW_ATTRIBUTE) {
1246 memcpy(ptr, reply->vp_octets, reply->length);
1247 len = reply->length;
1255 * Set the Message-Authenticator to the correct
1256 * length and initial value.
1258 if (reply->attribute == PW_MESSAGE_AUTHENTICATOR) {
1259 reply->length = AUTH_VECTOR_LEN;
1260 memset(reply->vp_strvalue, 0, AUTH_VECTOR_LEN);
1263 * Cache the offset to the
1264 * Message-Authenticator
1266 packet->offset = total_length;
1270 * Print out ONLY the attributes which
1271 * we're sending over the wire, and print
1272 * them out BEFORE they're encrypted.
1277 * Skip attributes that are encoded.
1279 if (reply->flags.encoded) continue;
1281 if (reply->flags.is_tlv) {
1282 len = rad_encode_wimax(packet, original, secret,
1284 ((uint8_t *) data) + sizeof(data) - ptr);
1287 len = rad_vp2attr(packet, original, secret, reply, ptr,
1288 ((uint8_t *) data) + sizeof(data) - ptr);
1291 if (len < 0) return -1;
1295 total_length += len;
1296 } /* done looping over all attributes */
1299 * Fill in the rest of the fields, and copy the data over
1300 * from the local stack to the newly allocated memory.
1302 * Yes, all this 'memcpy' is slow, but it means
1303 * that we only allocate the minimum amount of
1304 * memory for a request.
1306 packet->data_len = total_length;
1307 packet->data = (uint8_t *) malloc(packet->data_len);
1308 if (!packet->data) {
1309 fr_strerror_printf("Out of memory");
1313 memcpy(packet->data, hdr, packet->data_len);
1314 hdr = (radius_packet_t *) packet->data;
1316 total_length = htons(total_length);
1317 memcpy(hdr->length, &total_length, sizeof(total_length));
1324 * Sign a previously encoded packet.
1326 int rad_sign(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1329 radius_packet_t *hdr = (radius_packet_t *)packet->data;
1332 * It wasn't assigned an Id, this is bad!
1334 if (packet->id < 0) {
1335 fr_strerror_printf("ERROR: RADIUS packets must be assigned an Id.");
1339 if (!packet->data || (packet->data_len < AUTH_HDR_LEN) ||
1340 (packet->offset < 0)) {
1341 fr_strerror_printf("ERROR: You must call rad_encode() before rad_sign()");
1346 * If there's a Message-Authenticator, update it
1347 * now, BEFORE updating the authentication vector.
1349 if (packet->offset > 0) {
1350 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
1352 switch (packet->code) {
1353 case PW_ACCOUNTING_REQUEST:
1354 case PW_ACCOUNTING_RESPONSE:
1355 case PW_DISCONNECT_REQUEST:
1356 case PW_DISCONNECT_ACK:
1357 case PW_DISCONNECT_NAK:
1358 case PW_COA_REQUEST:
1361 memset(hdr->vector, 0, AUTH_VECTOR_LEN);
1364 case PW_AUTHENTICATION_ACK:
1365 case PW_AUTHENTICATION_REJECT:
1366 case PW_ACCESS_CHALLENGE:
1368 fr_strerror_printf("ERROR: Cannot sign response packet without a request packet.");
1371 memcpy(hdr->vector, original->vector,
1375 default: /* others have vector already set to zero */
1381 * Set the authentication vector to zero,
1382 * calculate the signature, and put it
1383 * into the Message-Authenticator
1386 fr_hmac_md5(packet->data, packet->data_len,
1387 (const uint8_t *) secret, strlen(secret),
1389 memcpy(packet->data + packet->offset + 2,
1390 calc_auth_vector, AUTH_VECTOR_LEN);
1393 * Copy the original request vector back
1394 * to the raw packet.
1396 memcpy(hdr->vector, packet->vector, AUTH_VECTOR_LEN);
1400 * Switch over the packet code, deciding how to
1403 switch (packet->code) {
1405 * Request packets are not signed, bur
1406 * have a random authentication vector.
1408 case PW_AUTHENTICATION_REQUEST:
1409 case PW_STATUS_SERVER:
1413 * Reply packets are signed with the
1414 * authentication vector of the request.
1421 fr_MD5Init(&context);
1422 fr_MD5Update(&context, packet->data, packet->data_len);
1423 fr_MD5Update(&context, (const uint8_t *) secret,
1425 fr_MD5Final(digest, &context);
1427 memcpy(hdr->vector, digest, AUTH_VECTOR_LEN);
1428 memcpy(packet->vector, digest, AUTH_VECTOR_LEN);
1431 }/* switch over packet codes */
1437 * Reply to the request. Also attach
1438 * reply attribute value pairs and any user message provided.
1440 int rad_send(RADIUS_PACKET *packet, const RADIUS_PACKET *original,
1445 char ip_buffer[128];
1448 * Maybe it's a fake packet. Don't send it.
1450 if (!packet || (packet->sockfd < 0)) {
1454 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
1455 what = fr_packet_codes[packet->code];
1461 * First time through, allocate room for the packet
1463 if (!packet->data) {
1465 * Encode the packet.
1467 if (rad_encode(packet, original, secret) < 0) {
1472 * Re-sign it, including updating the
1473 * Message-Authenticator.
1475 if (rad_sign(packet, original, secret) < 0) {
1480 * If packet->data points to data, then we print out
1481 * the VP list again only for debugging.
1483 } else if (fr_debug_flag) {
1484 DEBUG("Sending %s of id %d to %s port %d\n", what, packet->id,
1485 inet_ntop(packet->dst_ipaddr.af,
1486 &packet->dst_ipaddr.ipaddr,
1487 ip_buffer, sizeof(ip_buffer)),
1490 for (reply = packet->vps; reply; reply = reply->next) {
1491 if ((reply->vendor == 0) &&
1492 ((reply->attribute & 0xFFFF) > 0xff)) continue;
1498 * And send it on it's way.
1500 return rad_sendto(packet->sockfd, packet->data, packet->data_len, 0,
1501 &packet->src_ipaddr, packet->src_port,
1502 &packet->dst_ipaddr, packet->dst_port);
1506 * Do a comparison of two authentication digests by comparing
1507 * the FULL digest. Otehrwise, the server can be subject to
1508 * timing attacks that allow attackers find a valid message
1511 * http://www.cs.rice.edu/~dwallach/pub/crosby-timing2009.pdf
1513 static int digest_cmp(const uint8_t *a, const uint8_t *b, size_t length)
1518 for (i = 0; i < length; i++) {
1519 result |= a[i] ^ b[i];
1522 return result; /* 0 is OK, !0 is !OK, just like memcmp */
1527 * Validates the requesting client NAS. Calculates the
1528 * signature based on the clients private key.
1530 static int calc_acctdigest(RADIUS_PACKET *packet, const char *secret)
1532 uint8_t digest[AUTH_VECTOR_LEN];
1536 * Zero out the auth_vector in the received packet.
1537 * Then append the shared secret to the received packet,
1538 * and calculate the MD5 sum. This must be the same
1539 * as the original MD5 sum (packet->vector).
1541 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
1544 * MD5(packet + secret);
1546 fr_MD5Init(&context);
1547 fr_MD5Update(&context, packet->data, packet->data_len);
1548 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1549 fr_MD5Final(digest, &context);
1552 * Return 0 if OK, 2 if not OK.
1554 if (digest_cmp(digest, packet->vector, AUTH_VECTOR_LEN) != 0) return 2;
1560 * Validates the requesting client NAS. Calculates the
1561 * signature based on the clients private key.
1563 static int calc_replydigest(RADIUS_PACKET *packet, RADIUS_PACKET *original,
1566 uint8_t calc_digest[AUTH_VECTOR_LEN];
1572 if (original == NULL) {
1577 * Copy the original vector in place.
1579 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
1582 * MD5(packet + secret);
1584 fr_MD5Init(&context);
1585 fr_MD5Update(&context, packet->data, packet->data_len);
1586 fr_MD5Update(&context, (const uint8_t *) secret, strlen(secret));
1587 fr_MD5Final(calc_digest, &context);
1590 * Copy the packet's vector back to the packet.
1592 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
1595 * Return 0 if OK, 2 if not OK.
1597 if (digest_cmp(packet->vector, calc_digest, AUTH_VECTOR_LEN) != 0) return 2;
1603 * See if the data pointed to by PTR is a valid RADIUS packet.
1605 * packet is not 'const * const' because we may update data_len,
1606 * if there's more data in the UDP packet than in the RADIUS packet.
1608 int rad_packet_ok(RADIUS_PACKET *packet, int flags)
1613 radius_packet_t *hdr;
1614 char host_ipaddr[128];
1620 * Check for packets smaller than the packet header.
1622 * RFC 2865, Section 3., subsection 'length' says:
1624 * "The minimum length is 20 ..."
1626 if (packet->data_len < AUTH_HDR_LEN) {
1627 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (received %d < minimum %d)",
1628 inet_ntop(packet->src_ipaddr.af,
1629 &packet->src_ipaddr.ipaddr,
1630 host_ipaddr, sizeof(host_ipaddr)),
1631 (int) packet->data_len, AUTH_HDR_LEN);
1636 * RFC 2865, Section 3., subsection 'length' says:
1638 * " ... and maximum length is 4096."
1640 if (packet->data_len > MAX_PACKET_LEN) {
1641 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (received %d > maximum %d)",
1642 inet_ntop(packet->src_ipaddr.af,
1643 &packet->src_ipaddr.ipaddr,
1644 host_ipaddr, sizeof(host_ipaddr)),
1645 (int) packet->data_len, MAX_PACKET_LEN);
1650 * Check for packets with mismatched size.
1651 * i.e. We've received 128 bytes, and the packet header
1652 * says it's 256 bytes long.
1654 totallen = (packet->data[2] << 8) | packet->data[3];
1655 hdr = (radius_packet_t *)packet->data;
1658 * Code of 0 is not understood.
1659 * Code of 16 or greate is not understood.
1661 if ((hdr->code == 0) ||
1662 (hdr->code >= FR_MAX_PACKET_CODE)) {
1663 fr_strerror_printf("WARNING: Bad RADIUS packet from host %s: unknown packet code%d ",
1664 inet_ntop(packet->src_ipaddr.af,
1665 &packet->src_ipaddr.ipaddr,
1666 host_ipaddr, sizeof(host_ipaddr)),
1672 * Message-Authenticator is required in Status-Server
1673 * packets, otherwise they can be trivially forged.
1675 if (hdr->code == PW_STATUS_SERVER) require_ma = 1;
1678 * It's also required if the caller asks for it.
1680 if (flags) require_ma = 1;
1683 * Repeat the length checks. This time, instead of
1684 * looking at the data we received, look at the value
1685 * of the 'length' field inside of the packet.
1687 * Check for packets smaller than the packet header.
1689 * RFC 2865, Section 3., subsection 'length' says:
1691 * "The minimum length is 20 ..."
1693 if (totallen < AUTH_HDR_LEN) {
1694 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too short (length %d < minimum %d)",
1695 inet_ntop(packet->src_ipaddr.af,
1696 &packet->src_ipaddr.ipaddr,
1697 host_ipaddr, sizeof(host_ipaddr)),
1698 totallen, AUTH_HDR_LEN);
1703 * And again, for the value of the 'length' field.
1705 * RFC 2865, Section 3., subsection 'length' says:
1707 * " ... and maximum length is 4096."
1709 if (totallen > MAX_PACKET_LEN) {
1710 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: too long (length %d > maximum %d)",
1711 inet_ntop(packet->src_ipaddr.af,
1712 &packet->src_ipaddr.ipaddr,
1713 host_ipaddr, sizeof(host_ipaddr)),
1714 totallen, MAX_PACKET_LEN);
1719 * RFC 2865, Section 3., subsection 'length' says:
1721 * "If the packet is shorter than the Length field
1722 * indicates, it MUST be silently discarded."
1724 * i.e. No response to the NAS.
1726 if (packet->data_len < totallen) {
1727 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: received %d octets, packet length says %d",
1728 inet_ntop(packet->src_ipaddr.af,
1729 &packet->src_ipaddr.ipaddr,
1730 host_ipaddr, sizeof(host_ipaddr)),
1731 (int) packet->data_len, totallen);
1736 * RFC 2865, Section 3., subsection 'length' says:
1738 * "Octets outside the range of the Length field MUST be
1739 * treated as padding and ignored on reception."
1741 if (packet->data_len > totallen) {
1743 * We're shortening the packet below, but just
1744 * to be paranoid, zero out the extra data.
1746 memset(packet->data + totallen, 0, packet->data_len - totallen);
1747 packet->data_len = totallen;
1751 * Walk through the packet's attributes, ensuring that
1752 * they add up EXACTLY to the size of the packet.
1754 * If they don't, then the attributes either under-fill
1755 * or over-fill the packet. Any parsing of the packet
1756 * is impossible, and will result in unknown side effects.
1758 * This would ONLY happen with buggy RADIUS implementations,
1759 * or with an intentional attack. Either way, we do NOT want
1760 * to be vulnerable to this problem.
1763 count = totallen - AUTH_HDR_LEN;
1768 * We need at least 2 bytes to check the
1772 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute header overflows the packet",
1773 inet_ntop(packet->src_ipaddr.af,
1774 &packet->src_ipaddr.ipaddr,
1775 host_ipaddr, sizeof(host_ipaddr)));
1780 * Attribute number zero is NOT defined.
1783 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Invalid attribute 0",
1784 inet_ntop(packet->src_ipaddr.af,
1785 &packet->src_ipaddr.ipaddr,
1786 host_ipaddr, sizeof(host_ipaddr)));
1791 * Attributes are at LEAST as long as the ID & length
1792 * fields. Anything shorter is an invalid attribute.
1795 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u too short",
1796 inet_ntop(packet->src_ipaddr.af,
1797 &packet->src_ipaddr.ipaddr,
1798 host_ipaddr, sizeof(host_ipaddr)),
1804 * If there are fewer bytes in the packet than in the
1805 * attribute, it's a bad packet.
1807 if (count < attr[1]) {
1808 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: attribute %u data overflows the packet",
1809 inet_ntop(packet->src_ipaddr.af,
1810 &packet->src_ipaddr.ipaddr,
1811 host_ipaddr, sizeof(host_ipaddr)),
1817 * Sanity check the attributes for length.
1820 default: /* don't do anything by default */
1824 * If there's an EAP-Message, we require
1825 * a Message-Authenticator.
1827 case PW_EAP_MESSAGE:
1831 case PW_MESSAGE_AUTHENTICATOR:
1832 if (attr[1] != 2 + AUTH_VECTOR_LEN) {
1833 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: Message-Authenticator has invalid length %d",
1834 inet_ntop(packet->src_ipaddr.af,
1835 &packet->src_ipaddr.ipaddr,
1836 host_ipaddr, sizeof(host_ipaddr)),
1845 * FIXME: Look up the base 255 attributes in the
1846 * dictionary, and switch over their type. For
1847 * integer/date/ip, the attribute length SHOULD
1850 count -= attr[1]; /* grab the attribute length */
1852 num_attributes++; /* seen one more attribute */
1856 * If the attributes add up to a packet, it's allowed.
1858 * If not, we complain, and throw the packet away.
1861 fr_strerror_printf("WARNING: Malformed RADIUS packet from host %s: packet attributes do NOT exactly fill the packet",
1862 inet_ntop(packet->src_ipaddr.af,
1863 &packet->src_ipaddr.ipaddr,
1864 host_ipaddr, sizeof(host_ipaddr)));
1869 * If we're configured to look for a maximum number of
1870 * attributes, and we've seen more than that maximum,
1871 * then throw the packet away, as a possible DoS.
1873 if ((fr_max_attributes > 0) &&
1874 (num_attributes > fr_max_attributes)) {
1875 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
1876 inet_ntop(packet->src_ipaddr.af,
1877 &packet->src_ipaddr.ipaddr,
1878 host_ipaddr, sizeof(host_ipaddr)),
1879 num_attributes, fr_max_attributes);
1884 * http://www.freeradius.org/rfc/rfc2869.html#EAP-Message
1886 * A packet with an EAP-Message attribute MUST also have
1887 * a Message-Authenticator attribute.
1889 * A Message-Authenticator all by itself is OK, though.
1891 * Similarly, Status-Server packets MUST contain
1892 * Message-Authenticator attributes.
1894 if (require_ma && ! seen_ma) {
1895 fr_strerror_printf("WARNING: Insecure packet from host %s: Packet does not contain required Message-Authenticator attribute",
1896 inet_ntop(packet->src_ipaddr.af,
1897 &packet->src_ipaddr.ipaddr,
1898 host_ipaddr, sizeof(host_ipaddr)));
1903 * Fill RADIUS header fields
1905 packet->code = hdr->code;
1906 packet->id = hdr->id;
1907 memcpy(packet->vector, hdr->vector, AUTH_VECTOR_LEN);
1914 * Receive UDP client requests, and fill in
1915 * the basics of a RADIUS_PACKET structure.
1917 RADIUS_PACKET *rad_recv(int fd, int flags)
1920 RADIUS_PACKET *packet;
1923 * Allocate the new request data structure
1925 if ((packet = malloc(sizeof(*packet))) == NULL) {
1926 fr_strerror_printf("out of memory");
1929 memset(packet, 0, sizeof(*packet));
1932 sock_flags = MSG_PEEK;
1936 packet->data_len = rad_recvfrom(fd, &packet->data, sock_flags,
1937 &packet->src_ipaddr, &packet->src_port,
1938 &packet->dst_ipaddr, &packet->dst_port);
1941 * Check for socket errors.
1943 if (packet->data_len < 0) {
1944 fr_strerror_printf("Error receiving packet: %s", strerror(errno));
1945 /* packet->data is NULL */
1951 * If the packet is too big, then rad_recvfrom did NOT
1952 * allocate memory. Instead, it just discarded the
1955 if (packet->data_len > MAX_PACKET_LEN) {
1956 fr_strerror_printf("Discarding packet: Larger than RFC limitation of 4096 bytes.");
1957 /* packet->data is NULL */
1963 * Read no data. Continue.
1964 * This check is AFTER the MAX_PACKET_LEN check above, because
1965 * if the packet is larger than MAX_PACKET_LEN, we also have
1966 * packet->data == NULL
1968 if ((packet->data_len == 0) || !packet->data) {
1969 fr_strerror_printf("Empty packet: Socket is not ready.");
1975 * See if it's a well-formed RADIUS packet.
1977 if (!rad_packet_ok(packet, flags)) {
1983 * Remember which socket we read the packet from.
1985 packet->sockfd = fd;
1988 * FIXME: Do even more filtering by only permitting
1989 * certain IP's. The problem is that we don't know
1990 * how to do this properly for all possible clients...
1994 * Explicitely set the VP list to empty.
1998 if (fr_debug_flag) {
1999 char host_ipaddr[128];
2001 if ((packet->code > 0) && (packet->code < FR_MAX_PACKET_CODE)) {
2002 DEBUG("rad_recv: %s packet from host %s port %d",
2003 fr_packet_codes[packet->code],
2004 inet_ntop(packet->src_ipaddr.af,
2005 &packet->src_ipaddr.ipaddr,
2006 host_ipaddr, sizeof(host_ipaddr)),
2009 DEBUG("rad_recv: Packet from host %s port %d code=%d",
2010 inet_ntop(packet->src_ipaddr.af,
2011 &packet->src_ipaddr.ipaddr,
2012 host_ipaddr, sizeof(host_ipaddr)),
2016 DEBUG(", id=%d, length=%d\n",
2017 packet->id, (int) packet->data_len);
2025 * Verify the signature of a packet.
2027 int rad_verify(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2034 if (!packet || !packet->data) return -1;
2037 * Before we allocate memory for the attributes, do more
2040 ptr = packet->data + AUTH_HDR_LEN;
2041 length = packet->data_len - AUTH_HDR_LEN;
2042 while (length > 0) {
2043 uint8_t msg_auth_vector[AUTH_VECTOR_LEN];
2044 uint8_t calc_auth_vector[AUTH_VECTOR_LEN];
2049 default: /* don't do anything. */
2053 * Note that more than one Message-Authenticator
2054 * attribute is invalid.
2056 case PW_MESSAGE_AUTHENTICATOR:
2057 memcpy(msg_auth_vector, &ptr[2], sizeof(msg_auth_vector));
2058 memset(&ptr[2], 0, AUTH_VECTOR_LEN);
2060 switch (packet->code) {
2064 case PW_ACCOUNTING_REQUEST:
2065 case PW_ACCOUNTING_RESPONSE:
2066 case PW_DISCONNECT_REQUEST:
2067 case PW_DISCONNECT_ACK:
2068 case PW_DISCONNECT_NAK:
2069 case PW_COA_REQUEST:
2072 memset(packet->data + 4, 0, AUTH_VECTOR_LEN);
2075 case PW_AUTHENTICATION_ACK:
2076 case PW_AUTHENTICATION_REJECT:
2077 case PW_ACCESS_CHALLENGE:
2079 fr_strerror_printf("ERROR: Cannot validate Message-Authenticator in response packet without a request packet.");
2082 memcpy(packet->data + 4, original->vector, AUTH_VECTOR_LEN);
2086 fr_hmac_md5(packet->data, packet->data_len,
2087 (const uint8_t *) secret, strlen(secret),
2089 if (digest_cmp(calc_auth_vector, msg_auth_vector,
2090 sizeof(calc_auth_vector)) != 0) {
2092 fr_strerror_printf("Received packet from %s with invalid Message-Authenticator! (Shared secret is incorrect.)",
2093 inet_ntop(packet->src_ipaddr.af,
2094 &packet->src_ipaddr.ipaddr,
2095 buffer, sizeof(buffer)));
2096 /* Silently drop packet, according to RFC 3579 */
2098 } /* else the message authenticator was good */
2101 * Reinitialize Authenticators.
2103 memcpy(&ptr[2], msg_auth_vector, AUTH_VECTOR_LEN);
2104 memcpy(packet->data + 4, packet->vector, AUTH_VECTOR_LEN);
2106 } /* switch over the attributes */
2110 } /* loop over the packet, sanity checking the attributes */
2113 * It looks like a RADIUS packet, but we can't validate
2116 if ((packet->code == 0) || (packet->code >= FR_MAX_PACKET_CODE)) {
2118 fr_strerror_printf("Received Unknown packet code %d "
2119 "from client %s port %d: Cannot validate signature.",
2121 inet_ntop(packet->src_ipaddr.af,
2122 &packet->src_ipaddr.ipaddr,
2123 buffer, sizeof(buffer)),
2129 * Calculate and/or verify digest.
2131 switch(packet->code) {
2135 case PW_AUTHENTICATION_REQUEST:
2136 case PW_STATUS_SERVER:
2138 * The authentication vector is random
2139 * nonsense, invented by the client.
2143 case PW_COA_REQUEST:
2144 case PW_DISCONNECT_REQUEST:
2145 case PW_ACCOUNTING_REQUEST:
2146 if (calc_acctdigest(packet, secret) > 1) {
2147 fr_strerror_printf("Received %s packet "
2148 "from %s with invalid signature! (Shared secret is incorrect.)",
2149 fr_packet_codes[packet->code],
2150 inet_ntop(packet->src_ipaddr.af,
2151 &packet->src_ipaddr.ipaddr,
2152 buffer, sizeof(buffer)));
2157 /* Verify the reply digest */
2158 case PW_AUTHENTICATION_ACK:
2159 case PW_AUTHENTICATION_REJECT:
2160 case PW_ACCESS_CHALLENGE:
2161 case PW_ACCOUNTING_RESPONSE:
2162 case PW_DISCONNECT_ACK:
2163 case PW_DISCONNECT_NAK:
2166 rcode = calc_replydigest(packet, original, secret);
2168 fr_strerror_printf("Received %s packet "
2169 "from client %s port %d with invalid signature (err=%d)! (Shared secret is incorrect.)",
2170 fr_packet_codes[packet->code],
2171 inet_ntop(packet->src_ipaddr.af,
2172 &packet->src_ipaddr.ipaddr,
2173 buffer, sizeof(buffer)),
2181 fr_strerror_printf("Received Unknown packet code %d "
2182 "from client %s port %d: Cannot validate signature",
2184 inet_ntop(packet->src_ipaddr.af,
2185 &packet->src_ipaddr.ipaddr,
2186 buffer, sizeof(buffer)),
2195 static VALUE_PAIR *data2vp(const RADIUS_PACKET *packet,
2196 const RADIUS_PACKET *original,
2197 const char *secret, size_t length,
2198 const uint8_t *data, VALUE_PAIR *vp)
2203 * If length is greater than 253, something is SERIOUSLY
2206 if (length > 253) length = 253; /* paranoia (pair-anoia?) */
2208 vp->length = length;
2209 vp->operator = T_OP_EQ;
2215 if (vp->flags.has_tag) {
2216 if (TAG_VALID(data[0]) ||
2217 (vp->flags.encrypt == FLAG_ENCRYPT_TUNNEL_PASSWORD)) {
2219 * Tunnel passwords REQUIRE a tag, even
2220 * if don't have a valid tag.
2222 vp->flags.tag = data[0];
2224 if ((vp->type == PW_TYPE_STRING) ||
2225 (vp->type == PW_TYPE_OCTETS)) {
2226 if (length == 0) goto raw;
2233 * Copy the data to be decrypted
2235 memcpy(&vp->vp_octets[0], data + offset, length - offset);
2236 vp->length -= offset;
2239 * Decrypt the attribute.
2241 switch (vp->flags.encrypt) {
2245 case FLAG_ENCRYPT_USER_PASSWORD:
2247 rad_pwdecode((char *)vp->vp_strvalue,
2251 rad_pwdecode((char *)vp->vp_strvalue,
2255 if (vp->attribute == PW_USER_PASSWORD) {
2256 vp->length = strlen(vp->vp_strvalue);
2261 * Tunnel-Password's may go ONLY
2262 * in response packets.
2264 case FLAG_ENCRYPT_TUNNEL_PASSWORD:
2265 if (!original) goto raw;
2267 if (rad_tunnel_pwdecode(vp->vp_octets, &vp->length,
2268 secret, original->vector) < 0) {
2274 * Ascend-Send-Secret
2275 * Ascend-Receive-Secret
2277 case FLAG_ENCRYPT_ASCEND_SECRET:
2281 uint8_t my_digest[AUTH_VECTOR_LEN];
2282 make_secret(my_digest,
2285 memcpy(vp->vp_strvalue, my_digest,
2287 vp->vp_strvalue[AUTH_VECTOR_LEN] = '\0';
2288 vp->length = strlen(vp->vp_strvalue);
2294 } /* switch over encryption flags */
2298 case PW_TYPE_STRING:
2299 case PW_TYPE_OCTETS:
2300 case PW_TYPE_ABINARY:
2301 /* nothing more to do */
2305 if (vp->length != 1) goto raw;
2307 vp->vp_integer = vp->vp_octets[0];
2312 if (vp->length != 2) goto raw;
2314 vp->vp_integer = (vp->vp_octets[0] << 8) | vp->vp_octets[1];
2317 case PW_TYPE_INTEGER:
2318 if (vp->length != 4) goto raw;
2320 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2321 vp->vp_integer = ntohl(vp->vp_integer);
2323 if (vp->flags.has_tag) vp->vp_integer &= 0x00ffffff;
2326 * Try to get named VALUEs
2330 dval = dict_valbyattr(vp->attribute, vp->vendor,
2333 strlcpy(vp->vp_strvalue,
2335 sizeof(vp->vp_strvalue));
2341 if (vp->length != 4) goto raw;
2343 memcpy(&vp->vp_date, vp->vp_octets, 4);
2344 vp->vp_date = ntohl(vp->vp_date);
2348 case PW_TYPE_IPADDR:
2349 if (vp->length != 4) goto raw;
2351 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2355 * IPv6 interface ID is 8 octets long.
2358 if (vp->length != 8) goto raw;
2359 /* vp->vp_ifid == vp->vp_octets */
2363 * IPv6 addresses are 16 octets long
2365 case PW_TYPE_IPV6ADDR:
2366 if (vp->length != 16) goto raw;
2367 /* vp->vp_ipv6addr == vp->vp_octets */
2371 * IPv6 prefixes are 2 to 18 octets long.
2373 * RFC 3162: The first octet is unused.
2374 * The second is the length of the prefix
2375 * the rest are the prefix data.
2377 * The prefix length can have value 0 to 128.
2379 case PW_TYPE_IPV6PREFIX:
2380 if (vp->length < 2 || vp->length > 18) goto raw;
2381 if (vp->vp_octets[1] > 128) goto raw;
2384 * FIXME: double-check that
2385 * (vp->vp_octets[1] >> 3) matches vp->length + 2
2387 if (vp->length < 18) {
2388 memset(vp->vp_octets + vp->length, 0,
2393 case PW_TYPE_SIGNED:
2394 if (vp->length != 4) goto raw;
2397 * Overload vp_integer for ntohl, which takes
2398 * uint32_t, not int32_t
2400 memcpy(&vp->vp_integer, vp->vp_octets, 4);
2401 vp->vp_integer = ntohl(vp->vp_integer);
2402 memcpy(&vp->vp_signed, &vp->vp_integer, 4);
2406 vp->length = length;
2407 vp->vp_tlv = malloc(length);
2410 fr_strerror_printf("No memory");
2413 memcpy(vp->vp_tlv, data, length);
2416 case PW_TYPE_COMBO_IP:
2417 if (vp->length == 4) {
2418 vp->type = PW_TYPE_IPADDR;
2419 memcpy(&vp->vp_ipaddr, vp->vp_octets, 4);
2422 } else if (vp->length == 16) {
2423 vp->type = PW_TYPE_IPV6ADDR;
2424 /* vp->vp_ipv6addr == vp->vp_octets */
2432 vp->type = PW_TYPE_OCTETS;
2433 vp->length = length;
2434 memcpy(vp->vp_octets, data, length);
2438 * Ensure there's no encryption or tag stuff,
2439 * we just pass the attribute as-is.
2441 memset(&vp->flags, 0, sizeof(vp->flags));
2447 static void rad_sortvp(VALUE_PAIR **head)
2450 VALUE_PAIR *vp, **tail;
2453 * Walk over the VP's, sorting them in order. Did I
2454 * mention that I hate WiMAX continuations?
2456 * And bubble sort! WTF is up with that?
2463 if (!vp->next) break;
2465 if (vp->attribute > vp->next->attribute) {
2467 vp->next = (*tail)->next;
2478 * Walk the packet, looking for continuations of this attribute.
2480 * This is (worst-case) O(N^2) in the number of RADIUS
2481 * attributes. That happens only when perverse clients create
2482 * continued attributes, AND separate the fragmented portions
2483 * with a lot of other attributes.
2485 * Sane clients should put the fragments next to each other, in
2486 * which case this is O(N), in the number of fragments.
2488 static uint8_t *rad_coalesce(unsigned int attribute, int vendor,
2489 size_t length, uint8_t *data,
2490 size_t packet_length, size_t *ptlv_length)
2494 size_t tlv_length = length;
2495 uint8_t *ptr, *tlv, *tlv_data;
2497 for (ptr = data + length;
2498 ptr != (data + packet_length);
2500 /* FIXME: Check that there are 6 bytes of data here... */
2501 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2502 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2503 (ptr[2] != 0) || (ptr[3] != 0) || /* our requirement */
2504 (ptr[4] != ((vendor >> 8) & 0xff)) ||
2505 (ptr[5] != (vendor & 0xff))) {
2509 memcpy(&lvalue, ptr + 2, 4); /* Vendor Id */
2510 lvalue = ntohl(lvalue);
2512 lvalue |= ptr[2 + 4]; /* add in VSA number */
2513 if (lvalue != attribute) continue;
2516 * If the vendor-length is too small, it's badly
2517 * formed, so we stop.
2519 if ((ptr[2 + 4 + 1]) < 3) break;
2521 tlv_length += ptr[2 + 4 + 1] - 3;
2522 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2525 tlv = tlv_data = malloc(tlv_length);
2526 if (!tlv_data) return NULL;
2528 memcpy(tlv, data, length);
2532 * Now we walk the list again, copying the data over to
2533 * our newly created memory.
2535 for (ptr = data + length;
2536 ptr != (data + packet_length);
2540 if ((ptr[0] != PW_VENDOR_SPECIFIC) ||
2541 (ptr[1] < (2 + 4 + 3)) || /* WiMAX VSA with continuation */
2542 (ptr[2] != 0) || (ptr[3] != 0)) { /* our requirement */
2546 memcpy(&lvalue, ptr + 2, 4);
2547 lvalue = ntohl(lvalue);
2549 lvalue |= ptr[2 + 4];
2550 if (lvalue != attribute) continue;
2553 * If the vendor-length is too small, it's badly
2554 * formed, so we stop.
2556 if ((ptr[2 + 4 + 1]) < 3) break;
2558 this_length = ptr[2 + 4 + 1] - 3;
2559 memcpy(tlv, ptr + 2 + 4 + 3, this_length);
2562 ptr[2 + 4] = 0; /* What a hack! */
2563 if ((ptr[2 + 4 + 1 + 1] & 0x80) == 0) break;
2566 *ptlv_length = tlv_length;
2572 * Walk over Evil WIMAX TLVs, creating attributes.
2574 static VALUE_PAIR *tlv2wimax(const RADIUS_PACKET *packet,
2575 const RADIUS_PACKET *original,
2577 int attribute, int vendor,
2578 uint8_t *ptr, size_t len, int nest)
2580 VALUE_PAIR *head = NULL;
2581 VALUE_PAIR **tail = &head;
2583 uint8_t *y; /* why do I need to do this? */
2585 if (nest > fr_wimax_max_tlv) return NULL;
2588 * Sanity check the attribute.
2590 for (y = ptr; y < (ptr + len); y += y[1]) {
2591 if ((y[0] == 0) || ((y + 2) > (ptr + len)) ||
2592 (y[1] < 2) || ((y + y[1]) > (ptr + len))) {
2597 * Attribute number is too large for us to
2598 * represent it in our horrible internal
2601 if ((ptr[0] & ~fr_wimax_mask[nest]) != 0) {
2606 for (y = ptr; y < (ptr + len); y += y[1]) {
2609 da = dict_attrbyvalue(attribute | (ptr[0] << fr_wimax_shift[nest]), vendor);
2610 if (da && (da->type == PW_TYPE_TLV)) {
2611 vp = tlv2wimax(packet, original, secret,
2612 attribute | (ptr[0] << fr_wimax_shift[nest]),
2613 vendor, ptr + 2, ptr[1] - 2,
2615 if (!vp) goto error;
2617 vp = paircreate(attribute | (ptr[0] << fr_wimax_shift[nest]), vendor,
2625 if (!data2vp(packet, original, secret,
2626 y[1] - 2, y + 2, vp)) {
2632 while (*tail) tail = &((*tail)->next);
2639 * Start at the *data* portion of a continued attribute. search
2640 * through the rest of the attributes to find a matching one, and
2641 * add it's contents to our contents.
2643 static VALUE_PAIR *rad_continuation2vp(const RADIUS_PACKET *packet,
2644 const RADIUS_PACKET *original,
2645 const char *secret, int attribute,
2647 int length, /* CANNOT be zero */
2648 uint8_t *data, size_t packet_length,
2649 int flag, DICT_ATTR *da)
2651 size_t tlv_length, left;
2654 VALUE_PAIR *vp, *head, **tail;
2658 * Ensure we have data that hasn't been split across
2659 * multiple attributes.
2662 tlv_data = rad_coalesce(attribute, vendor, length,
2663 data, packet_length, &tlv_length);
2664 if (!tlv_data) return NULL;
2667 tlv_length = length;
2671 * Non-TLV types cannot be continued across multiple
2672 * attributes. This is true even of keys that are
2673 * encrypted with the tunnel-password method. The spec
2674 * says that they can be continued... but also that the
2675 * keys are 160 bits, which means that they CANNOT be
2678 * Note that we don't check "flag" here. The calling
2681 if (!da || (da->type != PW_TYPE_TLV)) {
2683 if (tlv_data == data) { /* true if we had 'goto' */
2684 tlv_data = malloc(tlv_length);
2685 if (!tlv_data) return NULL;
2686 memcpy(tlv_data, data, tlv_length);
2689 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2690 if (!vp) return NULL;
2692 vp->type = PW_TYPE_TLV;
2693 vp->flags.encrypt = FLAG_ENCRYPT_NONE;
2694 vp->flags.has_tag = 0;
2695 vp->flags.is_tlv = 0;
2696 vp->vp_tlv = tlv_data;
2697 vp->length = tlv_length;
2699 } /* else it WAS a TLV, go decode the sub-tlv's */
2702 * Now (sigh) we walk over the TLV, seeing if it is
2706 for (ptr = tlv_data;
2707 ptr != (tlv_data + tlv_length);
2712 goto not_well_formed;
2719 * Now we walk over the TLV *again*, creating sub-tlv's.
2724 for (ptr = tlv_data;
2725 ptr != (tlv_data + tlv_length);
2728 tlv_da = dict_attrbyvalue(attribute | (ptr[0] << fr_wimax_shift[1]), vendor);
2729 if (tlv_da && (tlv_da->type == PW_TYPE_TLV)) {
2730 vp = tlv2wimax(packet, original, secret,
2731 attribute | (ptr[0] << 8),
2732 vendor, ptr + 2, ptr[1] - 2, 2);
2734 if (!vp) goto error;
2736 vp = paircreate(attribute | (ptr[0] << fr_wimax_shift[1]), vendor,
2741 goto not_well_formed;
2744 if (!data2vp(packet, original, secret,
2745 ptr[1] - 2, ptr + 2, vp)) {
2752 while (*tail) tail = &((*tail)->next);
2756 * TLV's MAY be continued, but sometimes they're not.
2758 if (tlv_data != data) free(tlv_data);
2760 if (head->next) rad_sortvp(&head);
2767 * Parse a RADIUS attribute into a data structure.
2769 VALUE_PAIR *rad_attr2vp(const RADIUS_PACKET *packet,
2770 const RADIUS_PACKET *original,
2771 const char *secret, int attribute, int vendor,
2772 int length, const uint8_t *data)
2776 vp = paircreate(attribute, vendor, PW_TYPE_OCTETS);
2777 if (!vp) return NULL;
2779 return data2vp(packet, original, secret, length, data, vp);
2784 * Calculate/check digest, and decode radius attributes.
2786 * -1 on decoding error
2789 int rad_decode(RADIUS_PACKET *packet, RADIUS_PACKET *original,
2793 uint32_t vendorcode;
2796 uint8_t *ptr, *vsa_ptr;
2801 radius_packet_t *hdr;
2802 int vsa_tlen, vsa_llen, vsa_offset;
2803 DICT_VENDOR *dv = NULL;
2804 int num_attributes = 0;
2807 * Extract attribute-value pairs
2809 hdr = (radius_packet_t *)packet->data;
2811 packet_length = packet->data_len - AUTH_HDR_LEN;
2814 * There may be VP's already in the packet. Don't
2817 for (tail = &packet->vps; *tail != NULL; tail = &((*tail)->next)) {
2823 vsa_tlen = vsa_llen = 1;
2827 * We have to read at least two bytes.
2829 * rad_recv() above ensures that this is OK.
2831 while (packet_length > 0) {
2836 * Normal attribute, handle it like normal.
2838 if (vendorcode == 0) {
2840 * No room to read attr/length,
2841 * or bad attribute, or attribute is
2842 * too short, or attribute is too long,
2843 * stop processing the packet.
2845 if ((packet_length < 2) ||
2846 (ptr[0] == 0) || (ptr[1] < 2) ||
2847 (ptr[1] > packet_length)) break;
2855 if (attribute != PW_VENDOR_SPECIFIC) goto create_pair;
2858 * No vendor code, or ONLY vendor code.
2860 if (attrlen <= 4) goto create_pair;
2866 * Handle Vendor-Specific
2868 if (vendorlen == 0) {
2874 * attrlen was checked above.
2876 memcpy(&lvalue, ptr, 4);
2877 myvendor = ntohl(lvalue);
2880 * Zero isn't allowed.
2882 if (myvendor == 0) goto create_pair;
2885 * Allow vendors up to 2^24. Past that,
2888 if (myvendor > FR_MAX_VENDOR) goto create_pair;
2890 vsa_tlen = vsa_llen = 1;
2892 dv = dict_vendorbyvalue(myvendor);
2894 vsa_tlen = dv->type;
2895 vsa_llen = dv->length;
2896 if (dv->flags) vsa_offset = 1;
2900 * Sweep through the list of VSA's,
2901 * seeing if they exactly fill the
2902 * outer Vendor-Specific attribute.
2904 * If not, create a raw Vendor-Specific.
2907 sublen = attrlen - 4;
2910 * See if we can parse it.
2916 * Not enough room for one more
2919 if (sublen < (vsa_tlen + vsa_llen + vsa_offset)) goto create_pair;
2922 * Ensure that the attribute number
2931 myattr = (subptr[0] << 8) | subptr[1];
2935 if ((subptr[0] != 0) ||
2936 (subptr[1] != 0)) goto create_pair;
2938 myattr = (subptr[2] << 8) | subptr[3];
2942 * Our dictionary is broken.
2951 ptr += 4 + vsa_tlen;
2952 attrlen -= (4 + vsa_tlen);
2953 packet_length -= 4 + vsa_tlen;
2957 if (subptr[vsa_tlen] < (vsa_tlen + vsa_llen + vsa_offset))
2960 if (subptr[vsa_tlen] > sublen)
2965 * Reserved bits MUST be
2969 ((subptr[vsa_tlen + vsa_llen] & 0x7f) != 0))
2972 sublen -= subptr[vsa_tlen];
2973 subptr += subptr[vsa_tlen];
2977 if (subptr[vsa_tlen] != 0) goto create_pair;
2978 if (subptr[vsa_tlen + 1] < (vsa_tlen + vsa_llen))
2980 if (subptr[vsa_tlen + 1] > sublen)
2982 sublen -= subptr[vsa_tlen + 1];
2983 subptr += subptr[vsa_tlen + 1];
2987 * Our dictionaries are
2993 } while (sublen > 0);
2995 vendorcode = myvendor;
2996 vendorlen = attrlen - 4;
3003 * attrlen is the length of this attribute.
3004 * total_len is the length of the encompassing
3013 attribute = (ptr[0] << 8) | ptr[1];
3016 default: /* can't hit this. */
3024 attrlen = ptr[0] - (vsa_tlen + vsa_llen + vsa_offset);
3028 attrlen = ptr[1] - (vsa_tlen + vsa_llen);
3031 default: /* can't hit this. */
3035 ptr += vsa_llen + vsa_offset;
3036 vendorlen -= vsa_tlen + vsa_llen + vsa_offset + attrlen;
3037 packet_length -= (vsa_tlen + vsa_llen + vsa_offset);
3040 * Ignore VSAs that have no data.
3042 if (attrlen == 0) goto next;
3045 * WiMAX attributes of type 0 are ignored. They
3046 * are a secret flag to us that the attribute has
3047 * already been dealt with.
3049 if ((vendorcode == VENDORPEC_WIMAX) && (attribute == 0)) {
3056 da = dict_attrbyvalue(attribute, vendorcode);
3059 * If it's NOT continued, AND we know
3060 * about it, AND it's not a TLV, we can
3061 * create a normal pair.
3063 if (((vsa_ptr[2] & 0x80) == 0) &&
3064 da && (da->type != PW_TYPE_TLV)) goto create_pair;
3067 * Else it IS continued, or it's a TLV.
3068 * Go do a lot of work to find the stuff.
3070 pair = rad_continuation2vp(packet, original, secret,
3071 attribute, vendorcode,
3074 ((vsa_ptr[2] & 0x80) != 0),
3080 * Create the attribute, setting the default type
3081 * to 'octets'. If the type in the dictionary
3082 * is different, then the dictionary type will
3083 * over-ride this one.
3085 * If the attribute has no data, then discard it.
3087 * Unless it's CUI. Damn you, CUI!
3091 (attribute != PW_CHARGEABLE_USER_IDENTITY)) goto next;
3093 pair = rad_attr2vp(packet, original, secret,
3094 attribute, vendorcode, attrlen, ptr);
3096 pairfree(&packet->vps);
3097 fr_strerror_printf("out of memory");
3111 * VSA's may not have been counted properly in
3112 * rad_packet_ok() above, as it is hard to count
3113 * then without using the dictionary. We
3114 * therefore enforce the limits here, too.
3116 if ((fr_max_attributes > 0) &&
3117 (num_attributes > fr_max_attributes)) {
3118 char host_ipaddr[128];
3120 pairfree(&packet->vps);
3121 fr_strerror_printf("WARNING: Possible DoS attack from host %s: Too many attributes in request (received %d, max %d are allowed).",
3122 inet_ntop(packet->src_ipaddr.af,
3123 &packet->src_ipaddr.ipaddr,
3124 host_ipaddr, sizeof(host_ipaddr)),
3125 num_attributes, fr_max_attributes);
3130 if (vendorlen == 0) vendorcode = 0;
3132 packet_length -= attrlen;
3136 * Merge information from the outside world into our
3139 fr_rand_seed(packet->data, AUTH_HDR_LEN);
3148 * We assume that the passwd buffer passed is big enough.
3149 * RFC2138 says the password is max 128 chars, so the size
3150 * of the passwd buffer must be at least 129 characters.
3151 * Preferably it's just MAX_STRING_LEN.
3153 * int *pwlen is updated to the new length of the encrypted
3154 * password - a multiple of 16 bytes.
3156 int rad_pwencode(char *passwd, size_t *pwlen, const char *secret,
3157 const uint8_t *vector)
3159 FR_MD5_CTX context, old;
3160 uint8_t digest[AUTH_VECTOR_LEN];
3161 int i, n, secretlen;
3165 * RFC maximum is 128 bytes.
3167 * If length is zero, pad it out with zeros.
3169 * If the length isn't aligned to 16 bytes,
3170 * zero out the extra data.
3174 if (len > 128) len = 128;
3177 memset(passwd, 0, AUTH_PASS_LEN);
3178 len = AUTH_PASS_LEN;
3179 } else if ((len % AUTH_PASS_LEN) != 0) {
3180 memset(&passwd[len], 0, AUTH_PASS_LEN - (len % AUTH_PASS_LEN));
3181 len += AUTH_PASS_LEN - (len % AUTH_PASS_LEN);
3186 * Use the secret to setup the decryption digest
3188 secretlen = strlen(secret);
3190 fr_MD5Init(&context);
3191 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3192 old = context; /* save intermediate work */
3195 * Encrypt it in place. Don't bother checking
3196 * len, as we've ensured above that it's OK.
3198 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3200 fr_MD5Update(&context, vector, AUTH_PASS_LEN);
3201 fr_MD5Final(digest, &context);
3204 fr_MD5Update(&context,
3205 (uint8_t *) passwd + n - AUTH_PASS_LEN,
3207 fr_MD5Final(digest, &context);
3210 for (i = 0; i < AUTH_PASS_LEN; i++) {
3211 passwd[i + n] ^= digest[i];
3221 int rad_pwdecode(char *passwd, size_t pwlen, const char *secret,
3222 const uint8_t *vector)
3224 FR_MD5_CTX context, old;
3225 uint8_t digest[AUTH_VECTOR_LEN];
3227 size_t n, secretlen;
3230 * The RFC's say that the maximum is 128.
3231 * The buffer we're putting it into above is 254, so
3232 * we don't need to do any length checking.
3234 if (pwlen > 128) pwlen = 128;
3239 if (pwlen == 0) goto done;
3242 * Use the secret to setup the decryption digest
3244 secretlen = strlen(secret);
3246 fr_MD5Init(&context);
3247 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3248 old = context; /* save intermediate work */
3251 * The inverse of the code above.
3253 for (n = 0; n < pwlen; n += AUTH_PASS_LEN) {
3255 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3256 fr_MD5Final(digest, &context);
3259 if (pwlen > AUTH_PASS_LEN) {
3260 fr_MD5Update(&context, (uint8_t *) passwd,
3264 fr_MD5Final(digest, &context);
3267 if (pwlen > (n + AUTH_PASS_LEN)) {
3268 fr_MD5Update(&context, (uint8_t *) passwd + n,
3273 for (i = 0; i < AUTH_PASS_LEN; i++) {
3274 passwd[i + n] ^= digest[i];
3279 passwd[pwlen] = '\0';
3280 return strlen(passwd);
3285 * Encode Tunnel-Password attributes when sending them out on the wire.
3287 * int *pwlen is updated to the new length of the encrypted
3288 * password - a multiple of 16 bytes.
3290 * This is per RFC-2868 which adds a two char SALT to the initial intermediate
3293 int rad_tunnel_pwencode(char *passwd, size_t *pwlen, const char *secret,
3294 const uint8_t *vector)
3296 uint8_t buffer[AUTH_VECTOR_LEN + MAX_STRING_LEN + 3];
3297 unsigned char digest[AUTH_VECTOR_LEN];
3299 int i, n, secretlen;
3304 if (len > 127) len = 127;
3307 * Shift the password 3 positions right to place a salt and original
3308 * length, tag will be added automatically on packet send
3310 for (n=len ; n>=0 ; n--) passwd[n+3] = passwd[n];
3314 * save original password length as first password character;
3321 * Generate salt. The RFC's say:
3323 * The high bit of salt[0] must be set, each salt in a
3324 * packet should be unique, and they should be random
3326 * So, we set the high bit, add in a counter, and then
3327 * add in some CSPRNG data. should be OK..
3329 salt[0] = (0x80 | ( ((salt_offset++) & 0x0f) << 3) |
3330 (fr_rand() & 0x07));
3331 salt[1] = fr_rand();
3334 * Padd password to multiple of AUTH_PASS_LEN bytes.
3336 n = len % AUTH_PASS_LEN;
3338 n = AUTH_PASS_LEN - n;
3339 for (; n > 0; n--, len++)
3342 /* set new password length */
3346 * Use the secret to setup the decryption digest
3348 secretlen = strlen(secret);
3349 memcpy(buffer, secret, secretlen);
3351 for (n2 = 0; n2 < len; n2+=AUTH_PASS_LEN) {
3353 memcpy(buffer + secretlen, vector, AUTH_VECTOR_LEN);
3354 memcpy(buffer + secretlen + AUTH_VECTOR_LEN, salt, 2);
3355 fr_md5_calc(digest, buffer, secretlen + AUTH_VECTOR_LEN + 2);
3357 memcpy(buffer + secretlen, passwd + n2 - AUTH_PASS_LEN, AUTH_PASS_LEN);
3358 fr_md5_calc(digest, buffer, secretlen + AUTH_PASS_LEN);
3361 for (i = 0; i < AUTH_PASS_LEN; i++) {
3362 passwd[i + n2] ^= digest[i];
3370 * Decode Tunnel-Password encrypted attributes.
3372 * Defined in RFC-2868, this uses a two char SALT along with the
3373 * initial intermediate value, to differentiate it from the
3376 int rad_tunnel_pwdecode(uint8_t *passwd, size_t *pwlen, const char *secret,
3377 const uint8_t *vector)
3379 FR_MD5_CTX context, old;
3380 uint8_t digest[AUTH_VECTOR_LEN];
3382 unsigned i, n, len, reallen;
3387 * We need at least a salt.
3390 fr_strerror_printf("tunnel password is too short");
3395 * There's a salt, but no password. Or, there's a salt
3396 * and a 'data_len' octet. It's wrong, but at least we
3397 * can figure out what it means: the password is empty.
3399 * Note that this means we ignore the 'data_len' field,
3400 * if the attribute length tells us that there's no
3401 * more data. So the 'data_len' field may be wrong,
3410 len -= 2; /* discount the salt */
3413 * Use the secret to setup the decryption digest
3415 secretlen = strlen(secret);
3417 fr_MD5Init(&context);
3418 fr_MD5Update(&context, (const uint8_t *) secret, secretlen);
3419 old = context; /* save intermediate work */
3422 * Set up the initial key:
3424 * b(1) = MD5(secret + vector + salt)
3426 fr_MD5Update(&context, vector, AUTH_VECTOR_LEN);
3427 fr_MD5Update(&context, passwd, 2);
3430 for (n = 0; n < len; n += AUTH_PASS_LEN) {
3434 fr_MD5Final(digest, &context);
3439 * A quick check: decrypt the first octet
3440 * of the password, which is the
3441 * 'data_len' field. Ensure it's sane.
3443 reallen = passwd[2] ^ digest[0];
3444 if (reallen >= len) {
3445 fr_strerror_printf("tunnel password is too long for the attribute");
3449 fr_MD5Update(&context, passwd + 2, AUTH_PASS_LEN);
3453 fr_MD5Final(digest, &context);
3456 fr_MD5Update(&context, passwd + n + 2, AUTH_PASS_LEN);
3459 for (i = base; i < AUTH_PASS_LEN; i++) {
3460 passwd[n + i - 1] = passwd[n + i + 2] ^ digest[i];
3465 * See make_tunnel_password, above.
3467 if (reallen > 239) reallen = 239;
3470 passwd[reallen] = 0;
3476 * Encode a CHAP password
3478 * FIXME: might not work with Ascend because
3479 * we use vp->length, and Ascend gear likes
3480 * to send an extra '\0' in the string!
3482 int rad_chap_encode(RADIUS_PACKET *packet, uint8_t *output, int id,
3483 VALUE_PAIR *password)
3487 uint8_t string[MAX_STRING_LEN * 2 + 1];
3488 VALUE_PAIR *challenge;
3491 * Sanity check the input parameters
3493 if ((packet == NULL) || (password == NULL)) {
3498 * Note that the password VP can be EITHER
3499 * a User-Password attribute (from a check-item list),
3500 * or a CHAP-Password attribute (the client asking
3501 * the library to encode it).
3509 memcpy(ptr, password->vp_strvalue, password->length);
3510 ptr += password->length;
3511 i += password->length;
3514 * Use Chap-Challenge pair if present,
3515 * Request-Authenticator otherwise.
3517 challenge = pairfind(packet->vps, PW_CHAP_CHALLENGE, 0);
3519 memcpy(ptr, challenge->vp_strvalue, challenge->length);
3520 i += challenge->length;
3522 memcpy(ptr, packet->vector, AUTH_VECTOR_LEN);
3523 i += AUTH_VECTOR_LEN;
3527 fr_md5_calc((uint8_t *)output + 1, (uint8_t *)string, i);
3534 * Seed the random number generator.
3536 * May be called any number of times.
3538 void fr_rand_seed(const void *data, size_t size)
3543 * Ensure that the pool is initialized.
3545 if (!fr_rand_initialized) {
3548 memset(&fr_rand_pool, 0, sizeof(fr_rand_pool));
3550 fd = open("/dev/urandom", O_RDONLY);
3556 while (total < sizeof(fr_rand_pool.randrsl)) {
3557 this = read(fd, fr_rand_pool.randrsl,
3558 sizeof(fr_rand_pool.randrsl) - total);
3559 if ((this < 0) && (errno != EINTR)) break;
3560 if (this > 0) total += this;
3564 fr_rand_pool.randrsl[0] = fd;
3565 fr_rand_pool.randrsl[1] = time(NULL);
3566 fr_rand_pool.randrsl[2] = errno;
3569 fr_randinit(&fr_rand_pool, 1);
3570 fr_rand_pool.randcnt = 0;
3571 fr_rand_initialized = 1;
3577 * Hash the user data
3580 if (!hash) hash = fr_rand();
3581 hash = fr_hash_update(data, size, hash);
3583 fr_rand_pool.randmem[fr_rand_pool.randcnt] ^= hash;
3588 * Return a 32-bit random number.
3590 uint32_t fr_rand(void)
3595 * Ensure that the pool is initialized.
3597 if (!fr_rand_initialized) {
3598 fr_rand_seed(NULL, 0);
3601 num = fr_rand_pool.randrsl[fr_rand_pool.randcnt++];
3602 if (fr_rand_pool.randcnt >= 256) {
3603 fr_rand_pool.randcnt = 0;
3604 fr_isaac(&fr_rand_pool);
3612 * Allocate a new RADIUS_PACKET
3614 RADIUS_PACKET *rad_alloc(int newvector)
3618 if ((rp = malloc(sizeof(RADIUS_PACKET))) == NULL) {
3619 fr_strerror_printf("out of memory");
3622 memset(rp, 0, sizeof(*rp));
3628 uint32_t hash, base;
3631 * Don't expose the actual contents of the random
3635 for (i = 0; i < AUTH_VECTOR_LEN; i += sizeof(uint32_t)) {
3636 hash = fr_rand() ^ base;
3637 memcpy(rp->vector + i, &hash, sizeof(hash));
3640 fr_rand(); /* stir the pool again */
3645 RADIUS_PACKET *rad_alloc_reply(RADIUS_PACKET *packet)
3647 RADIUS_PACKET *reply;
3649 if (!packet) return NULL;
3651 reply = rad_alloc(0);
3652 if (!reply) return NULL;
3655 * Initialize the fields from the request.
3657 reply->sockfd = packet->sockfd;
3658 reply->dst_ipaddr = packet->src_ipaddr;
3659 reply->src_ipaddr = packet->dst_ipaddr;
3660 reply->dst_port = packet->src_port;
3661 reply->src_port = packet->dst_port;
3662 reply->id = packet->id;
3663 reply->code = 0; /* UNKNOWN code */
3664 memcpy(reply->vector, packet->vector,
3665 sizeof(reply->vector));
3668 reply->data_len = 0;
3675 * Free a RADIUS_PACKET
3677 void rad_free(RADIUS_PACKET **radius_packet_ptr)
3679 RADIUS_PACKET *radius_packet;
3681 if (!radius_packet_ptr || !*radius_packet_ptr) return;
3682 radius_packet = *radius_packet_ptr;
3684 free(radius_packet->data);
3686 pairfree(&radius_packet->vps);
3688 free(radius_packet);
3690 *radius_packet_ptr = NULL;