diff --git a/sys/netinet/libalias/alias.c b/sys/netinet/libalias/alias.c index 0e2756affcb4..39e9b060623d 100644 --- a/sys/netinet/libalias/alias.c +++ b/sys/netinet/libalias/alias.c @@ -1,1794 +1,1792 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 Charles Mott * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* Alias.c provides supervisory control for the functions of the packet aliasing software. It consists of routines to monitor TCP connection state, protocol-specific aliasing routines, fragment handling and the following outside world functional interfaces: SaveFragmentPtr, GetFragmentPtr, FragmentAliasIn, PacketAliasIn and PacketAliasOut. The other C program files are briefly described. The data structure framework which holds information needed to translate packets is encapsulated in alias_db.c. Data is accessed by function calls, so other segments of the program need not know about the underlying data structures. Alias_ftp.c contains special code for modifying the ftp PORT command used to establish data connections, while alias_irc.c does the same for IRC DCC. Alias_util.c contains a few utility routines. Version 1.0 August, 1996 (cjm) Version 1.1 August 20, 1996 (cjm) PPP host accepts incoming connections for ports 0 to 1023. (Gary Roberts pointed out the need to handle incoming connections.) Version 1.2 September 7, 1996 (cjm) Fragment handling error in alias_db.c corrected. (Tom Torrance helped fix this problem.) Version 1.4 September 16, 1996 (cjm) - A more generalized method for handling incoming connections, without the 0-1023 restriction, is implemented in alias_db.c - Improved ICMP support in alias.c. Traceroute packet streams can now be correctly aliased. - TCP connection closing logic simplified in alias.c and now allows for additional 1 minute "grace period" after FIN or RST is observed. Version 1.5 September 17, 1996 (cjm) Corrected error in handling incoming UDP packets with 0 checksum. (Tom Torrance helped fix this problem.) Version 1.6 September 18, 1996 (cjm) Simplified ICMP aliasing scheme. Should now support traceroute from Win95 as well as FreeBSD. Version 1.7 January 9, 1997 (cjm) - Out-of-order fragment handling. - IP checksum error fixed for ftp transfers from aliasing host. - Integer return codes added to all aliasing/de-aliasing functions. - Some obsolete comments cleaned up. - Differential checksum computations for IP header (TCP, UDP and ICMP were already differential). Version 2.1 May 1997 (cjm) - Added support for outgoing ICMP error messages. - Added two functions PacketAliasIn2() and PacketAliasOut2() for dynamic address control (e.g. round-robin allocation of incoming packets). Version 2.2 July 1997 (cjm) - Rationalized API function names to begin with "PacketAlias..." - Eliminated PacketAliasIn2() and PacketAliasOut2() as poorly conceived. Version 2.3 Dec 1998 (dillon) - Major bounds checking additions, see FreeBSD/CVS Version 3.1 May, 2000 (salander) - Added hooks to handle PPTP. Version 3.2 July, 2000 (salander and satoh) - Added PacketUnaliasOut routine. - Added hooks to handle RTSP/RTP. See HISTORY file for additional revisions. */ #ifdef _KERNEL #include #include #include #include #else #include #include #include #include #include #include #include #endif #include #include #include #include #include #include #ifdef _KERNEL #include #include #include #else #include #include "alias.h" #include "alias_local.h" #include "alias_mod.h" #endif /* * Define libalias SYSCTL Node */ #ifdef SYSCTL_NODE SYSCTL_DECL(_net_inet); SYSCTL_DECL(_net_inet_ip); SYSCTL_NODE(_net_inet_ip, OID_AUTO, alias, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, "Libalias sysctl API"); #endif static __inline int twowords(void *p) { uint8_t *c = p; #if BYTE_ORDER == LITTLE_ENDIAN uint16_t s1 = ((uint16_t)c[1] << 8) + (uint16_t)c[0]; uint16_t s2 = ((uint16_t)c[3] << 8) + (uint16_t)c[2]; #else uint16_t s1 = ((uint16_t)c[0] << 8) + (uint16_t)c[1]; uint16_t s2 = ((uint16_t)c[2] << 8) + (uint16_t)c[3]; #endif return (s1 + s2); } /* TCP Handling Routines TcpMonitorIn() -- These routines monitor TCP connections, and TcpMonitorOut() delete a link when a connection is closed. These routines look for SYN, FIN and RST flags to determine when TCP connections open and close. When a TCP connection closes, the data structure containing packet aliasing information is deleted after a timeout period. */ /* Local prototypes */ static void TcpMonitorIn(u_char, struct alias_link *); static void TcpMonitorOut(u_char, struct alias_link *); static void TcpMonitorIn(u_char th_flags, struct alias_link *lnk) { switch (GetStateIn(lnk)) { case ALIAS_TCP_STATE_NOT_CONNECTED: if (th_flags & TH_RST) SetStateIn(lnk, ALIAS_TCP_STATE_DISCONNECTED); else if (th_flags & TH_SYN) SetStateIn(lnk, ALIAS_TCP_STATE_CONNECTED); break; case ALIAS_TCP_STATE_CONNECTED: if (th_flags & (TH_FIN | TH_RST)) SetStateIn(lnk, ALIAS_TCP_STATE_DISCONNECTED); break; } } static void TcpMonitorOut(u_char th_flags, struct alias_link *lnk) { switch (GetStateOut(lnk)) { case ALIAS_TCP_STATE_NOT_CONNECTED: if (th_flags & TH_RST) SetStateOut(lnk, ALIAS_TCP_STATE_DISCONNECTED); else if (th_flags & TH_SYN) SetStateOut(lnk, ALIAS_TCP_STATE_CONNECTED); break; case ALIAS_TCP_STATE_CONNECTED: if (th_flags & (TH_FIN | TH_RST)) SetStateOut(lnk, ALIAS_TCP_STATE_DISCONNECTED); break; } } /* Protocol Specific Packet Aliasing Routines IcmpAliasIn(), IcmpAliasIn1(), IcmpAliasIn2() IcmpAliasOut(), IcmpAliasOut1(), IcmpAliasOut2() ProtoAliasIn(), ProtoAliasOut() UdpAliasIn(), UdpAliasOut() TcpAliasIn(), TcpAliasOut() These routines handle protocol specific details of packet aliasing. One may observe a certain amount of repetitive arithmetic in these functions, the purpose of which is to compute a revised checksum without actually summing over the entire data packet, which could be unnecessarily time consuming. The purpose of the packet aliasing routines is to replace the source address of the outgoing packet and then correctly put it back for any incoming packets. For TCP and UDP, ports are also re-mapped. For ICMP echo/timestamp requests and replies, the following scheme is used: the ID number is replaced by an alias for the outgoing packet. ICMP error messages are handled by looking at the IP fragment in the data section of the message. For TCP and UDP protocols, a port number is chosen for an outgoing packet, and then incoming packets are identified by IP address and port numbers. For TCP packets, there is additional logic in the event that sequence and ACK numbers have been altered (as in the case for FTP data port commands). The port numbers used by the packet aliasing module are not true ports in the Unix sense. No sockets are actually bound to ports. They are more correctly thought of as placeholders. All packets go through the aliasing mechanism, whether they come from the gateway machine or other machines on a local area network. */ /* Local prototypes */ static int IcmpAliasIn1(struct libalias *, struct ip *); static int IcmpAliasIn2(struct libalias *, struct ip *); static int IcmpAliasIn(struct libalias *, struct ip *); static int IcmpAliasOut1(struct libalias *, struct ip *, int create); static int IcmpAliasOut2(struct libalias *, struct ip *); static int IcmpAliasOut(struct libalias *, struct ip *, int create); static int ProtoAliasIn(struct libalias *la, struct in_addr ip_src, struct ip *pip, u_char ip_p, u_short *ip_sum); static int ProtoAliasOut(struct libalias *la, struct ip *pip, struct in_addr ip_dst, u_char ip_p, u_short *ip_sum, int create); static int UdpAliasIn(struct libalias *, struct ip *); static int UdpAliasOut(struct libalias *, struct ip *, int, int create); static int TcpAliasIn(struct libalias *, struct ip *); static int TcpAliasOut(struct libalias *, struct ip *, int, int create); /* De-alias incoming echo and timestamp replies. Alias incoming echo and timestamp requests. */ static int IcmpAliasIn1(struct libalias *la, struct ip *pip) { struct alias_link *lnk; struct icmp *ic; LIBALIAS_LOCK_ASSERT(la); ic = (struct icmp *)ip_next(pip); /* Get source address from ICMP data field and restore original data */ lnk = FindIcmpIn(la, pip->ip_src, pip->ip_dst, ic->icmp_id, 1); if (lnk != NULL) { u_short original_id; int accumulate; original_id = GetOriginalPort(lnk); /* Adjust ICMP checksum */ accumulate = ic->icmp_id; accumulate -= original_id; ADJUST_CHECKSUM(accumulate, ic->icmp_cksum); /* Put original sequence number back in */ ic->icmp_id = original_id; /* Put original address back into IP header */ { struct in_addr original_address; original_address = GetOriginalAddress(lnk); DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; } return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } /* Alias incoming ICMP error messages containing IP header and first 64 bits of datagram. */ static int IcmpAliasIn2(struct libalias *la, struct ip *pip) { struct ip *ip; struct icmp *ic, *ic2; struct udphdr *ud; struct tcphdr *tc; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); ic = (struct icmp *)ip_next(pip); ip = &ic->icmp_ip; ud = (struct udphdr *)ip_next(ip); tc = (struct tcphdr *)ip_next(ip); ic2 = (struct icmp *)ip_next(ip); if (ip->ip_p == IPPROTO_UDP) lnk = FindUdpTcpIn(la, ip->ip_dst, ip->ip_src, ud->uh_dport, ud->uh_sport, IPPROTO_UDP, 0); else if (ip->ip_p == IPPROTO_TCP) lnk = FindUdpTcpIn(la, ip->ip_dst, ip->ip_src, tc->th_dport, tc->th_sport, IPPROTO_TCP, 0); else if (ip->ip_p == IPPROTO_ICMP) { if (ic2->icmp_type == ICMP_ECHO || ic2->icmp_type == ICMP_TSTAMP) lnk = FindIcmpIn(la, ip->ip_dst, ip->ip_src, ic2->icmp_id, 0); else lnk = NULL; } else lnk = NULL; if (lnk != NULL) { if (ip->ip_p == IPPROTO_UDP || ip->ip_p == IPPROTO_TCP) { int accumulate, accumulate2; struct in_addr original_address; u_short original_port; original_address = GetOriginalAddress(lnk); original_port = GetOriginalPort(lnk); /* Adjust ICMP checksum */ accumulate = twowords(&ip->ip_src); accumulate -= twowords(&original_address); accumulate += ud->uh_sport; accumulate -= original_port; accumulate2 = accumulate; accumulate2 += ip->ip_sum; ADJUST_CHECKSUM(accumulate, ip->ip_sum); accumulate2 -= ip->ip_sum; ADJUST_CHECKSUM(accumulate2, ic->icmp_cksum); /* Un-alias address in IP header */ DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; /* Un-alias address and port number of * original IP packet fragment contained * in ICMP data section */ ip->ip_src = original_address; ud->uh_sport = original_port; } else if (ip->ip_p == IPPROTO_ICMP) { int accumulate, accumulate2; struct in_addr original_address; u_short original_id; original_address = GetOriginalAddress(lnk); original_id = GetOriginalPort(lnk); /* Adjust ICMP checksum */ accumulate = twowords(&ip->ip_src); accumulate -= twowords(&original_address); accumulate += ic2->icmp_id; accumulate -= original_id; accumulate2 = accumulate; accumulate2 += ip->ip_sum; ADJUST_CHECKSUM(accumulate, ip->ip_sum); accumulate2 -= ip->ip_sum; ADJUST_CHECKSUM(accumulate2, ic->icmp_cksum); /* Un-alias address in IP header */ DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; /* Un-alias address of original IP packet and * sequence number of embedded ICMP datagram */ ip->ip_src = original_address; ic2->icmp_id = original_id; } return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int IcmpAliasIn(struct libalias *la, struct ip *pip) { struct icmp *ic; int iresult; size_t dlen; LIBALIAS_LOCK_ASSERT(la); dlen = ntohs(pip->ip_len) - (pip->ip_hl << 2); if (dlen < ICMP_MINLEN) return (PKT_ALIAS_IGNORED); /* Return if proxy-only mode is enabled */ if (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY) return (PKT_ALIAS_OK); ic = (struct icmp *)ip_next(pip); iresult = PKT_ALIAS_IGNORED; switch (ic->icmp_type) { case ICMP_ECHOREPLY: case ICMP_TSTAMPREPLY: if (ic->icmp_code == 0) { iresult = IcmpAliasIn1(la, pip); } break; case ICMP_UNREACH: case ICMP_SOURCEQUENCH: case ICMP_TIMXCEED: case ICMP_PARAMPROB: if (dlen < ICMP_ADVLENMIN || dlen < (size_t)ICMP_ADVLEN(ic)) return (PKT_ALIAS_IGNORED); iresult = IcmpAliasIn2(la, pip); break; case ICMP_ECHO: case ICMP_TSTAMP: iresult = IcmpAliasIn1(la, pip); break; } return (iresult); } /* Alias outgoing echo and timestamp requests. De-alias outgoing echo and timestamp replies. */ static int IcmpAliasOut1(struct libalias *la, struct ip *pip, int create) { struct alias_link *lnk; struct icmp *ic; LIBALIAS_LOCK_ASSERT(la); ic = (struct icmp *)ip_next(pip); /* Save overwritten data for when echo packet returns */ lnk = FindIcmpOut(la, pip->ip_src, pip->ip_dst, ic->icmp_id, create); if (lnk != NULL) { u_short alias_id; int accumulate; alias_id = GetAliasPort(lnk); /* Since data field is being modified, adjust ICMP checksum */ accumulate = ic->icmp_id; accumulate -= alias_id; ADJUST_CHECKSUM(accumulate, ic->icmp_cksum); /* Alias sequence number */ ic->icmp_id = alias_id; /* Change source address */ { struct in_addr alias_address; alias_address = GetAliasAddress(lnk); DifferentialChecksum(&pip->ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; } return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } /* Alias outgoing ICMP error messages containing IP header and first 64 bits of datagram. */ static int IcmpAliasOut2(struct libalias *la, struct ip *pip) { struct ip *ip; struct icmp *ic, *ic2; struct udphdr *ud; struct tcphdr *tc; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); ic = (struct icmp *)ip_next(pip); ip = &ic->icmp_ip; ud = (struct udphdr *)ip_next(ip); tc = (struct tcphdr *)ip_next(ip); ic2 = (struct icmp *)ip_next(ip); if (ip->ip_p == IPPROTO_UDP) lnk = FindUdpTcpOut(la, ip->ip_dst, ip->ip_src, ud->uh_dport, ud->uh_sport, IPPROTO_UDP, 0); else if (ip->ip_p == IPPROTO_TCP) lnk = FindUdpTcpOut(la, ip->ip_dst, ip->ip_src, tc->th_dport, tc->th_sport, IPPROTO_TCP, 0); else if (ip->ip_p == IPPROTO_ICMP) { if (ic2->icmp_type == ICMP_ECHO || ic2->icmp_type == ICMP_TSTAMP) lnk = FindIcmpOut(la, ip->ip_dst, ip->ip_src, ic2->icmp_id, 0); else lnk = NULL; } else lnk = NULL; if (lnk != NULL) { if (ip->ip_p == IPPROTO_UDP || ip->ip_p == IPPROTO_TCP) { int accumulate; struct in_addr alias_address; u_short alias_port; alias_address = GetAliasAddress(lnk); alias_port = GetAliasPort(lnk); /* Adjust ICMP checksum */ accumulate = twowords(&ip->ip_dst); accumulate -= twowords(&alias_address); accumulate += ud->uh_dport; accumulate -= alias_port; ADJUST_CHECKSUM(accumulate, ic->icmp_cksum); /* * Alias address in IP header if it comes from the host * the original TCP/UDP packet was destined for. */ if (pip->ip_src.s_addr == ip->ip_dst.s_addr) { DifferentialChecksum(&pip->ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; } /* Alias address and port number of original IP packet * fragment contained in ICMP data section */ ip->ip_dst = alias_address; ud->uh_dport = alias_port; } else if (ip->ip_p == IPPROTO_ICMP) { int accumulate; struct in_addr alias_address; u_short alias_id; alias_address = GetAliasAddress(lnk); alias_id = GetAliasPort(lnk); /* Adjust ICMP checksum */ accumulate = twowords(&ip->ip_dst); accumulate -= twowords(&alias_address); accumulate += ic2->icmp_id; accumulate -= alias_id; ADJUST_CHECKSUM(accumulate, ic->icmp_cksum); /* * Alias address in IP header if it comes from the host * the original ICMP message was destined for. */ if (pip->ip_src.s_addr == ip->ip_dst.s_addr) { DifferentialChecksum(&pip->ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; } /* Alias address of original IP packet and * sequence number of embedded ICMP datagram */ ip->ip_dst = alias_address; ic2->icmp_id = alias_id; } return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int IcmpAliasOut(struct libalias *la, struct ip *pip, int create) { int iresult; struct icmp *ic; LIBALIAS_LOCK_ASSERT(la); (void)create; /* Return if proxy-only mode is enabled */ if (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY) return (PKT_ALIAS_OK); ic = (struct icmp *)ip_next(pip); iresult = PKT_ALIAS_IGNORED; switch (ic->icmp_type) { case ICMP_ECHO: case ICMP_TSTAMP: if (ic->icmp_code == 0) { iresult = IcmpAliasOut1(la, pip, create); } break; case ICMP_UNREACH: case ICMP_SOURCEQUENCH: case ICMP_TIMXCEED: case ICMP_PARAMPROB: iresult = IcmpAliasOut2(la, pip); break; case ICMP_ECHOREPLY: case ICMP_TSTAMPREPLY: iresult = IcmpAliasOut1(la, pip, create); } return (iresult); } /* Handle incoming IP packets. The only thing which is done in this case is to alias the dest IP address of the packet to our inside machine. */ static int ProtoAliasIn(struct libalias *la, struct in_addr ip_src, struct ip *pip, u_char ip_p, u_short *ip_sum) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); /* Return if proxy-only mode is enabled */ if (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY) return (PKT_ALIAS_OK); lnk = FindProtoIn(la, ip_src, pip->ip_dst, ip_p); if (lnk != NULL) { struct in_addr original_address; original_address = GetOriginalAddress(lnk); /* Restore original IP address */ DifferentialChecksum(ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } /* Handle outgoing IP packets. The only thing which is done in this case is to alias the source IP address of the packet. */ static int ProtoAliasOut(struct libalias *la, struct ip *pip, struct in_addr ip_dst, u_char ip_p, u_short *ip_sum, int create) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); /* Return if proxy-only mode is enabled */ if (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY) return (PKT_ALIAS_OK); if (!create) return (PKT_ALIAS_IGNORED); lnk = FindProtoOut(la, pip->ip_src, ip_dst, ip_p); if (lnk != NULL) { struct in_addr alias_address; alias_address = GetAliasAddress(lnk); /* Change source address */ DifferentialChecksum(ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int UdpAliasIn(struct libalias *la, struct ip *pip) { struct udphdr *ud; struct alias_link *lnk; size_t dlen; LIBALIAS_LOCK_ASSERT(la); dlen = ntohs(pip->ip_len) - (pip->ip_hl << 2); if (dlen < sizeof(struct udphdr)) return (PKT_ALIAS_IGNORED); ud = (struct udphdr *)ip_next(pip); if (dlen < ntohs(ud->uh_ulen)) return (PKT_ALIAS_IGNORED); lnk = FindUdpTcpIn(la, pip->ip_src, pip->ip_dst, ud->uh_sport, ud->uh_dport, IPPROTO_UDP, !(la->packetAliasMode & PKT_ALIAS_PROXY_ONLY)); if (lnk != NULL) { struct in_addr alias_address; struct in_addr original_address; struct in_addr proxy_address; u_short alias_port; u_short proxy_port; int accumulate; int error; struct alias_data ad = { .lnk = lnk, .oaddr = &original_address, .aaddr = &alias_address, .aport = &alias_port, .sport = &ud->uh_sport, .dport = &ud->uh_dport, .maxpktsize = 0 }; alias_address = GetAliasAddress(lnk); original_address = GetOriginalAddress(lnk); proxy_address = GetProxyAddress(lnk); alias_port = ud->uh_dport; ud->uh_dport = GetOriginalPort(lnk); proxy_port = GetProxyPort(lnk); /* Walk out chain. */ error = find_handler(IN, UDP, la, pip, &ad); /* If we cannot figure out the packet, ignore it. */ if (error < 0) return (PKT_ALIAS_IGNORED); /* If UDP checksum is not zero, then adjust since * destination port is being unaliased and * destination address is being altered. */ if (ud->uh_sum != 0) { accumulate = alias_port; accumulate -= ud->uh_dport; accumulate += twowords(&alias_address); accumulate -= twowords(&original_address); /* If this is a proxy packet, modify checksum * because of source change.*/ if (proxy_port != 0) { accumulate += ud->uh_sport; accumulate -= proxy_port; } if (proxy_address.s_addr != 0) { accumulate += twowords(&pip->ip_src); accumulate -= twowords(&proxy_address); } ADJUST_CHECKSUM(accumulate, ud->uh_sum); } /* XXX: Could the two if's below be concatenated to one ? */ /* Restore source port and/or address in case of proxying*/ if (proxy_port != 0) ud->uh_sport = proxy_port; if (proxy_address.s_addr != 0) { DifferentialChecksum(&pip->ip_sum, &proxy_address, &pip->ip_src, 2); pip->ip_src = proxy_address; } /* Restore original IP address */ DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int UdpAliasOut(struct libalias *la, struct ip *pip, int maxpacketsize, int create) { struct udphdr *ud; struct alias_link *lnk; struct in_addr dest_address; struct in_addr proxy_server_address; u_short dest_port; u_short proxy_server_port; int proxy_type; int error; size_t dlen; LIBALIAS_LOCK_ASSERT(la); /* Return if proxy-only mode is enabled and not proxyrule found.*/ dlen = ntohs(pip->ip_len) - (pip->ip_hl << 2); if (dlen < sizeof(struct udphdr)) return (PKT_ALIAS_IGNORED); ud = (struct udphdr *)ip_next(pip); if (dlen < ntohs(ud->uh_ulen)) return (PKT_ALIAS_IGNORED); proxy_type = ProxyCheck(la, &proxy_server_address, &proxy_server_port, pip->ip_src, pip->ip_dst, ud->uh_dport, pip->ip_p); if (proxy_type == 0 && (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY)) return (PKT_ALIAS_OK); /* If this is a transparent proxy, save original destination, * then alter the destination and adjust checksums */ dest_port = ud->uh_dport; dest_address = pip->ip_dst; if (proxy_type != 0) { int accumulate; accumulate = twowords(&pip->ip_dst); accumulate -= twowords(&proxy_server_address); ADJUST_CHECKSUM(accumulate, pip->ip_sum); if (ud->uh_sum != 0) { accumulate = twowords(&pip->ip_dst); accumulate -= twowords(&proxy_server_address); accumulate += ud->uh_dport; accumulate -= proxy_server_port; ADJUST_CHECKSUM(accumulate, ud->uh_sum); } pip->ip_dst = proxy_server_address; ud->uh_dport = proxy_server_port; } lnk = FindUdpTcpOut(la, pip->ip_src, pip->ip_dst, ud->uh_sport, ud->uh_dport, IPPROTO_UDP, create); if (lnk != NULL) { u_short alias_port; struct in_addr alias_address; struct alias_data ad = { .lnk = lnk, .oaddr = NULL, .aaddr = &alias_address, .aport = &alias_port, .sport = &ud->uh_sport, .dport = &ud->uh_dport, .maxpktsize = 0 }; /* Save original destination address, if this is a proxy packet. * Also modify packet to include destination encoding. This may * change the size of IP header. */ if (proxy_type != 0) { SetProxyPort(lnk, dest_port); SetProxyAddress(lnk, dest_address); ProxyModify(la, lnk, pip, maxpacketsize, proxy_type); ud = (struct udphdr *)ip_next(pip); } alias_address = GetAliasAddress(lnk); alias_port = GetAliasPort(lnk); /* Walk out chain. */ error = find_handler(OUT, UDP, la, pip, &ad); /* If UDP checksum is not zero, adjust since source port is */ /* being aliased and source address is being altered */ if (ud->uh_sum != 0) { int accumulate; accumulate = ud->uh_sport; accumulate -= alias_port; accumulate += twowords(&pip->ip_src); accumulate -= twowords(&alias_address); ADJUST_CHECKSUM(accumulate, ud->uh_sum); } /* Put alias port in UDP header */ ud->uh_sport = alias_port; /* Change source address */ DifferentialChecksum(&pip->ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int TcpAliasIn(struct libalias *la, struct ip *pip) { struct tcphdr *tc; struct alias_link *lnk; size_t dlen; LIBALIAS_LOCK_ASSERT(la); dlen = ntohs(pip->ip_len) - (pip->ip_hl << 2); if (dlen < sizeof(struct tcphdr)) return (PKT_ALIAS_IGNORED); tc = (struct tcphdr *)ip_next(pip); lnk = FindUdpTcpIn(la, pip->ip_src, pip->ip_dst, tc->th_sport, tc->th_dport, IPPROTO_TCP, !(la->packetAliasMode & PKT_ALIAS_PROXY_ONLY)); if (lnk != NULL) { struct in_addr alias_address; struct in_addr original_address; struct in_addr proxy_address; u_short alias_port; u_short proxy_port; int accumulate, error; /* * The init of MANY vars is a bit below, but aliashandlepptpin * seems to need the destination port that came within the * packet and not the original one looks below [*]. */ struct alias_data ad = { .lnk = lnk, .oaddr = NULL, .aaddr = NULL, .aport = NULL, .sport = &tc->th_sport, .dport = &tc->th_dport, .maxpktsize = 0 }; /* Walk out chain. */ error = find_handler(IN, TCP, la, pip, &ad); alias_address = GetAliasAddress(lnk); original_address = GetOriginalAddress(lnk); proxy_address = GetProxyAddress(lnk); alias_port = tc->th_dport; tc->th_dport = GetOriginalPort(lnk); proxy_port = GetProxyPort(lnk); /* * Look above, if anyone is going to add find_handler AFTER * this aliashandlepptpin/point, please redo alias_data too. * Uncommenting the piece here below should be enough. */ #if 0 struct alias_data ad = { .lnk = lnk, .oaddr = &original_address, .aaddr = &alias_address, .aport = &alias_port, .sport = &ud->uh_sport, .dport = &ud->uh_dport, .maxpktsize = 0 }; /* Walk out chain. */ error = find_handler(la, pip, &ad); if (error == EHDNOF) printf("Protocol handler not found\n"); #endif /* Adjust TCP checksum since destination port is being * unaliased and destination port is being altered. */ accumulate = alias_port; accumulate -= tc->th_dport; accumulate += twowords(&alias_address); accumulate -= twowords(&original_address); /* If this is a proxy, then modify the TCP source port * and checksum accumulation */ if (proxy_port != 0) { accumulate += tc->th_sport; tc->th_sport = proxy_port; accumulate -= tc->th_sport; accumulate += twowords(&pip->ip_src); accumulate -= twowords(&proxy_address); } /* See if ACK number needs to be modified */ if (GetAckModified(lnk) == 1) { int delta; tc = (struct tcphdr *)ip_next(pip); delta = GetDeltaAckIn(tc->th_ack, lnk); if (delta != 0) { accumulate += twowords(&tc->th_ack); tc->th_ack = htonl(ntohl(tc->th_ack) - delta); accumulate -= twowords(&tc->th_ack); } } ADJUST_CHECKSUM(accumulate, tc->th_sum); /* Restore original IP address */ accumulate = twowords(&pip->ip_dst); pip->ip_dst = original_address; accumulate -= twowords(&pip->ip_dst); /* If this is a transparent proxy packet, * then modify the source address */ if (proxy_address.s_addr != 0) { accumulate += twowords(&pip->ip_src); pip->ip_src = proxy_address; accumulate -= twowords(&pip->ip_src); } ADJUST_CHECKSUM(accumulate, pip->ip_sum); /* Monitor TCP connection state */ tc = (struct tcphdr *)ip_next(pip); TcpMonitorIn(tc->th_flags, lnk); return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } static int TcpAliasOut(struct libalias *la, struct ip *pip, int maxpacketsize, int create) { int proxy_type, error; u_short dest_port; u_short proxy_server_port; size_t dlen; struct in_addr dest_address; struct in_addr proxy_server_address; struct tcphdr *tc; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); dlen = ntohs(pip->ip_len) - (pip->ip_hl << 2); if (dlen < sizeof(struct tcphdr)) return (PKT_ALIAS_IGNORED); tc = (struct tcphdr *)ip_next(pip); if (create) proxy_type = ProxyCheck(la, &proxy_server_address, &proxy_server_port, pip->ip_src, pip->ip_dst, tc->th_dport, pip->ip_p); else proxy_type = 0; if (proxy_type == 0 && (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY)) return (PKT_ALIAS_OK); /* If this is a transparent proxy, save original destination, * then alter the destination and adjust checksums */ dest_port = tc->th_dport; dest_address = pip->ip_dst; if (proxy_type != 0) { int accumulate; accumulate = tc->th_dport; tc->th_dport = proxy_server_port; accumulate -= tc->th_dport; accumulate += twowords(&pip->ip_dst); accumulate -= twowords(&proxy_server_address); ADJUST_CHECKSUM(accumulate, tc->th_sum); accumulate = twowords(&pip->ip_dst); pip->ip_dst = proxy_server_address; accumulate -= twowords(&pip->ip_dst); ADJUST_CHECKSUM(accumulate, pip->ip_sum); } lnk = FindUdpTcpOut(la, pip->ip_src, pip->ip_dst, tc->th_sport, tc->th_dport, IPPROTO_TCP, create); if (lnk == NULL) return (PKT_ALIAS_IGNORED); if (lnk != NULL) { u_short alias_port; struct in_addr alias_address; int accumulate; struct alias_data ad = { .lnk = lnk, .oaddr = NULL, .aaddr = &alias_address, .aport = &alias_port, .sport = &tc->th_sport, .dport = &tc->th_dport, .maxpktsize = maxpacketsize }; /* Save original destination address, if this is a proxy packet. * Also modify packet to include destination * encoding. This may change the size of IP header. */ if (proxy_type != 0) { SetProxyPort(lnk, dest_port); SetProxyAddress(lnk, dest_address); ProxyModify(la, lnk, pip, maxpacketsize, proxy_type); tc = (struct tcphdr *)ip_next(pip); } /* Get alias address and port */ alias_port = GetAliasPort(lnk); alias_address = GetAliasAddress(lnk); /* Monitor TCP connection state */ tc = (struct tcphdr *)ip_next(pip); TcpMonitorOut(tc->th_flags, lnk); /* Walk out chain. */ error = find_handler(OUT, TCP, la, pip, &ad); /* Adjust TCP checksum since source port is being aliased * and source address is being altered */ accumulate = tc->th_sport; tc->th_sport = alias_port; accumulate -= tc->th_sport; accumulate += twowords(&pip->ip_src); accumulate -= twowords(&alias_address); /* Modify sequence number if necessary */ if (GetAckModified(lnk) == 1) { int delta; tc = (struct tcphdr *)ip_next(pip); delta = GetDeltaSeqOut(tc->th_seq, lnk); if (delta != 0) { accumulate += twowords(&tc->th_seq); tc->th_seq = htonl(ntohl(tc->th_seq) + delta); accumulate -= twowords(&tc->th_seq); } } ADJUST_CHECKSUM(accumulate, tc->th_sum); /* Change source address */ accumulate = twowords(&pip->ip_src); pip->ip_src = alias_address; accumulate -= twowords(&pip->ip_src); ADJUST_CHECKSUM(accumulate, pip->ip_sum); return (PKT_ALIAS_OK); } return (PKT_ALIAS_IGNORED); } /* Fragment Handling FragmentIn() FragmentOut() The packet aliasing module has a limited ability for handling IP fragments. If the ICMP, TCP or UDP header is in the first fragment received, then the ID number of the IP packet is saved, and other fragments are identified according to their ID number and IP address they were sent from. Pointers to unresolved fragments can also be saved and recalled when a header fragment is seen. */ /* Local prototypes */ static int FragmentIn(struct libalias *la, struct in_addr ip_src, struct ip *pip, u_short ip_id, u_short *ip_sum); static int FragmentOut(struct libalias *, struct ip *pip, u_short *ip_sum); static int FragmentIn(struct libalias *la, struct in_addr ip_src, struct ip *pip, u_short ip_id, u_short *ip_sum) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindFragmentIn2(la, ip_src, pip->ip_dst, ip_id); if (lnk != NULL) { struct in_addr original_address; GetFragmentAddr(lnk, &original_address); DifferentialChecksum(ip_sum, &original_address, &pip->ip_dst, 2); pip->ip_dst = original_address; return (PKT_ALIAS_OK); } return (PKT_ALIAS_UNRESOLVED_FRAGMENT); } static int FragmentOut(struct libalias *la, struct ip *pip, u_short *ip_sum) { struct in_addr alias_address; LIBALIAS_LOCK_ASSERT(la); alias_address = FindAliasAddress(la, pip->ip_src); DifferentialChecksum(ip_sum, &alias_address, &pip->ip_src, 2); pip->ip_src = alias_address; return (PKT_ALIAS_OK); } /* Outside World Access PacketAliasSaveFragment() PacketAliasGetFragment() PacketAliasFragmentIn() PacketAliasIn() PacketAliasOut() PacketUnaliasOut() (prototypes in alias.h) */ int LibAliasSaveFragment(struct libalias *la, void *ptr) { int iresult; struct alias_link *lnk; struct ip *pip; LIBALIAS_LOCK(la); pip = (struct ip *)ptr; lnk = AddFragmentPtrLink(la, pip->ip_src, pip->ip_id); iresult = PKT_ALIAS_ERROR; if (lnk != NULL) { SetFragmentPtr(lnk, ptr); iresult = PKT_ALIAS_OK; } LIBALIAS_UNLOCK(la); return (iresult); } void * LibAliasGetFragment(struct libalias *la, void *ptr) { struct alias_link *lnk; void *fptr; struct ip *pip; LIBALIAS_LOCK(la); pip = (struct ip *)ptr; lnk = FindFragmentPtr(la, pip->ip_src, pip->ip_id); if (lnk != NULL) { GetFragmentPtr(lnk, &fptr); SetFragmentPtr(lnk, NULL); SetExpire(lnk, 0); /* Deletes link */ } else fptr = NULL; LIBALIAS_UNLOCK(la); return (fptr); } void LibAliasFragmentIn(struct libalias *la, void *ptr, /* Points to correctly de-aliased header fragment */ void *ptr_fragment /* fragment which must be de-aliased */ ) { struct ip *pip; struct ip *fpip; LIBALIAS_LOCK(la); (void)la; pip = (struct ip *)ptr; fpip = (struct ip *)ptr_fragment; DifferentialChecksum(&fpip->ip_sum, &pip->ip_dst, &fpip->ip_dst, 2); fpip->ip_dst = pip->ip_dst; LIBALIAS_UNLOCK(la); } /* Local prototypes */ static int LibAliasOutLocked(struct libalias *la, struct ip *pip, int maxpacketsize, int create); static int LibAliasInLocked(struct libalias *la, struct ip *pip, int maxpacketsize); int LibAliasIn(struct libalias *la, void *ptr, int maxpacketsize) { int res; LIBALIAS_LOCK(la); res = LibAliasInLocked(la, (struct ip *)ptr, maxpacketsize); LIBALIAS_UNLOCK(la); return (res); } static int LibAliasInLocked(struct libalias *la, struct ip *pip, int maxpacketsize) { struct in_addr alias_addr; int iresult; if (la->packetAliasMode & PKT_ALIAS_REVERSE) { la->packetAliasMode &= ~PKT_ALIAS_REVERSE; iresult = LibAliasOutLocked(la, pip, maxpacketsize, 1); la->packetAliasMode |= PKT_ALIAS_REVERSE; goto getout; } HouseKeeping(la); - ClearCheckNewLink(la); alias_addr = pip->ip_dst; /* Defense against mangled packets */ if (ntohs(pip->ip_len) > maxpacketsize || (pip->ip_hl << 2) > maxpacketsize) { iresult = PKT_ALIAS_IGNORED; goto getout; } iresult = PKT_ALIAS_IGNORED; if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0) { switch (pip->ip_p) { case IPPROTO_ICMP: iresult = IcmpAliasIn(la, pip); break; case IPPROTO_UDP: iresult = UdpAliasIn(la, pip); break; case IPPROTO_TCP: iresult = TcpAliasIn(la, pip); break; #ifdef _KERNEL case IPPROTO_SCTP: iresult = SctpAlias(la, pip, SN_TO_LOCAL); break; #endif case IPPROTO_GRE: { int error; struct alias_data ad = { .lnk = NULL, .oaddr = NULL, .aaddr = NULL, .aport = NULL, .sport = NULL, .dport = NULL, .maxpktsize = 0 }; /* Walk out chain. */ error = find_handler(IN, IP, la, pip, &ad); if (error == 0) iresult = PKT_ALIAS_OK; else iresult = ProtoAliasIn(la, pip->ip_src, pip, pip->ip_p, &pip->ip_sum); break; } default: iresult = ProtoAliasIn(la, pip->ip_src, pip, pip->ip_p, &pip->ip_sum); break; } if (ntohs(pip->ip_off) & IP_MF) { struct alias_link *lnk; lnk = FindFragmentIn1(la, pip->ip_src, alias_addr, pip->ip_id); if (lnk != NULL) { iresult = PKT_ALIAS_FOUND_HEADER_FRAGMENT; SetFragmentAddr(lnk, pip->ip_dst); } else { iresult = PKT_ALIAS_ERROR; } } } else { iresult = FragmentIn(la, pip->ip_src, pip, pip->ip_id, &pip->ip_sum); } getout: return (iresult); } /* Unregistered address ranges */ /* 10.0.0.0 -> 10.255.255.255 */ #define UNREG_ADDR_A_LOWER 0x0a000000 #define UNREG_ADDR_A_UPPER 0x0affffff /* 172.16.0.0 -> 172.31.255.255 */ #define UNREG_ADDR_B_LOWER 0xac100000 #define UNREG_ADDR_B_UPPER 0xac1fffff /* 192.168.0.0 -> 192.168.255.255 */ #define UNREG_ADDR_C_LOWER 0xc0a80000 #define UNREG_ADDR_C_UPPER 0xc0a8ffff /* 100.64.0.0 -> 100.127.255.255 (RFC 6598 - Carrier Grade NAT) */ #define UNREG_ADDR_CGN_LOWER 0x64400000 #define UNREG_ADDR_CGN_UPPER 0x647fffff int LibAliasOut(struct libalias *la, void *ptr, int maxpacketsize) { int res; LIBALIAS_LOCK(la); res = LibAliasOutLocked(la, (struct ip *)ptr, maxpacketsize, 1); LIBALIAS_UNLOCK(la); return (res); } int LibAliasOutTry(struct libalias *la, void *ptr, int maxpacketsize, int create) { int res; LIBALIAS_LOCK(la); res = LibAliasOutLocked(la, (struct ip *)ptr, maxpacketsize, create); LIBALIAS_UNLOCK(la); return (res); } static int LibAliasOutLocked(struct libalias *la, struct ip *pip, /* valid IP packet */ int maxpacketsize, /* How much the packet data may grow (FTP and IRC inline changes) */ int create /* Create new entries ? */ ) { int iresult; struct in_addr addr_save; if (la->packetAliasMode & PKT_ALIAS_REVERSE) { la->packetAliasMode &= ~PKT_ALIAS_REVERSE; iresult = LibAliasInLocked(la, pip, maxpacketsize); la->packetAliasMode |= PKT_ALIAS_REVERSE; goto getout; } HouseKeeping(la); - ClearCheckNewLink(la); /* Defense against mangled packets */ if (ntohs(pip->ip_len) > maxpacketsize || (pip->ip_hl << 2) > maxpacketsize) { iresult = PKT_ALIAS_IGNORED; goto getout; } addr_save = GetDefaultAliasAddress(la); if (la->packetAliasMode & PKT_ALIAS_UNREGISTERED_ONLY || la->packetAliasMode & PKT_ALIAS_UNREGISTERED_CGN) { u_long addr; int iclass; iclass = 0; addr = ntohl(pip->ip_src.s_addr); if (addr >= UNREG_ADDR_C_LOWER && addr <= UNREG_ADDR_C_UPPER) iclass = 3; else if (addr >= UNREG_ADDR_B_LOWER && addr <= UNREG_ADDR_B_UPPER) iclass = 2; else if (addr >= UNREG_ADDR_A_LOWER && addr <= UNREG_ADDR_A_UPPER) iclass = 1; else if (addr >= UNREG_ADDR_CGN_LOWER && addr <= UNREG_ADDR_CGN_UPPER && la->packetAliasMode & PKT_ALIAS_UNREGISTERED_CGN) iclass = 4; if (iclass == 0) { SetDefaultAliasAddress(la, pip->ip_src); } } else if (la->packetAliasMode & PKT_ALIAS_PROXY_ONLY) { SetDefaultAliasAddress(la, pip->ip_src); } iresult = PKT_ALIAS_IGNORED; if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0) { switch (pip->ip_p) { case IPPROTO_ICMP: iresult = IcmpAliasOut(la, pip, create); break; case IPPROTO_UDP: iresult = UdpAliasOut(la, pip, maxpacketsize, create); break; case IPPROTO_TCP: iresult = TcpAliasOut(la, pip, maxpacketsize, create); break; #ifdef _KERNEL case IPPROTO_SCTP: iresult = SctpAlias(la, pip, SN_TO_GLOBAL); break; #endif case IPPROTO_GRE: { int error; struct alias_data ad = { .lnk = NULL, .oaddr = NULL, .aaddr = NULL, .aport = NULL, .sport = NULL, .dport = NULL, .maxpktsize = 0 }; /* Walk out chain. */ error = find_handler(OUT, IP, la, pip, &ad); if (error == 0) iresult = PKT_ALIAS_OK; else iresult = ProtoAliasOut(la, pip, pip->ip_dst, pip->ip_p, &pip->ip_sum, create); break; } default: iresult = ProtoAliasOut(la, pip, pip->ip_dst, pip->ip_p, &pip->ip_sum, create); break; } } else { iresult = FragmentOut(la, pip, &pip->ip_sum); } SetDefaultAliasAddress(la, addr_save); getout: return (iresult); } int LibAliasUnaliasOut(struct libalias *la, void *ptr, /* valid IP packet */ int maxpacketsize /* for error checking */ ) { struct ip *pip; struct icmp *ic; struct udphdr *ud; struct tcphdr *tc; struct alias_link *lnk; int iresult = PKT_ALIAS_IGNORED; LIBALIAS_LOCK(la); pip = (struct ip *)ptr; /* Defense against mangled packets */ if (ntohs(pip->ip_len) > maxpacketsize || (pip->ip_hl << 2) > maxpacketsize) goto getout; ud = (struct udphdr *)ip_next(pip); tc = (struct tcphdr *)ip_next(pip); ic = (struct icmp *)ip_next(pip); /* Find a link */ if (pip->ip_p == IPPROTO_UDP) lnk = FindUdpTcpIn(la, pip->ip_dst, pip->ip_src, ud->uh_dport, ud->uh_sport, IPPROTO_UDP, 0); else if (pip->ip_p == IPPROTO_TCP) lnk = FindUdpTcpIn(la, pip->ip_dst, pip->ip_src, tc->th_dport, tc->th_sport, IPPROTO_TCP, 0); else if (pip->ip_p == IPPROTO_ICMP) lnk = FindIcmpIn(la, pip->ip_dst, pip->ip_src, ic->icmp_id, 0); else lnk = NULL; /* Change it from an aliased packet to an unaliased packet */ if (lnk != NULL) { if (pip->ip_p == IPPROTO_UDP || pip->ip_p == IPPROTO_TCP) { int accumulate; struct in_addr original_address; u_short original_port; original_address = GetOriginalAddress(lnk); original_port = GetOriginalPort(lnk); /* Adjust TCP/UDP checksum */ accumulate = twowords(&pip->ip_src); accumulate -= twowords(&original_address); if (pip->ip_p == IPPROTO_UDP) { accumulate += ud->uh_sport; accumulate -= original_port; ADJUST_CHECKSUM(accumulate, ud->uh_sum); } else { accumulate += tc->th_sport; accumulate -= original_port; ADJUST_CHECKSUM(accumulate, tc->th_sum); } /* Adjust IP checksum */ DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_src, 2); /* Un-alias source address and port number */ pip->ip_src = original_address; if (pip->ip_p == IPPROTO_UDP) ud->uh_sport = original_port; else tc->th_sport = original_port; iresult = PKT_ALIAS_OK; } else if (pip->ip_p == IPPROTO_ICMP) { int accumulate; struct in_addr original_address; u_short original_id; original_address = GetOriginalAddress(lnk); original_id = GetOriginalPort(lnk); /* Adjust ICMP checksum */ accumulate = twowords(&pip->ip_src); accumulate -= twowords(&original_address); accumulate += ic->icmp_id; accumulate -= original_id; ADJUST_CHECKSUM(accumulate, ic->icmp_cksum); /* Adjust IP checksum */ DifferentialChecksum(&pip->ip_sum, &original_address, &pip->ip_src, 2); /* Un-alias source address and port number */ pip->ip_src = original_address; ic->icmp_id = original_id; iresult = PKT_ALIAS_OK; } } getout: LIBALIAS_UNLOCK(la); return (iresult); } #ifndef _KERNEL int LibAliasRefreshModules(void) { char buf[256], conf[] = "/etc/libalias.conf"; FILE *fd; int i, len; fd = fopen(conf, "r"); if (fd == NULL) err(1, "fopen(%s)", conf); LibAliasUnLoadAllModule(); for (;;) { fgets(buf, 256, fd); if (feof(fd)) break; len = strlen(buf); if (len > 1) { for (i = 0; i < len; i++) if (!isspace(buf[i])) break; if (buf[i] == '#') continue; buf[len - 1] = '\0'; LibAliasLoadModule(buf); } } fclose(fd); return (0); } int LibAliasLoadModule(char *path) { struct dll *t; void *handle; struct proto_handler *m; const char *error; moduledata_t *p; handle = dlopen (path, RTLD_LAZY); if (!handle) { fprintf(stderr, "%s\n", dlerror()); return (EINVAL); } p = dlsym(handle, "alias_mod"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", dlerror()); return (EINVAL); } t = malloc(sizeof(struct dll)); if (t == NULL) return (ENOMEM); strncpy(t->name, p->name, DLL_LEN); t->handle = handle; if (attach_dll(t) == EEXIST) { free(t); fprintf(stderr, "dll conflict\n"); return (EEXIST); } m = dlsym(t->handle, "handlers"); if ((error = dlerror()) != NULL) { fprintf(stderr, "%s\n", error); return (EINVAL); } LibAliasAttachHandlers(m); return (0); } int LibAliasUnLoadAllModule(void) { struct dll *t; struct proto_handler *p; /* Unload all modules then reload everything. */ while ((p = first_handler()) != NULL) { LibAliasDetachHandlers(p); } while ((t = walk_dll_chain()) != NULL) { dlclose(t->handle); free(t); } return (1); } #endif #ifdef _KERNEL /* * m_megapullup() - this function is a big hack. * Thankfully, it's only used in ng_nat and ipfw+nat. * * It allocates an mbuf with cluster and copies the specified part of the chain * into cluster, so that it is all contiguous and can be accessed via a plain * (char *) pointer. This is required, because libalias doesn't know how to * handle mbuf chains. * * On success, m_megapullup returns an mbuf (possibly with cluster) containing * the input packet, on failure NULL. The input packet is always consumed. */ struct mbuf * m_megapullup(struct mbuf *m, int len) { struct mbuf *mcl; if (len > m->m_pkthdr.len) goto bad; if (m->m_next == NULL && M_WRITABLE(m)) return (m); if (len <= MJUMPAGESIZE) mcl = m_get2(len, M_NOWAIT, MT_DATA, M_PKTHDR); else if (len <= MJUM9BYTES) mcl = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUM9BYTES); else if (len <= MJUM16BYTES) mcl = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUM16BYTES); else goto bad; if (mcl == NULL) goto bad; m_align(mcl, len); m_move_pkthdr(mcl, m); m_copydata(m, 0, len, mtod(mcl, caddr_t)); mcl->m_len = mcl->m_pkthdr.len = len; m_freem(m); return (mcl); bad: m_freem(m); return (NULL); } #endif diff --git a/sys/netinet/libalias/alias.h b/sys/netinet/libalias/alias.h index 36f1ca168823..558a750b4fd8 100644 --- a/sys/netinet/libalias/alias.h +++ b/sys/netinet/libalias/alias.h @@ -1,242 +1,244 @@ /* lint -save -library Flexelint comment for external headers */ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 Charles Mott * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /* * Alias.h defines the outside world interfaces for the packet aliasing * software. * * This software is placed into the public domain with no restrictions on its * distribution. */ #ifndef _ALIAS_H_ #define _ALIAS_H_ #include #include #include #define LIBALIAS_BUF_SIZE 128 #ifdef _KERNEL /* * The kernel version of libalias does not support these features. */ #define NO_FW_PUNCH #define NO_USE_SOCKETS #endif /* * The external interface to libalias, the packet aliasing engine. * * There are two sets of functions: * * PacketAlias*() the old API which doesn't take an instance pointer * and therefore can only have one packet engine at a time. * * LibAlias*() the new API which takes as first argument a pointer to * the instance of the packet aliasing engine. * * The functions otherwise correspond to each other one for one, except * for the LibAliasUnaliasOut()/PacketUnaliasOut() function which were * were misnamed in the old API. */ /* * The instance structure */ struct libalias; /* * An anonymous structure, a pointer to which is returned from * PacketAliasRedirectAddr(), PacketAliasRedirectPort() or * PacketAliasRedirectProto(), passed to PacketAliasAddServer(), * and freed by PacketAliasRedirectDelete(). */ struct alias_link; /* Initialization and control functions. */ struct libalias *LibAliasInit(struct libalias *); void LibAliasSetAddress(struct libalias *, struct in_addr _addr); void LibAliasSetAliasPortRange(struct libalias *la, u_short port_low, u_short port_hi); void LibAliasSetFWBase(struct libalias *, unsigned int _base, unsigned int _num); void LibAliasSetSkinnyPort(struct libalias *, unsigned int _port); unsigned int LibAliasSetMode(struct libalias *, unsigned int _flags, unsigned int _mask); void LibAliasUninit(struct libalias *); /* Packet Handling functions. */ int LibAliasIn (struct libalias *, void *_ptr, int _maxpacketsize); int LibAliasOut(struct libalias *, void *_ptr, int _maxpacketsize); int LibAliasOutTry(struct libalias *, void *_ptr, int _maxpacketsize, int _create); int LibAliasUnaliasOut(struct libalias *, void *_ptr, int _maxpacketsize); /* Port and address redirection functions. */ int LibAliasAddServer(struct libalias *, struct alias_link *_lnk, struct in_addr _addr, unsigned short _port); struct alias_link * LibAliasRedirectAddr(struct libalias *, struct in_addr _src_addr, struct in_addr _alias_addr); int LibAliasRedirectDynamic(struct libalias *, struct alias_link *_lnk); void LibAliasRedirectDelete(struct libalias *, struct alias_link *_lnk); struct alias_link * LibAliasRedirectPort(struct libalias *, struct in_addr _src_addr, unsigned short _src_port, struct in_addr _dst_addr, unsigned short _dst_port, struct in_addr _alias_addr, unsigned short _alias_port, unsigned char _proto); struct alias_link * LibAliasRedirectProto(struct libalias *, struct in_addr _src_addr, struct in_addr _dst_addr, struct in_addr _alias_addr, unsigned char _proto); /* Fragment Handling functions. */ void LibAliasFragmentIn(struct libalias *, void *_ptr, void *_ptr_fragment); void *LibAliasGetFragment(struct libalias *, void *_ptr); int LibAliasSaveFragment(struct libalias *, void *_ptr); /* Miscellaneous functions. */ -int LibAliasCheckNewLink(struct libalias *); unsigned short LibAliasInternetChecksum(struct libalias *, unsigned short *_ptr, int _nbytes); void LibAliasSetTarget(struct libalias *, struct in_addr _target_addr); +/* never used and never worked, to be removed in FreeBSD 14 */ +int LibAliasCheckNewLink(struct libalias *); + /* Transparent proxying routines. */ int LibAliasProxyRule(struct libalias *, const char *_cmd); /* Module handling API */ int LibAliasLoadModule(char *); int LibAliasUnLoadAllModule(void); int LibAliasRefreshModules(void); /* Mbuf helper function. */ struct mbuf *m_megapullup(struct mbuf *, int); /* * Mode flags and other constants. */ /* Mode flags, set using PacketAliasSetMode() */ /* * If PKT_ALIAS_LOG is set, a message will be printed to /var/log/alias.log * every time a link is created or deleted. This is useful for debugging. */ #define PKT_ALIAS_LOG 0x01 /* * If PKT_ALIAS_DENY_INCOMING is set, then incoming connections (e.g. to ftp, * telnet or web servers will be prevented by the aliasing mechanism. */ #define PKT_ALIAS_DENY_INCOMING 0x02 /* * If PKT_ALIAS_SAME_PORTS is set, packets will be attempted sent from the * same port as they originated on. This allows e.g. rsh to work *99% of the * time*, but _not_ 100% (it will be slightly flakey instead of not working * at all). This mode bit is set by PacketAliasInit(), so it is a default * mode of operation. */ #define PKT_ALIAS_SAME_PORTS 0x04 /* * If PKT_ALIAS_USE_SOCKETS is set, then when partially specified links (e.g. * destination port and/or address is zero), the packet aliasing engine will * attempt to allocate a socket for the aliasing port it chooses. This will * avoid interference with the host machine. Fully specified links do not * require this. This bit is set after a call to PacketAliasInit(), so it is * a default mode of operation. */ #ifndef NO_USE_SOCKETS #define PKT_ALIAS_USE_SOCKETS 0x08 #endif /*- * If PKT_ALIAS_UNREGISTERED_ONLY is set, then only packets with * unregistered source addresses will be aliased. Private * addresses are those in the following ranges: * * 10.0.0.0 -> 10.255.255.255 * 172.16.0.0 -> 172.31.255.255 * 192.168.0.0 -> 192.168.255.255 */ #define PKT_ALIAS_UNREGISTERED_ONLY 0x10 /* * If PKT_ALIAS_RESET_ON_ADDR_CHANGE is set, then the table of dynamic * aliasing links will be reset whenever PacketAliasSetAddress() changes the * default aliasing address. If the default aliasing address is left * unchanged by this function call, then the table of dynamic aliasing links * will be left intact. This bit is set after a call to PacketAliasInit(). */ #define PKT_ALIAS_RESET_ON_ADDR_CHANGE 0x20 /* * If PKT_ALIAS_PROXY_ONLY is set, then NAT will be disabled and only * transparent proxying is performed. */ #define PKT_ALIAS_PROXY_ONLY 0x40 /* * If PKT_ALIAS_REVERSE is set, the actions of PacketAliasIn() and * PacketAliasOut() are reversed. */ #define PKT_ALIAS_REVERSE 0x80 #ifndef NO_FW_PUNCH /* * If PKT_ALIAS_PUNCH_FW is set, active FTP and IRC DCC connections will * create a 'hole' in the firewall to allow the transfers to work. The * ipfw rule number that the hole is created with is controlled by * PacketAliasSetFWBase(). The hole will be attached to that * particular alias_link, so when the link goes away the hole is deleted. */ #define PKT_ALIAS_PUNCH_FW 0x100 #endif /* * If PKT_ALIAS_SKIP_GLOBAL is set, nat instance is not checked for matching * states in 'ipfw nat global' rule. */ #define PKT_ALIAS_SKIP_GLOBAL 0x200 /* * Like PKT_ALIAS_UNREGISTERED_ONLY, but includes the RFC 6598 * (Carrier Grade NAT) address range as follows: * * 100.64.0.0 -> 100.127.255.255 */ #define PKT_ALIAS_UNREGISTERED_CGN 0x400 /* Function return codes. */ #define PKT_ALIAS_ERROR -1 #define PKT_ALIAS_OK 1 #define PKT_ALIAS_IGNORED 2 #define PKT_ALIAS_UNRESOLVED_FRAGMENT 3 #define PKT_ALIAS_FOUND_HEADER_FRAGMENT 4 #endif /* !_ALIAS_H_ */ /* lint -restore */ diff --git a/sys/netinet/libalias/alias_db.c b/sys/netinet/libalias/alias_db.c index 7a84cf310d5a..0273cc84773d 100644 --- a/sys/netinet/libalias/alias_db.c +++ b/sys/netinet/libalias/alias_db.c @@ -1,2853 +1,2842 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 Charles Mott * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* Alias_db.c encapsulates all data structures used for storing packet aliasing data. Other parts of the aliasing software access data through functions provided in this file. Data storage is based on the notion of a "link", which is established for ICMP echo/reply packets, UDP datagrams and TCP stream connections. A link stores the original source and destination addresses. For UDP and TCP, it also stores source and destination port numbers, as well as an alias port number. Links are also used to store information about fragments. There is a facility for sweeping through and deleting old links as new packets are sent through. A simple timeout is used for ICMP and UDP links. TCP links are left alone unless there is an incomplete connection, in which case the link can be deleted after a certain amount of time. Initial version: August, 1996 (cjm) Version 1.4: September 16, 1996 (cjm) Facility for handling incoming links added. Version 1.6: September 18, 1996 (cjm) ICMP data handling simplified. Version 1.7: January 9, 1997 (cjm) Fragment handling simplified. Saves pointers for unresolved fragments. Permits links for unspecified remote ports or unspecified remote addresses. Fixed bug which did not properly zero port table entries after a link was deleted. Cleaned up some obsolete comments. Version 1.8: January 14, 1997 (cjm) Fixed data type error in StartPoint(). (This error did not exist prior to v1.7 and was discovered and fixed by Ari Suutari) Version 1.9: February 1, 1997 Optionally, connections initiated from packet aliasing host machine will will not have their port number aliased unless it conflicts with an aliasing port already being used. (cjm) All options earlier being #ifdef'ed are now available through a new interface, SetPacketAliasMode(). This allows run time control (which is now available in PPP+pktAlias through the 'alias' keyword). (ee) Added ability to create an alias port without either destination address or port specified. port type = ALIAS_PORT_UNKNOWN_DEST_ALL (ee) Removed K&R style function headers and general cleanup. (ee) Added packetAliasMode to replace compiler #defines's (ee) Allocates sockets for partially specified ports if ALIAS_USE_SOCKETS defined. (cjm) Version 2.0: March, 1997 SetAliasAddress() will now clean up alias links if the aliasing address is changed. (cjm) PacketAliasPermanentLink() function added to support permanent links. (J. Fortes suggested the need for this.) Examples: (192.168.0.1, port 23) <-> alias port 6002, unknown dest addr/port (192.168.0.2, port 21) <-> alias port 3604, known dest addr unknown dest port These permanent links allow for incoming connections to machines on the local network. They can be given with a user-chosen amount of specificity, with increasing specificity meaning more security. (cjm) Quite a bit of rework to the basic engine. The portTable[] array, which kept track of which ports were in use was replaced by a table/linked list structure. (cjm) SetExpire() function added. (cjm) DeleteLink() no longer frees memory association with a pointer to a fragment (this bug was first recognized by E. Eklund in v1.9). Version 2.1: May, 1997 (cjm) Packet aliasing engine reworked so that it can handle multiple external addresses rather than just a single host address. PacketAliasRedirectPort() and PacketAliasRedirectAddr() added to the API. The first function is a more generalized version of PacketAliasPermanentLink(). The second function implements static network address translation. Version 3.2: July, 2000 (salander and satoh) Added FindNewPortGroup to get contiguous range of port values. Added QueryUdpTcpIn and QueryUdpTcpOut to look for an aliasing link but not actually add one. Added FindRtspOut, which is closely derived from FindUdpTcpOut, except that the alias port (from FindNewPortGroup) is provided as input. See HISTORY file for additional revisions. */ #ifdef _KERNEL #include #include #include #include #include #include #include #include #else #include #include #include #include #include #include #endif #include #include #ifdef _KERNEL #include #include #include #include #else #include "alias.h" #include "alias_local.h" #include "alias_mod.h" #endif static LIST_HEAD(, libalias) instancehead = LIST_HEAD_INITIALIZER(instancehead); /* Constants (note: constants are also defined near relevant functions or structs) */ /* Parameters used for cleanup of expired links */ /* NOTE: ALIAS_CLEANUP_INTERVAL_SECS must be less then LINK_TABLE_OUT_SIZE */ #define ALIAS_CLEANUP_INTERVAL_SECS 64 #define ALIAS_CLEANUP_MAX_SPOKES (LINK_TABLE_OUT_SIZE/5) /* Timeouts (in seconds) for different link types */ #define ICMP_EXPIRE_TIME 60 #define UDP_EXPIRE_TIME 60 #define PROTO_EXPIRE_TIME 60 #define FRAGMENT_ID_EXPIRE_TIME 10 #define FRAGMENT_PTR_EXPIRE_TIME 30 /* TCP link expire time for different cases */ /* When the link has been used and closed - minimal grace time to allow ACKs and potential re-connect in FTP (XXX - is this allowed?) */ #ifndef TCP_EXPIRE_DEAD #define TCP_EXPIRE_DEAD 10 #endif /* When the link has been used and closed on one side - the other side is allowed to still send data */ #ifndef TCP_EXPIRE_SINGLEDEAD #define TCP_EXPIRE_SINGLEDEAD 90 #endif /* When the link isn't yet up */ #ifndef TCP_EXPIRE_INITIAL #define TCP_EXPIRE_INITIAL 300 #endif /* When the link is up */ #ifndef TCP_EXPIRE_CONNECTED #define TCP_EXPIRE_CONNECTED 86400 #endif /* Dummy port number codes used for FindLinkIn/Out() and AddLink(). These constants can be anything except zero, which indicates an unknown port number. */ #define NO_DEST_PORT 1 #define NO_SRC_PORT 1 /* Matches any/unknown address in FindLinkIn/Out() and AddLink(). */ static struct in_addr const ANY_ADDR = { INADDR_ANY }; /* Data Structures The fundamental data structure used in this program is "struct alias_link". Whenever a TCP connection is made, a UDP datagram is sent out, or an ICMP echo request is made, a link record is made (if it has not already been created). The link record is identified by the source address/port and the destination address/port. In the case of an ICMP echo request, the source port is treated as being equivalent with the 16-bit ID number of the ICMP packet. The link record also can store some auxiliary data. For TCP connections that have had sequence and acknowledgment modifications, data space is available to track these changes. A state field is used to keep track in changes to the TCP connection state. ID numbers of fragments can also be stored in the auxiliary space. Pointers to unresolved fragments can also be stored. The link records support two independent chainings. Lookup tables for input and out tables hold the initial pointers the link chains. On input, the lookup table indexes on alias port and link type. On output, the lookup table indexes on source address, destination address, source port, destination port and link type. */ /* used to save changes to ACK/sequence numbers */ struct ack_data_record { u_long ack_old; u_long ack_new; int delta; int active; }; /* Information about TCP connection */ struct tcp_state { int in; /* State for outside -> inside */ int out; /* State for inside -> outside */ int index; /* Index to ACK data array */ /* Indicates whether ACK and sequence numbers been modified */ int ack_modified; }; /* Number of distinct ACK number changes * saved for a modified TCP stream */ #define N_LINK_TCP_DATA 3 struct tcp_dat { struct tcp_state state; struct ack_data_record ack[N_LINK_TCP_DATA]; /* Which firewall record is used for this hole? */ int fwhole; }; /* LSNAT server pool (circular list) */ struct server { struct in_addr addr; u_short port; struct server *next; }; /* Main data structure */ struct alias_link { struct libalias *la; /* Address and port information */ struct in_addr src_addr; struct in_addr dst_addr; struct in_addr alias_addr; struct in_addr proxy_addr; u_short src_port; u_short dst_port; u_short alias_port; u_short proxy_port; struct server *server; /* Type of link: TCP, UDP, ICMP, proto, frag */ int link_type; /* values for link_type */ #define LINK_ICMP IPPROTO_ICMP #define LINK_UDP IPPROTO_UDP #define LINK_TCP IPPROTO_TCP #define LINK_FRAGMENT_ID (IPPROTO_MAX + 1) #define LINK_FRAGMENT_PTR (IPPROTO_MAX + 2) #define LINK_ADDR (IPPROTO_MAX + 3) #define LINK_PPTP (IPPROTO_MAX + 4) int flags; /* indicates special characteristics */ int pflags; /* protocol-specific flags */ /* flag bits */ #define LINK_UNKNOWN_DEST_PORT 0x01 #define LINK_UNKNOWN_DEST_ADDR 0x02 #define LINK_PERMANENT 0x04 #define LINK_PARTIALLY_SPECIFIED 0x03 /* logical-or of first two bits */ #define LINK_UNFIREWALLED 0x08 int timestamp; /* Time link was last accessed */ int expire_time; /* Expire time for link */ #ifndef NO_USE_SOCKETS int sockfd; /* socket descriptor */ #endif /* Linked list of pointers for input and output lookup tables */ LIST_ENTRY (alias_link) list_out; LIST_ENTRY (alias_link) list_in; /* Auxiliary data */ union { char *frag_ptr; struct in_addr frag_addr; struct tcp_dat *tcp; } data; }; /* Clean up procedure. */ static void finishoff(void); /* Kernel module definition. */ #ifdef _KERNEL MALLOC_DEFINE(M_ALIAS, "libalias", "packet aliasing"); MODULE_VERSION(libalias, 1); static int alias_mod_handler(module_t mod, int type, void *data) { switch (type) { case MOD_QUIESCE: case MOD_UNLOAD: finishoff(); case MOD_LOAD: return (0); default: return (EINVAL); } } static moduledata_t alias_mod = { "alias", alias_mod_handler, NULL }; DECLARE_MODULE(alias, alias_mod, SI_SUB_DRIVERS, SI_ORDER_SECOND); #endif /* Internal utility routines (used only in alias_db.c) Lookup table starting points: StartPointIn() -- link table initial search point for incoming packets StartPointOut() -- link table initial search point for outgoing packets Miscellaneous: SeqDiff() -- difference between two TCP sequences ShowAliasStats() -- send alias statistics to a monitor file */ /* Local prototypes */ static u_int StartPointIn(struct in_addr, u_short, int); static u_int StartPointOut(struct in_addr, struct in_addr, u_short, u_short, int); static int SeqDiff(u_long, u_long); #ifndef NO_FW_PUNCH /* Firewall control */ static void InitPunchFW(struct libalias *); static void UninitPunchFW(struct libalias *); static void ClearFWHole(struct alias_link *); #endif /* Log file control */ static void ShowAliasStats(struct libalias *); static int InitPacketAliasLog(struct libalias *); static void UninitPacketAliasLog(struct libalias *); void SctpShowAliasStats(struct libalias *la); static u_int StartPointIn(struct in_addr alias_addr, u_short alias_port, int link_type) { u_int n; n = alias_addr.s_addr; if (link_type != LINK_PPTP) n += alias_port; n += link_type; return (n % LINK_TABLE_IN_SIZE); } static u_int StartPointOut(struct in_addr src_addr, struct in_addr dst_addr, u_short src_port, u_short dst_port, int link_type) { u_int n; n = src_addr.s_addr; n += dst_addr.s_addr; if (link_type != LINK_PPTP) { n += src_port; n += dst_port; } n += link_type; return (n % LINK_TABLE_OUT_SIZE); } static int SeqDiff(u_long x, u_long y) { /* Return the difference between two TCP sequence numbers * This function is encapsulated in case there are any unusual * arithmetic conditions that need to be considered. */ return (ntohl(y) - ntohl(x)); } #ifdef _KERNEL static void AliasLog(char *str, const char *format, ...) { va_list ap; va_start(ap, format); vsnprintf(str, LIBALIAS_BUF_SIZE, format, ap); va_end(ap); } #else static void AliasLog(FILE *stream, const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(stream, format, ap); va_end(ap); fflush(stream); } #endif static void ShowAliasStats(struct libalias *la) { LIBALIAS_LOCK_ASSERT(la); /* Used for debugging */ if (la->logDesc) { int tot = la->icmpLinkCount + la->udpLinkCount + (la->sctpLinkCount>>1) + /* sctp counts half associations */ la->tcpLinkCount + la->pptpLinkCount + la->protoLinkCount + la->fragmentIdLinkCount + la->fragmentPtrLinkCount; AliasLog(la->logDesc, "icmp=%u, udp=%u, tcp=%u, sctp=%u, pptp=%u, proto=%u, frag_id=%u frag_ptr=%u / tot=%u", la->icmpLinkCount, la->udpLinkCount, la->tcpLinkCount, la->sctpLinkCount>>1, /* sctp counts half associations */ la->pptpLinkCount, la->protoLinkCount, la->fragmentIdLinkCount, la->fragmentPtrLinkCount, tot); #ifndef _KERNEL AliasLog(la->logDesc, " (sock=%u)\n", la->sockCount); #endif } } void SctpShowAliasStats(struct libalias *la) { ShowAliasStats(la); } /* Internal routines for finding, deleting and adding links Port Allocation: GetNewPort() -- find and reserve new alias port number GetSocket() -- try to allocate a socket for a given port Link creation and deletion: CleanupAliasData() - remove all link chains from lookup table IncrementalCleanup() - look for stale links in a single chain DeleteLink() - remove link AddLink() - add link ReLink() - change link Link search: FindLinkOut() - find link for outgoing packets FindLinkIn() - find link for incoming packets Port search: FindNewPortGroup() - find an available group of ports */ /* Local prototypes */ static int GetNewPort(struct libalias *, struct alias_link *, int); #ifndef NO_USE_SOCKETS static u_short GetSocket(struct libalias *, u_short, int *, int); #endif static void CleanupAliasData(struct libalias *); static void IncrementalCleanup(struct libalias *); static void DeleteLink(struct alias_link *); static struct alias_link * ReLink(struct alias_link *, struct in_addr, struct in_addr, struct in_addr, u_short, u_short, int, int); static struct alias_link * FindLinkOut(struct libalias *, struct in_addr, struct in_addr, u_short, u_short, int, int); static struct alias_link * FindLinkIn(struct libalias *, struct in_addr, struct in_addr, u_short, u_short, int, int); #define ALIAS_PORT_BASE 0x08000 #define ALIAS_PORT_MASK 0x07fff #define ALIAS_PORT_MASK_EVEN 0x07ffe #define GET_NEW_PORT_MAX_ATTEMPTS 20 #define FIND_EVEN_ALIAS_BASE 1 /* GetNewPort() allocates port numbers. Note that if a port number is already in use, that does not mean that it cannot be used by another link concurrently. This is because GetNewPort() looks for unused triplets: (dest addr, dest port, alias port). */ static int GetNewPort(struct libalias *la, struct alias_link *lnk, int alias_port_param) { int i; int max_trials; u_short port_sys; u_short port_net; LIBALIAS_LOCK_ASSERT(la); /* * Description of alias_port_param for GetNewPort(). When * this parameter is zero or positive, it precisely specifies * the port number. GetNewPort() will return this number * without check that it is in use. * When this parameter is GET_ALIAS_PORT, it indicates to get * a randomly selected port number. */ if (alias_port_param == GET_ALIAS_PORT) { /* * The aliasing port is automatically selected by one of * two methods below: */ max_trials = GET_NEW_PORT_MAX_ATTEMPTS; if (la->packetAliasMode & PKT_ALIAS_SAME_PORTS) { /* * When the PKT_ALIAS_SAME_PORTS option is chosen, * the first try will be the actual source port. If * this is already in use, the remainder of the * trials will be random. */ port_net = lnk->src_port; port_sys = ntohs(port_net); } else if (la->aliasPortLower) { /* First trial is a random port in the aliasing range. */ port_sys = la->aliasPortLower + (arc4random() % la->aliasPortLength); port_net = htons(port_sys); } else { /* First trial and all subsequent are random. */ port_sys = arc4random() & ALIAS_PORT_MASK; port_sys += ALIAS_PORT_BASE; port_net = htons(port_sys); } } else if (alias_port_param >= 0 && alias_port_param < 0x10000) { lnk->alias_port = (u_short) alias_port_param; return (0); } else { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/GetNewPort(): "); fprintf(stderr, "input parameter error\n"); #endif return (-1); } /* Port number search */ for (i = 0; i < max_trials; i++) { int go_ahead; struct alias_link *search_result; search_result = FindLinkIn(la, lnk->dst_addr, lnk->alias_addr, lnk->dst_port, port_net, lnk->link_type, 0); if (search_result == NULL) go_ahead = 1; else if (!(lnk->flags & LINK_PARTIALLY_SPECIFIED) && (search_result->flags & LINK_PARTIALLY_SPECIFIED)) go_ahead = 1; else go_ahead = 0; if (go_ahead) { #ifndef NO_USE_SOCKETS if ((la->packetAliasMode & PKT_ALIAS_USE_SOCKETS) && (lnk->flags & LINK_PARTIALLY_SPECIFIED) && ((lnk->link_type == LINK_TCP) || (lnk->link_type == LINK_UDP))) { if (GetSocket(la, port_net, &lnk->sockfd, lnk->link_type)) { lnk->alias_port = port_net; return (0); } } else { #endif lnk->alias_port = port_net; return (0); #ifndef NO_USE_SOCKETS } #endif } if (la->aliasPortLower) { port_sys = la->aliasPortLower + (arc4random() % la->aliasPortLength); port_net = htons(port_sys); } else { port_sys = arc4random() & ALIAS_PORT_MASK; port_sys += ALIAS_PORT_BASE; port_net = htons(port_sys); } } #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/GetNewPort(): "); fprintf(stderr, "could not find free port\n"); #endif return (-1); } #ifndef NO_USE_SOCKETS static u_short GetSocket(struct libalias *la, u_short port_net, int *sockfd, int link_type) { int err; int sock; struct sockaddr_in sock_addr; LIBALIAS_LOCK_ASSERT(la); if (link_type == LINK_TCP) sock = socket(AF_INET, SOCK_STREAM, 0); else if (link_type == LINK_UDP) sock = socket(AF_INET, SOCK_DGRAM, 0); else { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/GetSocket(): "); fprintf(stderr, "incorrect link type\n"); #endif return (0); } if (sock < 0) { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/GetSocket(): "); fprintf(stderr, "socket() error %d\n", *sockfd); #endif return (0); } sock_addr.sin_family = AF_INET; sock_addr.sin_addr.s_addr = htonl(INADDR_ANY); sock_addr.sin_port = port_net; err = bind(sock, (struct sockaddr *)&sock_addr, sizeof(sock_addr)); if (err == 0) { la->sockCount++; *sockfd = sock; return (1); } else { close(sock); return (0); } } #endif /* FindNewPortGroup() returns a base port number for an available range of contiguous port numbers. Note that if a port number is already in use, that does not mean that it cannot be used by another link concurrently. This is because FindNewPortGroup() looks for unused triplets: (dest addr, dest port, alias port). */ int FindNewPortGroup(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short src_port, u_short dst_port, u_short port_count, u_char proto, u_char align) { int i, j; int max_trials; u_short port_sys; int link_type; LIBALIAS_LOCK_ASSERT(la); /* * Get link_type from protocol */ switch (proto) { case IPPROTO_UDP: link_type = LINK_UDP; break; case IPPROTO_TCP: link_type = LINK_TCP; break; default: return (0); break; } /* * The aliasing port is automatically selected by one of two * methods below: */ max_trials = GET_NEW_PORT_MAX_ATTEMPTS; if (la->packetAliasMode & PKT_ALIAS_SAME_PORTS) { /* * When the ALIAS_SAME_PORTS option is chosen, the first * try will be the actual source port. If this is already * in use, the remainder of the trials will be random. */ port_sys = ntohs(src_port); } else { /* First trial and all subsequent are random. */ if (align == FIND_EVEN_ALIAS_BASE) port_sys = arc4random() & ALIAS_PORT_MASK_EVEN; else port_sys = arc4random() & ALIAS_PORT_MASK; port_sys += ALIAS_PORT_BASE; } /* Port number search */ for (i = 0; i < max_trials; i++) { struct alias_link *search_result; for (j = 0; j < port_count; j++) if ((search_result = FindLinkIn(la, dst_addr, alias_addr, dst_port, htons(port_sys + j), link_type, 0)) != NULL) break; /* Found a good range, return base */ if (j == port_count) return (htons(port_sys)); /* Find a new base to try */ if (align == FIND_EVEN_ALIAS_BASE) port_sys = arc4random() & ALIAS_PORT_MASK_EVEN; else port_sys = arc4random() & ALIAS_PORT_MASK; port_sys += ALIAS_PORT_BASE; } #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/FindNewPortGroup(): "); fprintf(stderr, "could not find free port(s)\n"); #endif return (0); } static void CleanupAliasData(struct libalias *la) { struct alias_link *lnk; int i; LIBALIAS_LOCK_ASSERT(la); for (i = 0; i < LINK_TABLE_OUT_SIZE; i++) { lnk = LIST_FIRST(&la->linkTableOut[i]); while (lnk != NULL) { struct alias_link *link_next = LIST_NEXT(lnk, list_out); DeleteLink(lnk); lnk = link_next; } } la->cleanupIndex = 0; } static void IncrementalCleanup(struct libalias *la) { struct alias_link *lnk, *lnk_tmp; LIBALIAS_LOCK_ASSERT(la); LIST_FOREACH_SAFE(lnk, &la->linkTableOut[la->cleanupIndex++], list_out, lnk_tmp) { if (la->timeStamp - lnk->timestamp > lnk->expire_time) DeleteLink(lnk); } if (la->cleanupIndex == LINK_TABLE_OUT_SIZE) la->cleanupIndex = 0; } static void DeleteLink(struct alias_link *lnk) { struct libalias *la = lnk->la; LIBALIAS_LOCK_ASSERT(la); /* Don't do anything if the link is marked permanent */ if (la->deleteAllLinks == 0 && lnk->flags & LINK_PERMANENT) return; #ifndef NO_FW_PUNCH /* Delete associated firewall hole, if any */ ClearFWHole(lnk); #endif /* Free memory allocated for LSNAT server pool */ if (lnk->server != NULL) { struct server *head, *curr, *next; head = curr = lnk->server; do { next = curr->next; free(curr); } while ((curr = next) != head); } /* Adjust output table pointers */ LIST_REMOVE(lnk, list_out); /* Adjust input table pointers */ LIST_REMOVE(lnk, list_in); #ifndef NO_USE_SOCKETS /* Close socket, if one has been allocated */ if (lnk->sockfd != -1) { la->sockCount--; close(lnk->sockfd); } #endif /* Link-type dependent cleanup */ switch (lnk->link_type) { case LINK_ICMP: la->icmpLinkCount--; break; case LINK_UDP: la->udpLinkCount--; break; case LINK_TCP: la->tcpLinkCount--; free(lnk->data.tcp); break; case LINK_PPTP: la->pptpLinkCount--; break; case LINK_FRAGMENT_ID: la->fragmentIdLinkCount--; break; case LINK_FRAGMENT_PTR: la->fragmentPtrLinkCount--; if (lnk->data.frag_ptr != NULL) free(lnk->data.frag_ptr); break; case LINK_ADDR: break; default: la->protoLinkCount--; break; } /* Free memory */ free(lnk); /* Write statistics, if logging enabled */ if (la->packetAliasMode & PKT_ALIAS_LOG) { ShowAliasStats(la); } } struct alias_link * AddLink(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, struct in_addr alias_addr, u_short src_port, u_short dst_port, int alias_port_param, int link_type) { u_int start_point; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = malloc(sizeof(struct alias_link)); if (lnk != NULL) { /* Basic initialization */ lnk->la = la; lnk->src_addr = src_addr; lnk->dst_addr = dst_addr; lnk->alias_addr = alias_addr; lnk->proxy_addr.s_addr = INADDR_ANY; lnk->src_port = src_port; lnk->dst_port = dst_port; lnk->proxy_port = 0; lnk->server = NULL; lnk->link_type = link_type; #ifndef NO_USE_SOCKETS lnk->sockfd = -1; #endif lnk->flags = 0; lnk->pflags = 0; lnk->timestamp = la->timeStamp; /* Expiration time */ switch (link_type) { case LINK_ICMP: lnk->expire_time = ICMP_EXPIRE_TIME; break; case LINK_UDP: lnk->expire_time = UDP_EXPIRE_TIME; break; case LINK_TCP: lnk->expire_time = TCP_EXPIRE_INITIAL; break; case LINK_PPTP: lnk->flags |= LINK_PERMANENT; /* no timeout. */ break; case LINK_FRAGMENT_ID: lnk->expire_time = FRAGMENT_ID_EXPIRE_TIME; break; case LINK_FRAGMENT_PTR: lnk->expire_time = FRAGMENT_PTR_EXPIRE_TIME; break; case LINK_ADDR: break; default: lnk->expire_time = PROTO_EXPIRE_TIME; break; } /* Determine alias flags */ if (dst_addr.s_addr == INADDR_ANY) lnk->flags |= LINK_UNKNOWN_DEST_ADDR; if (dst_port == 0) lnk->flags |= LINK_UNKNOWN_DEST_PORT; /* Determine alias port */ if (GetNewPort(la, lnk, alias_port_param) != 0) { free(lnk); return (NULL); } /* Link-type dependent initialization */ switch (link_type) { struct tcp_dat *aux_tcp; case LINK_ICMP: la->icmpLinkCount++; break; case LINK_UDP: la->udpLinkCount++; break; case LINK_TCP: aux_tcp = malloc(sizeof(struct tcp_dat)); if (aux_tcp != NULL) { int i; la->tcpLinkCount++; aux_tcp->state.in = ALIAS_TCP_STATE_NOT_CONNECTED; aux_tcp->state.out = ALIAS_TCP_STATE_NOT_CONNECTED; aux_tcp->state.index = 0; aux_tcp->state.ack_modified = 0; for (i = 0; i < N_LINK_TCP_DATA; i++) aux_tcp->ack[i].active = 0; aux_tcp->fwhole = -1; lnk->data.tcp = aux_tcp; } else { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/AddLink: "); fprintf(stderr, " cannot allocate auxiliary TCP data\n"); #endif free(lnk); return (NULL); } break; case LINK_PPTP: la->pptpLinkCount++; break; case LINK_FRAGMENT_ID: la->fragmentIdLinkCount++; break; case LINK_FRAGMENT_PTR: la->fragmentPtrLinkCount++; break; case LINK_ADDR: break; default: la->protoLinkCount++; break; } /* Set up pointers for output lookup table */ start_point = StartPointOut(src_addr, dst_addr, src_port, dst_port, link_type); LIST_INSERT_HEAD(&la->linkTableOut[start_point], lnk, list_out); /* Set up pointers for input lookup table */ start_point = StartPointIn(alias_addr, lnk->alias_port, link_type); LIST_INSERT_HEAD(&la->linkTableIn[start_point], lnk, list_in); } else { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/AddLink(): "); fprintf(stderr, "malloc() call failed.\n"); #endif } if (la->packetAliasMode & PKT_ALIAS_LOG) { ShowAliasStats(la); } return (lnk); } /* * If alias_port_param is less than zero, alias port will be automatically * chosen. If greater than zero, equal to alias port */ static struct alias_link * ReLink(struct alias_link *old_lnk, struct in_addr src_addr, struct in_addr dst_addr, struct in_addr alias_addr, u_short src_port, u_short dst_port, int alias_port_param, int link_type) { struct alias_link *new_lnk; struct libalias *la = old_lnk->la; LIBALIAS_LOCK_ASSERT(la); new_lnk = AddLink(la, src_addr, dst_addr, alias_addr, src_port, dst_port, alias_port_param, link_type); #ifndef NO_FW_PUNCH if (new_lnk != NULL && old_lnk->link_type == LINK_TCP && old_lnk->data.tcp->fwhole > 0) { PunchFWHole(new_lnk); } #endif DeleteLink(old_lnk); return (new_lnk); } static struct alias_link * _FindLinkOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_short src_port, u_short dst_port, int link_type, int replace_partial_links) { u_int i; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); i = StartPointOut(src_addr, dst_addr, src_port, dst_port, link_type); LIST_FOREACH(lnk, &la->linkTableOut[i], list_out) { if (lnk->dst_addr.s_addr == dst_addr.s_addr && lnk->src_addr.s_addr == src_addr.s_addr && lnk->src_port == src_port && lnk->dst_port == dst_port && lnk->link_type == link_type && lnk->server == NULL) { lnk->timestamp = la->timeStamp; break; } } /* Search for partially specified links. */ if (lnk == NULL && replace_partial_links) { if (dst_port != 0 && dst_addr.s_addr != INADDR_ANY) { lnk = _FindLinkOut(la, src_addr, dst_addr, src_port, 0, link_type, 0); if (lnk == NULL) lnk = _FindLinkOut(la, src_addr, ANY_ADDR, src_port, dst_port, link_type, 0); } if (lnk == NULL && (dst_port != 0 || dst_addr.s_addr != INADDR_ANY)) { lnk = _FindLinkOut(la, src_addr, ANY_ADDR, src_port, 0, link_type, 0); } if (lnk != NULL) { lnk = ReLink(lnk, src_addr, dst_addr, lnk->alias_addr, src_port, dst_port, lnk->alias_port, link_type); } } return (lnk); } static struct alias_link * FindLinkOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_short src_port, u_short dst_port, int link_type, int replace_partial_links) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = _FindLinkOut(la, src_addr, dst_addr, src_port, dst_port, link_type, replace_partial_links); if (lnk == NULL) { /* * The following allows permanent links to be specified as * using the default source address (i.e. device interface * address) without knowing in advance what that address * is. */ if (la->aliasAddress.s_addr != INADDR_ANY && src_addr.s_addr == la->aliasAddress.s_addr) { lnk = _FindLinkOut(la, ANY_ADDR, dst_addr, src_port, dst_port, link_type, replace_partial_links); } } return (lnk); } static struct alias_link * _FindLinkIn(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short dst_port, u_short alias_port, int link_type, int replace_partial_links) { int flags_in; u_int start_point; struct alias_link *lnk; struct alias_link *lnk_fully_specified; struct alias_link *lnk_unknown_all; struct alias_link *lnk_unknown_dst_addr; struct alias_link *lnk_unknown_dst_port; LIBALIAS_LOCK_ASSERT(la); /* Initialize pointers */ lnk_fully_specified = NULL; lnk_unknown_all = NULL; lnk_unknown_dst_addr = NULL; lnk_unknown_dst_port = NULL; /* If either the dest addr or port is unknown, the search * loop will have to know about this. */ flags_in = 0; if (dst_addr.s_addr == INADDR_ANY) flags_in |= LINK_UNKNOWN_DEST_ADDR; if (dst_port == 0) flags_in |= LINK_UNKNOWN_DEST_PORT; /* Search loop */ start_point = StartPointIn(alias_addr, alias_port, link_type); LIST_FOREACH(lnk, &la->linkTableIn[start_point], list_in) { int flags; flags = flags_in | lnk->flags; if (!(flags & LINK_PARTIALLY_SPECIFIED)) { if (lnk->alias_addr.s_addr == alias_addr.s_addr && lnk->alias_port == alias_port && lnk->dst_addr.s_addr == dst_addr.s_addr && lnk->dst_port == dst_port && lnk->link_type == link_type) { lnk_fully_specified = lnk; break; } } else if ((flags & LINK_UNKNOWN_DEST_ADDR) && (flags & LINK_UNKNOWN_DEST_PORT)) { if (lnk->alias_addr.s_addr == alias_addr.s_addr && lnk->alias_port == alias_port && lnk->link_type == link_type) { if (lnk_unknown_all == NULL) lnk_unknown_all = lnk; } } else if (flags & LINK_UNKNOWN_DEST_ADDR) { if (lnk->alias_addr.s_addr == alias_addr.s_addr && lnk->alias_port == alias_port && lnk->link_type == link_type && lnk->dst_port == dst_port) { if (lnk_unknown_dst_addr == NULL) lnk_unknown_dst_addr = lnk; } } else if (flags & LINK_UNKNOWN_DEST_PORT) { if (lnk->alias_addr.s_addr == alias_addr.s_addr && lnk->alias_port == alias_port && lnk->link_type == link_type && lnk->dst_addr.s_addr == dst_addr.s_addr) { if (lnk_unknown_dst_port == NULL) lnk_unknown_dst_port = lnk; } } } if (lnk_fully_specified != NULL) { lnk_fully_specified->timestamp = la->timeStamp; lnk = lnk_fully_specified; } else if (lnk_unknown_dst_port != NULL) lnk = lnk_unknown_dst_port; else if (lnk_unknown_dst_addr != NULL) lnk = lnk_unknown_dst_addr; else if (lnk_unknown_all != NULL) lnk = lnk_unknown_all; else return (NULL); if (replace_partial_links && (lnk->flags & LINK_PARTIALLY_SPECIFIED || lnk->server != NULL)) { struct in_addr src_addr; u_short src_port; if (lnk->server != NULL) { /* LSNAT link */ src_addr = lnk->server->addr; src_port = lnk->server->port; lnk->server = lnk->server->next; } else { src_addr = lnk->src_addr; src_port = lnk->src_port; } if (link_type == LINK_SCTP) { lnk->src_addr = src_addr; lnk->src_port = src_port; return (lnk); } lnk = ReLink(lnk, src_addr, dst_addr, alias_addr, src_port, dst_port, alias_port, link_type); } return (lnk); } static struct alias_link * FindLinkIn(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short dst_port, u_short alias_port, int link_type, int replace_partial_links) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = _FindLinkIn(la, dst_addr, alias_addr, dst_port, alias_port, link_type, replace_partial_links); if (lnk == NULL) { /* * The following allows permanent links to be specified as * using the default aliasing address (i.e. device * interface address) without knowing in advance what that * address is. */ if (la->aliasAddress.s_addr != INADDR_ANY && alias_addr.s_addr == la->aliasAddress.s_addr) { lnk = _FindLinkIn(la, dst_addr, ANY_ADDR, dst_port, alias_port, link_type, replace_partial_links); } } return (lnk); } /* External routines for finding/adding links -- "external" means outside alias_db.c, but within alias*.c -- FindIcmpIn(), FindIcmpOut() FindFragmentIn1(), FindFragmentIn2() AddFragmentPtrLink(), FindFragmentPtr() FindProtoIn(), FindProtoOut() FindUdpTcpIn(), FindUdpTcpOut() AddPptp(), FindPptpOutByCallId(), FindPptpInByCallId(), FindPptpOutByPeerCallId(), FindPptpInByPeerCallId() FindOriginalAddress(), FindAliasAddress() (prototypes in alias_local.h) */ struct alias_link * FindIcmpIn(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short id_alias, int create) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, dst_addr, alias_addr, NO_DEST_PORT, id_alias, LINK_ICMP, 0); if (lnk == NULL && create && !(la->packetAliasMode & PKT_ALIAS_DENY_INCOMING)) { struct in_addr target_addr; target_addr = FindOriginalAddress(la, alias_addr); lnk = AddLink(la, target_addr, dst_addr, alias_addr, id_alias, NO_DEST_PORT, id_alias, LINK_ICMP); } return (lnk); } struct alias_link * FindIcmpOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_short id, int create) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkOut(la, src_addr, dst_addr, id, NO_DEST_PORT, LINK_ICMP, 0); if (lnk == NULL && create) { struct in_addr alias_addr; alias_addr = FindAliasAddress(la, src_addr); lnk = AddLink(la, src_addr, dst_addr, alias_addr, id, NO_DEST_PORT, GET_ALIAS_ID, LINK_ICMP); } return (lnk); } struct alias_link * FindFragmentIn1(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short ip_id) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, dst_addr, alias_addr, NO_DEST_PORT, ip_id, LINK_FRAGMENT_ID, 0); if (lnk == NULL) { lnk = AddLink(la, ANY_ADDR, dst_addr, alias_addr, NO_SRC_PORT, NO_DEST_PORT, ip_id, LINK_FRAGMENT_ID); } return (lnk); } /* Doesn't add a link if one is not found. */ struct alias_link * FindFragmentIn2(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short ip_id) { LIBALIAS_LOCK_ASSERT(la); return FindLinkIn(la, dst_addr, alias_addr, NO_DEST_PORT, ip_id, LINK_FRAGMENT_ID, 0); } struct alias_link * AddFragmentPtrLink(struct libalias *la, struct in_addr dst_addr, u_short ip_id) { LIBALIAS_LOCK_ASSERT(la); return AddLink(la, ANY_ADDR, dst_addr, ANY_ADDR, NO_SRC_PORT, NO_DEST_PORT, ip_id, LINK_FRAGMENT_PTR); } struct alias_link * FindFragmentPtr(struct libalias *la, struct in_addr dst_addr, u_short ip_id) { LIBALIAS_LOCK_ASSERT(la); return FindLinkIn(la, dst_addr, ANY_ADDR, NO_DEST_PORT, ip_id, LINK_FRAGMENT_PTR, 0); } struct alias_link * FindProtoIn(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_char proto) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, dst_addr, alias_addr, NO_DEST_PORT, 0, proto, 1); if (lnk == NULL && !(la->packetAliasMode & PKT_ALIAS_DENY_INCOMING)) { struct in_addr target_addr; target_addr = FindOriginalAddress(la, alias_addr); lnk = AddLink(la, target_addr, dst_addr, alias_addr, NO_SRC_PORT, NO_DEST_PORT, 0, proto); } return (lnk); } struct alias_link * FindProtoOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_char proto) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkOut(la, src_addr, dst_addr, NO_SRC_PORT, NO_DEST_PORT, proto, 1); if (lnk == NULL) { struct in_addr alias_addr; alias_addr = FindAliasAddress(la, src_addr); lnk = AddLink(la, src_addr, dst_addr, alias_addr, NO_SRC_PORT, NO_DEST_PORT, 0, proto); } return (lnk); } struct alias_link * FindUdpTcpIn(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_short dst_port, u_short alias_port, u_char proto, int create) { int link_type; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); switch (proto) { case IPPROTO_UDP: link_type = LINK_UDP; break; case IPPROTO_TCP: link_type = LINK_TCP; break; default: return (NULL); break; } lnk = FindLinkIn(la, dst_addr, alias_addr, dst_port, alias_port, link_type, create); if (lnk == NULL && create && !(la->packetAliasMode & PKT_ALIAS_DENY_INCOMING)) { struct in_addr target_addr; target_addr = FindOriginalAddress(la, alias_addr); lnk = AddLink(la, target_addr, dst_addr, alias_addr, alias_port, dst_port, alias_port, link_type); } return (lnk); } struct alias_link * FindUdpTcpOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_short src_port, u_short dst_port, u_char proto, int create) { int link_type; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); switch (proto) { case IPPROTO_UDP: link_type = LINK_UDP; break; case IPPROTO_TCP: link_type = LINK_TCP; break; default: return (NULL); break; } lnk = FindLinkOut(la, src_addr, dst_addr, src_port, dst_port, link_type, create); if (lnk == NULL && create) { struct in_addr alias_addr; alias_addr = FindAliasAddress(la, src_addr); lnk = AddLink(la, src_addr, dst_addr, alias_addr, src_port, dst_port, GET_ALIAS_PORT, link_type); } return (lnk); } struct alias_link * AddPptp(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, struct in_addr alias_addr, u_int16_t src_call_id) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = AddLink(la, src_addr, dst_addr, alias_addr, src_call_id, 0, GET_ALIAS_PORT, LINK_PPTP); return (lnk); } struct alias_link * FindPptpOutByCallId(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_int16_t src_call_id) { u_int i; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); i = StartPointOut(src_addr, dst_addr, 0, 0, LINK_PPTP); LIST_FOREACH(lnk, &la->linkTableOut[i], list_out) if (lnk->link_type == LINK_PPTP && lnk->src_addr.s_addr == src_addr.s_addr && lnk->dst_addr.s_addr == dst_addr.s_addr && lnk->src_port == src_call_id) break; return (lnk); } struct alias_link * FindPptpOutByPeerCallId(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_int16_t dst_call_id) { u_int i; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); i = StartPointOut(src_addr, dst_addr, 0, 0, LINK_PPTP); LIST_FOREACH(lnk, &la->linkTableOut[i], list_out) if (lnk->link_type == LINK_PPTP && lnk->src_addr.s_addr == src_addr.s_addr && lnk->dst_addr.s_addr == dst_addr.s_addr && lnk->dst_port == dst_call_id) break; return (lnk); } struct alias_link * FindPptpInByCallId(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_int16_t dst_call_id) { u_int i; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); i = StartPointIn(alias_addr, 0, LINK_PPTP); LIST_FOREACH(lnk, &la->linkTableIn[i], list_in) if (lnk->link_type == LINK_PPTP && lnk->dst_addr.s_addr == dst_addr.s_addr && lnk->alias_addr.s_addr == alias_addr.s_addr && lnk->dst_port == dst_call_id) break; return (lnk); } struct alias_link * FindPptpInByPeerCallId(struct libalias *la, struct in_addr dst_addr, struct in_addr alias_addr, u_int16_t alias_call_id) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, dst_addr, alias_addr, 0 /* any */ , alias_call_id, LINK_PPTP, 0); return (lnk); } struct alias_link * FindRtspOut(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, u_short src_port, u_short alias_port, u_char proto) { int link_type; struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); switch (proto) { case IPPROTO_UDP: link_type = LINK_UDP; break; case IPPROTO_TCP: link_type = LINK_TCP; break; default: return (NULL); break; } lnk = FindLinkOut(la, src_addr, dst_addr, src_port, 0, link_type, 1); if (lnk == NULL) { struct in_addr alias_addr; alias_addr = FindAliasAddress(la, src_addr); lnk = AddLink(la, src_addr, dst_addr, alias_addr, src_port, 0, alias_port, link_type); } return (lnk); } struct in_addr FindOriginalAddress(struct libalias *la, struct in_addr alias_addr) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, ANY_ADDR, alias_addr, 0, 0, LINK_ADDR, 0); if (lnk == NULL) { - la->newDefaultLink = 1; if (la->targetAddress.s_addr == INADDR_ANY) return (alias_addr); else if (la->targetAddress.s_addr == INADDR_NONE) return (la->aliasAddress.s_addr != INADDR_ANY) ? la->aliasAddress : alias_addr; else return (la->targetAddress); } else { if (lnk->server != NULL) { /* LSNAT link */ struct in_addr src_addr; src_addr = lnk->server->addr; lnk->server = lnk->server->next; return (src_addr); } else if (lnk->src_addr.s_addr == INADDR_ANY) return (la->aliasAddress.s_addr != INADDR_ANY) ? la->aliasAddress : alias_addr; else return (lnk->src_addr); } } struct in_addr FindAliasAddress(struct libalias *la, struct in_addr original_addr) { struct alias_link *lnk; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkOut(la, original_addr, ANY_ADDR, 0, 0, LINK_ADDR, 0); if (lnk == NULL) { return (la->aliasAddress.s_addr != INADDR_ANY) ? la->aliasAddress : original_addr; } else { if (lnk->alias_addr.s_addr == INADDR_ANY) return (la->aliasAddress.s_addr != INADDR_ANY) ? la->aliasAddress : original_addr; else return (lnk->alias_addr); } } /* External routines for getting or changing link data (external to alias_db.c, but internal to alias*.c) SetFragmentData(), GetFragmentData() SetFragmentPtr(), GetFragmentPtr() SetStateIn(), SetStateOut(), GetStateIn(), GetStateOut() GetOriginalAddress(), GetDestAddress(), GetAliasAddress() GetOriginalPort(), GetAliasPort() SetAckModified(), GetAckModified() GetDeltaAckIn(), GetDeltaSeqOut(), AddSeq() SetProtocolFlags(), GetProtocolFlags() SetDestCallId() */ void SetFragmentAddr(struct alias_link *lnk, struct in_addr src_addr) { lnk->data.frag_addr = src_addr; } void GetFragmentAddr(struct alias_link *lnk, struct in_addr *src_addr) { *src_addr = lnk->data.frag_addr; } void SetFragmentPtr(struct alias_link *lnk, void *fptr) { lnk->data.frag_ptr = fptr; } void GetFragmentPtr(struct alias_link *lnk, void **fptr) { *fptr = lnk->data.frag_ptr; } void SetStateIn(struct alias_link *lnk, int state) { /* TCP input state */ switch (state) { case ALIAS_TCP_STATE_DISCONNECTED: if (lnk->data.tcp->state.out != ALIAS_TCP_STATE_CONNECTED) lnk->expire_time = TCP_EXPIRE_DEAD; else lnk->expire_time = TCP_EXPIRE_SINGLEDEAD; break; case ALIAS_TCP_STATE_CONNECTED: if (lnk->data.tcp->state.out == ALIAS_TCP_STATE_CONNECTED) lnk->expire_time = TCP_EXPIRE_CONNECTED; break; default: #ifdef _KERNEL panic("libalias:SetStateIn() unknown state"); #else abort(); #endif } lnk->data.tcp->state.in = state; } void SetStateOut(struct alias_link *lnk, int state) { /* TCP output state */ switch (state) { case ALIAS_TCP_STATE_DISCONNECTED: if (lnk->data.tcp->state.in != ALIAS_TCP_STATE_CONNECTED) lnk->expire_time = TCP_EXPIRE_DEAD; else lnk->expire_time = TCP_EXPIRE_SINGLEDEAD; break; case ALIAS_TCP_STATE_CONNECTED: if (lnk->data.tcp->state.in == ALIAS_TCP_STATE_CONNECTED) lnk->expire_time = TCP_EXPIRE_CONNECTED; break; default: #ifdef _KERNEL panic("libalias:SetStateOut() unknown state"); #else abort(); #endif } lnk->data.tcp->state.out = state; } int GetStateIn(struct alias_link *lnk) { /* TCP input state */ return (lnk->data.tcp->state.in); } int GetStateOut(struct alias_link *lnk) { /* TCP output state */ return (lnk->data.tcp->state.out); } struct in_addr GetOriginalAddress(struct alias_link *lnk) { if (lnk->src_addr.s_addr == INADDR_ANY) return (lnk->la->aliasAddress); else return (lnk->src_addr); } struct in_addr GetDestAddress(struct alias_link *lnk) { return (lnk->dst_addr); } struct in_addr GetAliasAddress(struct alias_link *lnk) { if (lnk->alias_addr.s_addr == INADDR_ANY) return (lnk->la->aliasAddress); else return (lnk->alias_addr); } struct in_addr GetDefaultAliasAddress(struct libalias *la) { LIBALIAS_LOCK_ASSERT(la); return (la->aliasAddress); } void SetDefaultAliasAddress(struct libalias *la, struct in_addr alias_addr) { LIBALIAS_LOCK_ASSERT(la); la->aliasAddress = alias_addr; } u_short GetOriginalPort(struct alias_link *lnk) { return (lnk->src_port); } u_short GetAliasPort(struct alias_link *lnk) { return (lnk->alias_port); } #ifndef NO_FW_PUNCH static u_short GetDestPort(struct alias_link *lnk) { return (lnk->dst_port); } #endif /* Indicate that ACK numbers have been modified in a TCP connection */ void SetAckModified(struct alias_link *lnk) { lnk->data.tcp->state.ack_modified = 1; } struct in_addr GetProxyAddress(struct alias_link *lnk) { return (lnk->proxy_addr); } void SetProxyAddress(struct alias_link *lnk, struct in_addr addr) { lnk->proxy_addr = addr; } u_short GetProxyPort(struct alias_link *lnk) { return (lnk->proxy_port); } void SetProxyPort(struct alias_link *lnk, u_short port) { lnk->proxy_port = port; } /* See if ACK numbers have been modified */ int GetAckModified(struct alias_link *lnk) { return (lnk->data.tcp->state.ack_modified); } /* * Find out how much the ACK number has been altered for an * incoming TCP packet. To do this, a circular list of ACK * numbers where the TCP packet size was altered is searched. */ // XXX ip free int GetDeltaAckIn(u_long ack, struct alias_link *lnk) { int i, j; int delta, ack_diff_min; delta = 0; ack_diff_min = -1; i = lnk->data.tcp->state.index; for (j = 0; j < N_LINK_TCP_DATA; j++) { struct ack_data_record x; if (i == 0) i = N_LINK_TCP_DATA; i--; x = lnk->data.tcp->ack[i]; if (x.active == 1) { int ack_diff; ack_diff = SeqDiff(x.ack_new, ack); if (ack_diff >= 0) { if (ack_diff_min >= 0) { if (ack_diff < ack_diff_min) { delta = x.delta; ack_diff_min = ack_diff; } } else { delta = x.delta; ack_diff_min = ack_diff; } } } } return (delta); } /* * Find out how much the sequence number has been altered for an * outgoing TCP packet. To do this, a circular list of ACK numbers * where the TCP packet size was altered is searched. */ // XXX ip free int GetDeltaSeqOut(u_long seq, struct alias_link *lnk) { int i, j; int delta, seq_diff_min; delta = 0; seq_diff_min = -1; i = lnk->data.tcp->state.index; for (j = 0; j < N_LINK_TCP_DATA; j++) { struct ack_data_record x; if (i == 0) i = N_LINK_TCP_DATA; i--; x = lnk->data.tcp->ack[i]; if (x.active == 1) { int seq_diff; seq_diff = SeqDiff(x.ack_old, seq); if (seq_diff >= 0) { if (seq_diff_min >= 0) { if (seq_diff < seq_diff_min) { delta = x.delta; seq_diff_min = seq_diff; } } else { delta = x.delta; seq_diff_min = seq_diff; } } } } return (delta); } /* * When a TCP packet has been altered in length, save this * information in a circular list. If enough packets have been * altered, then this list will begin to overwrite itself. */ // XXX ip free void AddSeq(struct alias_link *lnk, int delta, u_int ip_hl, u_short ip_len, u_long th_seq, u_int th_off) { struct ack_data_record x; int hlen, tlen, dlen; int i; hlen = (ip_hl + th_off) << 2; tlen = ntohs(ip_len); dlen = tlen - hlen; x.ack_old = htonl(ntohl(th_seq) + dlen); x.ack_new = htonl(ntohl(th_seq) + dlen + delta); x.delta = delta; x.active = 1; i = lnk->data.tcp->state.index; lnk->data.tcp->ack[i] = x; i++; if (i == N_LINK_TCP_DATA) lnk->data.tcp->state.index = 0; else lnk->data.tcp->state.index = i; } void SetExpire(struct alias_link *lnk, int expire) { if (expire == 0) { lnk->flags &= ~LINK_PERMANENT; DeleteLink(lnk); } else if (expire == -1) { lnk->flags |= LINK_PERMANENT; } else if (expire > 0) { lnk->expire_time = expire; } else { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/SetExpire(): "); fprintf(stderr, "error in expire parameter\n"); #endif } } -void -ClearCheckNewLink(struct libalias *la) -{ - LIBALIAS_LOCK_ASSERT(la); - la->newDefaultLink = 0; -} - void SetProtocolFlags(struct alias_link *lnk, int pflags) { lnk->pflags = pflags; } int GetProtocolFlags(struct alias_link *lnk) { return (lnk->pflags); } void SetDestCallId(struct alias_link *lnk, u_int16_t cid) { struct libalias *la = lnk->la; LIBALIAS_LOCK_ASSERT(la); la->deleteAllLinks = 1; ReLink(lnk, lnk->src_addr, lnk->dst_addr, lnk->alias_addr, lnk->src_port, cid, lnk->alias_port, lnk->link_type); la->deleteAllLinks = 0; } /* Miscellaneous Functions HouseKeeping() InitPacketAliasLog() UninitPacketAliasLog() */ /* Whenever an outgoing or incoming packet is handled, HouseKeeping() is called to find and remove timed-out aliasing links. Logic exists to sweep through the entire table and linked list structure every 60 seconds. (prototype in alias_local.h) */ void HouseKeeping(struct libalias *la) { int i, n; #ifndef _KERNEL struct timeval tv; #endif LIBALIAS_LOCK_ASSERT(la); /* * Save system time (seconds) in global variable timeStamp for use * by other functions. This is done so as not to unnecessarily * waste timeline by making system calls. */ #ifdef _KERNEL la->timeStamp = time_uptime; #else gettimeofday(&tv, NULL); la->timeStamp = tv.tv_sec; #endif /* Compute number of spokes (output table link chains) to cover */ n = LINK_TABLE_OUT_SIZE * (la->timeStamp - la->lastCleanupTime); n /= ALIAS_CLEANUP_INTERVAL_SECS; /* Handle different cases */ if (n > 0) { if (n > ALIAS_CLEANUP_MAX_SPOKES) n = ALIAS_CLEANUP_MAX_SPOKES; la->lastCleanupTime = la->timeStamp; for (i = 0; i < n; i++) IncrementalCleanup(la); } else if (n < 0) { #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAlias/HouseKeeping(): "); fprintf(stderr, "something unexpected in time values\n"); #endif la->lastCleanupTime = la->timeStamp; } } /* Init the log file and enable logging */ static int InitPacketAliasLog(struct libalias *la) { LIBALIAS_LOCK_ASSERT(la); if (~la->packetAliasMode & PKT_ALIAS_LOG) { #ifdef _KERNEL if ((la->logDesc = malloc(LIBALIAS_BUF_SIZE))) ; #else if ((la->logDesc = fopen("/var/log/alias.log", "w"))) fprintf(la->logDesc, "PacketAlias/InitPacketAliasLog: Packet alias logging enabled.\n"); #endif else return (ENOMEM); /* log initialization failed */ la->packetAliasMode |= PKT_ALIAS_LOG; } return (1); } /* Close the log-file and disable logging. */ static void UninitPacketAliasLog(struct libalias *la) { LIBALIAS_LOCK_ASSERT(la); if (la->logDesc) { #ifdef _KERNEL free(la->logDesc); #else fclose(la->logDesc); #endif la->logDesc = NULL; } la->packetAliasMode &= ~PKT_ALIAS_LOG; } /* Outside world interfaces -- "outside world" means other than alias*.c routines -- PacketAliasRedirectPort() PacketAliasAddServer() PacketAliasRedirectProto() PacketAliasRedirectAddr() PacketAliasRedirectDynamic() PacketAliasRedirectDelete() PacketAliasSetAddress() PacketAliasInit() PacketAliasUninit() PacketAliasSetMode() (prototypes in alias.h) */ /* Redirection from a specific public addr:port to a private addr:port */ struct alias_link * LibAliasRedirectPort(struct libalias *la, struct in_addr src_addr, u_short src_port, struct in_addr dst_addr, u_short dst_port, struct in_addr alias_addr, u_short alias_port, u_char proto) { int link_type; struct alias_link *lnk; LIBALIAS_LOCK(la); switch (proto) { case IPPROTO_UDP: link_type = LINK_UDP; break; case IPPROTO_TCP: link_type = LINK_TCP; break; case IPPROTO_SCTP: link_type = LINK_SCTP; break; default: #ifdef LIBALIAS_DEBUG fprintf(stderr, "PacketAliasRedirectPort(): "); fprintf(stderr, "only SCTP, TCP and UDP protocols allowed\n"); #endif lnk = NULL; goto getout; } lnk = AddLink(la, src_addr, dst_addr, alias_addr, src_port, dst_port, alias_port, link_type); if (lnk != NULL) { lnk->flags |= LINK_PERMANENT; } #ifdef LIBALIAS_DEBUG else { fprintf(stderr, "PacketAliasRedirectPort(): " "call to AddLink() failed\n"); } #endif getout: LIBALIAS_UNLOCK(la); return (lnk); } /* Add server to the pool of servers */ int LibAliasAddServer(struct libalias *la, struct alias_link *lnk, struct in_addr addr, u_short port) { struct server *server; int res; LIBALIAS_LOCK(la); (void)la; server = malloc(sizeof(struct server)); if (server != NULL) { struct server *head; server->addr = addr; server->port = port; head = lnk->server; if (head == NULL) server->next = server; else { struct server *s; for (s = head; s->next != head; s = s->next) ; s->next = server; server->next = head; } lnk->server = server; res = 0; } else res = -1; LIBALIAS_UNLOCK(la); return (res); } /* Redirect packets of a given IP protocol from a specific public address to a private address */ struct alias_link * LibAliasRedirectProto(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, struct in_addr alias_addr, u_char proto) { struct alias_link *lnk; LIBALIAS_LOCK(la); lnk = AddLink(la, src_addr, dst_addr, alias_addr, NO_SRC_PORT, NO_DEST_PORT, 0, proto); if (lnk != NULL) { lnk->flags |= LINK_PERMANENT; } #ifdef LIBALIAS_DEBUG else { fprintf(stderr, "PacketAliasRedirectProto(): " "call to AddLink() failed\n"); } #endif LIBALIAS_UNLOCK(la); return (lnk); } /* Static address translation */ struct alias_link * LibAliasRedirectAddr(struct libalias *la, struct in_addr src_addr, struct in_addr alias_addr) { struct alias_link *lnk; LIBALIAS_LOCK(la); lnk = AddLink(la, src_addr, ANY_ADDR, alias_addr, 0, 0, 0, LINK_ADDR); if (lnk != NULL) { lnk->flags |= LINK_PERMANENT; } #ifdef LIBALIAS_DEBUG else { fprintf(stderr, "PacketAliasRedirectAddr(): " "call to AddLink() failed\n"); } #endif LIBALIAS_UNLOCK(la); return (lnk); } /* Mark the aliasing link dynamic */ int LibAliasRedirectDynamic(struct libalias *la, struct alias_link *lnk) { int res; LIBALIAS_LOCK(la); (void)la; if (lnk->flags & LINK_PARTIALLY_SPECIFIED) res = -1; else { lnk->flags &= ~LINK_PERMANENT; res = 0; } LIBALIAS_UNLOCK(la); return (res); } /* This is a dangerous function to put in the API, because an invalid pointer can crash the program. */ void LibAliasRedirectDelete(struct libalias *la, struct alias_link *lnk) { LIBALIAS_LOCK(la); la->deleteAllLinks = 1; DeleteLink(lnk); la->deleteAllLinks = 0; LIBALIAS_UNLOCK(la); } void LibAliasSetAddress(struct libalias *la, struct in_addr addr) { LIBALIAS_LOCK(la); if (la->packetAliasMode & PKT_ALIAS_RESET_ON_ADDR_CHANGE && la->aliasAddress.s_addr != addr.s_addr) CleanupAliasData(la); la->aliasAddress = addr; LIBALIAS_UNLOCK(la); } void LibAliasSetAliasPortRange(struct libalias *la, u_short port_low, u_short port_high) { LIBALIAS_LOCK(la); la->aliasPortLower = port_low; /* Add 1 to the aliasPortLength as modulo has range of 1 to n-1 */ la->aliasPortLength = port_high - port_low + 1; LIBALIAS_UNLOCK(la); } void LibAliasSetTarget(struct libalias *la, struct in_addr target_addr) { LIBALIAS_LOCK(la); la->targetAddress = target_addr; LIBALIAS_UNLOCK(la); } static void finishoff(void) { while (!LIST_EMPTY(&instancehead)) LibAliasUninit(LIST_FIRST(&instancehead)); } struct libalias * LibAliasInit(struct libalias *la) { int i; #ifndef _KERNEL struct timeval tv; #endif if (la == NULL) { #ifdef _KERNEL #undef malloc /* XXX: ugly */ la = malloc(sizeof *la, M_ALIAS, M_WAITOK | M_ZERO); #else la = calloc(sizeof *la, 1); if (la == NULL) return (la); #endif #ifndef _KERNEL /* kernel cleans up on module unload */ if (LIST_EMPTY(&instancehead)) atexit(finishoff); #endif LIST_INSERT_HEAD(&instancehead, la, instancelist); #ifdef _KERNEL la->timeStamp = time_uptime; la->lastCleanupTime = time_uptime; #else gettimeofday(&tv, NULL); la->timeStamp = tv.tv_sec; la->lastCleanupTime = tv.tv_sec; #endif for (i = 0; i < LINK_TABLE_OUT_SIZE; i++) LIST_INIT(&la->linkTableOut[i]); for (i = 0; i < LINK_TABLE_IN_SIZE; i++) LIST_INIT(&la->linkTableIn[i]); #ifdef _KERNEL AliasSctpInit(la); #endif LIBALIAS_LOCK_INIT(la); LIBALIAS_LOCK(la); } else { LIBALIAS_LOCK(la); la->deleteAllLinks = 1; CleanupAliasData(la); la->deleteAllLinks = 0; #ifdef _KERNEL AliasSctpTerm(la); AliasSctpInit(la); #endif } la->aliasAddress.s_addr = INADDR_ANY; la->targetAddress.s_addr = INADDR_ANY; la->icmpLinkCount = 0; la->udpLinkCount = 0; la->tcpLinkCount = 0; la->sctpLinkCount = 0; la->pptpLinkCount = 0; la->protoLinkCount = 0; la->fragmentIdLinkCount = 0; la->fragmentPtrLinkCount = 0; la->sockCount = 0; la->cleanupIndex = 0; la->packetAliasMode = PKT_ALIAS_SAME_PORTS #ifndef NO_USE_SOCKETS | PKT_ALIAS_USE_SOCKETS #endif | PKT_ALIAS_RESET_ON_ADDR_CHANGE; #ifndef NO_FW_PUNCH la->fireWallFD = -1; #endif #ifndef _KERNEL LibAliasRefreshModules(); #endif LIBALIAS_UNLOCK(la); return (la); } void LibAliasUninit(struct libalias *la) { LIBALIAS_LOCK(la); #ifdef _KERNEL AliasSctpTerm(la); #endif la->deleteAllLinks = 1; CleanupAliasData(la); la->deleteAllLinks = 0; UninitPacketAliasLog(la); #ifndef NO_FW_PUNCH UninitPunchFW(la); #endif LIST_REMOVE(la, instancelist); LIBALIAS_UNLOCK(la); LIBALIAS_LOCK_DESTROY(la); free(la); } /* Change mode for some operations */ unsigned int LibAliasSetMode( struct libalias *la, unsigned int flags, /* Which state to bring flags to */ unsigned int mask /* Mask of which flags to affect (use 0 to * do a probe for flag values) */ ) { int res = -1; LIBALIAS_LOCK(la); if (flags & mask & PKT_ALIAS_LOG) { /* Enable logging */ if (InitPacketAliasLog(la) == ENOMEM) goto getout; } else if (~flags & mask & PKT_ALIAS_LOG) /* _Disable_ logging */ UninitPacketAliasLog(la); #ifndef NO_FW_PUNCH if (flags & mask & PKT_ALIAS_PUNCH_FW) /* Start punching holes in the firewall? */ InitPunchFW(la); else if (~flags & mask & PKT_ALIAS_PUNCH_FW) /* Stop punching holes in the firewall? */ UninitPunchFW(la); #endif /* Other flags can be set/cleared without special action */ la->packetAliasMode = (flags & mask) | (la->packetAliasMode & ~mask); res = la->packetAliasMode; getout: LIBALIAS_UNLOCK(la); return (res); } +/* never used and never worked, to be removed in FreeBSD 14 */ int LibAliasCheckNewLink(struct libalias *la) { - int res; - - LIBALIAS_LOCK(la); - res = la->newDefaultLink; - LIBALIAS_UNLOCK(la); - return (res); + (void)la; + return (0); } #ifndef NO_FW_PUNCH /***************** Code to support firewall punching. This shouldn't really be in this file, but making variables global is evil too. ****************/ /* Firewall include files */ #include #include #include #include /* * helper function, updates the pointer to cmd with the length * of the current command, and also cleans up the first word of * the new command in case it has been clobbered before. */ static ipfw_insn * next_cmd(ipfw_insn * cmd) { cmd += F_LEN(cmd); bzero(cmd, sizeof(*cmd)); return (cmd); } /* * A function to fill simple commands of size 1. * Existing flags are preserved. */ static ipfw_insn * fill_cmd(ipfw_insn * cmd, enum ipfw_opcodes opcode, int size, int flags, u_int16_t arg) { cmd->opcode = opcode; cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | (size & F_LEN_MASK); cmd->arg1 = arg; return next_cmd(cmd); } static ipfw_insn * fill_ip(ipfw_insn * cmd1, enum ipfw_opcodes opcode, u_int32_t addr) { ipfw_insn_ip *cmd = (ipfw_insn_ip *)cmd1; cmd->addr.s_addr = addr; return fill_cmd(cmd1, opcode, F_INSN_SIZE(ipfw_insn_u32), 0, 0); } static ipfw_insn * fill_one_port(ipfw_insn * cmd1, enum ipfw_opcodes opcode, u_int16_t port) { ipfw_insn_u16 *cmd = (ipfw_insn_u16 *)cmd1; cmd->ports[0] = cmd->ports[1] = port; return fill_cmd(cmd1, opcode, F_INSN_SIZE(ipfw_insn_u16), 0, 0); } static int fill_rule(void *buf, int bufsize, int rulenum, enum ipfw_opcodes action, int proto, struct in_addr sa, u_int16_t sp, struct in_addr da, u_int16_t dp) { struct ip_fw *rule = (struct ip_fw *)buf; ipfw_insn *cmd = (ipfw_insn *)rule->cmd; bzero(buf, bufsize); rule->rulenum = rulenum; cmd = fill_cmd(cmd, O_PROTO, F_INSN_SIZE(ipfw_insn), 0, proto); cmd = fill_ip(cmd, O_IP_SRC, sa.s_addr); cmd = fill_one_port(cmd, O_IP_SRCPORT, sp); cmd = fill_ip(cmd, O_IP_DST, da.s_addr); cmd = fill_one_port(cmd, O_IP_DSTPORT, dp); rule->act_ofs = (u_int32_t *)cmd - (u_int32_t *)rule->cmd; cmd = fill_cmd(cmd, action, F_INSN_SIZE(ipfw_insn), 0, 0); rule->cmd_len = (u_int32_t *)cmd - (u_int32_t *)rule->cmd; return ((char *)cmd - (char *)buf); } static void ClearAllFWHoles(struct libalias *la); #define fw_setfield(la, field, num) \ do { \ (field)[(num) - la->fireWallBaseNum] = 1; \ } /*lint -save -e717 */ while(0)/* lint -restore */ #define fw_clrfield(la, field, num) \ do { \ (field)[(num) - la->fireWallBaseNum] = 0; \ } /*lint -save -e717 */ while(0)/* lint -restore */ #define fw_tstfield(la, field, num) ((field)[(num) - la->fireWallBaseNum]) static void InitPunchFW(struct libalias *la) { la->fireWallField = malloc(la->fireWallNumNums); if (la->fireWallField) { memset(la->fireWallField, 0, la->fireWallNumNums); if (la->fireWallFD < 0) { la->fireWallFD = socket(AF_INET, SOCK_RAW, IPPROTO_RAW); } ClearAllFWHoles(la); la->fireWallActiveNum = la->fireWallBaseNum; } } static void UninitPunchFW(struct libalias *la) { ClearAllFWHoles(la); if (la->fireWallFD >= 0) close(la->fireWallFD); la->fireWallFD = -1; if (la->fireWallField) free(la->fireWallField); la->fireWallField = NULL; la->packetAliasMode &= ~PKT_ALIAS_PUNCH_FW; } /* Make a certain link go through the firewall */ void PunchFWHole(struct alias_link *lnk) { struct libalias *la; int r; /* Result code */ struct ip_fw rule; /* On-the-fly built rule */ int fwhole; /* Where to punch hole */ la = lnk->la; /* Don't do anything unless we are asked to */ if (!(la->packetAliasMode & PKT_ALIAS_PUNCH_FW) || la->fireWallFD < 0 || lnk->link_type != LINK_TCP) return; memset(&rule, 0, sizeof rule); /** Build rule **/ /* Find empty slot */ for (fwhole = la->fireWallActiveNum; fwhole < la->fireWallBaseNum + la->fireWallNumNums && fw_tstfield(la, la->fireWallField, fwhole); fwhole++); if (fwhole == la->fireWallBaseNum + la->fireWallNumNums) { for (fwhole = la->fireWallBaseNum; fwhole < la->fireWallActiveNum && fw_tstfield(la, la->fireWallField, fwhole); fwhole++); if (fwhole == la->fireWallActiveNum) { /* No rule point empty - we can't punch more holes. */ la->fireWallActiveNum = la->fireWallBaseNum; #ifdef LIBALIAS_DEBUG fprintf(stderr, "libalias: Unable to create firewall hole!\n"); #endif return; } } /* Start next search at next position */ la->fireWallActiveNum = fwhole + 1; /* * generate two rules of the form * * add fwhole accept tcp from OAddr OPort to DAddr DPort add fwhole * accept tcp from DAddr DPort to OAddr OPort */ if (GetOriginalPort(lnk) != 0 && GetDestPort(lnk) != 0) { u_int32_t rulebuf[255]; int i; i = fill_rule(rulebuf, sizeof(rulebuf), fwhole, O_ACCEPT, IPPROTO_TCP, GetOriginalAddress(lnk), ntohs(GetOriginalPort(lnk)), GetDestAddress(lnk), ntohs(GetDestPort(lnk))); r = setsockopt(la->fireWallFD, IPPROTO_IP, IP_FW_ADD, rulebuf, i); if (r) err(1, "alias punch inbound(1) setsockopt(IP_FW_ADD)"); i = fill_rule(rulebuf, sizeof(rulebuf), fwhole, O_ACCEPT, IPPROTO_TCP, GetDestAddress(lnk), ntohs(GetDestPort(lnk)), GetOriginalAddress(lnk), ntohs(GetOriginalPort(lnk))); r = setsockopt(la->fireWallFD, IPPROTO_IP, IP_FW_ADD, rulebuf, i); if (r) err(1, "alias punch inbound(2) setsockopt(IP_FW_ADD)"); } /* Indicate hole applied */ lnk->data.tcp->fwhole = fwhole; fw_setfield(la, la->fireWallField, fwhole); } /* Remove a hole in a firewall associated with a particular alias lnk. Calling this too often is harmless. */ static void ClearFWHole(struct alias_link *lnk) { struct libalias *la; la = lnk->la; if (lnk->link_type == LINK_TCP) { int fwhole = lnk->data.tcp->fwhole; /* Where is the firewall hole? */ struct ip_fw rule; if (fwhole < 0) return; memset(&rule, 0, sizeof rule); /* useless for ipfw2 */ while (!setsockopt(la->fireWallFD, IPPROTO_IP, IP_FW_DEL, &fwhole, sizeof fwhole)); fw_clrfield(la, la->fireWallField, fwhole); lnk->data.tcp->fwhole = -1; } } /* Clear out the entire range dedicated to firewall holes. */ static void ClearAllFWHoles(struct libalias *la) { struct ip_fw rule; /* On-the-fly built rule */ int i; if (la->fireWallFD < 0) return; memset(&rule, 0, sizeof rule); for (i = la->fireWallBaseNum; i < la->fireWallBaseNum + la->fireWallNumNums; i++) { int r = i; while (!setsockopt(la->fireWallFD, IPPROTO_IP, IP_FW_DEL, &r, sizeof r)); } /* XXX: third arg correct here ? /phk */ memset(la->fireWallField, 0, la->fireWallNumNums); } #endif /* !NO_FW_PUNCH */ void LibAliasSetFWBase(struct libalias *la, unsigned int base, unsigned int num) { LIBALIAS_LOCK(la); #ifndef NO_FW_PUNCH la->fireWallBaseNum = base; la->fireWallNumNums = num; #endif LIBALIAS_UNLOCK(la); } void LibAliasSetSkinnyPort(struct libalias *la, unsigned int port) { LIBALIAS_LOCK(la); la->skinnyPort = port; LIBALIAS_UNLOCK(la); } /* * Find the address to redirect incoming packets */ struct in_addr FindSctpRedirectAddress(struct libalias *la, struct sctp_nat_msg *sm) { struct alias_link *lnk; struct in_addr redir; LIBALIAS_LOCK_ASSERT(la); lnk = FindLinkIn(la, sm->ip_hdr->ip_src, sm->ip_hdr->ip_dst, sm->sctp_hdr->dest_port,sm->sctp_hdr->dest_port, LINK_SCTP, 1); if (lnk != NULL) { /* port redirect */ return (lnk->src_addr); } else { redir = FindOriginalAddress(la,sm->ip_hdr->ip_dst); if (redir.s_addr == la->aliasAddress.s_addr || redir.s_addr == la->targetAddress.s_addr) { /* No address found */ lnk = FindLinkIn(la, sm->ip_hdr->ip_src, sm->ip_hdr->ip_dst, NO_DEST_PORT, 0, LINK_SCTP, 1); if (lnk != NULL) /* redirect proto */ return (lnk->src_addr); } return (redir); /* address redirect */ } } diff --git a/sys/netinet/libalias/alias_local.h b/sys/netinet/libalias/alias_local.h index 63bfd857f14f..61cd30737ce5 100644 --- a/sys/netinet/libalias/alias_local.h +++ b/sys/netinet/libalias/alias_local.h @@ -1,383 +1,379 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 Charles Mott * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /* * Alias_local.h contains the function prototypes for alias.c, * alias_db.c, alias_util.c and alias_ftp.c, alias_irc.c (as well * as any future add-ons). It also includes macros, globals and * struct definitions shared by more than one alias*.c file. * * This include file is intended to be used only within the aliasing * software. Outside world interfaces are defined in alias.h * * This software is placed into the public domain with no restrictions * on its distribution. * * Initial version: August, 1996 (cjm) * * */ #ifndef _ALIAS_LOCAL_H_ #define _ALIAS_LOCAL_H_ #include #include #ifdef _KERNEL #include #include #include #include /* XXX: LibAliasSetTarget() uses this constant. */ #define INADDR_NONE 0xffffffff #include #else #include "alias_sctp.h" #endif /* Sizes of input and output link tables */ #define LINK_TABLE_OUT_SIZE 4001 #define LINK_TABLE_IN_SIZE 4001 #define GET_ALIAS_PORT -1 #define GET_ALIAS_ID GET_ALIAS_PORT #ifdef _KERNEL #define INET_NTOA_BUF(buf) (buf) #else #define INET_NTOA_BUF(buf) (buf), sizeof(buf) #endif struct proxy_entry; struct libalias { LIST_ENTRY(libalias) instancelist; /* Mode flags documented in alias.h */ int packetAliasMode; /* Address written onto source field of IP packet. */ struct in_addr aliasAddress; /* IP address incoming packets are sent to * if no aliasing link already exists */ struct in_addr targetAddress; /* Lookup table of pointers to chains of link records. * Each link record is doubly indexed into input and * output lookup tables. */ LIST_HEAD (, alias_link) linkTableOut[LINK_TABLE_OUT_SIZE]; LIST_HEAD (, alias_link) linkTableIn[LINK_TABLE_IN_SIZE]; /* Link statistics */ int icmpLinkCount; int udpLinkCount; int tcpLinkCount; int pptpLinkCount; int protoLinkCount; int fragmentIdLinkCount; int fragmentPtrLinkCount; int sockCount; /* Index to chain of link table being inspected for old links */ int cleanupIndex; /* System time in seconds for current packet */ int timeStamp; /* Last time IncrementalCleanup() was called */ int lastCleanupTime; /* If equal to zero, DeleteLink() * will not remove permanent links */ int deleteAllLinks; /* log descriptor */ #ifdef _KERNEL char *logDesc; #else FILE *logDesc; #endif - /* Indicates if a new aliasing link has been created - * after a call to PacketAliasIn/Out(). */ - int newDefaultLink; #ifndef NO_FW_PUNCH /* File descriptor to be able to control firewall. * Opened by PacketAliasSetMode on first setting * the PKT_ALIAS_PUNCH_FW flag. */ int fireWallFD; /* The first firewall entry free for our use */ int fireWallBaseNum; /* How many entries can we use? */ int fireWallNumNums; /* Which entry did we last use? */ int fireWallActiveNum; /* bool array for entries */ char *fireWallField; #endif /* TCP port used by the Skinny protocol. */ unsigned int skinnyPort; struct proxy_entry *proxyList; struct in_addr true_addr; /* in network byte order. */ u_short true_port; /* in host byte order. */ /* Port ranges for aliasing. */ u_short aliasPortLower; u_short aliasPortLength; /* * sctp code support */ /* counts associations that have progressed to UP and not yet removed */ int sctpLinkCount; #ifdef _KERNEL /* timing queue for keeping track of association timeouts */ struct sctp_nat_timer sctpNatTimer; /* size of hash table used in this instance */ u_int sctpNatTableSize; /* local look up table sorted by l_vtag/l_port */ LIST_HEAD(sctpNatTableL, sctp_nat_assoc) *sctpTableLocal; /* global look up table sorted by g_vtag/g_port */ LIST_HEAD(sctpNatTableG, sctp_nat_assoc) *sctpTableGlobal; /* avoid races in libalias: every public function has to use it. */ struct mtx mutex; #endif }; /* Macros */ #ifdef _KERNEL #define LIBALIAS_LOCK_INIT(l) \ mtx_init(&l->mutex, "per-instance libalias mutex", NULL, MTX_DEF) #define LIBALIAS_LOCK_ASSERT(l) mtx_assert(&l->mutex, MA_OWNED) #define LIBALIAS_LOCK(l) mtx_lock(&l->mutex) #define LIBALIAS_UNLOCK(l) mtx_unlock(&l->mutex) #define LIBALIAS_LOCK_DESTROY(l) mtx_destroy(&l->mutex) #else #define LIBALIAS_LOCK_INIT(l) #define LIBALIAS_LOCK_ASSERT(l) #define LIBALIAS_LOCK(l) #define LIBALIAS_UNLOCK(l) #define LIBALIAS_LOCK_DESTROY(l) #endif /* * The following macro is used to update an * internet checksum. "delta" is a 32-bit * accumulation of all the changes to the * checksum (adding in new 16-bit words and * subtracting out old words), and "cksum" * is the checksum value to be updated. */ #define ADJUST_CHECKSUM(acc, cksum) \ do { \ acc += cksum; \ if (acc < 0) { \ acc = -acc; \ acc = (acc >> 16) + (acc & 0xffff); \ acc += acc >> 16; \ cksum = (u_short) ~acc; \ } else { \ acc = (acc >> 16) + (acc & 0xffff); \ acc += acc >> 16; \ cksum = (u_short) acc; \ } \ } while (0) /* Prototypes */ /* * SctpFunction prototypes * */ void AliasSctpInit(struct libalias *la); void AliasSctpTerm(struct libalias *la); int SctpAlias(struct libalias *la, struct ip *ip, int direction); /* * We do not calculate TCP checksums when libalias is a kernel * module, since it has no idea about checksum offloading. * If TCP data has changed, then we just set checksum to zero, * and caller must recalculate it himself. * In case if libalias will edit UDP data, the same approach * should be used. */ #ifndef _KERNEL u_short IpChecksum(struct ip *_pip); u_short TcpChecksum(struct ip *_pip); #endif void DifferentialChecksum(u_short * _cksum, void * _new, void * _old, int _n); /* Internal data access */ struct alias_link * AddLink(struct libalias *la, struct in_addr src_addr, struct in_addr dst_addr, struct in_addr alias_addr, u_short src_port, u_short dst_port, int alias_param, int link_type); struct alias_link * FindIcmpIn(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_short _id_alias, int _create); struct alias_link * FindIcmpOut(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_short _id, int _create); struct alias_link * FindFragmentIn1(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_short _ip_id); struct alias_link * FindFragmentIn2(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_short _ip_id); struct alias_link * AddFragmentPtrLink(struct libalias *la, struct in_addr _dst_addr, u_short _ip_id); struct alias_link * FindFragmentPtr(struct libalias *la, struct in_addr _dst_addr, u_short _ip_id); struct alias_link * FindProtoIn(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_char _proto); struct alias_link * FindProtoOut(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_char _proto); struct alias_link * FindUdpTcpIn(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_short _dst_port, u_short _alias_port, u_char _proto, int _create); struct alias_link * FindUdpTcpOut(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_short _src_port, u_short _dst_port, u_char _proto, int _create); struct alias_link * AddPptp(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, struct in_addr _alias_addr, u_int16_t _src_call_id); struct alias_link * FindPptpOutByCallId(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_int16_t _src_call_id); struct alias_link * FindPptpInByCallId(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_int16_t _dst_call_id); struct alias_link * FindPptpOutByPeerCallId(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_int16_t _dst_call_id); struct alias_link * FindPptpInByPeerCallId(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_int16_t _alias_call_id); struct alias_link * FindRtspOut(struct libalias *la, struct in_addr _src_addr, struct in_addr _dst_addr, u_short _src_port, u_short _alias_port, u_char _proto); struct in_addr FindOriginalAddress(struct libalias *la, struct in_addr _alias_addr); struct in_addr FindAliasAddress(struct libalias *la, struct in_addr _original_addr); struct in_addr FindSctpRedirectAddress(struct libalias *la, struct sctp_nat_msg *sm); /* External data access/modification */ int FindNewPortGroup(struct libalias *la, struct in_addr _dst_addr, struct in_addr _alias_addr, u_short _src_port, u_short _dst_port, u_short _port_count, u_char _proto, u_char _align); void GetFragmentAddr(struct alias_link *_lnk, struct in_addr *_src_addr); void SetFragmentAddr(struct alias_link *_lnk, struct in_addr _src_addr); void GetFragmentPtr(struct alias_link *_lnk, void **_fptr); void SetFragmentPtr(struct alias_link *_lnk, void *fptr); void SetStateIn(struct alias_link *_lnk, int _state); void SetStateOut(struct alias_link *_lnk, int _state); int GetStateIn (struct alias_link *_lnk); int GetStateOut(struct alias_link *_lnk); struct in_addr GetOriginalAddress(struct alias_link *_lnk); struct in_addr GetDestAddress(struct alias_link *_lnk); struct in_addr GetAliasAddress(struct alias_link *_lnk); struct in_addr GetDefaultAliasAddress(struct libalias *la); void SetDefaultAliasAddress(struct libalias *la, struct in_addr _alias_addr); u_short GetOriginalPort(struct alias_link *_lnk); u_short GetAliasPort(struct alias_link *_lnk); struct in_addr GetProxyAddress(struct alias_link *_lnk); void SetProxyAddress(struct alias_link *_lnk, struct in_addr _addr); u_short GetProxyPort(struct alias_link *_lnk); void SetProxyPort(struct alias_link *_lnk, u_short _port); void SetAckModified(struct alias_link *_lnk); int GetAckModified(struct alias_link *_lnk); int GetDeltaAckIn(u_long, struct alias_link *_lnk); int GetDeltaSeqOut(u_long, struct alias_link *lnk); void AddSeq(struct alias_link *lnk, int delta, u_int ip_hl, u_short ip_len, u_long th_seq, u_int th_off); void SetExpire (struct alias_link *_lnk, int _expire); -void ClearCheckNewLink(struct libalias *la); void SetProtocolFlags(struct alias_link *_lnk, int _pflags); int GetProtocolFlags(struct alias_link *_lnk); void SetDestCallId(struct alias_link *_lnk, u_int16_t _cid); #ifndef NO_FW_PUNCH void PunchFWHole(struct alias_link *_lnk); #endif /* Housekeeping function */ void HouseKeeping(struct libalias *); /* Transparent proxy routines */ int ProxyCheck(struct libalias *la, struct in_addr *proxy_server_addr, u_short * proxy_server_port, struct in_addr src_addr, struct in_addr dst_addr, u_short dst_port, u_char ip_p); void ProxyModify(struct libalias *la, struct alias_link *_lnk, struct ip *_pip, int _maxpacketsize, int _proxy_type); /* Tcp specific routines */ /* lint -save -library Suppress flexelint warnings */ enum alias_tcp_state { ALIAS_TCP_STATE_NOT_CONNECTED, ALIAS_TCP_STATE_CONNECTED, ALIAS_TCP_STATE_DISCONNECTED }; #if defined(_NETINET_IP_H_) static __inline void * ip_next(struct ip *iphdr) { char *p = (char *)iphdr; return (&p[iphdr->ip_hl * 4]); } #endif #if defined(_NETINET_TCP_H_) static __inline void * tcp_next(struct tcphdr *tcphdr) { char *p = (char *)tcphdr; return (&p[tcphdr->th_off * 4]); } #endif #if defined(_NETINET_UDP_H_) static __inline void * udp_next(struct udphdr *udphdr) { return ((void *)(udphdr + 1)); } #endif #endif /* !_ALIAS_LOCAL_H_ */ diff --git a/sys/netinet/libalias/libalias.3 b/sys/netinet/libalias/libalias.3 index beef2ff7fca5..85ebe55f527c 100644 --- a/sys/netinet/libalias/libalias.3 +++ b/sys/netinet/libalias/libalias.3 @@ -1,1491 +1,1481 @@ .\"- .\" Copyright (c) 2001 Charles Mott .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" -.Dd January 1, 2020 +.Dd May 31, 2021 .Dt LIBALIAS 3 .Os .Sh NAME .Nm libalias .Nd packet aliasing library for masquerading and network address translation .Sh SYNOPSIS .In sys/types.h .In netinet/in.h .In alias.h .Pp Function prototypes are given in the main body of the text. .Sh DESCRIPTION The .Nm library is a collection of functions for aliasing and de-aliasing of IP packets, intended for masquerading and network address translation (NAT). .Sh INTRODUCTION This library is a moderately portable set of functions designed to assist in the process of IP masquerading and network address translation. Outgoing packets from a local network with unregistered IP addresses can be aliased to appear as if they came from an accessible IP address. Incoming packets are then de-aliased so that they are sent to the correct machine on the local network. .Pp A certain amount of flexibility is built into the packet aliasing engine. In the simplest mode of operation, a many-to-one address mapping takes place between the local network and the packet aliasing host. This is known as IP masquerading. In addition, one-to-one mappings between local and public addresses can also be implemented, which is known as static NAT. In between these extremes, different groups of private addresses can be linked to different public addresses, comprising several distinct many-to-one mappings. Also, a given public address and port can be statically redirected to a private address/port. .Sh INITIALIZATION AND CONTROL One special function, .Fn LibAliasInit , must always be called before any packet handling may be performed, and the returned instance pointer must be passed to all the other functions. Normally, the .Fn LibAliasSetAddress function is called afterwards, to set the default aliasing address. In addition, the operating mode of the packet aliasing engine can be customized by calling .Fn LibAliasSetMode . .Pp .Ft "struct libalias *" .Fn LibAliasInit "struct libalias *" .Bd -ragged -offset indent This function is used to initialize internal data structures. When called the first time, a .Dv NULL pointer should be passed as an argument. The following mode bits are always set after calling .Fn LibAliasInit . See the description of .Fn LibAliasSetMode below for the meaning of these mode bits. .Pp .Bl -item -offset indent -compact .It .Dv PKT_ALIAS_SAME_PORTS .It .Dv PKT_ALIAS_USE_SOCKETS .It .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE .El .Pp This function will always return the packet aliasing engine to the same initial state. The .Fn LibAliasSetAddress function is normally called afterwards, and any desired changes from the default mode bits listed above require a call to .Fn LibAliasSetMode . .Pp It is mandatory that this function be called at the beginning of a program prior to any packet handling. .Ed .Pp .Ft void .Fn LibAliasUninit "struct libalias *" .Bd -ragged -offset indent This function has no return value and is used to clear any resources attached to internal data structures. .Pp This function should be called when a program stops using the aliasing engine; amongst other things, it clears out any firewall holes. To provide backwards compatibility and extra security, it is added to the .Xr atexit 3 chain by .Fn LibAliasInit . .Ed .Pp .Ft void .Fn LibAliasSetAddress "struct libalias *" "struct in_addr addr" .Bd -ragged -offset indent This function sets the source address to which outgoing packets from the local area network are aliased. All outgoing packets are re-mapped to this address unless overridden by a static address mapping established by .Fn LibAliasRedirectAddr . If this function has not been called, and no static rules match, an outgoing packet retains its source address. .Pp If the .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE mode bit is set (the default mode of operation), then the internal aliasing link tables will be reset any time the aliasing address changes. This is useful for interfaces such as .Xr ppp 8 , where the IP address may or may not change on successive dial-up attempts. .Pp If the .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE mode bit is set to zero, this function can also be used to dynamically change the aliasing address on a packet-to-packet basis (it is a low overhead call). .Pp It is mandatory that this function be called prior to any packet handling. .Ed .Pp .Ft unsigned int .Fn LibAliasSetMode "struct libalias *" "unsigned int flags" "unsigned int mask" .Bd -ragged -offset indent This function sets or clears mode bits according to the value of .Fa flags . Only bits marked in .Fa mask are affected. The following mode bits are defined in .In alias.h : .Bl -tag -width indent .It Dv PKT_ALIAS_LOG Enables logging into .Pa /var/log/alias.log . Each time an aliasing link is created or deleted, the log file is appended to with the current number of ICMP, TCP and UDP links. Mainly useful for debugging when the log file is viewed continuously with .Xr tail 1 . .It Dv PKT_ALIAS_DENY_INCOMING If this mode bit is set, all incoming packets associated with new TCP connections or new UDP transactions will be marked for being ignored .Po .Fn LibAliasIn returns .Dv PKT_ALIAS_IGNORED code .Pc by the calling program. Response packets to connections or transactions initiated from the packet aliasing host or local network will be unaffected. This mode bit is useful for implementing a one-way firewall. .It Dv PKT_ALIAS_SAME_PORTS If this mode bit is set, the packet-aliasing engine will attempt to leave the alias port numbers unchanged from the actual local port numbers. This can be done as long as the quintuple (proto, alias addr, alias port, remote addr, remote port) is unique. If a conflict exists, a new aliasing port number is chosen even if this mode bit is set. .It Dv PKT_ALIAS_USE_SOCKETS This bit should be set when the packet aliasing host originates network traffic as well as forwards it. When the packet aliasing host is waiting for a connection from an unknown host address or unknown port number (e.g.\& an FTP data connection), this mode bit specifies that a socket be allocated as a place holder to prevent port conflicts. Once a connection is established, usually within a minute or so, the socket is closed. .It Dv PKT_ALIAS_UNREGISTERED_ONLY If this mode bit is set, traffic on the local network which does not originate from unregistered address spaces will be ignored. Standard Class A, B and C unregistered addresses are: .Pp 10.0.0.0 -> 10.255.255.255 (Class A subnet) 172.16.0.0 -> 172.31.255.255 (Class B subnets) 192.168.0.0 -> 192.168.255.255 (Class C subnets) .Pp This option is useful in the case that the packet aliasing host has both registered and unregistered subnets on different interfaces. The registered subnet is fully accessible to the outside world, so traffic from it does not need to be passed through the packet aliasing engine. .It Dv PKT_ALIAS_UNREGISTERED_CGN Like PKT_ALIAS_UNREGISTERED_ONLY, but includes the RFC 6598 (Carrier Grade NAT) subnet as follows: .Pp 100.64.0.0 -> 100.127.255.255 (RFC 6598 subnet) .It Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE When this mode bit is set and .Fn LibAliasSetAddress is called to change the aliasing address, the internal link table of the packet aliasing engine will be cleared. This operating mode is useful for .Xr ppp 8 links where the interface address can sometimes change or remain the same between dial-up attempts. If this mode bit is not set, the link table will never be reset in the event of an address change. .It Dv PKT_ALIAS_PUNCH_FW This option makes .Nm .Dq punch holes in an .Xr ipfirewall 4 - based firewall for FTP/IRC DCC connections. The holes punched are bound by from/to IP address and port; it will not be possible to use a hole for another connection. A hole is removed when the connection that uses it dies. To cater to unexpected death of a program using .Nm (e.g.\& kill -9), changing the state of the flag will clear the entire firewall range allocated for holes. This clearing will also happen on the initial call to .Fn LibAliasSetFWBase , which must happen prior to setting this flag. .It Dv PKT_ALIAS_REVERSE This option makes .Nm reverse the way it handles incoming and outgoing packets, allowing it to be fed with data that passes through the internal interface rather than the external one. .It Dv PKT_ALIAS_PROXY_ONLY This option tells .Nm to obey transparent proxy rules only. Normal packet aliasing is not performed. See .Fn LibAliasProxyRule below for details. .It Dv PKT_ALIAS_SKIP_GLOBAL This option is used by .Pa ipfw_nat only. Specifying it as a flag to .Fn LibAliasSetMode has no effect. See section .Sx NETWORK ADDRESS TRANSLATION in .Xr ipfw 8 for more details. .El .Ed .Pp .Ft void .Fn LibAliasSetFWBase "struct libalias *" "unsigned int base" "unsigned int num" .Bd -ragged -offset indent Set the firewall range allocated for punching firewall holes (with the .Dv PKT_ALIAS_PUNCH_FW flag). The range is cleared for all rules on initialization. .Ed .Pp .Ft void .Fn LibAliasSkinnyPort "struct libalias *" "unsigned int port" .Bd -ragged -offset indent Set the TCP port used by the Skinny Station protocol. Skinny is used by Cisco IP phones to communicate with Cisco Call Managers to set up voice over IP calls. If this is not set, Skinny aliasing will not be done. The typical port used by Skinny is 2000. .Ed .Sh PACKET HANDLING The packet handling functions are used to modify incoming (remote to local) and outgoing (local to remote) packets. The calling program is responsible for receiving and sending packets via network interfaces. .Pp Along with .Fn LibAliasInit and .Fn LibAliasSetAddress , the two packet handling functions, .Fn LibAliasIn and .Fn LibAliasOut , comprise the minimal set of functions needed for a basic IP masquerading implementation. .Pp .Ft int .Fn LibAliasIn "struct libalias *" "void *buffer" "int maxpacketsize" .Bd -ragged -offset indent An incoming packet coming from a remote machine to the local network is de-aliased by this function. The IP packet is pointed to by .Fa buffer , and .Fa maxpacketsize indicates the size of the data structure containing the packet and should be at least as large as the actual packet size. .Pp Return codes: .Bl -tag -width indent .It Dv PKT_ALIAS_OK The packet aliasing process was successful. .It Dv PKT_ALIAS_IGNORED The packet was ignored and not de-aliased. This can happen if the protocol is unrecognized, as for an ICMP message type that is not handled, or if incoming packets for new connections are being ignored (if the .Dv PKT_ALIAS_DENY_INCOMING mode bit was set using .Fn LibAliasSetMode ) . .It Dv PKT_ALIAS_UNRESOLVED_FRAGMENT This is returned when a fragment cannot be resolved because the header fragment has not been sent yet. In this situation, fragments must be saved with .Fn LibAliasSaveFragment until a header fragment is found. .It Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT The packet aliasing process was successful, and a header fragment was found. This is a signal to retrieve any unresolved fragments with .Fn LibAliasGetFragment and de-alias them with .Fn LibAliasFragmentIn . .It Dv PKT_ALIAS_ERROR An internal error within the packet aliasing engine occurred. .El .Ed .Pp .Ft int .Fn LibAliasOut "struct libalias *" "void *buffer" "int maxpacketsize" .Bd -ragged -offset indent An outgoing packet coming from the local network to a remote machine is aliased by this function. The IP packet is pointed to by .Fa buffer , and .Fa maxpacketsize indicates the maximum packet size permissible should the packet length be changed. IP encoding protocols place address and port information in the encapsulated data stream which has to be modified and can account for changes in packet length. Well known examples of such protocols are FTP and IRC DCC. .Pp Return codes: .Bl -tag -width indent .It Dv PKT_ALIAS_OK The packet aliasing process was successful. .It Dv PKT_ALIAS_IGNORED The packet was ignored and not aliased. This can happen if the protocol is unrecognized, or possibly an ICMP message type is not handled. .It Dv PKT_ALIAS_ERROR An internal error within the packet aliasing engine occurred. .El .Ed .Sh PORT AND ADDRESS REDIRECTION The functions described in this section allow machines on the local network to be accessible in some degree to new incoming connections from the external network. Individual ports can be re-mapped or static network address translations can be designated. .Pp .Ft struct alias_link * .Fo LibAliasRedirectPort .Fa "struct libalias *" .Fa "struct in_addr local_addr" .Fa "u_short local_port" .Fa "struct in_addr remote_addr" .Fa "u_short remote_port" .Fa "struct in_addr alias_addr" .Fa "u_short alias_port" .Fa "u_char proto" .Fc .Bd -ragged -offset indent This function specifies that traffic from a given remote address/port to an alias address/port be redirected to a specified local address/port. The parameter .Fa proto can be either .Dv IPPROTO_TCP or .Dv IPPROTO_UDP , as defined in .In netinet/in.h . .Pp If .Fa local_addr or .Fa alias_addr is zero, this indicates that the packet aliasing address as established by .Fn LibAliasSetAddress is to be used. Even if .Fn LibAliasSetAddress is called to change the address after .Fn LibAliasRedirectPort is called, a zero reference will track this change. .Pp If the link is further set up to operate with load sharing, then .Fa local_addr and .Fa local_port are ignored, and are selected dynamically from the server pool, as described in .Fn LibAliasAddServer below. .Pp If .Fa remote_addr is zero, this indicates to redirect packets from any remote address. Likewise, if .Fa remote_port is zero, this indicates to redirect packets originating from any remote port number. The remote port specification will almost always be zero, but non-zero remote addresses can sometimes be useful for firewalling. If two calls to .Fn LibAliasRedirectPort overlap in their address/port specifications, then the most recent call will have precedence. .Pp This function returns a pointer which can subsequently be used by .Fn LibAliasRedirectDelete . If .Dv NULL is returned, then the function call did not complete successfully. .Pp All port numbers should be in network address byte order, so it is necessary to use .Xr htons 3 to convert these parameters from internally readable numbers to network byte order. Addresses are also in network byte order, which is implicit in the use of the .Fa struct in_addr data type. .Ed .Pp .Ft struct alias_link * .Fo LibAliasRedirectAddr .Fa "struct libalias *" .Fa "struct in_addr local_addr" .Fa "struct in_addr alias_addr" .Fc .Bd -ragged -offset indent This function designates that all incoming traffic to .Fa alias_addr be redirected to .Fa local_addr . Similarly, all outgoing traffic from .Fa local_addr is aliased to .Fa alias_addr . .Pp If .Fa local_addr or .Fa alias_addr is zero, this indicates that the packet aliasing address as established by .Fn LibAliasSetAddress is to be used. Even if .Fn LibAliasSetAddress is called to change the address after .Fn LibAliasRedirectAddr is called, a zero reference will track this change. .Pp If the link is further set up to operate with load sharing, then the .Fa local_addr argument is ignored, and is selected dynamically from the server pool, as described in .Fn LibAliasAddServer below. .Pp If subsequent calls to .Fn LibAliasRedirectAddr use the same aliasing address, all new incoming traffic to this aliasing address will be redirected to the local address made in the last function call. New traffic generated by any of the local machines, designated in the several function calls, will be aliased to the same address. Consider the following example: .Pp LibAliasRedirectAddr(la, inet_aton("192.168.0.2"), inet_aton("141.221.254.101")); LibAliasRedirectAddr(la, inet_aton("192.168.0.3"), inet_aton("141.221.254.101")); LibAliasRedirectAddr(la, inet_aton("192.168.0.4"), inet_aton("141.221.254.101")); .Pp Any outgoing connections such as .Xr telnet 1 or .Xr ftp 1 from 192.168.0.2, 192.168.0.3 and 192.168.0.4 will appear to come from 141.221.254.101. Any incoming connections to 141.221.254.101 will be directed to 192.168.0.4. .Pp Any calls to .Fn LibAliasRedirectPort will have precedence over address mappings designated by .Fn LibAliasRedirectAddr . .Pp This function returns a pointer which can subsequently be used by .Fn LibAliasRedirectDelete . If .Dv NULL is returned, then the function call did not complete successfully. .Ed .Pp .Ft int .Fo LibAliasAddServer .Fa "struct libalias *" .Fa "struct alias_link *link" .Fa "struct in_addr addr" .Fa "u_short port" .Fc .Bd -ragged -offset indent This function sets the .Fa link up for Load Sharing using IP Network Address Translation (RFC 2391, LSNAT). LSNAT operates as follows. A client attempts to access a server by using the server virtual address. The LSNAT router transparently redirects the request to one of the hosts in the server pool, using a real-time load sharing algorithm. Multiple sessions may be initiated from the same client, and each session could be directed to a different host based on the load balance across server pool hosts when the sessions are initiated. If load sharing is desired for just a few specific services, the configuration on LSNAT could be defined to restrict load sharing to just the services desired. .Pp Currently, only the simplest selection algorithm is implemented, where a host is selected on a round-robin basis only, without regard to load on the host. .Pp First, the .Fa link is created by either .Fn LibAliasRedirectPort or .Fn LibAliasRedirectAddr . Then, .Fn LibAliasAddServer is called multiple times to add entries to the .Fa link Ns 's server pool. .Pp For links created with .Fn LibAliasRedirectAddr , the .Fa port argument is ignored and could have any value, e.g.\& htons(~0). .Pp This function returns 0 on success, \-1 otherwise. .Ed .Pp .Ft int .Fn LibAliasRedirectDynamic "struct libalias *" "struct alias_link *link" .Bd -ragged -offset indent This function marks the specified static redirect rule entered by .Fn LibAliasRedirectPort as dynamic. This can be used to e.g.\& dynamically redirect a single TCP connection, after which the rule is removed. Only fully specified links can be made dynamic. (See the .Sx STATIC AND DYNAMIC LINKS and .Sx PARTIALLY SPECIFIED ALIASING LINKS sections below for a definition of static vs.\& dynamic, and partially vs.\& fully specified links.) .Pp This function returns 0 on success, \-1 otherwise. .Ed .Pp .Ft void .Fn LibAliasRedirectDelete "struct libalias *" "struct alias_link *link" .Bd -ragged -offset indent This function will delete a specific static redirect rule entered by .Fn LibAliasRedirectPort or .Fn LibAliasRedirectAddr . The parameter .Fa link is the pointer returned by either of the redirection functions. If an invalid pointer is passed to .Fn LibAliasRedirectDelete , then a program crash or unpredictable operation could result, so care is needed when using this function. .Ed .Pp .Ft int .Fn LibAliasProxyRule "struct libalias *" "const char *cmd" .Bd -ragged -offset indent The passed .Fa cmd string consists of one or more pairs of words. The first word in each pair is a token and the second is the value that should be applied for that token. Tokens and their argument types are as follows: .Bl -tag -width indent .It Cm type encode_ip_hdr | encode_tcp_stream | no_encode In order to support transparent proxying, it is necessary to somehow pass the original address and port information into the new destination server. If .Cm encode_ip_hdr is specified, the original destination address and port are passed as an extra IP option. If .Cm encode_tcp_stream is specified, the original destination address and port are passed as the first piece of data in the TCP stream in the format .Dq Li DEST Ar IP port . .It Cm port Ar portnum Only packets with the destination port .Ar portnum are proxied. .It Cm server Ar host Ns Op : Ns Ar portnum This specifies the .Ar host and .Ar portnum that the data is to be redirected to. .Ar host must be an IP address rather than a DNS host name. If .Ar portnum is not specified, the destination port number is not changed. .Pp The .Ar server specification is mandatory unless the .Cm delete command is being used. .It Cm rule Ar index Normally, each call to .Fn LibAliasProxyRule inserts the next rule at the start of a linear list of rules. If an .Ar index is specified, the new rule will be checked after all rules with lower indices. Calls to .Fn LibAliasProxyRule that do not specify a rule are assigned rule 0. .It Cm delete Ar index This token and its argument MUST NOT be used with any other tokens. When used, all existing rules with the given .Ar index are deleted. .It Cm proto tcp | udp If specified, only packets of the given protocol type are matched. .It Cm src Ar IP Ns Op / Ns Ar bits If specified, only packets with a source address matching the given .Ar IP are matched. If .Ar bits is also specified, then the first .Ar bits bits of .Ar IP are taken as a network specification, and all IP addresses from that network will be matched. .It Cm dst Ar IP Ns Op / Ns Ar bits If specified, only packets with a destination address matching the given .Ar IP are matched. If .Ar bits is also specified, then the first .Ar bits bits of .Ar IP are taken as a network specification, and all IP addresses from that network will be matched. .El .Pp This function is usually used to redirect outgoing connections for internal machines that are not permitted certain types of internet access, or to restrict access to certain external machines. .Ed .Pp .Ft struct alias_link * .Fo LibAliasRedirectProto .Fa "struct libalias *" .Fa "struct in_addr local_addr" .Fa "struct in_addr remote_addr" .Fa "struct in_addr alias_addr" .Fa "u_char proto" .Fc .Bd -ragged -offset indent This function specifies that any IP packet with protocol number of .Fa proto from a given remote address to an alias address will be redirected to a specified local address. .Pp If .Fa local_addr or .Fa alias_addr is zero, this indicates that the packet aliasing address as established by .Fn LibAliasSetAddress is to be used. Even if .Fn LibAliasSetAddress is called to change the address after .Fn LibAliasRedirectProto is called, a zero reference will track this change. .Pp If .Fa remote_addr is zero, this indicates to redirect packets from any remote address. Non-zero remote addresses can sometimes be useful for firewalling. .Pp If two calls to .Fn LibAliasRedirectProto overlap in their address specifications, then the most recent call will have precedence. .Pp This function returns a pointer which can subsequently be used by .Fn LibAliasRedirectDelete . If .Dv NULL is returned, then the function call did not complete successfully. .Ed .Sh FRAGMENT HANDLING The functions in this section are used to deal with incoming fragments. .Pp Outgoing fragments are handled within .Fn LibAliasOut by changing the address according to any applicable mapping set by .Fn LibAliasRedirectAddr , or the default aliasing address set by .Fn LibAliasSetAddress . .Pp Incoming fragments are handled in one of two ways. If the header of a fragmented IP packet has already been seen, then all subsequent fragments will be re-mapped in the same manner the header fragment was. Fragments which arrive before the header are saved and then retrieved once the header fragment has been resolved. .Pp .Ft int .Fn LibAliasSaveFragment "struct libalias *" "void *ptr" .Bd -ragged -offset indent When .Fn LibAliasIn returns .Dv PKT_ALIAS_UNRESOLVED_FRAGMENT , this function can be used to save the pointer to the unresolved fragment. .Pp It is implicitly assumed that .Fa ptr points to a block of memory allocated by .Xr malloc 3 . If the fragment is never resolved, the packet aliasing engine will automatically free the memory after a timeout period. [Eventually this function should be modified so that a callback function for freeing memory is passed as an argument.] .Pp This function returns .Dv PKT_ALIAS_OK if it was successful and .Dv PKT_ALIAS_ERROR if there was an error. .Ed .Pp .Ft void * .Fn LibAliasGetFragment "struct libalias *" "void *buffer" .Bd -ragged -offset indent This function can be used to retrieve fragment pointers saved by .Fn LibAliasSaveFragment . The IP header fragment pointed to by .Fa buffer is the header fragment indicated when .Fn LibAliasIn returns .Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT . Once a fragment pointer is retrieved, it becomes the calling program's responsibility to free the dynamically allocated memory for the fragment. .Pp The .Fn LibAliasGetFragment function can be called sequentially until there are no more fragments available, at which time it returns .Dv NULL . .Ed .Pp .Ft void .Fn LibAliasFragmentIn "struct libalias *" "void *header" "void *fragment" .Bd -ragged -offset indent When a fragment is retrieved with .Fn LibAliasGetFragment , it can then be de-aliased with a call to .Fn LibAliasFragmentIn . The .Fa header argument is the pointer to a header fragment used as a template, and .Fa fragment is the pointer to the packet to be de-aliased. .Ed .Sh MISCELLANEOUS FUNCTIONS .Ft struct alias_link * .Fn AddLink "struct libalias *" "struct in_addr src_addr" "struct in_addr dst_addr" \ "struct in_addr alias_addr" "u_short src_port" "u_short dst_port" \ "int alias_param" "int link_type" .Bd -ragged -offset indent This function adds new state to the instance hash table. The dst_address and/or dst_port may be given as zero, which introduces some dynamic character into the link, since LibAliasSetAddress can change the address that is used. However, in the current implementation, such links can only be used for inbound (ext -> int) traffic. .Ed .Pp .Ft void .Fn LibAliasSetTarget "struct libalias *" "struct in_addr addr" .Bd -ragged -offset indent When an incoming packet not associated with any pre-existing aliasing link arrives at the host machine, it will be sent to the address indicated by a call to .Fn LibAliasSetTarget . .Pp If this function is called with an .Dv INADDR_NONE address argument, then all new incoming packets go to the address set by .Fn LibAliasSetAddress . .Pp If this function is not called, or is called with an .Dv INADDR_ANY address argument, then all new incoming packets go to the address specified in the packet. This allows external machines to talk directly to internal machines if they can route packets to the machine in question. .Ed .Pp -.Ft int -.Fn LibAliasCheckNewLink "struct libalias *" -.Bd -ragged -offset indent -This function returns a non-zero value when a new aliasing link is created. -In circumstances where incoming traffic is being sequentially sent to -different local servers, this function can be used to trigger when -.Fn LibAliasSetTarget -is called to change the default target address. -.Ed -.Pp .Ft u_short .Fn LibAliasInternetChecksum "struct libalias *" "u_short *buffer" "int nbytes" .Bd -ragged -offset indent This is a utility function that does not seem to be available elsewhere and is included as a convenience. It computes the internet checksum, which is used in both IP and protocol-specific headers (TCP, UDP, ICMP). .Pp The .Fa buffer argument points to the data block to be checksummed, and .Fa nbytes is the number of bytes. The 16-bit checksum field should be zeroed before computing the checksum. .Pp Checksums can also be verified by operating on a block of data including its checksum. If the checksum is valid, .Fn LibAliasInternetChecksum will return zero. .Ed .Pp .Ft int .Fn LibAliasUnaliasOut "struct libalias *" "void *buffer" "int maxpacketsize" .Bd -ragged -offset indent An outgoing packet, which has already been aliased, has its private address/port information restored by this function. The IP packet is pointed to by .Fa buffer , and .Fa maxpacketsize is provided for error checking purposes. This function can be used if an already-aliased packet needs to have its original IP header restored for further processing (e.g.\& logging). .Ed .Sh CONCEPTUAL BACKGROUND This section is intended for those who are planning to modify the source code or want to create somewhat esoteric applications using the packet aliasing functions. .Pp The conceptual framework under which the packet aliasing engine operates is described here. Central to the discussion is the idea of an .Em aliasing link which describes the relationship for a given packet transaction between the local machine, aliased identity and remote machine. It is discussed how such links come into existence and are destroyed. .Ss ALIASING LINKS There is a notion of an .Em aliasing link , which is a 7-tuple describing a specific translation: .Bd -literal -offset indent (local addr, local port, alias addr, alias port, remote addr, remote port, protocol) .Ed .Pp Outgoing packets have the local address and port number replaced with the alias address and port number. Incoming packets undergo the reverse process. The packet aliasing engine attempts to match packets against an internal table of aliasing links to determine how to modify a given IP packet. Both the IP header and protocol dependent headers are modified as necessary. Aliasing links are created and deleted as necessary according to network traffic. .Pp Protocols can be TCP, UDP or even ICMP in certain circumstances. (Some types of ICMP packets can be aliased according to sequence or ID number which acts as an equivalent port number for identifying how individual packets should be handled.) .Pp Each aliasing link must have a unique combination of the following five quantities: alias address/port, remote address/port and protocol. This ensures that several machines on a local network can share the same aliasing IP address. In cases where conflicts might arise, the aliasing port is chosen so that uniqueness is maintained. .Ss STATIC AND DYNAMIC LINKS Aliasing links can either be static or dynamic. Static links persist indefinitely and represent fixed rules for translating IP packets. Dynamic links come into existence for a specific TCP connection or UDP transaction or ICMP ECHO sequence. For the case of TCP, the connection can be monitored to see when the associated aliasing link should be deleted. Aliasing links for UDP transactions (and ICMP ECHO and TIMESTAMP requests) work on a simple timeout rule. When no activity is observed on a dynamic link for a certain amount of time it is automatically deleted. Timeout rules also apply to TCP connections which do not open or close properly. .Ss PARTIALLY SPECIFIED ALIASING LINKS Aliasing links can be partially specified, meaning that the remote address and/or remote port are unknown. In this case, when a packet matching the incomplete specification is found, a fully specified dynamic link is created. If the original partially specified link is dynamic, it will be deleted after the fully specified link is created, otherwise it will persist. .Pp For instance, a partially specified link might be .Bd -literal -offset indent (192.168.0.4, 23, 204.228.203.215, 8066, 0, 0, tcp) .Ed .Pp The zeros denote unspecified components for the remote address and port. If this link were static it would have the effect of redirecting all incoming traffic from port 8066 of 204.228.203.215 to port 23 (telnet) of machine 192.168.0.4 on the local network. Each individual telnet connection would initiate the creation of a distinct dynamic link. .Ss DYNAMIC LINK CREATION In addition to aliasing links, there are also address mappings that can be stored within the internal data table of the packet aliasing mechanism. .Bd -literal -offset indent (local addr, alias addr) .Ed .Pp Address mappings are searched when creating new dynamic links. .Pp All outgoing packets from the local network automatically create a dynamic link if they do not match an already existing fully specified link. If an address mapping exists for the outgoing packet, this determines the alias address to be used. If no mapping exists, then a default address, usually the address of the packet aliasing host, is used. If necessary, this default address can be changed as often as each individual packet arrives. .Pp The aliasing port number is determined such that the new dynamic link does not conflict with any existing links. In the default operating mode, the packet aliasing engine attempts to set the aliasing port equal to the local port number. If this results in a conflict, then port numbers are randomly chosen until a unique aliasing link can be established. In an alternate operating mode, the first choice of an aliasing port is also random and unrelated to the local port number. .Sh MODULAR ARCHITECTURE Po AND Xr ipfw 4 SUPPORT Pc One of the latest improvements to .Nm was to make its support for new protocols independent from the rest of the library, giving it the ability to load/unload support for new protocols at run-time. To achieve this feature, all the code for protocol handling was moved to a series of modules outside of the main library. These modules are compiled from the same sources but work in different ways, depending on whether they are compiled to work inside a kernel or as part of the userland library. .Ss LIBALIAS MODULES IN KERNEL LAND When compiled for the kernel, .Nm modules are plain KLDs recognizable with the .Pa alias_ prefix. .Pp To add support for a new protocol, load the corresponding module. For example: .Pp .Dl "kldload alias_ftp" .Pp When support for a protocol is no longer needed, its module can be unloaded: .Pp .Dl "kldunload alias_ftp" .Ss LIBALIAS MODULES IN USERLAND Due to the differences between kernel and userland (no KLD mechanism, many different address spaces, etc.), we had to change a bit how to handle module loading/tracking/unloading in userland. .Pp While compiled for a userland .Nm , all the modules are plain libraries, residing in .Pa /usr/lib , and recognizable with the .Pa libalias_ prefix. .Pp There is a configuration file, .Pa /etc/libalias.conf , with the following contents (by default): .Bd -literal -offset indent /usr/lib/libalias_ftp.so /usr/lib/libalias_irc.so /usr/lib/libalias_nbt.so /usr/lib/libalias_pptp.so /usr/lib/libalias_skinny.so /usr/lib/libalias_smedia.so .Ed .Pp This file contains the paths to the modules that .Nm will load. To load/unload a new module, just add its path to .Pa libalias.conf and call .Fn LibAliasRefreshModules from the program. In case the application provides a .Dv SIGHUP signal handler, add a call to .Fn LibAliasRefreshModules inside the handler, and every time you want to refresh the loaded modules, send it the .Dv SIGHUP signal: .Pp .Dl "kill -HUP " .Ss MODULAR ARCHITECURE: HOW IT WORKS The modular architecture of .Nm works similar whether it is running inside the kernel or in userland. From .Pa alias_mod.c : .Bd -literal /* Protocol and userland module handlers chains. */ LIST_HEAD(handler_chain, proto_handler) handler_chain ... \&... SLIST_HEAD(dll_chain, dll) dll_chain ... .Ed .Pp .Va handler_chain keeps track of all the protocol handlers loaded, while .Va ddl_chain tracks which userland modules are loaded. .Pp .Va handler_chain is composed of .Vt "struct proto_handler" entries: .Bd -literal struct proto_handler { u_int pri; int16_t dir; uint8_t proto; int (*fingerprint)(struct libalias *la, struct ip *pip, struct alias_data *ah); int (*protohandler)(struct libalias *la, struct ip *pip, struct alias_data *ah); TAILQ_ENTRY(proto_handler) link; }; .Ed .Pp where: .Bl -inset .It Va pri is the priority assigned to a protocol handler; lower priority is better. .It Va dir is the direction of packets: ingoing or outgoing. .It Va proto indicates to which protocol this packet belongs: IP, TCP or UDP. .It Va fingerprint points to the fingerprint function while protohandler points to the protocol handler function. .El .Pp The .Va fingerprint function has the dual role of checking if the incoming packet is found, and if it belongs to any categories that this module can handle. .Pp The .Va protohandler function actually manipulates the packet to make .Nm correctly NAT it. .Pp When a packet enters .Nm , if it meets a module hook, .Va handler_chain is searched to see if there is an handler that matches this type of a packet (it checks protocol and direction of packet). Then, if more than one handler is found, it starts with the module with the lowest priority number: it calls the .Va fingerprint function and interprets the result. .Pp If the result value is equal to 0 then it calls the protocol handler of this handler and returns. Otherwise, it proceeds to the next eligible module until the .Va handler_chain is exhausted. .Pp Inside .Nm , the module hook looks like this: .Bd -literal -offset indent struct alias_data ad = { lnk, &original_address, &alias_address, &alias_port, &ud->uh_sport, /* original source port */ &ud->uh_dport, /* original dest port */ 256 /* maxpacketsize */ }; \&... /* walk out chain */ err = find_handler(IN, UDP, la, pip, &ad); .Ed .Pp All data useful to a module are gathered together in an .Vt alias_data structure, then .Fn find_handler is called. The .Fn find_handler function is responsible for walking the handler chain; it receives as input parameters: .Bl -tag -width indent .It Fa IN direction .It Fa UDP working protocol .It Fa la pointer to this instance of libalias .It Fa pip pointer to a .Vt "struct ip" .It Fa ad pointer to .Vt "struct alias_data" (see above) .El .Pp In this case, .Fn find_handler will search only for modules registered for supporting INcoming UDP packets. .Pp As was mentioned earlier, .Nm in userland is a bit different, as care must be taken in module handling as well (avoiding duplicate load of modules, avoiding modules with same name, etc.) so .Va dll_chain was introduced. .Pp .Va dll_chain contains a list of all userland .Nm modules loaded. .Pp When an application calls .Fn LibAliasRefreshModules , .Nm first unloads all the loaded modules, then reloads all the modules listed in .Pa /etc/libalias.conf : for every module loaded, a new entry is added to .Va dll_chain . .Pp .Va dll_chain is composed of .Vt "struct dll" entries: .Bd -literal struct dll { /* name of module */ char name[DLL_LEN]; /* * ptr to shared obj obtained through * dlopen() - use this ptr to get access * to any symbols from a loaded module * via dlsym() */ void *handle; struct dll *next; }; .Ed .Bl -inset .It Va name is the name of the module. .It Va handle is a pointer to the module obtained through .Xr dlopen 3 . .El Whenever a module is loaded in userland, an entry is added to .Va dll_chain , then every protocol handler present in that module is resolved and registered in .Va handler_chain . .Ss HOW TO WRITE A MODULE FOR LIBALIAS There is a module (called .Pa alias_dummy.[ch] ) in .Nm that can be used as a skeleton for future work. Here we analyse some parts of that module. From .Pa alias_dummy.c : .Bd -literal struct proto_handler handlers[] = { { .pri = 666, .dir = IN|OUT, .proto = UDP|TCP, .fingerprint = fingerprint, .protohandler= protohandler, }, { EOH } }; .Ed .Pp The variable .Va handlers is the .Dq "most important thing" in a module since it describes the handlers present and lets the outside world use it in an opaque way. .Pp It must ALWAYS be present in every module, and it MUST retain the name .Va handlers , otherwise attempting to load a module in userland will fail and complain about missing symbols: for more information about module load/unload, please refer to .Fn LibAliasRefreshModules , .Fn LibAliasLoadModule and .Fn LibAliasUnloadModule in .Pa alias.c . .Pp .Va handlers contains all the .Vt proto_handler structures present in a module. .Bd -literal static int mod_handler(module_t mod, int type, void *data) { int error; switch (type) { case MOD_LOAD: error = LibAliasAttachHandlers(handlers); break; case MOD_UNLOAD: error = LibAliasDetachHandlers(handlers); break; default: error = EINVAL; } return (error); } .Ed When running as KLD, .Fn mod_handler registers/deregisters the module using .Fn LibAliasAttachHandlers and .Fn LibAliasDetachHandlers , respectively. .Pp Every module must contain at least 2 functions: one fingerprint function and a protocol handler function. .Bd -literal #ifdef _KERNEL static #endif int fingerprint(struct libalias *la, struct ip *pip, struct alias_data *ah) { \&... } #ifdef _KERNEL static #endif int protohandler(struct libalias *la, struct ip *pip, struct alias_data *ah) { \&... } .Ed and they must accept exactly these input parameters. .Ss PATCHING AN APPLICATION FOR USERLAND LIBALIAS MODULES To add module support into an application that uses .Nm , the following simple steps can be followed. .Bl -enum .It Find the main file of an application (let us call it .Pa main.c ) . .It Add this to the header section of .Pa main.c , if not already present: .Pp .Dl "#include " .Pp and this just after the header section: .Pp .Dl "static void signal_handler(int);" .It Add the following line to the init function of an application or, if it does not have any init function, put it in .Fn main : .Pp .Dl "signal(SIGHUP, signal_handler);" .Pp and place the .Fn signal_handler function somewhere in .Pa main.c : .Bd -literal -offset indent static void signal_handler(int sig) { LibAliasRefreshModules(); } .Ed .Pp Otherwise, if an application already traps the .Dv SIGHUP signal, just add a call to .Fn LibAliasRefreshModules in the signal handler function. .El For example, to patch .Xr natd 8 to use .Nm modules, just add the following line to .Fn RefreshAddr "int sig __unused" : .Pp .Dl "LibAliasRefreshModules()" .Pp recompile and you are done. .Ss LOGGING SUPPORT IN KERNEL LAND When working as KLD, .Nm now has log support that happens on a buffer allocated inside .Vt "struct libalias" (from .Pa alias_local.h ) : .Bd -literal struct libalias { ... /* log descriptor */ #ifdef KERNEL_LOG char *logDesc; /* * ptr to an auto-malloced * memory buffer when libalias * works as kld */ #else FILE *logDesc; /* * ptr to /var/log/alias.log * when libalias runs as a * userland lib */ #endif ... } .Ed so all applications using .Nm will be able to handle their own logs, if they want, accessing .Va logDesc . Moreover, every change to a log buffer is automatically added to .Xr syslog 3 with the .Dv LOG_SECURITY facility and the .Dv LOG_INFO level. .Sh AUTHORS .An Charles Mott Aq cm@linktel.net , versions 1.0 - 1.8, 2.0 - 2.4. .An Eivind Eklund Aq eivind@FreeBSD.org , versions 1.8b, 1.9 and 2.5. Added IRC DCC support as well as contributing a number of architectural improvements; added the firewall bypass for FTP/IRC DCC. .An Erik Salander Aq erik@whistle.com added support for PPTP and RTSP. .An Junichi Satoh Aq junichi@junichi.org added support for RTSP/PNA. .An Ruslan Ermilov Aq ru@FreeBSD.org added support for PPTP and LSNAT as well as general hacking. .An Gleb Smirnoff Aq glebius@FreeBSD.org ported the library to kernel space. .An Paolo Pisati Aq piso@FreeBSD.org made the library modular, moving support for all protocols (except for IP, TCP and UDP) to external modules. .Sh ACKNOWLEDGEMENTS Listed below, in approximate chronological order, are individuals who have provided valuable comments and/or debugging assistance. .Bd -ragged -offset indent .An -split .An Gary Roberts .An Tom Torrance .An Reto Burkhalter .An Martin Renters .An Brian Somers .An Paul Traina .An Ari Suutari .An Dave Remien .An J. Fortes .An Andrzej Bialecki .An Gordon Burditt .Ed