|
NAMElibalias —
packet aliasing library for masquerading and network address
translation
SYNOPSIS#include <sys/types.h>
#include <netinet/in.h>
#include <alias.h>
Function prototypes are given in the main body of the text. DESCRIPTIONThelibalias library is a collection of functions for
aliasing and de-aliasing of IP packets, intended for masquerading and network
address translation (NAT).
INTRODUCTIONThis 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.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. INITIALIZATION AND CONTROLOne special function,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
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
LibAliasSetMode ().
struct libalias *
This function is used to initialize internal data
structures. When called the first time, a
NULL pointer
should be passed as an argument. The following mode bits are always set after
calling LibAliasInit (). See the description of
LibAliasSetMode () below for the meaning of these mode
bits.
This function will always return the packet aliasing engine to the
same initial state. The It is mandatory that this function be called at the beginning of a program prior to any packet handling. void
This function has no return value and is used to
clear any resources attached to internal data structures.
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
atexit(3)
chain by void
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
LibAliasRedirectAddr (). If this
function has not been called, and no static rules match, an outgoing packet
retains its source address.
If the If the It is mandatory that this function be called prior to any packet handling. unsigned int
This function sets or clears mode bits according to
the value of flags. Only bits marked in
mask are affected. The following mode bits are defined
in
<alias.h> :
void
Set the firewall range allocated for punching
firewall holes (with the
PKT_ALIAS_PUNCH_FW flag). The
range is cleared for all rules on initialization.void
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.
PACKET HANDLINGThe 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.Along with int
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 buffer, and maxpacketsize
indicates the size of the data structure containing the packet and should be
at least as large as the actual packet size.
Return codes:
int
An outgoing packet coming from the local network to
a remote machine is aliased by this function. The IP packet is pointed to by
buffer, and 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.
Return codes:
PORT AND ADDRESS REDIRECTIONThe 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.struct alias_link *
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 proto can be either
IPPROTO_TCP or IPPROTO_UDP , as
defined in <netinet/in.h> .
If local_addr or
alias_addr is zero, this indicates that the packet
aliasing address as established by
If the link is further set up to operate with load sharing, then
local_addr and local_port are
ignored, and are selected dynamically from the server pool, as described in
If remote_addr is zero, this indicates to
redirect packets from any remote address. Likewise, if
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
This function returns a pointer which can subsequently be used by
All port numbers should be in network address byte order, so it is necessary to use 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 struct in_addr data type. struct alias_link *
This function designates that all incoming traffic
to alias_addr be redirected to
local_addr. Similarly, all outgoing traffic from
local_addr is aliased to
alias_addr.
If local_addr or
alias_addr is zero, this indicates that the packet
aliasing address as established by
If the link is further set up to operate with load sharing, then
the local_addr argument is ignored, and is selected
dynamically from the server pool, as described in
If subsequent calls to
LibAliasRedirectAddr(la, inet_aton("192.168.0.2"),
Any outgoing connections such as telnet(1) or 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. Any calls to This function returns a pointer which can subsequently be used by
int
This function sets the 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.
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. First, the link is created by either
For links created with
This function returns 0 on success, -1 otherwise. int
This function marks the specified static redirect
rule entered by
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 STATIC AND DYNAMIC
LINKS and
PARTIALLY SPECIFIED
ALIASING LINKS sections below for a definition of static vs. dynamic, and
partially vs. fully specified links.)
This function returns 0 on success, -1 otherwise. void
This function will delete a specific static
redirect rule entered by
LibAliasRedirectPort () or
LibAliasRedirectAddr (). The parameter
link is the pointer returned by either of the
redirection functions. If an invalid pointer is passed to
LibAliasRedirectDelete (), then a program crash or
unpredictable operation could result, so care is needed when using this
function.int
The passed 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:
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. struct alias_link *
This function specifies that any IP packet with
protocol number of proto from a given remote address to
an alias address will be redirected to a specified local address.
If local_addr or
alias_addr is zero, this indicates that the packet
aliasing address as established by
If remote_addr is zero, this indicates to redirect packets from any remote address. Non-zero remote addresses can sometimes be useful for firewalling. If two calls to This function returns a pointer which can subsequently be used by
FRAGMENT HANDLINGThe functions in this section are used to deal with incoming fragments.Outgoing fragments are handled within
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. int
When
LibAliasIn () returns
PKT_ALIAS_UNRESOLVED_FRAGMENT , this function can be
used to save the pointer to the unresolved fragment.
It is implicitly assumed that ptr points to a block of memory allocated by 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.] This function returns void *
This function can be used to retrieve fragment
pointers saved by
LibAliasSaveFragment (). The IP
header fragment pointed to by buffer is the header
fragment indicated when LibAliasIn () returns
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.
The void
When a fragment is retrieved with
LibAliasGetFragment (), it can then be de-aliased with
a call to LibAliasFragmentIn (). The
header argument is the pointer to a header fragment used
as a template, and fragment is the pointer to the packet
to be de-aliased.MISCELLANEOUS FUNCTIONSstruct alias_link *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)
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.
void
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
LibAliasSetTarget ().
If this function is called with an
If this function is not called, or is called with an
u_short
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).
The buffer argument points to the data block to be checksummed, and nbytes is the number of bytes. The 16-bit checksum field should be zeroed before computing the checksum. Checksums can also be verified by operating on a block of data
including its checksum. If the checksum is valid,
int
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 buffer, and
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).
CONCEPTUAL BACKGROUNDThis 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.The conceptual framework under which the packet aliasing engine operates is described here. Central to the discussion is the idea of an 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. ALIASING LINKSThere is a notion of an aliasing link, which is a 7-tuple describing a specific translation:(local addr, local port, alias addr, alias port, remote addr, remote port, protocol) 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. 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.) 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. STATIC AND DYNAMIC LINKSAliasing 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.PARTIALLY SPECIFIED ALIASING LINKSAliasing 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.For instance, a partially specified link might be (192.168.0.4, 23, 204.228.203.215, 8066, 0, 0, tcp) 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. DYNAMIC LINK CREATIONIn addition to aliasing links, there are also address mappings that can be stored within the internal data table of the packet aliasing mechanism.(local addr, alias addr) Address mappings are searched when creating new dynamic links. 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. 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. MODULAR ARCHITECTURE (AND ipfw(4) SUPPORT)One of the latest improvements tolibalias 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.
LIBALIAS MODULES IN KERNEL LANDWhen compiled for the kernel,libalias modules are plain
KLDs recognizable with the alias_ prefix.
To add support for a new protocol, load the corresponding module. For example: kldload alias_ftp When support for a protocol is no longer needed, its module can be unloaded: kldunload alias_ftp LIBALIAS MODULES IN USERLANDDue 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.While compiled for a userland There is a configuration file, /etc/libalias.conf, with the following contents (by default): /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 This file contains the paths to the modules that
kill -HUP
<process_pid> MODULAR ARCHITECURE: HOW IT WORKSThe modular architecture oflibalias works similar
whether it is running inside the kernel or in userland. From
alias_mod.c:
/* Protocol and userland module handlers chains. */ LIST_HEAD(handler_chain, proto_handler) handler_chain ... ... SLIST_HEAD(dll_chain, dll) dll_chain ... handler_chain keeps track of all the protocol handlers loaded, while ddl_chain tracks which userland modules are loaded. handler_chain is composed of struct proto_handler entries: 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; }; where:
The 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. The protohandler function actually
manipulates the packet to make When a packet enters 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 handler_chain is exhausted. Inside 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); All data useful to a module are gathered together in an
alias_data structure, then
In this case, As was mentioned earlier, dll_chain contains a list of all userland
When an application calls
dll_chain is composed of struct dll entries: 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; };
HOW TO WRITE A MODULE FOR LIBALIASThere is a module (called alias_dummy.[ch]) inlibalias that can be used as a skeleton for future
work. Here we analyse some parts of that module. From
alias_dummy.c:
struct proto_handler handlers[] = { { .pri = 666, .dir = IN|OUT, .proto = UDP|TCP, .fingerprint = fingerprint, .protohandler= protohandler, }, { EOH } }; The variable handlers is the “most important thing” in a module since it describes the handlers present and lets the outside world use it in an opaque way. It must ALWAYS be present in every module, and it MUST retain the
name 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
handlers contains all the proto_handler structures present in a module. 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); } mod_handler () registers/deregisters
the module using LibAliasAttachHandlers () and
LibAliasDetachHandlers (), respectively.
Every module must contain at least 2 functions: one fingerprint function and a protocol handler function. #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) { ... } PATCHING AN APPLICATION FOR USERLAND LIBALIAS MODULESTo add module support into an application that useslibalias , the following simple steps can be followed.
libalias modules, just add the following line to
RefreshAddr (int sig __unused):
LibAliasRefreshModules() recompile and you are done. LOGGING SUPPORT IN KERNEL LANDWhen working as KLD,libalias now has log support that
happens on a buffer allocated inside struct libalias
(from alias_local.h):
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 ... } libalias will be able to
handle their own logs, if they want, accessing logDesc.
Moreover, every change to a log buffer is automatically added to
syslog(3)
with the LOG_SECURITY facility and the
LOG_INFO level.
AUTHORSCharles Mott ⟨cm@linktel.net⟩, versions 1.0 - 1.8, 2.0 - 2.4.Eivind Eklund ⟨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. Erik Salander ⟨erik@whistle.com⟩ added support for PPTP and RTSP. Junichi Satoh ⟨junichi@junichi.org⟩ added support for RTSP/PNA. Ruslan Ermilov ⟨ru@FreeBSD.org⟩ added support for PPTP and LSNAT as well as general hacking. Gleb Smirnoff ⟨glebius@FreeBSD.org⟩ ported the library to kernel space. Paolo Pisati ⟨piso@FreeBSD.org⟩ made the library modular, moving support for all protocols (except for IP, TCP and UDP) to external modules. ACKNOWLEDGEMENTSListed below, in approximate chronological order, are individuals who have provided valuable comments and/or debugging assistance.Gary Roberts Tom Torrance Reto Burkhalter Martin Renters Brian Somers Paul Traina Ari Suutari Dave Remien J. Fortes Andrzej Bialecki Gordon Burditt
Visit the GSP FreeBSD Man Page Interface. |