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.Bd -ragged -offset indent 903.An -split 904.An Gary Roberts 905.An Tom Torrance 906.An Reto Burkhalter 907.An Martin Renters 908.An Brian Somers 909.An Paul Traina 910.An Ari Suutari 911.An Dave Remien 912.An J. Fortes 913.An Andrzej Bialecki 914.An Gordon Burditt 915.Ed 916.Sh CONCEPTUAL BACKGROUND 917This section is intended for those who are planning to modify the source 918code or want to create somewhat esoteric applications using the packet 919aliasing functions. 920.Pp 921The conceptual framework under which the packet aliasing engine operates 922is described here. 923Central to the discussion is the idea of an 924.Em aliasing link 925which describes the relationship for a given packet transaction between 926the local machine, aliased identity and remote machine. 927It is discussed how such links come into existence and are destroyed. 928.Ss ALIASING LINKS 929There is a notion of an 930.Em aliasing link , 931which is a 7-tuple describing a specific translation: 932.Bd -literal -offset indent 933(local addr, local port, alias addr, alias port, 934 remote addr, remote port, protocol) 935.Ed 936.Pp 937Outgoing packets have the local address and port number replaced with the 938alias address and port number. 939Incoming packets undergo the reverse process. 940The packet aliasing engine attempts to match packets against an internal 941table of aliasing links to determine how to modify a given IP packet. 942Both the IP header and protocol dependent headers are modified as necessary. 943Aliasing links are created and deleted as necessary according to network 944traffic. 945.Pp 946Protocols can be TCP, UDP or even ICMP in certain circumstances. 947(Some types of ICMP packets can be aliased according to sequence or ID 948number which acts as an equivalent port number for identifying how 949individual packets should be handled.) 950.Pp 951Each aliasing link must have a unique combination of the following five 952quantities: alias address/port, remote address/port and protocol. 953This ensures that several machines on a local network can share the 954same aliasing IP address. 955In cases where conflicts might arise, the aliasing port is chosen so that 956uniqueness is maintained. 957.Ss STATIC AND DYNAMIC LINKS 958Aliasing links can either be static or dynamic. 959Static links persist indefinitely and represent fixed rules for translating 960IP packets. 961Dynamic links come into existence for a specific TCP connection or UDP 962transaction or ICMP ECHO sequence. 963For the case of TCP, the connection can be monitored to see when the 964associated aliasing link should be deleted. 965Aliasing links for UDP transactions (and ICMP ECHO and TIMESTAMP requests) 966work on a simple timeout rule. 967When no activity is observed on a dynamic link for a certain amount of time 968it is automatically deleted. 969Timeout rules also apply to TCP connections which do not open or close 970properly. 971.Ss PARTIALLY SPECIFIED ALIASING LINKS 972Aliasing links can be partially specified, meaning that the remote address 973and/or remote port are unknown. 974In this case, when a packet matching the incomplete specification is found, 975a fully specified dynamic link is created. 976If the original partially specified link is dynamic, it will be deleted 977after the fully specified link is created, otherwise it will persist. 978.Pp 979For instance, a partially specified link might be 980.Bd -literal -offset indent 981(192.168.0.4, 23, 204.228.203.215, 8066, 0, 0, tcp) 982.Ed 983.Pp 984The zeros denote unspecified components for the remote address and port. 985If this link were static it would have the effect of redirecting all 986incoming traffic from port 8066 of 204.228.203.215 to port 23 (telnet) 987of machine 192.168.0.4 on the local network. 988Each individual telnet connection would initiate the creation of a distinct 989dynamic link. 990.Ss DYNAMIC LINK CREATION 991In addition to aliasing links, there are also address mappings that can be 992stored within the internal data table of the packet aliasing mechanism. 993.Bd -literal -offset indent 994(local addr, alias addr) 995.Ed 996.Pp 997Address mappings are searched when creating new dynamic links. 998.Pp 999All outgoing packets from the local network automatically create a dynamic 1000link if they do not match an already existing fully specified link. 1001If an address mapping exists for the outgoing packet, this determines 1002the alias address to be used. 1003If no mapping exists, then a default address, usually the address of the 1004packet aliasing host, is used. 1005If necessary, this default address can be changed as often as each individual 1006packet arrives. 1007.Pp 1008The aliasing port number is determined such that the new dynamic link does 1009not conflict with any existing links. 1010In the default operating mode, the packet aliasing engine attempts to set 1011the aliasing port equal to the local port number. 1012If this results in a conflict, then port numbers are randomly chosen until 1013a unique aliasing link can be established. 1014In an alternate operating mode, the first choice of an aliasing port is also 1015random and unrelated to the local port number. 1016.Sh MODULAR ARCHITECTURE (AND Xr ipfw 4 Sh SUPPORT) 1017One of the latest improvements to 1018.Nm 1019was to make its support 1020for new protocols independent from the rest of the library, giving it 1021the ability to load/unload support for new protocols at run-time. 1022To achieve this feature, all the code for protocol handling was moved 1023to a series of modules outside of the main library. 1024These modules are compiled from the same sources but work in 1025different ways, depending on whether they are compiled to work inside a kernel 1026or as part of the userland library. 1027.Ss LIBALIAS MODULES IN KERNEL LAND 1028When compiled for the kernel, 1029.Nm 1030modules are plain KLDs recognizable with the 1031.Pa alias_ 1032prefix. 1033.Pp 1034To add support for a new protocol, load the corresponding module. 1035For example: 1036.Pp 1037.Dl "kldload alias_ftp" 1038.Pp 1039When support for a protocol is no longer needed, its module can be unloaded: 1040.Pp 1041.Dl "kldunload alias_ftp" 1042.Ss LIBALIAS MODULES IN USERLAND 1043Due to the differences between kernel and userland (no KLD mechanism, 1044many different address spaces, etc.), we had to change a bit how to 1045handle module loading/tracking/unloading in userland. 1046.Pp 1047While compiled for a userland 1048.Nm , 1049all the modules are plain libraries, residing in 1050.Pa /usr/lib , 1051and recognizable with the 1052.Pa libalias_ 1053prefix. 1054.Pp 1055There is a configuration file, 1056.Pa /etc/libalias.conf , 1057with the following contents (by default): 1058.Bd -literal -offset indent 1059/usr/lib/libalias_cuseeme.so 1060/usr/lib/libalias_ftp.so 1061/usr/lib/libalias_irc.so 1062/usr/lib/libalias_nbt.so 1063/usr/lib/libalias_pptp.so 1064/usr/lib/libalias_skinny.so 1065/usr/lib/libalias_smedia.so 1066.Ed 1067.Pp 1068This file contains the paths to the modules that 1069.Nm 1070will load. 1071To load/unload a new module, just add its path to 1072.Pa libalias.conf 1073and call 1074.Fn LibAliasRefreshModules 1075from the program. 1076In case the application provides a 1077.Dv SIGHUP 1078signal handler, add a call to 1079.Fn LibAliasRefreshModules 1080inside the handler, and everytime you want to refresh the loaded modules, 1081send it the 1082.Dv SIGHUP 1083signal: 1084.Pp 1085.Dl "kill -HUP <process_pid>" 1086.Ss MODULAR ARCHITECURE: HOW IT WORKS 1087The modular architecture of 1088.Nm 1089works similar whether it is running inside the 1090kernel or in userland. 1091From 1092.Pa alias_mod.c : 1093.Bd -literal 1094/* Protocol and userland module handlers chains. */ 1095LIST_HEAD(handler_chain, proto_handler) handler_chain ... 1096\&... 1097SLIST_HEAD(dll_chain, dll) dll_chain ... 1098.Ed 1099.Pp 1100.Va handler_chain 1101keep tracks of all the protocol handlers loaded, while 1102.Va ddl_chain 1103takes care of userland modules loaded. 1104.Pp 1105.Va handler_chain 1106is composed of 1107.Vt "struct proto_handler" 1108entries: 1109.Bd -literal 1110struct proto_handler { 1111 u_int pri; 1112 int16_t dir; 1113 uint8_t proto; 1114 int (*fingerprint)(struct libalias *la, 1115 struct ip *pip, struct alias_data *ah); 1116 int (*protohandler)(struct libalias *la, 1117 struct ip *pip, struct alias_data *ah); 1118 LIST_ENTRY(proto_handler) entries; 1119}; 1120.Ed 1121.Pp 1122where: 1123.Bl -inset 1124.It Va pri 1125is the priority assigned to a protocol handler, lower 1126is better. 1127.It Va dir 1128is the direction of packets: ingoing or outgoing. 1129.It Va proto 1130says at which protocol this packet belongs: IP, TCP or UDP. 1131.It Va fingerprint 1132points to the fingerprint function while protohandler points 1133to the protocol handler function. 1134.El 1135.Pp 1136The 1137.Va fingerprint 1138function has the double of scope of checking if the 1139incoming packet is found and if it belongs to any categories that this 1140module can handle. 1141.Pp 1142The 1143.Va protohandler 1144function actually manipulates 1145the packet to make 1146.Nm 1147correctly NAT it. 1148.Pp 1149When a packet enters 1150.Nm , 1151if it meets a module hook, 1152.Va handler_chain 1153is searched to see if there is an handler that matches 1154this type of a packet (it checks protocol and direction of packet), then if 1155more than one handler is found, it starts with the module with 1156the lowest priority number: it calls the 1157.Va fingerprint 1158function and interprets the result. 1159.Pp 1160If the result value is equal to 0 then it calls the protocol handler 1161of this handler and returns. 1162Otherwise, it proceeds to the next eligible module until the 1163.Va handler_chain 1164is exhausted. 1165.Pp 1166Inside 1167.Nm , 1168the module hook looks like this: 1169.Bd -literal -offset indent 1170struct alias_data ad = { 1171 lnk, 1172 &original_address, 1173 &alias_address, 1174 &alias_port, 1175 &ud->uh_sport, /* original source port */ 1176 &ud->uh_dport, /* original dest port */ 1177 256 /* maxpacketsize */ 1178}; 1179 1180\&... 1181 1182/* walk out chain */ 1183err = find_handler(IN, UDP, la, pip, &ad); 1184.Ed 1185.Pp 1186All data useful to a module are gathered together in an 1187.Vt alias_data 1188structure, then 1189.Fn find_handler 1190is called. 1191The 1192.Fn find_handler 1193function is responsible for walking out the handler 1194chain, it receives as input parameters: 1195.Bl -tag -width indent 1196.It Fa IN 1197direction 1198.It Fa UDP 1199working protocol 1200.It Fa la 1201pointer to this instance of libalias 1202.It Fa pip 1203pointer to a 1204.Vt "struct ip" 1205.It Fa ad 1206pointer to 1207.Vt "struct alias_data" 1208(see above) 1209.El 1210.Pp 1211In this case, 1212.Fn find_handler 1213will search only for modules registered for 1214supporting INcoming UDP packets. 1215.Pp 1216As was mentioned earlier, 1217.Nm 1218in userland is a bit different, cause 1219care has to be taken of module handling too (avoiding duplicate load of 1220module, avoiding module with same name, etc.) so 1221.Va dll_chain 1222was introduced. 1223.Pp 1224.Va dll_chain 1225contains a list of all userland 1226.Nm 1227modules loaded. 1228.Pp 1229When an application calls 1230.Fn LibAliasRefreshModules , 1231.Nm 1232first unloads all the loaded modules, then reloads all the modules listed in 1233.Pa /etc/libalias.conf : 1234for every module loaded, a new entry to 1235.Va dll_chain 1236is added. 1237.Pp 1238.Va dll_chain 1239is composed of 1240.Vt "struct dll" 1241entries: 1242.Bd -literal 1243struct dll { 1244 /* name of module */ 1245 char name[DLL_LEN]; 1246 /* 1247 * ptr to shared obj obtained through 1248 * dlopen() - use this ptr to get access 1249 * to any symbols from a loaded module 1250 * via dlsym() 1251 */ 1252 void *handle; 1253 struct dll *next; 1254}; 1255.Ed 1256.Bl -inset 1257.It Va name 1258is the name of the module 1259.It Va handle 1260is a pointer to the module obtained through 1261.Xr dlopen 3 1262.El 1263Whenever a module is loaded in userland, an entry is added to 1264.Va dll_chain , 1265then every protocol handler present in that module 1266is resolved and registered in 1267.Va handler_chain . 1268.Ss HOW TO WRITE A MODULE FOR LIBALIAS 1269There is a module (called 1270.Pa alias_dummy.[ch] ) 1271in 1272.Nm 1273that can be used as a skeleton for future work, here we analyse some parts of that 1274module. 1275From 1276.Pa alias_dummy.c : 1277.Bd -literal 1278struct proto_handler handlers [] = {{666, IN|OUT, UDP|TCP, 1279 &fingerprint, &protohandler}}; 1280.Ed 1281.Pp 1282The variable 1283.Va handlers 1284is the 1285.Dq "most important thing" 1286in a module 1287cause it describes the handlers present and lets the outside world use 1288it in an opaque way. 1289.Pp 1290It must ALWAYS be present in every module, and it MUST retain 1291the name 1292.Va handlers , 1293otherwise attempting to load a module in userland will fail and 1294complain about missing symbols: for more information about module 1295load/unload, please refer to 1296.Fn LibAliasRefreshModules , 1297.Fn LibAliasLoadModule 1298and 1299.Fn LibAliasUnloadModule 1300in 1301.Pa alias.c . 1302.Pp 1303.Va handlers 1304contains all the 1305.Vt proto_handler 1306structures present in a module. 1307.Bd -literal 1308static int 1309mod_handler(module_t mod, int type, void *data) 1310{ 1311 int error; 1312 1313 switch (type) { 1314 case MOD_LOAD: 1315 error = 0; 1316 attach_handlers(handlers); 1317 break; 1318 case MOD_UNLOAD: 1319 error = 0; 1320 detach_handlers(handlers; 1321 break; 1322 default: 1323 error = EINVAL; 1324 } 1325 return (error); 1326} 1327.Ed 1328When running as KLD, 1329.Fn mod_handler 1330register/deregister the module using 1331.Fn attach_handlers 1332and 1333.Fn detach_handlers , 1334respectively. 1335.Pp 1336Every module must contain at least 2 functions: one fingerprint 1337function and a protocol handler function. 1338.Bd -literal 1339#ifdef _KERNEL 1340static 1341#endif 1342int 1343fingerprint(struct libalias *la, struct ip *pip, struct alias_data *ah) 1344{ 1345 1346\&... 1347} 1348 1349#ifdef _KERNEL 1350static 1351#endif 1352int 1353protohandler(struct libalias *la, struct ip *pip, 1354 struct alias_data *ah) 1355{ 1356 1357\&... 1358} 1359.Ed 1360and they must accept exactly these input parameters. 1361.Ss PATCHING AN APPLICATION FOR USERLAND LIBALIAS MODULES 1362To add module support into an application that uses 1363.Nm , 1364the following simple steps can be followed. 1365.Bl -enum 1366.It 1367Find the main file of an application 1368(let us call it 1369.Pa main.c ) . 1370.It 1371Add this to the header section of 1372.Pa main.c , 1373if not already present: 1374.Pp 1375.Dl "#include <signal.h>" 1376.Pp 1377and this just after the header section: 1378.Pp 1379.Dl "static void signal_handler(int);" 1380.It 1381Add the following line to the init function of an application or, 1382if it does not have any init function, put it in 1383.Fn main : 1384.Pp 1385.Dl "signal(SIGHUP, signal_handler);" 1386.Pp 1387and place the 1388.Fn signal_handler 1389function somewhere in 1390.Pa main.c : 1391.Bd -literal -offset indent 1392static void 1393signal_handler(int sig) 1394{ 1395 1396 LibAliasRefreshModules(); 1397} 1398.Ed 1399.Pp 1400Otherwise, if an application already traps the 1401.Dv SIGHUP 1402signal, just add a call to 1403.Fn LibAliasRefreshModules 1404in the signal handler function. 1405.El 1406For example, to patch 1407.Xr natd 8 1408to use 1409.Nm 1410modules, just add the following line to 1411.Fn RefreshAddr "int sig __unused" : 1412.Pp 1413.Dl "LibAliasRefreshModules()" 1414.Pp 1415recompile and you are done. 1416.Ss LOGGING SUPPORT IN KERNEL LAND 1417When working as KLD, 1418.Nm 1419now has log support that 1420happens on a buffer allocated inside 1421.Vt "struct libalias" 1422(from 1423.Pa alias_local.h ) : 1424.Bd -literal 1425struct libalias { 1426 ... 1427 1428 /* log descriptor */ 1429#ifdef KERNEL_LOG 1430 char *logDesc; /* 1431 * ptr to an auto-malloced 1432 * memory buffer when libalias 1433 * works as kld 1434 */ 1435#else 1436 FILE *logDesc; /* 1437 * ptr to /var/log/alias.log 1438 * when libalias runs as a 1439 * userland lib 1440 */ 1441#endif 1442 1443 ... 1444} 1445.Ed 1446so all applications using 1447.Nm 1448will be able to handle their 1449own logs, if they want, accessing 1450.Va logDesc . 1451Moreover, every change to a log buffer is automatically added to 1452.Xr syslog 3 1453with the 1454.Dv LOG_SECURITY 1455facility and the 1456.Dv LOG_INFO 1457level. 1458