1.\"- 2.\" Copyright (c) 2001 Charles Mott <cm@linktel.net> 3.\" All rights reserved. 4.\" 5.\" Redistribution and use in source and binary forms, with or without 6.\" modification, are permitted provided that the following conditions 7.\" are met: 8.\" 1. Redistributions of source code must retain the above copyright 9.\" notice, this list of conditions and the following disclaimer. 10.\" 2. Redistributions in binary form must reproduce the above copyright 11.\" notice, this list of conditions and the following disclaimer in the 12.\" documentation and/or other materials provided with the distribution. 13.\" 14.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24.\" SUCH DAMAGE. 25.\" 26.\" $FreeBSD$ 27.\" 28.Dd October 1, 2006 29.Dt LIBALIAS 3 30.Os 31.Sh NAME 32.Nm libalias 33.Nd packet aliasing library for masquerading and network address translation 34.Sh SYNOPSIS 35.In sys/types.h 36.In netinet/in.h 37.In alias.h 38.Pp 39Function prototypes are given in the main body of the text. 40.Sh DESCRIPTION 41The 42.Nm 43library is a collection of functions for aliasing and de-aliasing of IP 44packets, intended for masquerading and network address translation (NAT). 45.Sh INTRODUCTION 46This library is a moderately portable set of functions designed to assist 47in the process of IP masquerading and network address translation. 48Outgoing packets from a local network with unregistered IP addresses can 49be aliased to appear as if they came from an accessible IP address. 50Incoming packets are then de-aliased so that they are sent to the correct 51machine on the local network. 52.Pp 53A certain amount of flexibility is built into the packet aliasing engine. 54In the simplest mode of operation, a many-to-one address mapping takes 55place between local network and the packet aliasing host. 56This is known as IP masquerading. 57In addition, one-to-one mappings between local and public addresses can 58also be implemented, which is known as static NAT. 59In between these extremes, different groups of private addresses can be 60linked to different public addresses, comprising several distinct 61many-to-one mappings. 62Also, a given public address and port can be statically redirected to a 63private address/port. 64.Pp 65The packet aliasing engine was designed to operate in user space outside 66of the kernel, without any access to private kernel data structure, but 67the source code can also be ported to a kernel environment. 68.Sh INITIALIZATION AND CONTROL 69One special function, 70.Fn LibAliasInit , 71must always be called before any packet handling may be performed and 72the returned instance pointer passed to all the other functions. 73Normally, the 74.Fn LibAliasSetAddress 75function is called afterwards, to set the default aliasing address. 76In addition, the operating mode of the packet aliasing engine can be 77customized by calling 78.Fn LibAliasSetMode . 79.Pp 80.Ft "struct libalias *" 81.Fn LibAliasInit "struct libalias *" 82.Bd -ragged -offset indent 83This function is used to initialize 84internal data structures. 85When called the first time, a 86.Dv NULL 87pointer should be passed as an argument. 88The following mode bits are always set after calling 89.Fn LibAliasInit . 90See the description of 91.Fn LibAliasSetMode 92below for the meaning of these mode bits. 93.Pp 94.Bl -item -offset indent -compact 95.It 96.Dv PKT_ALIAS_SAME_PORTS 97.It 98.Dv PKT_ALIAS_USE_SOCKETS 99.It 100.Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE 101.El 102.Pp 103This function will always return the packet aliasing engine to the same 104initial state. 105The 106.Fn LibAliasSetAddress 107function is normally called afterwards, and any desired changes from the 108default mode bits listed above require a call to 109.Fn LibAliasSetMode . 110.Pp 111It is mandatory that this function be called at the beginning of a program 112prior to any packet handling. 113.Ed 114.Pp 115.Ft void 116.Fn LibAliasUninit "struct libalias *" 117.Bd -ragged -offset indent 118This function has no return value and is used to clear any 119resources attached to internal data structures. 120.Pp 121This functions should be called when a program stops using the aliasing 122engine; it does, amongst other things, clear out any firewall holes. 123To provide backwards compatibility and extra security, it is added to 124the 125.Xr atexit 3 126chain by 127.Fn LibAliasInit . 128.Ed 129.Pp 130.Ft void 131.Fn LibAliasSetAddress "struct libalias *" "struct in_addr addr" 132.Bd -ragged -offset indent 133This function sets the source address to which outgoing packets from the 134local area network are aliased. 135All outgoing packets are re-mapped to this address unless overridden by a 136static address mapping established by 137.Fn LibAliasRedirectAddr . 138If this function is not called, and no static rules match, an outgoing 139packet retains its source address. 140.Pp 141If the 142.Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE 143mode bit is set (the default mode of operation), then the internal aliasing 144link tables will be reset any time the aliasing address changes. 145This is useful for interfaces such as 146.Xr ppp 8 , 147where the IP 148address may or may not change on successive dial-up attempts. 149.Pp 150If the 151.Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE 152mode bit is set to zero, this function can also be used to dynamically change 153the aliasing address on a packet to packet basis (it is a low overhead call). 154.Pp 155It is mandatory that this function be called prior to any packet handling. 156.Ed 157.Pp 158.Ft unsigned int 159.Fn LibAliasSetMode "struct libalias *" "unsigned int flags" "unsigned int mask" 160.Bd -ragged -offset indent 161This function sets or clears mode bits 162according to the value of 163.Fa flags . 164Only bits marked in 165.Fa mask 166are affected. 167The following mode bits are defined in 168.In alias.h : 169.Bl -tag -width indent 170.It Dv PKT_ALIAS_LOG 171Enables logging into 172.Pa /var/log/alias.log . 173Each time an aliasing link is created or deleted, the log file is appended 174with the current number of ICMP, TCP and UDP links. 175Mainly useful for debugging when the log file is viewed continuously with 176.Xr tail 1 . 177.It Dv PKT_ALIAS_DENY_INCOMING 178If this mode bit is set, all incoming packets associated with new TCP 179connections or new UDP transactions will be marked for being ignored 180.Fn ( LibAliasIn 181returns 182.Dv PKT_ALIAS_IGNORED 183code) 184by the calling program. 185Response packets to connections or transactions initiated from the packet 186aliasing host or local network will be unaffected. 187This mode bit is useful for implementing a one-way firewall. 188.It Dv PKT_ALIAS_SAME_PORTS 189If this mode bit is set, the packet aliasing engine will attempt to leave 190the alias port numbers unchanged from the actual local port numbers. 191This can be done as long as the quintuple (proto, alias addr, alias port, 192remote addr, remote port) is unique. 193If a conflict exists, a new aliasing port number is chosen even if this 194mode bit is set. 195.It Dv PKT_ALIAS_USE_SOCKETS 196This bit should be set when the packet aliasing host originates network 197traffic as well as forwards it. 198When the packet aliasing host is waiting for a connection from an unknown 199host address or unknown port number (e.g.\& an FTP data connection), this 200mode bit specifies that a socket be allocated as a place holder to prevent 201port conflicts. 202Once a connection is established, usually within a minute or so, the socket 203is closed. 204.It Dv PKT_ALIAS_UNREGISTERED_ONLY 205If this mode bit is set, traffic on the local network which does not 206originate from unregistered address spaces will be ignored. 207Standard Class A, B and C unregistered addresses are: 208.Bd -literal -offset indent 20910.0.0.0 -> 10.255.255.255 (Class A subnet) 210172.16.0.0 -> 172.31.255.255 (Class B subnets) 211192.168.0.0 -> 192.168.255.255 (Class C subnets) 212.Ed 213.Pp 214This option is useful in the case that packet aliasing host has both 215registered and unregistered subnets on different interfaces. 216The registered subnet is fully accessible to the outside world, so traffic 217from it does not need to be passed through the packet aliasing engine. 218.It Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE 219When this mode bit is set and 220.Fn LibAliasSetAddress 221is called to change the aliasing address, the internal link table of the 222packet aliasing engine will be cleared. 223This operating mode is useful for 224.Xr ppp 8 225links where the interface address can sometimes change or remain the same 226between dial-up attempts. 227If this mode bit is not set, the link table will never be reset in the event 228of an address change. 229.It Dv PKT_ALIAS_PUNCH_FW 230This option makes 231.Nm 232`punch holes' in an 233.Xr ipfirewall 4 234based firewall for FTP/IRC DCC connections. 235The holes punched are bound by from/to IP address and port; it will not be 236possible to use a hole for another connection. 237A hole is removed when the connection that uses it dies. 238To cater to unexpected death of a program using 239.Nm 240(e.g.\& kill -9), 241changing the state of the flag will clear the entire firewall range 242allocated for holes. 243This will also happen on the initial call to 244.Fn LibAliasSetFWBase . 245This call must happen prior to setting this flag. 246.It Dv PKT_ALIAS_REVERSE 247This option makes 248.Nm 249reverse the way it handles incoming and outgoing packets, allowing it 250to be fed with data that passes through the internal interface rather 251than the external one. 252.It Dv PKT_ALIAS_PROXY_ONLY 253This option tells 254.Nm 255to obey transparent proxy rules only. 256Normal packet aliasing is not performed. 257See 258.Fn LibAliasProxyRule 259below for details. 260.El 261.Ed 262.Pp 263.Ft void 264.Fn LibAliasSetFWBase "struct libalias *" "unsigned int base" "unsigned int num" 265.Bd -ragged -offset indent 266Set firewall range allocated for punching firewall holes (with the 267.Dv PKT_ALIAS_PUNCH_FW 268flag). 269The range will be cleared for all rules on initialization. 270.Ed 271.Pp 272.Ft void 273.Fn LibAliasSkinnyPort "struct libalias *" "unsigned int port" 274.Bd -ragged -offset indent 275Set the TCP port used by the Skinny Station protocol. 276Skinny is used by Cisco IP phones to communicate with 277Cisco Call Managers to set up voice over IP calls. 278If this is not set, Skinny aliasing will not be done. 279The typical port used by Skinny is 2000. 280.Ed 281.Sh PACKET HANDLING 282The packet handling functions are used to modify incoming (remote to local) 283and outgoing (local to remote) packets. 284The calling program is responsible for receiving and sending packets via 285network interfaces. 286.Pp 287Along with 288.Fn LibAliasInit 289and 290.Fn LibAliasSetAddress , 291the two packet handling functions, 292.Fn LibAliasIn 293and 294.Fn LibAliasOut , 295comprise minimal set of functions needed for a basic IP masquerading 296implementation. 297.Pp 298.Ft int 299.Fn LibAliasIn "struct libalias *" "char *buffer" "int maxpacketsize" 300.Bd -ragged -offset indent 301An incoming packet coming from a remote machine to the local network is 302de-aliased by this function. 303The IP packet is pointed to by 304.Fa buffer , 305and 306.Fa maxpacketsize 307indicates the size of the data structure containing the packet and should 308be at least as large as the actual packet size. 309.Pp 310Return codes: 311.Bl -tag -width indent 312.It Dv PKT_ALIAS_OK 313The packet aliasing process was successful. 314.It Dv PKT_ALIAS_IGNORED 315The packet was ignored and not de-aliased. 316This can happen if the protocol is unrecognized, possibly an ICMP message 317type is not handled or if incoming packets for new connections are being 318ignored (if 319.Dv PKT_ALIAS_DENY_INCOMING 320mode bit was set by 321.Fn LibAliasSetMode ) . 322.It Dv PKT_ALIAS_UNRESOLVED_FRAGMENT 323This is returned when a fragment cannot be resolved because the header 324fragment has not been sent yet. 325In this situation, fragments must be saved with 326.Fn LibAliasSaveFragment 327until a header fragment is found. 328.It Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT 329The packet aliasing process was successful, and a header fragment was found. 330This is a signal to retrieve any unresolved fragments with 331.Fn LibAliasGetFragment 332and de-alias them with 333.Fn LibAliasFragmentIn . 334.It Dv PKT_ALIAS_ERROR 335An internal error within the packet aliasing engine occurred. 336.El 337.Ed 338.Pp 339.Ft int 340.Fn LibAliasOut "struct libalias *" "char *buffer" "int maxpacketsize" 341.Bd -ragged -offset indent 342An outgoing packet coming from the local network to a remote machine is 343aliased by this function. 344The IP packet is pointed to by 345.Fa buffer , 346and 347.Fa maxpacketsize 348indicates the maximum packet size permissible should the packet length be 349changed. 350IP encoding protocols place address and port information in the encapsulated 351data stream which has to be modified and can account for changes in packet 352length. 353Well known examples of such protocols are FTP and IRC DCC. 354.Pp 355Return codes: 356.Bl -tag -width indent 357.It Dv PKT_ALIAS_OK 358The packet aliasing process was successful. 359.It Dv PKT_ALIAS_IGNORED 360The packet was ignored and not aliased. 361This can happen if the protocol is unrecognized, or possibly an ICMP message 362type is not handled. 363.It Dv PKT_ALIAS_ERROR 364An internal error within the packet aliasing engine occurred. 365.El 366.Ed 367.Sh PORT AND ADDRESS REDIRECTION 368The functions described in this section allow machines on the local network 369to be accessible in some degree to new incoming connections from the external 370network. 371Individual ports can be re-mapped or static network address translations can 372be designated. 373.Pp 374.Ft struct alias_link * 375.Fo LibAliasRedirectPort 376.Fa "struct libalias *" 377.Fa "struct in_addr local_addr" 378.Fa "u_short local_port" 379.Fa "struct in_addr remote_addr" 380.Fa "u_short remote_port" 381.Fa "struct in_addr alias_addr" 382.Fa "u_short alias_port" 383.Fa "u_char proto" 384.Fc 385.Bd -ragged -offset indent 386This function specifies that traffic from a given remote address/port to 387an alias address/port be redirected to a specified local address/port. 388The parameter 389.Fa proto 390can be either 391.Dv IPPROTO_TCP 392or 393.Dv IPPROTO_UDP , 394as defined in 395.In netinet/in.h . 396.Pp 397If 398.Fa local_addr 399or 400.Fa alias_addr 401is zero, this indicates that the packet aliasing address as established 402by 403.Fn LibAliasSetAddress 404is to be used. 405Even if 406.Fn LibAliasSetAddress 407is called to change the address after 408.Fn LibAliasRedirectPort 409is called, a zero reference will track this change. 410.Pp 411If the link is further set up to operate for a load sharing, then 412.Fa local_addr 413and 414.Fa local_port 415are ignored, and are selected dynamically from the server pool, as described in 416.Fn LibAliasAddServer 417below. 418.Pp 419If 420.Fa remote_addr 421is zero, this indicates to redirect packets from any remote address. 422Likewise, if 423.Fa remote_port 424is zero, this indicates to redirect packets originating from any remote 425port number. 426Almost always, the remote port specification will be zero, but non-zero 427remote addresses can sometimes be useful for firewalling. 428If two calls to 429.Fn LibAliasRedirectPort 430overlap in their address/port specifications, then the most recent call 431will have precedence. 432.Pp 433This function returns a pointer which can subsequently be used by 434.Fn LibAliasRedirectDelete . 435If 436.Dv NULL 437is returned, then the function call did not complete successfully. 438.Pp 439All port numbers should be in network address byte order, so it is necessary 440to use 441.Xr htons 3 442to convert these parameters from internally readable numbers to network byte 443order. 444Addresses are also in network byte order, which is implicit in the use of the 445.Fa struct in_addr 446data type. 447.Ed 448.Pp 449.Ft struct alias_link * 450.Fo LibAliasRedirectAddr 451.Fa "struct libalias *" 452.Fa "struct in_addr local_addr" 453.Fa "struct in_addr alias_addr" 454.Fc 455.Bd -ragged -offset indent 456This function designates that all incoming traffic to 457.Fa alias_addr 458be redirected to 459.Fa local_addr . 460Similarly, all outgoing traffic from 461.Fa local_addr 462is aliased to 463.Fa alias_addr . 464.Pp 465If 466.Fa local_addr 467or 468.Fa alias_addr 469is zero, this indicates that the packet aliasing address as established by 470.Fn LibAliasSetAddress 471is to be used. 472Even if 473.Fn LibAliasSetAddress 474is called to change the address after 475.Fn LibAliasRedirectAddr 476is called, a zero reference will track this change. 477.Pp 478If the link is further set up to operate for a load sharing, then 479.Fa local_addr 480is ignored, and is selected dynamically from the server pool, as described in 481.Fn LibAliasAddServer 482below. 483.Pp 484If subsequent calls to 485.Fn LibAliasRedirectAddr 486use the same aliasing address, all new incoming traffic to this aliasing 487address will be redirected to the local address made in the last function 488call. 489New traffic generated by any of the local machines, designated in the 490several function calls, will be aliased to the same address. 491Consider the following example: 492.Bd -literal -offset indent 493LibAliasRedirectAddr(la, inet_aton("192.168.0.2"), 494 inet_aton("141.221.254.101")); 495LibAliasRedirectAddr(la, inet_aton("192.168.0.3"), 496 inet_aton("141.221.254.101")); 497LibAliasRedirectAddr(la, inet_aton("192.168.0.4"), 498 inet_aton("141.221.254.101")); 499.Ed 500.Pp 501Any outgoing connections such as 502.Xr telnet 1 503or 504.Xr ftp 1 505from 192.168.0.2, 192.168.0.3 and 192.168.0.4 will appear to come from 506141.221.254.101. 507Any incoming connections to 141.221.254.101 will be directed to 192.168.0.4. 508.Pp 509Any calls to 510.Fn LibAliasRedirectPort 511will have precedence over address mappings designated by 512.Fn LibAliasRedirectAddr . 513.Pp 514This function returns a pointer which can subsequently be used by 515.Fn LibAliasRedirectDelete . 516If 517.Dv NULL 518is returned, then the function call did not complete successfully. 519.Ed 520.Pp 521.Ft int 522.Fo LibAliasAddServer 523.Fa "struct libalias *" 524.Fa "struct alias_link *link" 525.Fa "struct in_addr addr" 526.Fa "u_short port" 527.Fc 528.Bd -ragged -offset indent 529This function sets the 530.Fa link 531up for Load Sharing using IP Network Address Translation (RFC 2391, LSNAT). 532LSNAT operates as follows. 533A client attempts to access a server by using the server virtual address. 534The LSNAT router transparently redirects the request to one of the hosts 535in server pool, selected using a real-time load sharing algorithm. 536Multiple sessions may be initiated from the same client, and each session 537could be directed to a different host based on load balance across server 538pool hosts at the time. 539If load share is desired for just a few specific services, the configuration 540on LSNAT could be defined to restrict load share for just the services 541desired. 542.Pp 543Currently, only the simplest selection algorithm is implemented, where a 544host is selected on a round-robin basis only, without regard to load on 545the host. 546.Pp 547First, the 548.Fa link 549is created by either 550.Fn LibAliasRedirectPort 551or 552.Fn LibAliasRedirectAddr . 553Then, 554.Fn LibAliasAddServer 555is called multiple times to add entries to the 556.Fa link Ns 's 557server pool. 558.Pp 559For links created with 560.Fn LibAliasRedirectAddr , 561the 562.Fa port 563argument is ignored and could have any value, e.g.\& htons(~0). 564.Pp 565This function returns 0 on success, \-1 otherwise. 566.Ed 567.Pp 568.Ft int 569.Fn LibAliasRedirectDynamic "struct libalias *" "struct alias_link *link" 570.Bd -ragged -offset indent 571This function marks the specified static redirect rule entered by 572.Fn LibAliasRedirectPort 573as dynamic. 574This can be used to e.g.\& dynamically redirect a single TCP connection, 575after which the rule is removed. 576Only fully specified links can be made dynamic. 577(See the 578.Sx STATIC AND DYNAMIC LINKS 579and 580.Sx PARTIALLY SPECIFIED ALIASING LINKS 581sections below for a definition of static vs.\& dynamic, 582and partially vs.\& fully specified links.) 583.Pp 584This function returns 0 on success, \-1 otherwise. 585.Ed 586.Pp 587.Ft void 588.Fn LibAliasRedirectDelete "struct libalias *" "struct alias_link *link" 589.Bd -ragged -offset indent 590This function will delete a specific static redirect rule entered by 591.Fn LibAliasRedirectPort 592or 593.Fn LibAliasRedirectAddr . 594The parameter 595.Fa link 596is the pointer returned by either of the redirection functions. 597If an invalid pointer is passed to 598.Fn LibAliasRedirectDelete , 599then a program crash or unpredictable operation could result, so it is 600necessary to be careful using this function. 601.Ed 602.Pp 603.Ft int 604.Fn LibAliasProxyRule "struct libalias *" "const char *cmd" 605.Bd -ragged -offset indent 606The passed 607.Fa cmd 608string consists of one or more pairs of words. 609The first word in each pair is a token and the second is the value that 610should be applied for that token. 611Tokens and their argument types are as follows: 612.Bl -tag -width indent 613.It Cm type encode_ip_hdr | encode_tcp_stream | no_encode 614In order to support transparent proxying, it is necessary to somehow 615pass the original address and port information into the new destination 616server. 617If 618.Cm encode_ip_hdr 619is specified, the original destination address and port are passed 620as an extra IP option. 621If 622.Cm encode_tcp_stream 623is specified, the original destination address and port are passed 624as the first piece of data in the TCP stream in the format 625.Dq Li DEST Ar IP port . 626.It Cm port Ar portnum 627Only packets with the destination port 628.Ar portnum 629are proxied. 630.It Cm server Ar host Ns Op : Ns Ar portnum 631This specifies the 632.Ar host 633and 634.Ar portnum 635that the data is to be redirected to. 636.Ar host 637must be an IP address rather than a DNS host name. 638If 639.Ar portnum 640is not specified, the destination port number is not changed. 641.Pp 642The 643.Ar server 644specification is mandatory unless the 645.Cm delete 646command is being used. 647.It Cm rule Ar index 648Normally, each call to 649.Fn LibAliasProxyRule 650inserts the next rule at the start of a linear list of rules. 651If an 652.Ar index 653is specified, the new rule will be checked after all rules with lower 654indices. 655Calls to 656.Fn LibAliasProxyRule 657that do not specify a rule are assigned rule 0. 658.It Cm delete Ar index 659This token and its argument MUST NOT be used with any other tokens. 660When used, all existing rules with the given 661.Ar index 662are deleted. 663.It Cm proto tcp | udp 664If specified, only packets of the given protocol type are matched. 665.It Cm src Ar IP Ns Op / Ns Ar bits 666If specified, only packets with a source address matching the given 667.Ar IP 668are matched. 669If 670.Ar bits 671is also specified, then the first 672.Ar bits 673bits of 674.Ar IP 675are taken as a network specification, and all IP addresses from that 676network will be matched. 677.It Cm dst Ar IP Ns Op / Ns Ar bits 678If specified, only packets with a destination address matching the given 679.Ar IP 680are matched. 681If 682.Ar bits 683is also specified, then the first 684.Ar bits 685bits of 686.Ar IP 687are taken as a network specification, and all IP addresses from that 688network will be matched. 689.El 690.Pp 691This function is usually used to redirect outgoing connections for 692internal machines that are not permitted certain types of internet 693access, or to restrict access to certain external machines. 694.Ed 695.Pp 696.Ft struct alias_link * 697.Fo LibAliasRedirectProto 698.Fa "struct libalias *" 699.Fa "struct in_addr local_addr" 700.Fa "struct in_addr remote_addr" 701.Fa "struct in_addr alias_addr" 702.Fa "u_char proto" 703.Fc 704.Bd -ragged -offset indent 705This function specifies that any IP packet with protocol number of 706.Fa proto 707from a given remote address to an alias address be 708redirected to a specified local address. 709.Pp 710If 711.Fa local_addr 712or 713.Fa alias_addr 714is zero, this indicates that the packet aliasing address as established 715by 716.Fn LibAliasSetAddress 717is to be used. 718Even if 719.Fn LibAliasSetAddress 720is called to change the address after 721.Fn LibAliasRedirectProto 722is called, a zero reference will track this change. 723.Pp 724If 725.Fa remote_addr 726is zero, this indicates to redirect packets from any remote address. 727Non-zero remote addresses can sometimes be useful for firewalling. 728.Pp 729If two calls to 730.Fn LibAliasRedirectProto 731overlap in their address specifications, then the most recent call 732will have precedence. 733.Pp 734This function returns a pointer which can subsequently be used by 735.Fn LibAliasRedirectDelete . 736If 737.Dv NULL 738is returned, then the function call did not complete successfully. 739.Ed 740.Sh FRAGMENT HANDLING 741The functions in this section are used to deal with incoming fragments. 742.Pp 743Outgoing fragments are handled within 744.Fn LibAliasOut 745by changing the address according to any applicable mapping set by 746.Fn LibAliasRedirectAddr , 747or the default aliasing address set by 748.Fn LibAliasSetAddress . 749.Pp 750Incoming fragments are handled in one of two ways. 751If the header of a fragmented IP packet has already been seen, then all 752subsequent fragments will be re-mapped in the same manner the header 753fragment was. 754Fragments which arrive before the header are saved and then retrieved 755once the header fragment has been resolved. 756.Pp 757.Ft int 758.Fn LibAliasSaveFragment "struct libalias *" "char *ptr" 759.Bd -ragged -offset indent 760When 761.Fn LibAliasIn 762returns 763.Dv PKT_ALIAS_UNRESOLVED_FRAGMENT , 764this function can be used to save the pointer to the unresolved fragment. 765.Pp 766It is implicitly assumed that 767.Fa ptr 768points to a block of memory allocated by 769.Xr malloc 3 . 770If the fragment is never resolved, the packet aliasing engine will 771automatically free the memory after a timeout period. 772[Eventually this function should be modified so that a callback function 773for freeing memory is passed as an argument.] 774.Pp 775This function returns 776.Dv PKT_ALIAS_OK 777if it was successful and 778.Dv PKT_ALIAS_ERROR 779if there was an error. 780.Ed 781.Pp 782.Ft char * 783.Fn LibAliasGetFragment "struct libalias *" "char *buffer" 784.Bd -ragged -offset indent 785This function can be used to retrieve fragment pointers saved by 786.Fn LibAliasSaveFragment . 787The IP header fragment pointed to by 788.Fa buffer 789is the header fragment indicated when 790.Fn LibAliasIn 791returns 792.Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT . 793Once a fragment pointer is retrieved, it becomes the calling program's 794responsibility to free the dynamically allocated memory for the fragment. 795.Pp 796The 797.Fn LibAliasGetFragment 798function can be called sequentially until there are no more fragments 799available, at which time it returns 800.Dv NULL . 801.Ed 802.Pp 803.Ft void 804.Fn LibAliasFragmentIn "struct libalias *" "char *header" "char *fragment" 805.Bd -ragged -offset indent 806When a fragment is retrieved with 807.Fn LibAliasGetFragment , 808it can then be de-aliased with a call to 809.Fn LibAliasFragmentIn . 810The 811.Fa header 812argument is the pointer to a header fragment used as a template, and 813.Fa fragment 814is the pointer to the packet to be de-aliased. 815.Ed 816.Sh MISCELLANEOUS FUNCTIONS 817.Ft void 818.Fn LibAliasSetTarget "struct libalias *" "struct in_addr addr" 819.Bd -ragged -offset indent 820When an incoming packet not associated with any pre-existing aliasing link 821arrives at the host machine, it will be sent to the address indicated by a 822call to 823.Fn LibAliasSetTarget . 824.Pp 825If this function is called with an 826.Dv INADDR_NONE 827address argument, then all new incoming packets go to the address set by 828.Fn LibAliasSetAddress . 829.Pp 830If this function is not called, or is called with an 831.Dv INADDR_ANY 832address argument, then all new incoming packets go to the address specified 833in the packet. 834This allows external machines to talk directly to internal machines if they 835can route packets to the machine in question. 836.Ed 837.Pp 838.Ft int 839.Fn LibAliasCheckNewLink "struct libalias *" 840.Bd -ragged -offset indent 841This function returns a non-zero value when a new aliasing link is created. 842In circumstances where incoming traffic is being sequentially sent to 843different local servers, this function can be used to trigger when 844.Fn LibAliasSetTarget 845is called to change the default target address. 846.Ed 847.Pp 848.Ft u_short 849.Fn LibAliasInternetChecksum "struct libalias *" "u_short *buffer" "int nbytes" 850.Bd -ragged -offset indent 851This is a utility function that does not seem to be available elsewhere and 852is included as a convenience. 853It computes the internet checksum, which is used in both IP and 854protocol-specific headers (TCP, UDP, ICMP). 855.Pp 856The 857.Fa buffer 858argument points to the data block to be checksummed, and 859.Fa nbytes 860is the number of bytes. 861The 16-bit checksum field should be zeroed before computing the checksum. 862.Pp 863Checksums can also be verified by operating on a block of data including 864its checksum. 865If the checksum is valid, 866.Fn LibAliasInternetChecksum 867will return zero. 868.Ed 869.Pp 870.Ft int 871.Fn LibAliasUnaliasOut "struct libalias *" "char *buffer" "int maxpacketsize" 872.Bd -ragged -offset indent 873An outgoing packet, which has already been aliased, 874has its private address/port information restored by this function. 875The IP packet is pointed to by 876.Fa buffer , 877and 878.Fa maxpacketsize 879is provided for error checking purposes. 880This function can be used if an already-aliased packet needs to have its 881original IP header restored for further processing (e.g.\& logging). 882.Ed 883.Sh AUTHORS 884.An Charles Mott Aq cm@linktel.net , 885versions 1.0 - 1.8, 2.0 - 2.4. 886.An Eivind Eklund Aq eivind@FreeBSD.org , 887versions 1.8b, 1.9 and 2.5. 888Added IRC DCC support as well as contributing a number of architectural 889improvements; added the firewall bypass for FTP/IRC DCC. 890.An Erik Salander Aq erik@whistle.com 891added support for PPTP and RTSP. 892.An Junichi Satoh Aq junichi@junichi.org 893added support for RTSP/PNA. 894.An Ruslan Ermilov Aq ru@FreeBSD.org 895added support for PPTP and LSNAT as well as general hacking. 896.An Paolo Pisati Aq piso@FreeBSD.org 897made the library modular, moving support for all 898protocols (except for IP, TCP and UDP) to external modules. 899.Sh ACKNOWLEDGMENTS 900Listed below, in approximate chronological order, are individuals who 901have provided valuable comments and/or debugging assistance. 902.Pp 903.Bd -ragged -offset indent 904.An -split 905.An Gary Roberts 906.An Tom Torrance 907.An Reto Burkhalter 908.An Martin Renters 909.An Brian Somers 910.An Paul Traina 911.An Ari Suutari 912.An Dave Remien 913.An J. Fortes 914.An Andrzej Bialecki 915.An Gordon Burditt 916.Ed 917.Sh CONCEPTUAL BACKGROUND 918This section is intended for those who are planning to modify the source 919code or want to create somewhat esoteric applications using the packet 920aliasing functions. 921.Pp 922The conceptual framework under which the packet aliasing engine operates 923is described here. 924Central to the discussion is the idea of an 925.Em aliasing link 926which describes the relationship for a given packet transaction between 927the local machine, aliased identity and remote machine. 928It is discussed how such links come into existence and are destroyed. 929.Ss ALIASING LINKS 930There is a notion of an 931.Em aliasing link , 932which is a 7-tuple describing a specific translation: 933.Bd -literal -offset indent 934(local addr, local port, alias addr, alias port, 935 remote addr, remote port, protocol) 936.Ed 937.Pp 938Outgoing packets have the local address and port number replaced with the 939alias address and port number. 940Incoming packets undergo the reverse process. 941The packet aliasing engine attempts to match packets against an internal 942table of aliasing links to determine how to modify a given IP packet. 943Both the IP header and protocol dependent headers are modified as necessary. 944Aliasing links are created and deleted as necessary according to network 945traffic. 946.Pp 947Protocols can be TCP, UDP or even ICMP in certain circumstances. 948(Some types of ICMP packets can be aliased according to sequence or ID 949number which acts as an equivalent port number for identifying how 950individual packets should be handled.) 951.Pp 952Each aliasing link must have a unique combination of the following five 953quantities: alias address/port, remote address/port and protocol. 954This ensures that several machines on a local network can share the 955same aliasing IP address. 956In cases where conflicts might arise, the aliasing port is chosen so that 957uniqueness is maintained. 958.Ss STATIC AND DYNAMIC LINKS 959Aliasing links can either be static or dynamic. 960Static links persist indefinitely and represent fixed rules for translating 961IP packets. 962Dynamic links come into existence for a specific TCP connection or UDP 963transaction or ICMP ECHO sequence. 964For the case of TCP, the connection can be monitored to see when the 965associated aliasing link should be deleted. 966Aliasing links for UDP transactions (and ICMP ECHO and TIMESTAMP requests) 967work on a simple timeout rule. 968When no activity is observed on a dynamic link for a certain amount of time 969it is automatically deleted. 970Timeout rules also apply to TCP connections which do not open or close 971properly. 972.Ss PARTIALLY SPECIFIED ALIASING LINKS 973Aliasing links can be partially specified, meaning that the remote address 974and/or remote port are unknown. 975In this case, when a packet matching the incomplete specification is found, 976a fully specified dynamic link is created. 977If the original partially specified link is dynamic, it will be deleted 978after the fully specified link is created, otherwise it will persist. 979.Pp 980For instance, a partially specified link might be 981.Bd -literal -offset indent 982(192.168.0.4, 23, 204.228.203.215, 8066, 0, 0, tcp) 983.Ed 984.Pp 985The zeros denote unspecified components for the remote address and port. 986If this link were static it would have the effect of redirecting all 987incoming traffic from port 8066 of 204.228.203.215 to port 23 (telnet) 988of machine 192.168.0.4 on the local network. 989Each individual telnet connection would initiate the creation of a distinct 990dynamic link. 991.Ss DYNAMIC LINK CREATION 992In addition to aliasing links, there are also address mappings that can be 993stored within the internal data table of the packet aliasing mechanism. 994.Bd -literal -offset indent 995(local addr, alias addr) 996.Ed 997.Pp 998Address mappings are searched when creating new dynamic links. 999.Pp 1000All outgoing packets from the local network automatically create a dynamic 1001link if they do not match an already existing fully specified link. 1002If an address mapping exists for the outgoing packet, this determines 1003the alias address to be used. 1004If no mapping exists, then a default address, usually the address of the 1005packet aliasing host, is used. 1006If necessary, this default address can be changed as often as each individual 1007packet arrives. 1008.Pp 1009The aliasing port number is determined such that the new dynamic link does 1010not conflict with any existing links. 1011In the default operating mode, the packet aliasing engine attempts to set 1012the aliasing port equal to the local port number. 1013If this results in a conflict, then port numbers are randomly chosen until 1014a unique aliasing link can be established. 1015In an alternate operating mode, the first choice of an aliasing port is also 1016random and unrelated to the local port number. 1017.Sh MODULAR ARCHITECTURE (AND Xr ipfw 4 Sh SUPPORT) 1018One of the latest improvements to 1019.Nm 1020was to make its support 1021for new protocols independent from the rest of the library, giving it 1022the ability to load/unload support for new protocols at run-time. 1023To achieve this feature, all the code for protocol handling was moved 1024to a series of modules outside of the main library. 1025These modules are compiled from the same sources but work in 1026different ways, depending on whether they are compiled to work inside a kernel 1027or as part of the userland library. 1028.Ss LIBALIAS MODULES IN KERNEL LAND 1029When compiled for the kernel, 1030.Nm 1031modules are plain KLDs recognizable with the 1032.Pa alias_ 1033prefix. 1034.Pp 1035To add support for a new protocol, load the corresponding module. 1036For example: 1037.Pp 1038.Dl "kldload alias_ftp" 1039.Pp 1040When support for a protocol is no longer needed, its module can be unloaded: 1041.Pp 1042.Dl "kldunload alias_ftp" 1043.Ss LIBALIAS MODULES IN USERLAND 1044Due to the differences between kernel and userland (no KLD mechanism, 1045many different address spaces, etc.), we had to change a bit how to 1046handle module loading/tracking/unloading in userland. 1047.Pp 1048While compiled for a userland 1049.Nm , 1050all the modules are plain libraries, residing in 1051.Pa /usr/lib , 1052and recognizable with the 1053.Pa libalias_ 1054prefix. 1055.Pp 1056There is a configuration file, 1057.Pa /etc/libalias.conf , 1058with the following contents (by default): 1059.Bd -literal -offset indent 1060/usr/lib/libalias_cuseeme.so 1061/usr/lib/libalias_ftp.so 1062/usr/lib/libalias_irc.so 1063/usr/lib/libalias_nbt.so 1064/usr/lib/libalias_pptp.so 1065/usr/lib/libalias_skinny.so 1066/usr/lib/libalias_smedia.so 1067.Ed 1068.Pp 1069This file contains the paths to the modules that 1070.Nm 1071will load. 1072To load/unload a new module, just add its path to 1073.Pa libalias.conf 1074and call 1075.Fn LibAliasRefreshModules 1076from the program. 1077In case the application provides a 1078.Dv SIGHUP 1079signal handler, add a call to 1080.Fn LibAliasRefreshModules 1081inside the handler, and everytime you want to refresh the loaded modules, 1082send it the 1083.Dv SIGHUP 1084signal: 1085.Pp 1086.Dl "kill -HUP <process_pid>" 1087.Ss MODULAR ARCHITECURE: HOW IT WORKS 1088The modular architecture of 1089.Nm 1090works similar whether it is running inside the 1091kernel or in userland. 1092From 1093.Pa alias_mod.c : 1094.Bd -literal 1095/* Protocol and userland module handlers chains. */ 1096LIST_HEAD(handler_chain, proto_handler) handler_chain ... 1097\&... 1098SLIST_HEAD(dll_chain, dll) dll_chain ... 1099.Ed 1100.Pp 1101.Va handler_chain 1102keep tracks of all the protocol handlers loaded, while 1103.Va ddl_chain 1104takes care of userland modules loaded. 1105.Pp 1106.Va handler_chain 1107is composed of 1108.Vt "struct proto_handler" 1109entries: 1110.Bd -literal 1111struct proto_handler { 1112 u_int pri; 1113 int16_t dir; 1114 uint8_t proto; 1115 int (*fingerprint)(struct libalias *la, 1116 struct ip *pip, struct alias_data *ah); 1117 int (*protohandler)(struct libalias *la, 1118 struct ip *pip, struct alias_data *ah); 1119 LIST_ENTRY(proto_handler) entries; 1120}; 1121.Ed 1122.Pp 1123where: 1124.Bl -inset 1125.It Va pri 1126is the priority assigned to a protocol handler, lower 1127is better. 1128.It Va dir 1129is the direction of packets: ingoing or outgoing. 1130.It Va proto 1131says at which protocol this packet belongs: IP, TCP or UDP. 1132.It Va fingerprint 1133points to the fingerprint function while protohandler points 1134to the protocol handler function. 1135.El 1136.Pp 1137The 1138.Va fingerprint 1139function has the double of scope of checking if the 1140incoming packet is found and if it belongs to any categories that this 1141module can handle. 1142.Pp 1143The 1144.Va protohandler 1145function actually manipulates 1146the packet to make 1147.Nm 1148correctly NAT it. 1149.Pp 1150When a packet enters 1151.Nm , 1152if it meets a module hook, 1153.Va handler_chain 1154is searched to see if there is an handler that matches 1155this type of a packet (it checks protocol and direction of packet), then if 1156more than one handler is found, it starts with the module with 1157the lowest priority number: it calls the 1158.Va fingerprint 1159function and interprets the result. 1160.Pp 1161If the result value is equal to 0 then it calls the protocol handler 1162of this handler and returns. 1163Otherwise, it proceeds to the next eligible module until the 1164.Va handler_chain 1165is exhausted. 1166.Pp 1167Inside 1168.Nm , 1169the module hook looks like this: 1170.Bd -literal -offset indent 1171struct alias_data ad = { 1172 lnk, 1173 &original_address, 1174 &alias_address, 1175 &alias_port, 1176 &ud->uh_sport, /* original source port */ 1177 &ud->uh_dport, /* original dest port */ 1178 256 /* maxpacketsize */ 1179}; 1180 1181\&... 1182 1183/* walk out chain */ 1184err = find_handler(IN, UDP, la, pip, &ad); 1185.Ed 1186.Pp 1187All data useful to a module are gathered together in an 1188.Vt alias_data 1189structure, then 1190.Fn find_handler 1191is called. 1192The 1193.Fn find_handler 1194function is responsible for walking out the handler 1195chain, it receives as input parameters: 1196.Bl -tag -width indent 1197.It Fa IN 1198direction 1199.It Fa UDP 1200working protocol 1201.It Fa la 1202pointer to this instance of libalias 1203.It Fa pip 1204pointer to a 1205.Vt "struct ip" 1206.It Fa ad 1207pointer to 1208.Vt "struct alias_data" 1209(see above) 1210.El 1211.Pp 1212In this case, 1213.Fn find_handler 1214will search only for modules registered for 1215supporting INcoming UDP packets. 1216.Pp 1217As was mentioned earlier, 1218.Nm 1219in userland is a bit different, cause 1220care has to be taken of module handling too (avoiding duplicate load of 1221module, avoiding module with same name, etc.) so 1222.Va dll_chain 1223was introduced. 1224.Pp 1225.Va dll_chain 1226contains a list of all userland 1227.Nm 1228modules loaded. 1229.Pp 1230When an application calls 1231.Fn LibAliasRefreshModules , 1232.Nm 1233first unloads all the loaded modules, then reloads all the modules listed in 1234.Pa /etc/libalias.conf : 1235for every module loaded, a new entry to 1236.Va dll_chain 1237is added. 1238.Pp 1239.Va dll_chain 1240is composed of 1241.Vt "struct dll" 1242entries: 1243.Bd -literal 1244struct dll { 1245 /* name of module */ 1246 char name[DLL_LEN]; 1247 /* 1248 * ptr to shared obj obtained through 1249 * dlopen() - use this ptr to get access 1250 * to any symbols from a loaded module 1251 * via dlsym() 1252 */ 1253 void *handle; 1254 struct dll *next; 1255}; 1256.Ed 1257.Bl -inset 1258.It Va name 1259is the name of the module 1260.It Va handle 1261is a pointer to the module obtained through 1262.Xr dlopen 3 1263.El 1264Whenever a module is loaded in userland, an entry is added to 1265.Va dll_chain , 1266then every protocol handler present in that module 1267is resolved and registered in 1268.Va handler_chain . 1269.Ss HOW TO WRITE A MODULE FOR LIBALIAS 1270There is a module (called 1271.Pa alias_dummy.[ch] ) 1272in 1273.Nm 1274that can be used as a skeleton for future work, here we analyse some parts of that 1275module. 1276From 1277.Pa alias_dummy.c : 1278.Bd -literal 1279struct proto_handler handlers [] = {{666, IN|OUT, UDP|TCP, 1280 &fingerprint, &protohandler}}; 1281.Ed 1282.Pp 1283The variable 1284.Va handlers 1285is the 1286.Dq "most important thing" 1287in a module 1288cause it describes the handlers present and lets the outside world use 1289it in an opaque way. 1290.Pp 1291It must ALWAYS be present in every module, and it MUST retain 1292the name 1293.Va handlers , 1294otherwise attempting to load a module in userland will fail and 1295complain about missing symbols: for more information about module 1296load/unload, please refer to 1297.Fn LibAliasRefreshModules , 1298.Fn LibAliasLoadModule 1299and 1300.Fn LibAliasUnloadModule 1301in 1302.Pa alias.c . 1303.Pp 1304.Va handlers 1305contains all the 1306.Vt proto_handler 1307structures present in a module. 1308.Bd -literal 1309static int 1310mod_handler(module_t mod, int type, void *data) 1311{ 1312 int error; 1313 1314 switch (type) { 1315 case MOD_LOAD: 1316 error = 0; 1317 attach_handlers(handlers); 1318 break; 1319 case MOD_UNLOAD: 1320 error = 0; 1321 detach_handlers(handlers; 1322 break; 1323 default: 1324 error = EINVAL; 1325 } 1326 return (error); 1327} 1328.Ed 1329When running as KLD, 1330.Fn mod_handler 1331register/deregister the module using 1332.Fn attach_handlers 1333and 1334.Fn detach_handlers , 1335respectively. 1336.Pp 1337Every module must contain at least 2 functions: one fingerprint 1338function and a protocol handler function. 1339.Bd -literal 1340#ifdef _KERNEL 1341static 1342#endif 1343int 1344fingerprint(struct libalias *la, struct ip *pip, struct alias_data *ah) 1345{ 1346 1347\&... 1348} 1349 1350#ifdef _KERNEL 1351static 1352#endif 1353int 1354protohandler(struct libalias *la, struct ip *pip, 1355 struct alias_data *ah) 1356{ 1357 1358\&... 1359} 1360.Ed 1361and they must accept exactly these input parameters. 1362.Ss PATCHING AN APPLICATION FOR USERLAND LIBALIAS MODULES 1363To add module support into an application that uses 1364.Nm , 1365the following simple steps can be followed. 1366.Bl -enum 1367.It 1368Find the main file of an application 1369(let us call it 1370.Pa main.c ) . 1371.It 1372Add this to the header section of 1373.Pa main.c , 1374if not already present: 1375.Pp 1376.Dl "#include <signal.h>" 1377.Pp 1378and this just after the header section: 1379.Pp 1380.Dl "static void signal_handler(int);" 1381.It 1382Add the following line to the init function of an application or, 1383if it does not have any init function, put it in 1384.Fn main : 1385.Pp 1386.Dl "signal(SIGHUP, signal_handler);" 1387.Pp 1388and place the 1389.Fn signal_handler 1390function somewhere in 1391.Pa main.c : 1392.Bd -literal -offset indent 1393static void 1394signal_handler(int sig) 1395{ 1396 1397 LibAliasRefreshModules(); 1398} 1399.Ed 1400.Pp 1401Otherwise, if an application already traps the 1402.Dv SIGHUP 1403signal, just add a call to 1404.Fn LibAliasRefreshModules 1405in the signal handler function. 1406.El 1407For example, to patch 1408.Xr natd 8 1409to use 1410.Nm 1411modules, just add the following line to 1412.Fn RefreshAddr "int sig __unused" : 1413.Pp 1414.Dl "LibAliasRefreshModules()" 1415.Pp 1416recompile and you are done. 1417.Ss LOGGING SUPPORT IN KERNEL LAND 1418When working as KLD, 1419.Nm 1420now has log support that 1421happens on a buffer allocated inside 1422.Vt "struct libalias" 1423(from 1424.Pa alias_local.h ) : 1425.Bd -literal 1426struct libalias { 1427 ... 1428 1429 /* log descriptor */ 1430#ifdef KERNEL_LOG 1431 char *logDesc; /* 1432 * ptr to an auto-malloced 1433 * memory buffer when libalias 1434 * works as kld 1435 */ 1436#else 1437 FILE *logDesc; /* 1438 * ptr to /var/log/alias.log 1439 * when libalias runs as a 1440 * userland lib 1441 */ 1442#endif 1443 1444 ... 1445} 1446.Ed 1447so all applications using 1448.Nm 1449will be able to handle their 1450own logs, if they want, accessing 1451.Va logDesc . 1452Moreover, every change to a log buffer is automatically added to 1453.Xr syslog 3 1454with the 1455.Dv LOG_SECURITY 1456facility and the 1457.Dv LOG_INFO 1458level. 1459