diff --git a/en_US.ISO8859-1/books/handbook/advanced-networking/chapter.xml b/en_US.ISO8859-1/books/handbook/advanced-networking/chapter.xml index 49a988c9f4..af6d8e2e34 100644 --- a/en_US.ISO8859-1/books/handbook/advanced-networking/chapter.xml +++ b/en_US.ISO8859-1/books/handbook/advanced-networking/chapter.xml @@ -1,6117 +1,5733 @@ Advanced Networking Synopsis This chapter covers a number of advanced networking topics. After reading this chapter, you will know: The basics of gateways and routes. How to set up USB tethering. How to set up &ieee; 802.11 and &bluetooth; devices. How to make &os; act as a bridge. How to set up network booting on a diskless machine. How to set up network PXE booting with an NFS root file system. - - How to set up network address translation. - - How to set up IPv6 on a &os; machine. How to enable and utilize the features of the Common Address Redundancy Protocol (CARP) in &os;. Before reading this chapter, you should: Understand the basics of the /etc/rc scripts. Be familiar with basic network terminology. Know how to configure and install a new &os; kernel (). Know how to install additional third-party software (). Gateways and Routes Coranth Gryphon Contributed by routing gateway subnet For one machine to be able to find another over a network, there must be a mechanism in place to describe how to get from one to the other. This is called routing. A route is a defined pair of addresses: a destination and a gateway. The pair indicates that when trying to get to this destination, communicate through this gateway. There are three types of destinations: individual hosts, subnets, and default. The default route is used if none of the other routes apply. There are also three types of gateways: individual hosts, interfaces (also called links), and Ethernet hardware (MAC) addresses. An Example This example &man.netstat.1; output illustrates several aspects of routing: &prompt.user; netstat -r Routing tables Destination Gateway Flags Refs Use Netif Expire default outside-gw UGSc 37 418 ppp0 localhost localhost UH 0 181 lo0 test0 0:e0:b5:36:cf:4f UHLW 5 63288 ed0 77 10.20.30.255 link#1 UHLW 1 2421 example.com link#1 UC 0 0 host1 0:e0:a8:37:8:1e UHLW 3 4601 lo0 host2 0:e0:a8:37:8:1e UHLW 0 5 lo0 => host2.example.com link#1 UC 0 0 224 link#1 UC 0 0 default route The first two lines specify the default route, described in more detail in , and the localhost route. loopback device The interface (Netif column) that this routing table specifies to use for localhost is lo0, also known as the loopback device. This says to keep all traffic for this destination internal, rather than sending it out over the network. Ethernet MAC address The addresses beginning with 0:e0: are Ethernet hardware addresses, also known as MAC addresses. &os; will automatically identify any hosts, test0 in the example, on the local Ethernet and add a route for that host over the Ethernet interface, ed0. This type of route has a timeout, seen in the Expire column, which is used if the host does not respond in a specific amount of time. When this happens, the route to this host will be automatically deleted. These hosts are identified using the Routing Information Protocol (RIP), which calculates routes to local hosts based upon a shortest path determination. subnet &os; will add subnet routes for the local subnet. 10.20.30.255 is the broadcast address for the subnet 10.20.30 and example.com is the domain name associated with that subnet. The designation link#1 refers to the first Ethernet card in the machine. Local network hosts and local subnets have their routes automatically configured by a daemon called &man.routed.8;. If it is not running, only routes which are statically defined by the administrator will exist. The host1 line refers to the host by its Ethernet address. Since it is the sending host, &os; knows to use the loopback interface (lo0) rather than the Ethernet interface. The two host2 lines represent aliases which were created using &man.ifconfig.8;. The => symbol after the lo0 interface says that an alias has been set in addition to the loopback address. Such routes only show up on the host that supports the alias; all other hosts on the local network will have a link#1 line for such routes. The final line (destination subnet 224) deals with multicasting. Finally, various attributes of each route can be seen in the Flags column. Below is a short table of some of these flags and their meanings: U Up: The route is active. H Host: The route destination is a single host. G Gateway: Send anything for this destination on to this remote system, which will figure out from there where to send it. S Static: This route was configured manually, not automatically generated by the system. C Clone: Generates a new route based upon this route for machines to connect to. This type of route is normally used for local networks. W WasCloned: Indicated a route that was auto-configured based upon a local area network (Clone) route. L Link: Route involves references to Ethernet hardware. Default Routes default route When the local system needs to make a connection to a remote host, it checks the routing table to determine if a known path exists. If the remote host falls into a subnet that it knows how to reach, the system checks to see if it can connect using that interface. If all known paths fail, the system has one last option: the default route. This route is a special type of gateway route (usually the only one present in the system), and is always marked with a c in the flags field. For hosts on a local area network, this gateway is set to the system which has a direct connection to the Internet. The default route for a machine which itself is functioning as the gateway to the outside world, will be the gateway machine at the Internet Service Provider (ISP). This example is a common configuration for a default route: [Local2] <--ether--> [Local1] <--PPP--> [ISP-Serv] <--ether--> [T1-GW] The hosts Local1 and Local2 are on the local network. Local1 is connected to an ISP using a PPP connection. This PPP server is connected through a local area network to another gateway computer through an external interface to the ISP. The default routes for each machine will be: Host Default Gateway Interface Local2 Local1 Ethernet Local1 T1-GW PPP A common question is Why is T1-GW configured as the default gateway for Local1, rather than the ISP server it is connected to?. Since the PPP interface is using an address on the ISP's local network for the local side of the connection, routes for any other machines on the ISP's local network will be automatically generated. The system already knows how to reach the T1-GW machine, so there is no need for the intermediate step of sending traffic to the ISP's server. It is common to use the address X.X.X.1 as the gateway address for the local network. So, if the local class C address space is 10.20.30 and the ISP is using 10.9.9, the default routes would be: Host Default Route Local2 (10.20.30.2) Local1 (10.20.30.1) Local1 (10.20.30.1, 10.9.9.30) T1-GW (10.9.9.1) The default route can be easily defined in /etc/rc.conf. In this example, on Local2, add the following line to /etc/rc.conf: defaultrouter="10.20.30.1" It is also possible to add the route directly using &man.route.8;: &prompt.root; route add default 10.20.30.1 For more information on manual manipulation of network routing tables, refer to &man.route.8;. Dual Homed Hosts dual homed hosts A dual-homed system is a host which resides on two different networks. The dual-homed machine might have two Ethernet cards, each having an address on a separate subnet. Alternately, the machine can have one Ethernet card and uses &man.ifconfig.8; aliasing. The former is used if two physically separate Ethernet networks are in use and the latter if there is one physical network segment, but two logically separate subnets. Either way, routing tables are set up so that each subnet knows that this machine is the defined gateway (inbound route) to the other subnet. This configuration, with the machine acting as a router between the two subnets, is often used to implement packet filtering or firewall security in either or both directions. For this machine to forward packets between the two interfaces, &os; must be configured as a router, as demonstrated in the next section. Building a Router router A network router is a system that forwards packets from one interface to another. Internet standards and good engineering practice prevent the &os; Project from enabling this by default in &os;. This feature can be enabled by changing the following variable to YES in &man.rc.conf.5;: gateway_enable="YES" # Set to YES if this host will be a gateway This option will set the &man.sysctl.8; variable net.inet.ip.forwarding to 1. To stop routing, reset this to 0. BGP RIP OSPF The new router will need routes to know where to send the traffic. If the network is simple enough, static routes can be used. &os; comes with the standard BSD routing daemon &man.routed.8;, which speaks RIP versions 1 and 2, and IRDP. Support for BGPv4, OSPFv2, and other sophisticated routing protocols is available with the net/zebra package or port. Setting Up Static Routes Al Hoang Contributed by Manual Configuration Consider the following network: INTERNET | (10.0.0.1/24) Default Router to Internet | |Interface xl0 |10.0.0.10/24 +------+ | | RouterA | | (FreeBSD gateway) +------+ | Interface xl1 | 192.168.1.1/24 | +--------------------------------+ Internal Net 1 | 192.168.1.2/24 | +------+ | | RouterB | | +------+ | 192.168.2.1/24 | Internal Net 2 In this scenario, RouterA is a &os; machine that is acting as a router to the rest of the Internet. It has a default route set to 10.0.0.1 which allows it to connect with the outside world. RouterB is already configured properly as it uses 192.168.1.1 as the gateway. The routing table on RouterA looks something like this: &prompt.user; netstat -nr Routing tables Internet: Destination Gateway Flags Refs Use Netif Expire default 10.0.0.1 UGS 0 49378 xl0 127.0.0.1 127.0.0.1 UH 0 6 lo0 10.0.0.0/24 link#1 UC 0 0 xl0 192.168.1.0/24 link#2 UC 0 0 xl1 With the current routing table, RouterA cannot reach Internal Net 2 as it does not have a route for 192.168.2.0/24. The following command adds the Internal Net 2 network to RouterA's routing table using 192.168.1.2 as the next hop: &prompt.root; route add -net 192.168.2.0/24 192.168.1.2 Now RouterA can reach any hosts on the 192.168.2.0/24 network. Persistent Configuration The above example configures a static route on a running system. However, the routing information will not persist if the &os; system reboots. Persistent static routes can be entered in /etc/rc.conf: # Add Internal Net 2 as a static route static_routes="internalnet2" route_internalnet2="-net 192.168.2.0/24 192.168.1.2" The static_routes configuration variable is a list of strings separated by a space, where each string references a route name. This example only has one string in static_routes, internalnet2. The variable route_internalnet2 contains all of the configuration parameters to &man.route.8;. This example is equivalent to the command: &prompt.root; route add -net 192.168.2.0/24 192.168.1.2 Using more than one string in static_routes creates multiple static routes. The following shows an example of adding static routes for the 192.168.0.0/24 and 192.168.1.0/24 networks: static_routes="net1 net2" route_net1="-net 192.168.0.0/24 192.168.0.1" route_net2="-net 192.168.1.0/24 192.168.1.1" Routing Propagation When an address space is assigned to a network, the service provider configures their routing tables so that all traffic for the network will be sent to the link for the site. But how do external sites know to send their packets to the network's ISP? There is a system that keeps track of all assigned address spaces and defines their point of connection to the Internet backbone, or the main trunk lines that carry Internet traffic across the country and around the world. Each backbone machine has a copy of a master set of tables, which direct traffic for a particular network to a specific backbone carrier, and from there down the chain of service providers until it reaches your network. It is the task of the service provider to advertise to the backbone sites that they are the point of connection, and thus the path inward, for a site. This is known as route propagation. Troubleshooting &man.traceroute.8; Sometimes, there is a problem with routing propagation and some sites are unable to connect. Perhaps the most useful command for trying to figure out where routing is breaking down is &man.traceroute.8;. It is useful when &man.ping.8; fails. When using &man.traceroute.8;, include the name of the remote host to connect to. The output will show the gateway hosts along the path of the attempt, eventually either reaching the target host, or terminating because of a lack of connection. For more information, refer to &man.traceroute.8;. Multicast Routing multicast routing kernel options MROUTING &os; natively supports both multicast applications and multicast routing. Multicast applications do not require any special configuration of &os;; as applications will generally run out of the box. Multicast routing requires that support be compiled into a custom kernel: options MROUTING The multicast routing daemon, &man.mrouted.8;, must be configured to set up tunnels and DVMRP via /etc/mrouted.conf. More details on multicast configuration may be found in &man.mrouted.8;. The &man.mrouted.8; multicast routing daemon implements the DVMRP multicast routing protocol, which has largely been replaced by &man.pim.4; in many multicast installations. &man.mrouted.8; and the related &man.map-mbone.8; and &man.mrinfo.8; utilities are available in the &os; Ports Collection as net/mrouted. Wireless Networking Loader Marc Fonvieille Murray Stokely wireless networking 802.11 wireless networking Wireless Networking Basics Most wireless networks are based on the &ieee; 802.11 standards. A basic wireless network consists of multiple stations communicating with radios that broadcast in either the 2.4GHz or 5GHz band, though this varies according to the locale and is also changing to enable communication in the 2.3GHz and 4.9GHz ranges. 802.11 networks are organized in two ways. In infrastructure mode, one station acts as a master with all the other stations associating to it, the network is known as a BSS, and the master station is termed an access point (AP). In a BSS, all communication passes through the AP; even when one station wants to communicate with another wireless station, messages must go through the AP. In the second form of network, there is no master and stations communicate directly. This form of network is termed an IBSS and is commonly known as an ad-hoc network. 802.11 networks were first deployed in the 2.4GHz band using protocols defined by the &ieee; 802.11 and 802.11b standard. These specifications include the operating frequencies and the MAC layer characteristics, including framing and transmission rates, as communication can occur at various rates. Later, the 802.11a standard defined operation in the 5GHz band, including different signaling mechanisms and higher transmission rates. Still later, the 802.11g standard defined the use of 802.11a signaling and transmission mechanisms in the 2.4GHz band in such a way as to be backwards compatible with 802.11b networks. Separate from the underlying transmission techniques, 802.11 networks have a variety of security mechanisms. The original 802.11 specifications defined a simple security protocol called WEP. This protocol uses a fixed pre-shared key and the RC4 cryptographic cipher to encode data transmitted on a network. Stations must all agree on the fixed key in order to communicate. This scheme was shown to be easily broken and is now rarely used except to discourage transient users from joining networks. Current security practice is given by the &ieee; 802.11i specification that defines new cryptographic ciphers and an additional protocol to authenticate stations to an access point and exchange keys for data communication. Cryptographic keys are periodically refreshed and there are mechanisms for detecting and countering intrusion attempts. Another security protocol specification commonly used in wireless networks is termed WPA, which was a precursor to 802.11i. WPA specifies a subset of the requirements found in 802.11i and is designed for implementation on legacy hardware. Specifically, WPA requires only the TKIP cipher that is derived from the original WEP cipher. 802.11i permits use of TKIP but also requires support for a stronger cipher, AES-CCM, for encrypting data. The AES cipher was not required in WPA because it was deemed too computationally costly to be implemented on legacy hardware. The other standard to be aware of is 802.11e. It defines protocols for deploying multimedia applications, such as streaming video and voice over IP (VoIP), in an 802.11 network. Like 802.11i, 802.11e also has a precursor specification termed WME (later renamed WMM) that has been defined by an industry group as a subset of 802.11e that can be deployed now to enable multimedia applications while waiting for the final ratification of 802.11e. The most important thing to know about 802.11e and WME/WMM is that it enables prioritized traffic over a wireless network through Quality of Service (QoS) protocols and enhanced media access protocols. Proper implementation of these protocols enables high speed bursting of data and prioritized traffic flow. &os; supports networks that operate using 802.11a, 802.11b, and 802.11g. The WPA and 802.11i security protocols are likewise supported (in conjunction with any of 11a, 11b, and 11g) and QoS and traffic prioritization required by the WME/WMM protocols are supported for a limited set of wireless devices. Basic Setup Kernel Configuration To use wireless networking, a wireless networking card is needed and the kernel needs to be configured with the appropriate wireless networking support. The kernel is separated into multiple modules so that only the required support needs to be configured. The most commonly used wireless devices are those that use parts made by Atheros. These devices are supported by &man.ath.4; and require the following line to be added to /boot/loader.conf: if_ath_load="YES" The Atheros driver is split up into three separate pieces: the driver (&man.ath.4;), the hardware support layer that handles chip-specific functions (&man.ath.hal.4;), and an algorithm for selecting the rate for transmitting frames. When this support is loaded as kernel modules, any dependencies are automatically handled. To load support for a different type of wireless device, specify the module for that device. This example is for devices based on the Intersil Prism parts (&man.wi.4;) driver: if_wi_load="YES" The examples in this section use an &man.ath.4; device and the device name in the examples must be changed according to the configuration. A list of available wireless drivers and supported adapters can be found in the &os; Hardware Notes, available on the Release Information page of the &os; website. If a native &os; driver for the wireless device does not exist, it may be possible to use the &windows; driver with the help of the NDIS driver wrapper. In addition, the modules that implement cryptographic support for the security protocols to use must be loaded. These are intended to be dynamically loaded on demand by the &man.wlan.4; module, but for now they must be manually configured. The following modules are available: &man.wlan.wep.4;, &man.wlan.ccmp.4;, and &man.wlan.tkip.4;. The &man.wlan.ccmp.4; and &man.wlan.tkip.4; drivers are only needed when using the WPA or 802.11i security protocols. If the network does not use encryption, &man.wlan.wep.4; support is not needed. To load these modules at boot time, add the following lines to /boot/loader.conf: wlan_wep_load="YES" wlan_ccmp_load="YES" wlan_tkip_load="YES" Once this information has been added to /boot/loader.conf, reboot the &os; box. Alternately, load the modules by hand using &man.kldload.8;. For users who do not want to use modules, it is possible to compile these drivers into the kernel by adding the following lines to a custom kernel configuration file: device wlan # 802.11 support device wlan_wep # 802.11 WEP support device wlan_ccmp # 802.11 CCMP support device wlan_tkip # 802.11 TKIP support device wlan_amrr # AMRR transmit rate control algorithm device ath # Atheros pci/cardbus NIC's device ath_hal # pci/cardbus chip support options AH_SUPPORT_AR5416 # enable AR5416 tx/rx descriptors device ath_rate_sample # SampleRate tx rate control for ath With this information in the kernel configuration file, recompile the kernel and reboot the &os; machine. Information about the wireless device should appear in the boot messages, like this: ath0: <Atheros 5212> mem 0x88000000-0x8800ffff irq 11 at device 0.0 on cardbus1 ath0: [ITHREAD] ath0: AR2413 mac 7.9 RF2413 phy 4.5 Infrastructure Mode Infrastructure (BSS) mode is the mode that is typically used. In this mode, a number of wireless access points are connected to a wired network. Each wireless network has its own name, called the SSID. Wireless clients connect to the wireless access points. &os; Clients How to Find Access Points To scan for available networks, use &man.ifconfig.8;. This request may take a few moments to complete as it requires the system to switch to each available wireless frequency and probe for available access points. Only the superuser can initiate a scan: &prompt.root; ifconfig wlan0 create wlandev ath0 &prompt.root; ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS dlinkap 00:13:46:49:41:76 11 54M -90:96 100 EPS WPA WME freebsdap 00:11:95:c3:0d:ac 1 54M -83:96 100 EPS WPA The interface must be before it can scan. Subsequent scan requests do not require the interface to be marked as up again. The output of a scan request lists each BSS/IBSS network found. Besides listing the name of the network, the SSID, the output also shows the BSSID, which is the MAC address of the access point. The CAPS field identifies the type of each network and the capabilities of the stations operating there: Station Capability Codes Capability Code Meaning E Extended Service Set (ESS). Indicates that the station is part of an infrastructure network rather than an IBSS/ad-hoc network. I IBSS/ad-hoc network. Indicates that the station is part of an ad-hoc network rather than an ESS network. P Privacy. Encryption is required for all data frames exchanged within the BSS using cryptographic means such as WEP, TKIP or AES-CCMP. S Short Preamble. Indicates that the network is using short preambles, defined in 802.11b High Rate/DSSS PHY, and utilizes a 56 bit sync field rather than the 128 bit field used in long preamble mode. s Short slot time. Indicates that the 802.11g network is using a short slot time because there are no legacy (802.11b) stations present.
One can also display the current list of known networks with: &prompt.root; ifconfig wlan0 list scan This information may be updated automatically by the adapter or manually with a request. Old data is automatically removed from the cache, so over time this list may shrink unless more scans are done.
Basic Settings This section provides a simple example of how to make the wireless network adapter work in &os; without encryption. Once familiar with these concepts, it is strongly recommend to use WPA to set up the wireless network. There are three basic steps to configure a wireless network: select an access point, authenticate the station, and configure an IP address. The following sections discuss each step. Selecting an Access Point Most of the time, it is sufficient to let the system choose an access point using the builtin heuristics. This is the default behaviour when an interface is marked as up or it is listed in /etc/rc.conf: wlans_ath0="wlan0" ifconfig_wlan0="DHCP" If there are multiple access points, a specific one can be selected by its SSID: wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here DHCP" In an environment where there are multiple access points with the same SSID, which is often done to simplify roaming, it may be necessary to associate to one specific device. In this case, the BSSID of the access point can be specified, with or without the SSID: wlans_ath0="wlan0" ifconfig_wlan0="ssid your_ssid_here bssid xx:xx:xx:xx:xx:xx DHCP" There are other ways to constrain the choice of an access point, such as limiting the set of frequencies the system will scan on. This may be useful for a multi-band wireless card as scanning all the possible channels can be time-consuming. To limit operation to a specific band, use the parameter: wlans_ath0="wlan0" ifconfig_wlan0="mode 11g ssid your_ssid_here DHCP" This example will force the card to operate in 802.11g, which is defined only for 2.4GHz frequencies so any 5GHz channels will not be considered. This can also be achieved with the parameter, which locks operation to one specific frequency, and the parameter, to specify a list of channels for scanning. More information about these parameters can be found in &man.ifconfig.8;. Authentication Once an access point is selected, the station needs to authenticate before it can pass data. Authentication can happen in several ways. The most common scheme, open authentication, allows any station to join the network and communicate. This is the authentication to use for test purposes the first time a wireless network is setup. Other schemes require cryptographic handshakes to be completed before data traffic can flow, either using pre-shared keys or secrets, or more complex schemes that involve backend services such as RADIUS. Open authentication is the default setting. The next most common setup is WPA-PSK, also known as WPA Personal, which is described in . If using an &apple; &airport; Extreme base station for an access point, shared-key authentication together with a WEP key needs to be configured. This can be configured in /etc/rc.conf or by using &man.wpa.supplicant.8;. For a single &airport; base station, access can be configured with: wlans_ath0="wlan0" ifconfig_wlan0="authmode shared wepmode on weptxkey 1 wepkey 01234567 DHCP" In general, shared key authentication should be avoided because it uses the WEP key material in a highly-constrained manner, making it even easier to crack the key. If WEP must be used for compatibility with legacy devices, it is better to use WEP with open authentication. More information regarding WEP can be found in . Getting an <acronym>IP</acronym> Address with <acronym>DHCP</acronym> Once an access point is selected and the authentication parameters are set, an IP address must be obtained in order to communicate. Most of the time, the IP address is obtained via DHCP. To achieve that, edit /etc/rc.conf and add DHCP to the configuration for the device: wlans_ath0="wlan0" ifconfig_wlan0="DHCP" The wireless interface is now ready to bring up: &prompt.root; service netif start Once the interface is running, use &man.ifconfig.8; to see the status of the interface ath0: &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.1.100 netmask 0xffffff00 broadcast 192.168.1.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid dlinkap channel 11 (2462 Mhz 11g) bssid 00:13:46:49:41:76 country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst The status: associated line means that it is connected to the wireless network. The bssid 00:13:46:49:41:76 is the MAC address of the access point and authmode OPEN indicates that the communication is not encrypted. Static <acronym>IP</acronym> Address In an IP address cannot be obtained from a DHCP server, set a fixed IP address. Replace the DHCP keyword shown above with the address information. Be sure to retain any other parameters for selecting the access point: wlans_ath0="wlan0" ifconfig_wlan0="inet 192.168.1.100 netmask 255.255.255.0 ssid your_ssid_here" <acronym>WPA</acronym> Wi-Fi Protected Access (WPA) is a security protocol used together with 802.11 networks to address the lack of proper authentication and the weakness of WEP. WPA leverages the 802.1X authentication protocol and uses one of several ciphers instead of WEP for data integrity. The only cipher required by WPA is the Temporary Key Integrity Protocol (TKIP). TKIP is a cipher that extends the basic RC4 cipher used by WEP by adding integrity checking, tamper detection, and measures for responding to detected intrusions. TKIP is designed to work on legacy hardware with only software modification. It represents a compromise that improves security but is still not entirely immune to attack. WPA also specifies the AES-CCMP cipher as an alternative to TKIP, and that is preferred when possible. For this specification, the term WPA2 or RSN is commonly used. WPA defines authentication and encryption protocols. Authentication is most commonly done using one of two techniques: by 802.1X and a backend authentication service such as RADIUS, or by a minimal handshake between the station and the access point using a pre-shared secret. The former is commonly termed WPA Enterprise and the latter is known as WPA Personal. Since most people will not set up a RADIUS backend server for their wireless network, WPA-PSK is by far the most commonly encountered configuration for WPA. The control of the wireless connection and the key negotiation or authentication with a server is done using &man.wpa.supplicant.8;. This program requires a configuration file, /etc/wpa_supplicant.conf, to run. More information regarding this file can be found in &man.wpa.supplicant.conf.5;. <acronym>WPA-PSK</acronym> WPA-PSK, also known as WPA Personal, is based on a pre-shared key (PSK) which is generated from a given password and used as the master key in the wireless network. This means every wireless user will share the same key. WPA-PSK is intended for small networks where the use of an authentication server is not possible or desired. Always use strong passwords that are sufficiently long and made from a rich alphabet so that they will not be easily guessed or attacked. The first step is the configuration of /etc/wpa_supplicant.conf with the SSID and the pre-shared key of the network: network={ ssid="freebsdap" psk="freebsdmall" } Then, in /etc/rc.conf, indicate that the wireless device configuration will be done with WPA and the IP address will be obtained with DHCP: wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" Then, bring up the interface: &prompt.root; service netif start Starting wpa_supplicant. DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 5 DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 DHCPOFFER from 192.168.0.1 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL Or, try to configure the interface manually using the information in /etc/wpa_supplicant.conf: &prompt.root; wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:11:95:c3:0d:ac (SSID='freebsdap' freq=2412 MHz) Associated with 00:11:95:c3:0d:ac WPA: Key negotiation completed with 00:11:95:c3:0d:ac [PTK=CCMP GTK=CCMP] CTRL-EVENT-CONNECTED - Connection to 00:11:95:c3:0d:ac completed (auth) [id=0 id_str=] The next operation is to launch &man.dhclient.8; to get the IP address from the DHCP server: &prompt.root; dhclient wlan0 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 DHCPACK from 192.168.0.1 bound to 192.168.0.254 -- renewal in 300 seconds. &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL If /etc/rc.conf has an ifconfig_wlan0="DHCP" entry, &man.dhclient.8; will be launched automatically after &man.wpa.supplicant.8; associates with the access point. If DHCP is not possible or desired, set a static IP address after &man.wpa.supplicant.8; has authenticated the station: &prompt.root; ifconfig wlan0 inet 192.168.0.100 netmask 255.255.255.0 &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.100 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/36Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL When DHCP is not used, the default gateway and the nameserver also have to be manually set: &prompt.root; route add default your_default_router &prompt.root; echo "nameserver your_DNS_server" >> /etc/resolv.conf <acronym>WPA</acronym> with <acronym>EAP-TLS</acronym> The second way to use WPA is with an 802.1X backend authentication server. In this case, WPA is called WPA Enterprise to differentiate it from the less secure WPA Personal. Authentication in WPA Enterprise is based on the Extensible Authentication Protocol (EAP). EAP does not come with an encryption method. Instead, EAP is embedded inside an encrypted tunnel. There are many EAP authentication methods, but EAP-TLS, EAP-TTLS, and EAP-PEAP are the most common. EAP with Transport Layer Security (EAP-TLS) is a well-supported wireless authentication protocol since it was the first EAP method to be certified by the Wi-Fi alliance. EAP-TLS requires three certificates to run: the certificate of the Certificate Authority (CA) installed on all machines, the server certificate for the authentication server, and one client certificate for each wireless client. In this EAP method, both the authentication server and wireless client authenticate each other by presenting their respective certificates, and then verify that these certificates were signed by the organization's CA. As previously, the configuration is done via /etc/wpa_supplicant.conf: network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TLS identity="loader" ca_cert="/etc/certs/cacert.pem" client_cert="/etc/certs/clientcert.pem" private_key="/etc/certs/clientkey.pem" private_key_passwd="freebsdmallclient" } This field indicates the network name (SSID). This example uses the RSN &ieee; 802.11i protocol, also known as WPA2. The key_mgmt line refers to the key management protocol to use. In this example, it is WPA using EAP authentication. This field indicates the EAP method for the connection. The identity field contains the identity string for EAP. The ca_cert field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. The client_cert line gives the pathname to the client certificate file. This certificate is unique to each wireless client of the network. The private_key field is the pathname to the client certificate private key file. The private_key_passwd field contains the passphrase for the private key. Then, add the following lines to /etc/rc.conf: wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" The next step is to bring up the interface: &prompt.root; service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL It is also possible to bring up the interface manually using &man.wpa.supplicant.8; and &man.ifconfig.8;. <acronym>WPA</acronym> with <acronym>EAP-TTLS</acronym> With EAP-TTLS, both the authentication server and the client need a certificate. With EAP-TTLS, a client certificate is optional. This method is similar to a web server which creates a secure SSL tunnel even if visitors do not have client-side certificates. EAP-TTLS uses an encrypted TLS tunnel for safe transport of the authentication data. The required configuration can be added to /etc/wpa_supplicant.conf: network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=TTLS identity="test" password="test" ca_cert="/etc/certs/cacert.pem" phase2="auth=MD5" } This field specifies the EAP method for the connection. The identity field contains the identity string for EAP authentication inside the encrypted TLS tunnel. The password field contains the passphrase for the EAP authentication. The ca_cert field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. This field specifies the authentication method used in the encrypted TLS tunnel. In this example, EAP with MD5-Challenge is used. The inner authentication phase is often called phase2. Next, add the following lines to /etc/rc.conf: wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" The next step is to bring up the interface: &prompt.root; service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL <acronym>WPA</acronym> with <acronym>EAP-PEAP</acronym> PEAPv0/EAP-MSCHAPv2 is the most common PEAP method. In this chapter, the term PEAP is used to refer to that method. Protected EAP (PEAP) is designed as an alternative to EAP-TTLS and is the most used EAP standard after EAP-TLS. In a network with mixed operating systems, PEAP should be the most supported standard after EAP-TLS. PEAP is similar to EAP-TTLS as it uses a server-side certificate to authenticate clients by creating an encrypted TLS tunnel between the client and the authentication server, which protects the ensuing exchange of authentication information. PEAP authentication differs from EAP-TTLS as it broadcasts the username in the clear and only the password is sent in the encrypted TLS tunnel. EAP-TTLS will use the TLS tunnel for both the username and password. Add the following lines to /etc/wpa_supplicant.conf to configure the EAP-PEAP related settings: network={ ssid="freebsdap" proto=RSN key_mgmt=WPA-EAP eap=PEAP identity="test" password="test" ca_cert="/etc/certs/cacert.pem" phase1="peaplabel=0" phase2="auth=MSCHAPV2" } This field specifies the EAP method for the connection. The identity field contains the identity string for EAP authentication inside the encrypted TLS tunnel. The password field contains the passphrase for the EAP authentication. The ca_cert field indicates the pathname of the CA certificate file. This file is needed to verify the server certificate. This field contains the parameters for the first phase of authentication, the TLS tunnel. According to the authentication server used, specify a specific label for authentication. Most of the time, the label will be client EAP encryption which is set by using peaplabel=0. More information can be found in &man.wpa.supplicant.conf.5;. This field specifies the authentication protocol used in the encrypted TLS tunnel. In the case of PEAP, it is auth=MSCHAPV2. Add the following to /etc/rc.conf: wlans_ath0="wlan0" ifconfig_wlan0="WPA DHCP" Then, bring up the interface: &prompt.root; service netif start Starting wpa_supplicant. DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 7 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 15 DHCPREQUEST on wlan0 to 255.255.255.255 port 67 interval 21 DHCPACK from 192.168.0.20 bound to 192.168.0.254 -- renewal in 300 seconds. wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.254 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet DS/11Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode WPA2/802.11i privacy ON deftxkey UNDEF AES-CCM 3:128-bit txpower 21.5 bmiss 7 scanvalid 450 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst roaming MANUAL <acronym>WEP</acronym> Wired Equivalent Privacy (WEP) is part of the original 802.11 standard. There is no authentication mechanism, only a weak form of access control which is easily cracked. WEP can be set up using &man.ifconfig.8;: &prompt.root; ifconfig wlan0 create wlandev ath0 &prompt.root; ifconfig wlan0 inet 192.168.1.100 netmask 255.255.255.0 \ ssid my_net wepmode on weptxkey 3 wepkey 3:0x3456789012 The weptxkey specifies which WEP key will be used in the transmission. This example uses the third key. This must match the setting on the access point. When unsure which key is used by the access point, try 1 (the first key) for this value. The wepkey selects one of the WEP keys. It should be in the format index:key. Key 1 is used by default; the index only needs to be set when using a key other than the first key. Replace the 0x3456789012 with the key configured for use on the access point. Refer to &man.ifconfig.8; for further information. The &man.wpa.supplicant.8; facility can be used to configure a wireless interface with WEP. The example above can be set up by adding the following lines to /etc/wpa_supplicant.conf: network={ ssid="my_net" key_mgmt=NONE wep_key3=3456789012 wep_tx_keyidx=3 } Then: &prompt.root; wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf Trying to associate with 00:13:46:49:41:76 (SSID='dlinkap' freq=2437 MHz) Associated with 00:13:46:49:41:76
Ad-hoc Mode IBSS mode, also called ad-hoc mode, is designed for point to point connections. For example, to establish an ad-hoc network between the machines A and B, choose two IP addresses and a SSID. On A: &prompt.root; ifconfig wlan0 create wlandev ath0 wlanmode adhoc &prompt.root; ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g <adhoc> status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst The adhoc parameter indicates that the interface is running in IBSS mode. B should now be able to detect A: &prompt.root; ifconfig wlan0 create wlandev ath0 wlanmode adhoc &prompt.root; ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 02:11:95:c3:0d:ac 2 54M -64:-96 100 IS WME The I in the output confirms that A is in ad-hoc mode. Now, configure B with a different IP address: &prompt.root; ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g <adhoc> status: running ssid freebsdap channel 2 (2417 Mhz 11g) bssid 02:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst Both A and B are now ready to exchange information. &os; Host Access Points &os; can act as an Access Point (AP) which eliminates the need to buy a hardware AP or run an ad-hoc network. This can be particularly useful when a &os; machine is acting as a gateway to another network such as the Internet. Basic Settings Before configuring a &os; machine as an AP, the kernel must be configured with the appropriate networking support for the wireless card as well as the security protocols being used. For more details, see . The NDIS driver wrapper for &windows; drivers does not currently support AP operation. Only native &os; wireless drivers support AP mode. Once wireless networking support is loaded, check if the wireless device supports the host-based access point mode, also known as hostap mode: &prompt.root; ifconfig wlan0 create wlandev ath0 &prompt.root; ifconfig wlan0 list caps drivercaps=6f85edc1<STA,FF,TURBOP,IBSS,HOSTAP,AHDEMO,TXPMGT,SHSLOT,SHPREAMBLE,MONITOR,MBSS,WPA1,WPA2,BURST,WME,WDS,BGSCAN,TXFRAG> cryptocaps=1f<WEP,TKIP,AES,AES_CCM,TKIPMIC> This output displays the card's capabilities. The HOSTAP word confirms that this wireless card can act as an AP. Various supported ciphers are also listed: WEP, TKIP, and AES. This information indicates which security protocols can be used on the AP. The wireless device can only be put into hostap mode during the creation of the network pseudo-device, so a previously created device must be destroyed first: &prompt.root; ifconfig wlan0 destroy then regenerated with the correct option before setting the other parameters: &prompt.root; ifconfig wlan0 create wlandev ath0 wlanmode hostap &prompt.root; ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1 Use &man.ifconfig.8; again to see the status of the wlan0 interface: &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g <hostap> status: running ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs The hostap parameter indicates the interface is running in the host-based access point mode. The interface configuration can be done automatically at boot time by adding the following lines to /etc/rc.conf: wlans_ath0="wlan0" create_args_wlan0="wlanmode hostap" ifconfig_wlan0="inet 192.168.0.1 netmask 255.255.255.0 ssid freebsdap mode 11g channel 1" Host-based Access Point Without Authentication or Encryption Although it is not recommended to run an AP without any authentication or encryption, this is a simple way to check if the AP is working. This configuration is also important for debugging client issues. Once the AP is configured, initiate a scan from another wireless machine to find the AP: &prompt.root; ifconfig wlan0 create wlandev ath0 &prompt.root; ifconfig wlan0 up scan SSID/MESH ID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M -66:-96 100 ES WME The client machine found the AP and can be associated with it: &prompt.root; ifconfig wlan0 inet 192.168.0.2 netmask 255.255.255.0 ssid freebsdap &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 00:11:95:d5:43:62 inet 192.168.0.2 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet OFDM/54Mbps mode 11g status: associated ssid freebsdap channel 1 (2412 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy OFF txpower 21.5 bmiss 7 scanvalid 60 bgscan bgscanintvl 300 bgscanidle 250 roam:rssi 7 roam:rate 5 protmode CTS wme burst <acronym>WPA</acronym> Host-based Access Point This section focuses on setting up a &os; AP using the WPA security protocol. More details regarding WPA and the configuration of WPA-based wireless clients can be found in . The &man.hostapd.8; daemon is used to deal with client authentication and key management on the WPA-enabled AP. The following configuration operations are performed on the &os; machine acting as the AP. Once the AP is correctly working, &man.hostapd.8; should be automatically enabled at boot with the following line in /etc/rc.conf: hostapd_enable="YES" Before trying to configure &man.hostapd.8;, first configure the basic settings introduced in . <acronym>WPA-PSK</acronym> WPA-PSK is intended for small networks where the use of a backend authentication server is not possible or desired. The configuration is done in /etc/hostapd.conf: interface=wlan0 debug=1 ctrl_interface=/var/run/hostapd ctrl_interface_group=wheel ssid=freebsdap wpa=1 wpa_passphrase=freebsdmall wpa_key_mgmt=WPA-PSK wpa_pairwise=CCMP TKIP This field indicates the wireless interface used for the AP. This field sets the level of verbosity during the execution of &man.hostapd.8;. A value of 1 represents the minimal level. The ctrl_interface field gives the pathname of the directory used by &man.hostapd.8; to store its domain socket files for the communication with external programs such as &man.hostapd.cli.8;. The default value is used in this example. The ctrl_interface_group line sets the group which is allowed to access the control interface files. This field sets the network name. The wpa field enables WPA and specifies which WPA authentication protocol will be required. A value of 1 configures the AP for WPA-PSK. The wpa_passphrase field contains the ASCII passphrase for WPA authentication. Always use strong passwords that are sufficiently long and made from a rich alphabet so that they will not be easily guessed or attacked. The wpa_key_mgmt line refers to the key management protocol to use. This example sets WPA-PSK. The wpa_pairwise field indicates the set of accepted encryption algorithms by the AP. In this example, both TKIP (WPA) and CCMP (WPA2) ciphers are accepted. The CCMP cipher is an alternative to TKIP and is strongly preferred when possible. TKIP should be used solely for stations incapable of doing CCMP. The next step is to start &man.hostapd.8;: &prompt.root; service hostapd forcestart &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2290 inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 inet6 fe80::211:95ff:fec3:dac%ath0 prefixlen 64 scopeid 0x4 ether 00:11:95:c3:0d:ac media: IEEE 802.11 Wireless Ethernet autoselect mode 11g <hostap> status: associated ssid freebsdap channel 1 bssid 00:11:95:c3:0d:ac authmode WPA2/802.11i privacy MIXED deftxkey 2 TKIP 2:128-bit txpowmax 36 protmode CTS dtimperiod 1 bintval 100 Once the AP is running, the clients can associate with it. See for more details. It is possible to see the stations associated with the AP using ifconfig wlan0 list sta. <acronym>WEP</acronym> Host-based Access Point It is not recommended to use WEP for setting up an AP since there is no authentication mechanism and the encryption is easily cracked. Some legacy wireless cards only support WEP and these cards will only support an AP without authentication or encryption. The wireless device can now be put into hostap mode and configured with the correct SSID and IP address: &prompt.root; ifconfig wlan0 create wlandev ath0 wlanmode hostap &prompt.root; ifconfig wlan0 inet 192.168.0.1 netmask 255.255.255.0 \ ssid freebsdap wepmode on weptxkey 3 wepkey 3:0x3456789012 mode 11g The weptxkey indicates which WEP key will be used in the transmission. This example uses the third key as key numbering starts with 1. This parameter must be specified in order to encrypt the data. The wepkey sets the selected WEP key. It should be in the format index:key. If the index is not given, key 1 is set. The index needs to be set when using keys other than the first key. Use &man.ifconfig.8; to see the status of the wlan0 interface: &prompt.root; ifconfig wlan0 wlan0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 00:11:95:c3:0d:ac inet 192.168.0.1 netmask 0xffffff00 broadcast 192.168.0.255 media: IEEE 802.11 Wireless Ethernet autoselect mode 11g <hostap> status: running ssid freebsdap channel 4 (2427 Mhz 11g) bssid 00:11:95:c3:0d:ac country US ecm authmode OPEN privacy ON deftxkey 3 wepkey 3:40-bit txpower 21.5 scanvalid 60 protmode CTS wme burst dtimperiod 1 -dfs From another wireless machine, it is now possible to initiate a scan to find the AP: &prompt.root; ifconfig wlan0 create wlandev ath0 &prompt.root; ifconfig wlan0 up scan SSID BSSID CHAN RATE S:N INT CAPS freebsdap 00:11:95:c3:0d:ac 1 54M 22:1 100 EPS In this example, the client machine found the AP and can associate with it using the correct parameters. See for more details. Using Both Wired and Wireless Connections A wired connection provides better performance and reliability, while a wireless connection provides flexibility and mobility. Laptop users typically want to roam seamlessly between the two types of connections. On &os;, it is possible to combine two or even more network interfaces together in a failover fashion. This type of configuration uses the most preferred and available connection from a group of network interfaces, and the operating system switches automatically when the link state changes. Link aggregation and failover is covered in and an example for using both wired and wireless connections is provided at . Troubleshooting This section describes a number of steps to help troubleshoot common wireless networking problems. If the access point is not listed when scanning, check that the configuration has not limited the wireless device to a limited set of channels. If the device cannot associate with an access point, verify that the configuration matches the settings on the access point. This includes the authentication scheme and any security protocols. Simplify the configuration as much as possible. If using a security protocol such as WPA or WEP, configure the access point for open authentication and no security to see if traffic will pass. Once the system can associate with the access point, diagnose the security configuration using tools like &man.ping.8;. Debugging support is provided by &man.wpa.supplicant.8;. Try running this utility manually with the option and look at the system logs. There are many lower-level debugging tools. Debugging messages can be enabled in the 802.11 protocol support layer using &man.wlandebug.8;. On a &os; system prior to &os; 9.1, this program can be found in /usr/src/tools/tools/net80211. For example, to enable console messages related to scanning for access points and the 802.11 protocol handshakes required to arrange communication: &prompt.root; wlandebug -i ath0 +scan+auth+debug+assoc net.wlan.0.debug: 0 => 0xc80000<assoc,auth,scan> Many useful statistics are maintained by the 802.11 layer and wlanstats, found in /usr/src/tools/tools/net80211, will dump this information. These statistics should display all errors identified by the 802.11 layer. However, some errors are identified in the device drivers that lie below the 802.11 layer so they may not show up. To diagnose device-specific problems, refer to the drivers' documentation. If the above information does not help to clarify the problem, submit a problem report and include output from the above tools.
USB Tethering tether Many cellphones provide the option to share their data connection over USB (often called "tethering"). This feature uses the RNDIS or CDC protocol. Before attaching a device, load the appropriate driver into the kernel: &prompt.root; kldload if_urndis &prompt.root; kldload cdce Once the device is attached ue0 will be available for use like a normal network device. Be sure that the USB tethering option is enabled on the device. Bluetooth Pav Lucistnik Written by pav@FreeBSD.org Bluetooth Introduction Bluetooth is a wireless technology for creating personal networks operating in the 2.4 GHz unlicensed band, with a range of 10 meters. Networks are usually formed ad-hoc from portable devices such as cellular phones, handhelds and laptops. Unlike Wi-Fi wireless technology, Bluetooth offers higher level service profiles, such as FTP-like file servers, file pushing, voice transport, serial line emulation, and more. The Bluetooth stack in &os; is implemented using the &man.netgraph.4; framework. A broad variety of Bluetooth USB dongles is supported by &man.ng.ubt.4;. Broadcom BCM2033 based Bluetooth devices are supported by the &man.ubtbcmfw.4; and &man.ng.ubt.4; drivers. The 3Com Bluetooth PC Card 3CRWB60-A is supported by the &man.ng.bt3c.4; driver. Serial and UART based Bluetooth devices are supported by &man.sio.4;, &man.ng.h4.4; and &man.hcseriald.8;. This section describes the use of a USB Bluetooth dongle. Plugging in the Device By default, Bluetooth device drivers are available as kernel modules. Before attaching a device, load the driver into the kernel: &prompt.root; kldload ng_ubt If the Bluetooth device is present in the system during system startup, load the module from /boot/loader.conf: ng_ubt_load="YES" Plug in the USB dongle. Output similar to the following will appear on the console and in the system log: ubt0: vendor 0x0a12 product 0x0001, rev 1.10/5.25, addr 2 ubt0: Interface 0 endpoints: interrupt=0x81, bulk-in=0x82, bulk-out=0x2 ubt0: Interface 1 (alt.config 5) endpoints: isoc-in=0x83, isoc-out=0x3, wMaxPacketSize=49, nframes=6, buffer size=294 To start and stop the Bluetooth stack, use &man.service.8;. It is a good idea to stop the stack before unplugging the device. When starting the stack, the output should be similar to the following: &prompt.root; service bluetooth start ubt0 BD_ADDR: 00:02:72:00:d4:1a Features: 0xff 0xff 0xf 00 00 00 00 00 <3-Slot> <5-Slot> <Encryption> <Slot offset> <Timing accuracy> <Switch> <Hold mode> <Sniff mode> <Park mode> <RSSI> <Channel quality> <SCO link> <HV2 packets> <HV3 packets> <u-law log> <A-law log> <CVSD> <Paging scheme> <Power control> <Transparent SCO data> Max. ACL packet size: 192 bytes Number of ACL packets: 8 Max. SCO packet size: 64 bytes Number of SCO packets: 8 Host Controller Interface (<acronym>HCI</acronym>) HCI The Host Controller Interface (HCI) provides a command interface to the baseband controller and link manager as well as access to hardware status and control registers. This interface provides a uniform method for accessing Bluetooth baseband capabilities. The HCI layer on the host exchanges data and commands with the HCI firmware on the Bluetooth hardware. The Host Controller Transport Layer (physical bus) driver provides both HCI layers with the ability to exchange information. A single netgraph node of type hci is created for a single Bluetooth device. The HCI node is normally connected to the downstream Bluetooth device driver node and the upstream L2CAP node. All HCI operations must be performed on the HCI node and not on the device driver node. The default name for the HCI node is devicehci. For more details, refer to &man.ng.hci.4;. One of the most common tasks is discovery of Bluetooth devices in RF proximity. This operation is called inquiry. Inquiry and other HCI related operations are done using &man.hccontrol.8;. The example below shows how to find out which Bluetooth devices are in range. The list of devices should be displayed in a few seconds. Note that a remote device will only answer the inquiry if it is set to discoverable mode. &prompt.user; hccontrol -n ubt0hci inquiry Inquiry result, num_responses=1 Inquiry result #0 BD_ADDR: 00:80:37:29:19:a4 Page Scan Rep. Mode: 0x1 Page Scan Period Mode: 00 Page Scan Mode: 00 Class: 52:02:04 Clock offset: 0x78ef Inquiry complete. Status: No error [00] The BD_ADDR is the unique address of a Bluetooth device, similar to the MAC address of a network card. This address is needed for further communication with a device. It is possible to assign a human readable name to a BD_ADDR. Information regarding the known Bluetooth hosts is contained in /etc/bluetooth/hosts. The following example shows how to obtain the human readable name that was assigned to the remote device: &prompt.user; hccontrol -n ubt0hci remote_name_request 00:80:37:29:19:a4 BD_ADDR: 00:80:37:29:19:a4 Name: Pav's T39 If an inquiry is performed on a remote Bluetooth device, it will find the computer as your.host.name (ubt0). The name assigned to the local device can be changed at any time. The Bluetooth system provides a point-to-point connection between two Bluetooth units, or a point-to-multipoint connection which is shared among several Bluetooth devices. The following example shows how to obtain the list of active baseband connections for the local device: &prompt.user; hccontrol -n ubt0hci read_connection_list Remote BD_ADDR Handle Type Mode Role Encrypt Pending Queue State 00:80:37:29:19:a4 41 ACL 0 MAST NONE 0 0 OPEN A connection handle is useful when termination of the baseband connection is required, though it is normally not required to do this by hand. The stack will automatically terminate inactive baseband connections. &prompt.root; hccontrol -n ubt0hci disconnect 41 Connection handle: 41 Reason: Connection terminated by local host [0x16] Type hccontrol help for a complete listing of available HCI commands. Most of the HCI commands do not require superuser privileges. Logical Link Control and Adaptation Protocol (<acronym>L2CAP</acronym>) L2CAP The Logical Link Control and Adaptation Protocol (L2CAP) provides connection-oriented and connectionless data services to upper layer protocols with protocol multiplexing capability and segmentation and reassembly operation. L2CAP permits higher level protocols and applications to transmit and receive L2CAP data packets up to 64 kilobytes in length. L2CAP is based around the concept of channels. A channel is a logical connection on top of a baseband connection. Each channel is bound to a single protocol in a many-to-one fashion. Multiple channels can be bound to the same protocol, but a channel cannot be bound to multiple protocols. Each L2CAP packet received on a channel is directed to the appropriate higher level protocol. Multiple channels can share the same baseband connection. A single netgraph node of type l2cap is created for a single Bluetooth device. The L2CAP node is normally connected to the downstream Bluetooth HCI node and upstream Bluetooth socket nodes. The default name for the L2CAP node is devicel2cap. For more details refer to &man.ng.l2cap.4;. A useful command is &man.l2ping.8;, which can be used to ping other devices. Some Bluetooth implementations might not return all of the data sent to them, so 0 bytes in the following example is normal. &prompt.root; l2ping -a 00:80:37:29:19:a4 0 bytes from 0:80:37:29:19:a4 seq_no=0 time=48.633 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=1 time=37.551 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=2 time=28.324 ms result=0 0 bytes from 0:80:37:29:19:a4 seq_no=3 time=46.150 ms result=0 The &man.l2control.8; utility is used to perform various operations on L2CAP nodes. This example shows how to obtain the list of logical connections (channels) and the list of baseband connections for the local device: &prompt.user; l2control -a 00:02:72:00:d4:1a read_channel_list L2CAP channels: Remote BD_ADDR SCID/ DCID PSM IMTU/ OMTU State 00:07:e0:00:0b:ca 66/ 64 3 132/ 672 OPEN &prompt.user; l2control -a 00:02:72:00:d4:1a read_connection_list L2CAP connections: Remote BD_ADDR Handle Flags Pending State 00:07:e0:00:0b:ca 41 O 0 OPEN Another diagnostic tool is &man.btsockstat.1;. It is similar to &man.netstat.1;, but for Bluetooth network-related data structures. The example below shows the same logical connection as &man.l2control.8; above. &prompt.user; btsockstat Active L2CAP sockets PCB Recv-Q Send-Q Local address/PSM Foreign address CID State c2afe900 0 0 00:02:72:00:d4:1a/3 00:07:e0:00:0b:ca 66 OPEN Active RFCOMM sessions L2PCB PCB Flag MTU Out-Q DLCs State c2afe900 c2b53380 1 127 0 Yes OPEN Active RFCOMM sockets PCB Recv-Q Send-Q Local address Foreign address Chan DLCI State c2e8bc80 0 250 00:02:72:00:d4:1a 00:07:e0:00:0b:ca 3 6 OPEN <acronym>RFCOMM</acronym> Protocol The RFCOMM protocol provides emulation of serial ports over the L2CAP protocol. The protocol is based on the ETSI standard TS 07.10. RFCOMM is a simple transport protocol, with additional provisions for emulating the 9 circuits of RS-232 (EIATIA-232-E) serial ports. RFCOMM supports up to 60 simultaneous connections (RFCOMM channels) between two Bluetooth devices. For the purposes of RFCOMM, a complete communication path involves two applications running on the communication endpoints with a communication segment between them. RFCOMM is intended to cover applications that make use of the serial ports of the devices in which they reside. The communication segment is a direct connect Bluetooth link from one device to another. RFCOMM is only concerned with the connection between the devices in the direct connect case, or between the device and a modem in the network case. RFCOMM can support other configurations, such as modules that communicate via Bluetooth wireless technology on one side and provide a wired interface on the other side. In &os;, RFCOMM is implemented at the Bluetooth sockets layer. Pairing of Devices By default, Bluetooth communication is not authenticated, and any device can talk to any other device. A Bluetooth device, such as a cellular phone, may choose to require authentication to provide a particular service. Bluetooth authentication is normally done with a PIN code, an ASCII string up to 16 characters in length. The user is required to enter the same PIN code on both devices. Once the user has entered the PIN code, both devices will generate a link key. After that, the link key can be stored either in the devices or in a persistent storage. Next time, both devices will use the previously generated link key. This procedure is called pairing. Note that if the link key is lost by either device, the pairing must be repeated. The &man.hcsecd.8; daemon is responsible for handling Bluetooth authentication requests. The default configuration file is /etc/bluetooth/hcsecd.conf. An example section for a cellular phone with the PIN code arbitrarily set to 1234 is shown below: device { bdaddr 00:80:37:29:19:a4; name "Pav's T39"; key nokey; pin "1234"; } The only limitation on PIN codes is length. Some devices, such as Bluetooth headsets, may have a fixed PIN code built in. The switch forces &man.hcsecd.8; to stay in the foreground, so it is easy to see what is happening. Set the remote device to receive pairing and initiate the Bluetooth connection to the remote device. The remote device should indicate that pairing was accepted and request the PIN code. Enter the same PIN code listed in hcsecd.conf. Now the computer and the remote device are paired. Alternatively, pairing can be initiated on the remote device. The following line can be added to /etc/rc.conf to configure &man.hcsecd.8; to start automatically on system start: hcsecd_enable="YES" The following is a sample of the &man.hcsecd.8; daemon output: hcsecd[16484]: Got Link_Key_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', link key doesn't exist hcsecd[16484]: Sending Link_Key_Negative_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Got PIN_Code_Request event from 'ubt0hci', remote bdaddr 0:80:37:29:19:a4 hcsecd[16484]: Found matching entry, remote bdaddr 0:80:37:29:19:a4, name 'Pav's T39', PIN code exists hcsecd[16484]: Sending PIN_Code_Reply to 'ubt0hci' for remote bdaddr 0:80:37:29:19:a4 Service Discovery Protocol (<acronym>SDP</acronym>) SDP The Service Discovery Protocol (SDP) provides the means for client applications to discover the existence of services provided by server applications as well as the attributes of those services. The attributes of a service include the type or class of service offered and the mechanism or protocol information needed to utilize the service. SDP involves communication between a SDP server and a SDP client. The server maintains a list of service records that describe the characteristics of services associated with the server. Each service record contains information about a single service. A client may retrieve information from a service record maintained by the SDP server by issuing a SDP request. If the client, or an application associated with the client, decides to use a service, it must open a separate connection to the service provider in order to utilize the service. SDP provides a mechanism for discovering services and their attributes, but it does not provide a mechanism for utilizing those services. Normally, a SDP client searches for services based on some desired characteristics of the services. However, there are times when it is desirable to discover which types of services are described by an SDP server's service records without any prior information about the services. This process of looking for any offered services is called browsing. The Bluetooth SDP server, &man.sdpd.8;, and command line client, &man.sdpcontrol.8;, are included in the standard &os; installation. The following example shows how to perform a SDP browse query. &prompt.user; sdpcontrol -a 00:01:03:fc:6e:ec browse Record Handle: 00000000 Service Class ID List: Service Discovery Server (0x1000) Protocol Descriptor List: L2CAP (0x0100) Protocol specific parameter #1: u/int/uuid16 1 Protocol specific parameter #2: u/int/uuid16 1 Record Handle: 0x00000001 Service Class ID List: Browse Group Descriptor (0x1001) Record Handle: 0x00000002 Service Class ID List: LAN Access Using PPP (0x1102) Protocol Descriptor List: L2CAP (0x0100) RFCOMM (0x0003) Protocol specific parameter #1: u/int8/bool 1 Bluetooth Profile Descriptor List: LAN Access Using PPP (0x1102) ver. 1.0 Note that each service has a list of attributes, such as the RFCOMM channel. Depending on the service, the user might need to make note of some of the attributes. Some Bluetooth implementations do not support service browsing and may return an empty list. In this case, it is possible to search for the specific service. The example below shows how to search for the OBEX Object Push (OPUSH) service: &prompt.user; sdpcontrol -a 00:01:03:fc:6e:ec search OPUSH Offering services on &os; to Bluetooth clients is done with the &man.sdpd.8; server. The following line can be added to /etc/rc.conf: sdpd_enable="YES" Then the &man.sdpd.8; daemon can be started with: &prompt.root; service sdpd start The local server application that wants to provide Bluetooth service to the remote clients will register service with the local SDP daemon. An example of such an application is &man.rfcomm.pppd.8;. Once started, it will register the Bluetooth LAN service with the local SDP daemon. The list of services registered with the local SDP server can be obtained by issuing a SDP browse query via the local control channel: &prompt.root; sdpcontrol -l browse Dial-Up Networking and Network Access with <acronym>PPP</acronym> Profiles The Dial-Up Networking (DUN) profile is mostly used with modems and cellular phones. The scenarios covered by this profile are the following: Use of a cellular phone or modem by a computer as a wireless modem for connecting to a dial-up Internet access server, or for using other dial-up services. Use of a cellular phone or modem by a computer to receive data calls. Network access with a PPP profile can be used in the following situations: LAN access for a single Bluetooth device. LAN access for multiple Bluetooth devices. PC to PC connection using PPP networking over serial cable emulation. In &os;, these profiles are implemented with &man.ppp.8; and the &man.rfcomm.pppd.8; wrapper which converts a RFCOMM Bluetooth connection into something PPP can use. Before a profile can be used, a new PPP label must be created in /etc/ppp/ppp.conf. Consult &man.rfcomm.pppd.8; for examples. In the following example, &man.rfcomm.pppd.8; is used to open a RFCOMM connection to a remote device with a BD_ADDR of 00:80:37:29:19:a4 on a DUN RFCOMM channel. The actual RFCOMM channel number will be obtained from the remote device via SDP. It is possible to specify the RFCOMM channel by hand, and in this case &man.rfcomm.pppd.8; will not perform the SDP query. Use &man.sdpcontrol.8; to find out the RFCOMM channel on the remote device. &prompt.root; rfcomm_pppd -a 00:80:37:29:19:a4 -c -C dun -l rfcomm-dialup In order to provide network access with the PPP LAN service, &man.sdpd.8; must be running and a new entry for LAN clients must be created in /etc/ppp/ppp.conf. Consult &man.rfcomm.pppd.8; for examples. Finally, start the RFCOMM PPP server on a valid RFCOMM channel number. The RFCOMM PPP server will automatically register the Bluetooth LAN service with the local SDP daemon. The example below shows how to start the RFCOMM PPP server. &prompt.root; rfcomm_pppd -s -C 7 -l rfcomm-server <acronym>OBEX</acronym> Object Push (<acronym>OPUSH</acronym>) Profile OBEX OBEX is a widely used protocol for simple file transfers between mobile devices. Its main use is in infrared communication, where it is used for generic file transfers between notebooks or PDAs, and for sending business cards or calendar entries between cellular phones and other devices with PIM applications. The OBEX server and client are implemented as a third-party package, obexapp, which is available as comms/obexapp package or port. The OBEX client is used to push and/or pull objects from the OBEX server. An object can, for example, be a business card or an appointment. The OBEX client can obtain the RFCOMM channel number from the remote device via SDP. This can be done by specifying the service name instead of the RFCOMM channel number. Supported service names are: IrMC, FTRN, and OPUSH. It is also possible to specify the RFCOMM channel as a number. Below is an example of an OBEX session where the device information object is pulled from the cellular phone, and a new object, the business card, is pushed into the phone's directory. &prompt.user; obexapp -a 00:80:37:29:19:a4 -C IrMC obex> get telecom/devinfo.txt devinfo-t39.txt Success, response: OK, Success (0x20) obex> put new.vcf Success, response: OK, Success (0x20) obex> di Success, response: OK, Success (0x20) In order to provide the OPUSH service, &man.sdpd.8; must be running and a root folder, where all incoming objects will be stored, must be created. The default path to the root folder is /var/spool/obex. Finally, start the OBEX server on a valid RFCOMM channel number. The OBEX server will automatically register the OPUSH service with the local SDP daemon. The example below shows how to start the OBEX server. &prompt.root; obexapp -s -C 10 Serial Port Profile The Serial Port Profile (SPP) allows Bluetooth devices to perform serial cable emulation. This profile allows legacy applications to use Bluetooth as a cable replacement, through a virtual serial port abstraction. In &os;, &man.rfcomm.sppd.1; implements SPP and a pseudo tty is used as a virtual serial port abstraction. The example below shows how to connect to a remote device serial port service. A RFCOMM channel does not have to be specified as &man.rfcomm.sppd.1; can obtain it from the remote device via SDP. To override this, specify a RFCOMM channel on the command line. &prompt.root; rfcomm_sppd -a 00:07:E0:00:0B:CA -t /dev/ttyp6 rfcomm_sppd[94692]: Starting on /dev/ttyp6... Once connected, the pseudo tty can be used as serial port: &prompt.root; cu -l ttyp6 Troubleshooting A Remote Device Cannot Connect Some older Bluetooth devices do not support role switching. By default, when &os; is accepting a new connection, it tries to perform a role switch and become master. Devices, which do not support this will not be able to connect. Since role switching is performed when a new connection is being established, it is not possible to ask the remote device if it supports role switching. There is a HCI option to disable role switching on the local side: &prompt.root; hccontrol -n ubt0hci write_node_role_switch 0 Displaying Bluetooth Packets Use the third-party package hcidump, which is available as a comms/hcidump package or port. This utility is similar to &man.tcpdump.1; and can be used to display the contents of Bluetooth packets on the terminal and to dump the Bluetooth packets to a file. Bridging Andrew Thompson Written by Introduction IP subnet bridge It is sometimes useful to divide one physical network, such as an Ethernet segment, into two separate network segments without having to create IP subnets and use a router to connect the segments together. A device that connects two networks together in this fashion is called a bridge. A &os; system with two network interface cards can act as a bridge. The bridge works by learning the MAC layer (Ethernet) addresses of the devices on each of its network interfaces. It forwards traffic between two networks only when the source and destination are on different networks. In many respects, a bridge is like an Ethernet switch with very few ports. Situations Where Bridging Is Appropriate There are many common situations in which a bridge is used today. Connecting Networks The basic operation of a bridge is to join two or more network segments together. There are many reasons to use a host based bridge over plain networking equipment such as cabling constraints, firewalling, or connecting pseudo networks such as a virtual machine interface. A bridge can also connect a wireless interface running in hostap mode to a wired network and act as an access point. Filtering/Traffic Shaping Firewall firewall NAT A common situation is where firewall functionality is needed without routing or Network Address Translation (NAT). An example is a small company that is connected via DSL or ISDN to an ISP. There are thirteen globally-accessible IP addresses from the ISP and ten computers on the network. In this situation, using a router-based firewall is difficult because of subnetting issues. router DSL ISDN A bridge-based firewall can be configured and dropped into the path just downstream of the DSL or ISDN router without any IP numbering issues. Network Tap A bridge can join two network segments and be used to inspect all Ethernet frames that pass between them using &man.bpf.4; and &man.tcpdump.1; on the bridge interface or by sending a copy of all frames out an additional interface known as a span port. Layer 2 <acronym>VPN</acronym> Two Ethernet networks can be joined across an IP link by bridging the networks to an EtherIP tunnel or a &man.tap.4; based solution such as OpenVPN. Layer 2 Redundancy A network can be connected together with multiple links and use the Spanning Tree Protocol STP to block redundant paths. For an Ethernet network to function properly, only one active path can exist between two devices. STP will detect loops and put the redundant links into a blocked state. Should one of the active links fail, STP will calculate a different tree and enable one of the blocked paths to restore connectivity to all points in the network. Kernel Configuration This section covers the &man.if.bridge.4; implementation. A netgraph bridging driver is also available, and is described in &man.ng.bridge.4;. In &os;, &man.if.bridge.4; is a kernel module which is automatically loaded by &man.ifconfig.8; when creating a bridge interface. It is also possible to compile the bridge in to the kernel by adding device if_bridge to a custom kernel configuration file. Packet filtering can be used with any firewall package that hooks in via the &man.pfil.9; framework. The firewall can be loaded as a module or compiled into the kernel. The bridge can be used as a traffic shaper with &man.altq.4; or &man.dummynet.4;. Enabling the Bridge The bridge is created using interface cloning. To create a bridge use &man.ifconfig.8;: &prompt.root; ifconfig bridge create bridge0 &prompt.root; ifconfig bridge0 bridge0: flags=8802<BROADCAST,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:00:00:00:00:00 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:00:00:00:00:00 priority 0 ifcost 0 port 0 When a bridge interface is created, it is automatically assigned a randomly generated Ethernet address. The maxaddr and timeout parameters control how many MAC addresses the bridge will keep in its forwarding table and how many seconds before each entry is removed after it is last seen. The other parameters control how STP operates. Next, add the member network interfaces to the bridge. For the bridge to forward packets, all member interfaces and the bridge need to be up: &prompt.root; ifconfig bridge0 addm fxp0 addm fxp1 up &prompt.root; ifconfig fxp0 up &prompt.root; ifconfig fxp1 up The bridge is now forwarding Ethernet frames between fxp0 and fxp1. Add the following lines to /etc/rc.conf so the bridge is created at startup: cloned_interfaces="bridge0" ifconfig_bridge0="addm fxp0 addm fxp1 up" ifconfig_fxp0="up" ifconfig_fxp1="up" If the bridge host needs an IP address, the correct place to set this is on the bridge interface itself rather than one of the member interfaces. This can be set statically or via DHCP: &prompt.root; ifconfig bridge0 inet 192.168.0.1/24 It is also possible to assign an IPv6 address to a bridge interface. Firewalling firewall When packet filtering is enabled, bridged packets will pass through the filter inbound on the originating interface on the bridge interface, and outbound on the appropriate interfaces. Either stage can be disabled. When direction of the packet flow is important, it is best to firewall on the member interfaces rather than the bridge itself. The bridge has several configurable settings for passing non-IP and IP packets, and layer2 firewalling with &man.ipfw.8;. See &man.if.bridge.4; for more information. Spanning Tree The bridge driver implements the Rapid Spanning Tree Protocol (RSTP or 802.1w) with backwards compatibility with legacy STP. STP is used to detect and remove loops in a network topology. RSTP provides faster convergence than legacy STP, the protocol will exchange information with neighboring switches to quickly transition to forwarding without creating loops. &os; supports RSTP and STP as operating modes, with RSTP being the default mode. STP can be enabled on member interfaces using &man.ifconfig.8;. For a bridge with fxp0 and fxp1 as the current interfaces, enable STP with: &prompt.root; ifconfig bridge0 stp fxp0 stp fxp1 bridge0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether d6:cf:d5:a0:94:6d id 00:01:02:4b:d4:50 priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 0 port 0 member: fxp0 flags=1c7<LEARNING,DISCOVER,STP,AUTOEDGE,PTP,AUTOPTP> port 3 priority 128 path cost 200000 proto rstp role designated state forwarding member: fxp1 flags=1c7<LEARNING,DISCOVER,STP,AUTOEDGE,PTP,AUTOPTP> port 4 priority 128 path cost 200000 proto rstp role designated state forwarding This bridge has a spanning tree ID of 00:01:02:4b:d4:50 and a priority of 32768. As the root id is the same, it indicates that this is the root bridge for the tree. Another bridge on the network also has STP enabled: bridge0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 ether 96:3d:4b:f1:79:7a id 00:13:d4:9a:06:7a priority 32768 hellotime 2 fwddelay 15 maxage 20 holdcnt 6 proto rstp maxaddr 100 timeout 1200 root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 member: fxp0 flags=1c7<LEARNING,DISCOVER,STP,AUTOEDGE,PTP,AUTOPTP> port 4 priority 128 path cost 200000 proto rstp role root state forwarding member: fxp1 flags=1c7<LEARNING,DISCOVER,STP,AUTOEDGE,PTP,AUTOPTP> port 5 priority 128 path cost 200000 proto rstp role designated state forwarding The line root id 00:01:02:4b:d4:50 priority 32768 ifcost 400000 port 4 shows that the root bridge is 00:01:02:4b:d4:50 and has a path cost of 400000 from this bridge. The path to the root bridge is via port 4 which is fxp0. Advanced Bridging Reconstruct Traffic Flows The bridge supports monitor mode, where the packets are discarded after &man.bpf.4; processing and are not processed or forwarded further. This can be used to multiplex the input of two or more interfaces into a single &man.bpf.4; stream. This is useful for reconstructing the traffic for network taps that transmit the RX/TX signals out through two separate interfaces. To read the input from four network interfaces as one stream: &prompt.root; ifconfig bridge0 addm fxp0 addm fxp1 addm fxp2 addm fxp3 monitor up &prompt.root; tcpdump -i bridge0 Span Ports A copy of every Ethernet frame received by the bridge will be transmitted out a designated span port. The number of span ports configured on a bridge is unlimited, but if an interface is designated as a span port, it cannot also be used as a regular bridge port. This is most useful for snooping a bridged network passively on another host connected to one of the span ports of the bridge. To send a copy of all frames out the interface named fxp4: &prompt.root; ifconfig bridge0 span fxp4 Private Interfaces A private interface does not forward any traffic to any other port that is also a private interface. The traffic is blocked unconditionally so no Ethernet frames will be forwarded, including ARP. If traffic needs to be selectively blocked, a firewall should be used instead. Sticky Interfaces If a bridge member interface is marked as sticky, dynamically learned address entries are treated at static once entered into the forwarding cache. Sticky entries are never aged out of the cache or replaced, even if the address is seen on a different interface. This gives the benefit of static address entries without the need to pre-populate the forwarding table. Clients learned on a particular segment of the bridge can not roam to another segment. Another example of using sticky addresses is to combine the bridge with VLANs to create a router where customer networks are isolated without wasting IP address space. Consider that CustomerA is on vlan100 and CustomerB is on vlan101. The bridge has the address 192.168.0.1 and is also an Internet router. &prompt.root; ifconfig bridge0 addm vlan100 sticky vlan100 addm vlan101 sticky vlan101 &prompt.root; ifconfig bridge0 inet 192.168.0.1/24 In this example, both clients see 192.168.0.1 as their default gateway. Since the bridge cache is sticky, one host can not spoof the MAC address of the other customer in order to intercept their traffic. Any communication between the VLANs can be blocked using a firewall or, as seen in this example, private interfaces: &prompt.root; ifconfig bridge0 private vlan100 private vlan101 The customers are completely isolated from each other and the full /24 address range can be allocated without subnetting. Address Limits The number of unique source MAC addresses behind an interface can be limited. Once the limit is reached, packets with unknown source addresses are dropped until an existing host cache entry expires or is removed. The following example sets the maximum number of Ethernet devices for CustomerA on vlan100 to 10: &prompt.root; ifconfig bridge0 ifmaxaddr vlan100 10 <acronym>SNMP</acronym> Monitoring The bridge interface and STP parameters can be monitored via &man.bsnmpd.1; which is included in the &os; base system. The exported bridge MIBs conform to the IETF standards so any SNMP client or monitoring package can be used to retrieve the data. On the bridge, uncomment the begemotSnmpdModulePath."bridge" = "/usr/lib/snmp_bridge.so" line from /etc/snmp.config and start &man.bsnmpd.1;. Other configuration, such as community names and access lists, may need to be modified. See &man.bsnmpd.1; and &man.snmp.bridge.3; for more information. The following examples use the Net-SNMP software (net-mgmt/net-snmp) to query a bridge from a client system. The net-mgmt/bsnmptools port can also be used. From the SNMP client which is running Net-SNMP, add the following lines to $HOME/.snmp/snmp.conf in order to import the bridge MIB definitions: mibdirs +/usr/share/snmp/mibs mibs +BRIDGE-MIB:RSTP-MIB:BEGEMOT-MIB:BEGEMOT-BRIDGE-MIB To monitor a single bridge using the IETF BRIDGE-MIB (RFC4188): &prompt.user; snmpwalk -v 2c -c public bridge1.example.com mib-2.dot1dBridge BRIDGE-MIB::dot1dBaseBridgeAddress.0 = STRING: 66:fb:9b:6e:5c:44 BRIDGE-MIB::dot1dBaseNumPorts.0 = INTEGER: 1 ports BRIDGE-MIB::dot1dStpTimeSinceTopologyChange.0 = Timeticks: (189959) 0:31:39.59 centi-seconds BRIDGE-MIB::dot1dStpTopChanges.0 = Counter32: 2 BRIDGE-MIB::dot1dStpDesignatedRoot.0 = Hex-STRING: 80 00 00 01 02 4B D4 50 ... BRIDGE-MIB::dot1dStpPortState.3 = INTEGER: forwarding(5) BRIDGE-MIB::dot1dStpPortEnable.3 = INTEGER: enabled(1) BRIDGE-MIB::dot1dStpPortPathCost.3 = INTEGER: 200000 BRIDGE-MIB::dot1dStpPortDesignatedRoot.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedCost.3 = INTEGER: 0 BRIDGE-MIB::dot1dStpPortDesignatedBridge.3 = Hex-STRING: 80 00 00 01 02 4B D4 50 BRIDGE-MIB::dot1dStpPortDesignatedPort.3 = Hex-STRING: 03 80 BRIDGE-MIB::dot1dStpPortForwardTransitions.3 = Counter32: 1 RSTP-MIB::dot1dStpVersion.0 = INTEGER: rstp(2) The dot1dStpTopChanges.0 value is two, indicating that the STP bridge topology has changed twice. A topology change means that one or more links in the network have changed or failed and a new tree has been calculated. The dot1dStpTimeSinceTopologyChange.0 value will show when this happened. To monitor multiple bridge interfaces, the private BEGEMOT-BRIDGE-MIB can be used: &prompt.user; snmpwalk -v 2c -c public bridge1.example.com enterprises.fokus.begemot.begemotBridge BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge0" = STRING: bridge0 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseName."bridge2" = STRING: bridge2 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge0" = STRING: e:ce:3b:5a:9e:13 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseAddress."bridge2" = STRING: 12:5e:4d:74:d:fc BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge0" = INTEGER: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeBaseNumPorts."bridge2" = INTEGER: 1 ... BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge0" = Timeticks: (116927) 0:19:29.27 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTimeSinceTopologyChange."bridge2" = Timeticks: (82773) 0:13:47.73 centi-seconds BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge0" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpTopChanges."bridge2" = Counter32: 1 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge0" = Hex-STRING: 80 00 00 40 95 30 5E 31 BEGEMOT-BRIDGE-MIB::begemotBridgeStpDesignatedRoot."bridge2" = Hex-STRING: 80 00 00 50 8B B8 C6 A9 To change the bridge interface being monitored via the mib-2.dot1dBridge subtree: &prompt.user; snmpset -v 2c -c private bridge1.example.com BEGEMOT-BRIDGE-MIB::begemotBridgeDefaultBridgeIf.0 s bridge2 Link Aggregation and Failover Andrew Thompson Written by lagg failover FEC LACP loadbalance roundrobin &os; provides the &man.lagg.4; interface which can be used to aggregate multiple network interfaces into one virtual interface in order to provide failover and link aggregation. Failover allows traffic to continue to flow even if an interface becomes available. Link aggregation works best on switches which support LACP, as this protocol distributes traffic bi-directionally while responding to the failure of individual links. The aggregation protocols supported by the lagg interface determine which ports are used for outgoing traffic and whether or not a specific port accepts incoming traffic. The following protocols are supported by &man.lagg.4;: failover This mode sends and receives traffic only through the master port. If the master port becomes unavailable, the next active port is used. The first interface added to the virtual interface is the master port and all subsequently added interfaces are used as failover devices. If failover to a non-master port occurs, the original port becomes master once it becomes available again. fec / loadbalance &cisco; Fast ðerchannel; (FEC) is found on older &cisco; switches. It provides a static setup and does not negotiate aggregation with the peer or exchange frames to monitor the link. If the switch supports LACP, that should be used instead. lacp The &ieee; 802.3ad Link Aggregation Control Protocol (LACP) negotiates a set of aggregable links with the peer into one or more Link Aggregated Groups (LAGs). Each LAG is composed of ports of the same speed, set to full-duplex operation, and traffic is balanced across the ports in the LAG with the greatest total speed. Typically, there is only one LAG which contains all the ports. In the event of changes in physical connectivity, LACP will quickly converge to a new configuration. LACP balances outgoing traffic across the active ports based on hashed protocol header information and accepts incoming traffic from any active port. The hash includes the Ethernet source and destination address and, if available, the VLAN tag, and the IPv4 or IPv6 source and destination address. roundrobin This mode distributes outgoing traffic using a round-robin scheduler through all active ports and accepts incoming traffic from any active port. Since this mode violates Ethernet frame ordering, it should be used with caution. Configuration Examples This section demonstrates how to configure a &cisco; switch and a &os; system for LACP load balancing. It then shows how to configure two Ethernet interfaces in failover mode as well as how to configure failover mode between an Ethernet and a wireless interface. <acronym>LACP</acronym> Aggregation with a &cisco; Switch This example connects two &man.fxp.4; Ethernet interfaces on a &os; machine to the first two Ethernet ports on a &cisco; switch as a single load balanced and fault tolerant link. More interfaces can be added to increase throughput and fault tolerance. Replace the names of the &cisco; ports, Ethernet devices, channel group number, and IP address shown in the example to match the local configuration. Frame ordering is mandatory on Ethernet links and any traffic between two stations always flows over the same physical link, limiting the maximum speed to that of one interface. The transmit algorithm attempts to use as much information as it can to distinguish different traffic flows and balance the flows across the available interfaces. On the &cisco; switch, add the FastEthernet0/1 and FastEthernet0/2 interfaces to channel group 1: interface FastEthernet0/1 channel-group 1 mode active channel-protocol lacp ! interface FastEthernet0/2 channel-group 1 mode active channel-protocol lacp On the &os; system, create the &man.lagg.4; interface using the physical interfaces fxp0 and fxp1 and bring the interfaces up with an IP address of 10.0.0.3/24: &prompt.root; ifconfig fxp0 up &prompt.root; ifconfig fxp1 up &prompt.root; ifconfig lagg0 create &prompt.root; ifconfig lagg0 up laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24 Next, verify the status of the virtual interface: &prompt.root; ifconfig lagg0 lagg0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 options=8<VLAN_MTU> ether 00:05:5d:71:8d:b8 media: Ethernet autoselect status: active laggproto lacp laggport: fxp1 flags=1c<ACTIVE,COLLECTING,DISTRIBUTING> laggport: fxp0 flags=1c<ACTIVE,COLLECTING,DISTRIBUTING> Ports marked as ACTIVE are part of the LAG that has been negotiated with the remote switch. Traffic will be transmitted and received through these active ports. Add to the above command to view the LAG identifiers. To see the port status on the &cisco; switch: switch# show lacp neighbor Flags: S - Device is requesting Slow LACPDUs F - Device is requesting Fast LACPDUs A - Device is in Active mode P - Device is in Passive mode Channel group 1 neighbors Partner's information: LACP port Oper Port Port Port Flags Priority Dev ID Age Key Number State Fa0/1 SA 32768 0005.5d71.8db8 29s 0x146 0x3 0x3D Fa0/2 SA 32768 0005.5d71.8db8 29s 0x146 0x4 0x3D For more detail, type show lacp neighbor detail. To retain this configuration across reboots, add the following entries to /etc/rc.conf on the &os; system: ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto lacp laggport fxp0 laggport fxp1 10.0.0.3/24" Failover Mode Failover mode can be used to switch over to a secondary interface if the link is lost on the master interface. To configure failover, make sure that the underlying physical interfaces are up, then create the &man.lagg.4; interface. In this example, fxp0 is the master interface, fxp1 is the secondary interface, and the virtual interface is assigned an IP address of 10.0.0.15/24: &prompt.root; ifconfig fxp0 up &prompt.root; ifconfig fxp1 up &prompt.root; ifconfig lagg0 create &prompt.root; ifconfig lagg0 up laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24 The virtual interface should look something like this: &prompt.root; ifconfig lagg0 lagg0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 options=8<VLAN_MTU> ether 00:05:5d:71:8d:b8 inet 10.0.0.15 netmask 0xffffff00 broadcast 10.0.0.255 media: Ethernet autoselect status: active laggproto failover laggport: fxp1 flags=0<> laggport: fxp0 flags=5<MASTER,ACTIVE> Traffic will be transmitted and received on fxp0. If the link is lost on fxp0, fxp1 will become the active link. If the link is restored on the master interface, it will once again become the active link. To retain this configuration across reboots, add the following entries to /etc/rc.conf: ifconfig_fxp0="up" ifconfig_fxp1="up" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport fxp0 laggport fxp1 10.0.0.15/24" Failover Mode Between Ethernet and Wireless Interfaces For laptop users, it is usually desirable to configure the wireless device as a secondary which is only used when the Ethernet connection is not available. With &man.lagg.4;, it is possible to configure a failover which prefers the Ethernet connection for both performance and security reasons, while maintaining the ability to transfer data over the wireless connection. This is achieved by overriding the physical wireless interface's MAC address with that of the Ethernet interface. In this example, the Ethernet interface, bge0, is the master and the wireless interface, wlan0, is the failover. The wlan0 device was created from iwn0 wireless interface, which will be configured with the MAC address of the Ethernet interface. First, determine the MAC address of the Ethernet interface: &prompt.root; ifconfig bge0 bge0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 options=19b<RXCSUM,TXCSUM,VLAN_MTU,VLAN_HWTAGGING,VLAN_HWCSUM,TSO4> ether 00:21:70:da:ae:37 inet6 fe80::221:70ff:feda:ae37%bge0 prefixlen 64 scopeid 0x2 nd6 options=29<PERFORMNUD,IFDISABLED,AUTO_LINKLOCAL> media: Ethernet autoselect (1000baseT <full-duplex>) status: active Replace bge0 to match the system's Ethernet interface name. The ether line will contain the MAC address of the specified interface. Now, change the MAC address of the underlying wireless interface: &prompt.root; ifconfig iwn0 ether 00:21:70:da:ae:37 Bring the wireless interface up, but do not set an IP address: &prompt.root; ifconfig wlan0 create wlandev iwn0 ssid my_router up Make sure the bge0 interface is up, then create the &man.lagg.4; interface with bge0 as master with failover to wlan0: &prompt.root; ifconfig bge0 up &prompt.root; ifconfig lagg0 create &prompt.root; ifconfig lagg0 up laggproto failover laggport bge0 laggport wlan0 The virtual interface should look something like this: &prompt.root; ifconfig lagg0 lagg0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500 options=8<VLAN_MTU> ether 00:21:70:da:ae:37 media: Ethernet autoselect status: active laggproto failover laggport: wlan0 flags=0<> laggport: bge0 flags=5<MASTER,ACTIVE> Then, start the DHCP client to obtain an IP address: &prompt.root; dhclient lagg0 To retain this configuration across reboots, add the following entries to /etc/rc.conf: ifconfig_bge0="up" ifconfig_iwn0="ether 00:21:70:da:ae:37" wlans_iwn0="wlan0" ifconfig_wlan0="WPA" cloned_interfaces="lagg0" ifconfig_lagg0="laggproto failover laggport bge0 laggport wlan0 DHCP" Diskless Operation Jean-François Dockès Updated by Alex Dupre Reorganized and enhanced by diskless workstation diskless operation A &os; machine can boot over the network and operate without a local disk, using file systems mounted from an NFS server. No system modification is necessary, beyond standard configuration files. Such a system is relatively easy to set up because all the necessary elements are readily available: The &intel; Preboot eXecution Environment (PXE) can be used to load the kernel over the network. It provides a form of smart boot ROM built into some networking cards or motherboards. See &man.pxeboot.8; for more details. A sample script (/usr/share/examples/diskless/clone_root) eases the creation and maintenance of the workstation's root file system on the server. The script will probably require a little customization. Standard system startup files exist in /etc to detect and support a diskless system startup. Swapping, if needed, can be done either to an NFS file or to a local disk. There are many ways to set up diskless workstations. Many elements are involved, and most can be customized to suit local taste. The following will describe variations on the setup of a complete system, emphasizing simplicity and compatibility with the standard &os; startup scripts. The system described has the following characteristics: The diskless workstations use a shared, read-only / and /usr. The root file system is a copy of a standard &os; root, with some configuration files overridden by ones specific to diskless operation or, possibly, to the workstation they belong to. The parts of the root which have to be writable are overlaid with &man.md.4; file systems. Any changes will be lost when the system reboots. As described, this system is insecure. It should live in a protected area of a network and be untrusted by other hosts. Background Information Setting up diskless workstations is both relatively straightforward and prone to errors. These are sometimes difficult to diagnose for a number of reasons. For example: Compile time options may determine different behaviors at runtime. Error messages are often cryptic or totally absent. In this context, having some knowledge of the background mechanisms involved is useful to solve the problems that may arise. Several operations need to be performed for a successful bootstrap: The machine needs to obtain initial parameters such as its IP address, executable filename, server name, and root path. This is done using the DHCP or BOOTP protocols. DHCP is a compatible extension of BOOTP, and uses the same port numbers and basic packet format. It is possible to configure a system to use only BOOTP and &man.bootpd.8; is included in the base &os; system. DHCP has a number of advantages over BOOTP such as nicer configuration files and support for PXE. This section describes mainly a DHCP configuration, with equivalent examples using &man.bootpd.8; when possible. The sample configuration uses ISC DHCP which is available in the Ports Collection. The machine needs to transfer one or several programs to local memory. Either TFTP or NFS are used. The choice between TFTP and NFS is a compile time option in several places. A common source of error is to specify filenames for the wrong protocol. TFTP typically transfers all files from a single directory on the server and expects filenames relative to this directory. NFS needs absolute file paths. The possible intermediate bootstrap programs and the kernel need to be initialized and executed. PXE loads &man.pxeboot.8;, which is a modified version of the &os; third stage loader, &man.loader.8;. The third stage loader will obtain most parameters necessary to system startup and leave them in the kernel environment before transferring control. It is possible to use a GENERIC kernel in this case. Finally, the machine needs to access its file systems using NFS. Refer to &man.diskless.8; for more information. Setup Instructions Configuration Using <application>ISC DHCP</application> DHCP diskless operation The ISC DHCP server can answer both BOOTP and DHCP requests. ISC DHCP is not part of the base system. Install the net/isc-dhcp42-server port or package. Once ISC DHCP is installed, edit its configuration file, /usr/local/etc/dhcpd.conf. Here follows a commented example for PXE host corbieres: default-lease-time 600; max-lease-time 7200; authoritative; option domain-name "example.com"; option domain-name-servers 192.168.4.1; option routers 192.168.4.1; subnet 192.168.4.0 netmask 255.255.255.0 { use-host-decl-names on; option subnet-mask 255.255.255.0; option broadcast-address 192.168.4.255; host corbieres { hardware ethernet 00:02:b3:27:62:df; fixed-address corbieres.example.com; next-server 192.168.4.4; filename "pxeboot"; option root-path "192.168.4.4:/data/misc/diskless"; } } This option tells dhcpd to send the value in the host declarations as the hostname for the diskless host. An alternate way would be to add an option host-name corbieres inside the host declarations. The next-server directive designates the TFTP or NFS server to use for loading &man.loader.8; or the kernel file. The default is to use the same host as the DHCP server. The filename directive defines the file that PXE will load for the next execution step. It must be specified according to the transfer method used. PXE uses TFTP, which is why a relative filename is used here. Also, PXE loads pxeboot, not the kernel. There are other interesting possibilities, like loading pxeboot from a &os; CD-ROM /boot directory. Since &man.pxeboot.8; can load a GENERIC kernel, it is possible to use PXE to boot from a remote CD-ROM. The root-path option defines the path to the root file system, in usual NFS notation. When using PXE, it is possible to leave off the host's IP address as long as the BOOTP kernel option is not enabled. The NFS server will then be the same as the TFTP one. Booting with <acronym>PXE</acronym> By default, &man.pxeboot.8; loads the kernel via NFS. It can be compiled to use TFTP instead by specifying the LOADER_TFTP_SUPPORT option in /etc/make.conf. See the comments in /usr/share/examples/etc/make.conf for instructions. There are two other make.conf options which may be useful for setting up a serial console diskless machine: BOOT_PXELDR_PROBE_KEYBOARD, and BOOT_PXELDR_ALWAYS_SERIAL. To use PXE when the machine starts, select the Boot from network option in the BIOS setup or type a function key during system initialization. Configuring the <acronym>TFTP</acronym> and <acronym>NFS</acronym> Servers TFTP diskless operation NFS diskless operation If PXE is configured to use TFTP, enable &man.tftpd.8; on the file server: Create a directory from which &man.tftpd.8; will serve the files, such as /tftpboot. Add this line to /etc/inetd.conf: tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /tftpboot Some PXE versions require the TCP version of TFTP. In this case, add a second line, replacing dgram udp with stream tcp. Tell &man.inetd.8; to reread its configuration file. Add to /etc/rc.conf in order for this command to execute correctly: &prompt.root; service inetd restart Place tftpboot anywhere on the server. Make sure that the location is set in both /etc/inetd.conf and /usr/local/etc/dhcpd.conf. Enable NFS and export the appropriate file system on the NFS server. Add this line to /etc/rc.conf: nfs_server_enable="YES" Export the file system where the diskless root directory is located by adding the following to /etc/exports. Adjust the mount point and replace corbieres with the names of the diskless workstations: /data/misc -alldirs -ro margaux corbieres Tell &man.mountd.8; to reread its configuration file. If NFS is enabled in /etc/rc.conf, it is recommended to reboot instead. &prompt.root; service mountd restart Building a Diskless Kernel diskless operation kernel configuration When using PXE, building a custom kernel with the following options is not strictly necessary. These options cause more DHCP requests to be issued during kernel startup, with a small risk of inconsistency between the new values and those retrieved by &man.pxeboot.8; in some special cases. The advantage is that the host name will be set. Otherwise, set the host name in a client-specific /etc/rc.conf. options BOOTP # Use BOOTP to obtain IP address/hostname options BOOTP_NFSROOT # NFS mount root file system using BOOTP info The custom kernel can also include BOOTP_NFSV3, BOOT_COMPAT and BOOTP_WIRED_TO. Refer to NOTES for descriptions of these options. These option names are historical and slightly misleading as they actually enable indifferent use of DHCP and BOOTP inside the kernel. Build the custom kernel, using the instructions in , and copy it to the place specified in /usr/local/etc/dhcpd.conf. Preparing the Root File System root file system diskless operation Create a root file system for the diskless workstations in the location listed as root-path in /usr/local/etc/dhcpd.conf. Using <command>make world</command> to Populate Root This method is quick and will install a complete virgin system, not just the root file system, into DESTDIR. Execute the following script: #!/bin/sh export DESTDIR=/data/misc/diskless mkdir -p ${DESTDIR} cd /usr/src; make buildworld && make buildkernel make installworld && make installkernel cd /usr/src/etc; make distribution Once done, customize /etc/rc.conf and /etc/fstab placed into DESTDIR according to the system's requirements. Configuring Swap If needed, a swap file located on the server can be accessed via NFS. <acronym>NFS</acronym> Swap The kernel does not support enabling NFS swap at boot time. Swap must be enabled by the startup scripts, by mounting a writable file system and creating and enabling a swap file. To create a swap file: &prompt.root; dd if=/dev/zero of=/path/to/swapfile bs=1k count=1 oseek=100000 To enable the swap file, add the following line to /etc/rc.conf: swapfile=/path/to/swapfile Miscellaneous Issues Running with a Read-only <filename>/usr</filename> diskless operation /usr read-only If the diskless workstation is configured to run &xorg;, adjust the XDM configuration file as it puts the error log on /usr by default. Using a Non-&os; Server When the server for the root file system is not running &os;, create the root file system on a &os; machine, then copy it to its destination, using &man.tar.1; or &man.cpio.1;. In this situation, there are sometimes problems with the special files in /dev, due to differing major/minor integer sizes. A solution to this problem is to export a directory from the non-&os; server, mount this directory onto a &os; machine, and use &man.devfs.5; to allocate device nodes transparently for the user. PXE Booting with an <acronym>NFS</acronym> Root File System Craig Rodrigues
rodrigc@FreeBSD.org
Written by
The &intel; Preboot eXecution Environment (PXE) allows booting the operating system over the network. PXE support is usually provided in the BIOS where it can be enabled in the BIOS settings which enable booting from the network. A fully functioning PXE setup also requires properly configured DHCP and TFTP servers. When the host computer boots, it receives information over DHCP about where to obtain the initial boot loader via TFTP. After the host computer receives this information, it downloads the boot loader via TFTP and then executes the boot loader. This is documented in section 2.2.1 of the Preboot Execution Environment (PXE) Specification. In &os;, the boot loader retrieved during the PXE process is /boot/pxeboot. After /boot/pxeboot executes, the &os; kernel is loaded and the rest of the &os; bootup sequence proceeds. Refer to for more information about the &os; booting process. Setting Up the &man.chroot.8; Environment for the <acronym>NFS</acronym> Root File System Choose a directory which will have a &os; installation which will be NFS mountable. For example, a directory such as /b/tftpboot/FreeBSD/install can be used. &prompt.root; export NFSROOTDIR=/b/tftpboot/FreeBSD/install &prompt.root; mkdir -p ${NFSROOTDIR} Enable the NFS server by following the instructions in . Export the directory via NFS by adding the following to /etc/exports: /b -ro -alldirs Restart the NFS server: &prompt.root; service nfsd restart Enable &man.inetd.8; by following the steps outlined in . Add the following line to /etc/inetd.conf: tftp dgram udp wait root /usr/libexec/tftpd tftpd -l -s /b/tftpboot Restart &man.inetd.8;: &prompt.root; service inetd restart Rebuild the &os; kernel and userland (): &prompt.root; cd /usr/src &prompt.root; make buildworld &prompt.root; make buildkernel Install &os; into the directory mounted over NFS: &prompt.root; make installworld DESTDIR=${NFSROOTDIR} &prompt.root; make installkernel DESTDIR=${NFSROOTDIR} &prompt.root; make distribution DESTDIR=${NFSROOTDIR} Test that the TFTP server works and can download the boot loader which will be obtained via PXE: &prompt.root; tftp localhost tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds Edit ${NFSROOTDIR}/etc/fstab and create an entry to mount the root file system over NFS: # Device Mountpoint FSType Options Dump Pass myhost.example.com:/b/tftpboot/FreeBSD/install / nfs ro 0 0 Replace myhost.example.com with the hostname or IP address of the NFS server. In this example, the root file system is mounted read-only in order to prevent NFS clients from potentially deleting the contents of the root file system. Set the root password in the &man.chroot.8; environment: &prompt.root; chroot ${NFSROOTDIR} &prompt.root; passwd This sets the root password for client machines which are PXE booting. Enable &man.ssh.1; root logins for client machines which are PXE booting by editing ${NFSROOTDIR}/etc/ssh/sshd_config and enabling PermitRootLogin. This option is documented in &man.sshd.config.5;. Perform other customizations of the &man.chroot.8; environment in ${NFSROOTDIR}. These customizations could include things like adding packages with &man.pkg.add.1;, editing the password file with &man.vipw.8;, or editing &man.amd.conf.5; maps for automounting. For example: &prompt.root; chroot ${NFSROOTDIR} &prompt.root; pkg_add -r bash Configuring Memory File Systems Used by <filename>/etc/rc.initdiskless</filename> When booting from an NFS root volume, /etc/rc detects the NFS boot and runs /etc/rc.initdiskless. Read the comments in this script to understand what is going on. In this case, /etc and /var need to be memory backed file systems so that these directories are writable but the NFS root directory is read-only: &prompt.root; chroot ${NFSROOTDIR} &prompt.root; mkdir -p conf/base &prompt.root; tar -c -v -f conf/base/etc.cpio.gz --format cpio --gzip etc &prompt.root; tar -c -v -f conf/base/var.cpio.gz --format cpio --gzip var When the system boots, memory file systems for /etc and /var will be created and mounted and the contents of the cpio.gz files will be copied into them. Setting up the <acronym>DHCP</acronym> Server PXE requires a TFTP and a DHCP server to be set up. The DHCP server does not need to be the same machine as the TFTP server, but it needs to be accessible in the network. Install the DHCP server by following the instructions documented at . Make sure that /etc/rc.conf and /usr/local/etc/dhcpd.conf are correctly configured. In /usr/local/etc/dhcpd.conf, configure the next-server, filename, and option root-path settings to specify the TFTP server IP address, the path to /boot/pxeboot in TFTP, and the path to the NFS root file system. Here is a sample dhcpd.conf setup: subnet 192.168.0.0 netmask 255.255.255.0 { range 192.168.0.2 192.168.0.3 ; option subnet-mask 255.255.255.0 ; option routers 192.168.0.1 ; option broadcast-address 192.168.0.255 ; option domain-name-servers 192.168.35.35, 192.168.35.36 ; option domain-name "example.com"; # IP address of TFTP server next-server 192.168.0.1 ; # path of boot loader obtained # via tftp filename "FreeBSD/install/boot/pxeboot" ; # pxeboot boot loader will try to NFS mount this directory for root FS option root-path "192.168.0.1:/b/tftpboot/FreeBSD/install/" ; } Configuring the <acronym>PXE</acronym> Client and Debugging Connection Problems When the client machine boots up, enter the BIOS configuration menu. Configure the BIOS to boot from the network. If all previous configuration steps are correct, everything should "just work". Use the net/wireshark package or port to debug the network traffic involved during the PXE booting process, as illustrated in the diagram below. In , an example configuration is shown where the DHCP, TFTP, and NFS servers are on the same machine. However, these servers can be on separate machines.
<acronym>PXE</acronym> Booting Process with <acronym>NFS</acronym> Root Mount Client broadcasts a DHCPDISCOVER message. The DHCP server responds with the IP address, next-server, filename, and root-path values. The client sends a TFTP request to next-server, asking to retrieve filename. The TFTP server responds and sends filename to client. The client executes filename, which is &man.pxeboot.8;, which then loads the kernel. When the kernel executes, the root file system specified by root-path is mounted over NFS.
Make sure that the pxeboot file can be retrieved by TFTP. On the TFTP server, read /var/log/xferlog to ensure that the pxeboot file is being retrieved from the correct location. To test this example configuration: &prompt.root; tftp 192.168.0.1 tftp> get FreeBSD/install/boot/pxeboot Received 264951 bytes in 0.1 seconds The BUGS sections in &man.tftpd.8; and &man.tftp.1; document some limitations with TFTP. Make sure that the root file system can be mounted via NFS. To test this example configuration: &prompt.root; mount -t nfs 192.168.0.1:/b/tftpboot/FreeBSD/install /mnt Read the code in src/sys/boot/i386/libi386/pxe.c to understand how the pxeboot loader sets variables like boot.nfsroot.server and boot.nfsroot.path. These variables are then used in the NFS diskless root mount code in src/sys/nfsclient/nfs_diskless.c. Read &man.pxeboot.8; and &man.loader.8;.
- - - Network Address Translation - - - - - Chern - Lee - - Contributed by - - - - - - Overview - - - &man.natd.8; - - - &os;'s Network Address Translation - (NAT) daemon, &man.natd.8;, accepts - incoming raw IP packets, changes the - source to the local machine, and injects these packets back - into the outgoing IP packet stream. The - source IP address and port are changed - such that when data is received back, it is able to determine - the original location of the data and forward it back to its - original requester. - - - Internet connection sharing - - - NAT - - - The most common use of NAT is to - perform what is commonly known as Internet Connection - Sharing. - - - - Setup - - Due to the diminishing IP address - space in IPv4 and the increased number of - users on high-speed consumer lines such as cable or - DSL, people are increasingly in need of - an Internet Connection Sharing solution. The ability to - connect several computers online through one connection and - IP address makes &man.natd.8; a reasonable - choice. - - Most commonly, a user has a machine connected to a cable - or DSL line with one IP - address and wishes to use this one connected computer to - provide Internet access to several more over a - LAN. - - To do this, the &os; machine connected to the Internet - must act as a gateway. This gateway machine must have two - NICs: one connects to the Internet router - and the other connects to a LAN. All the - machines on the LAN are connected through - a hub or switch. - - - There are many ways to get a LAN - connected to the Internet through a &os; gateway. This - example will only cover a gateway with at least two - NICs. - - - - - - - - - _______ __________ ________ - | | | | | | - | Hub |-----| Client B |-----| Router |----- Internet - |_______| |__________| |________| - | - ____|_____ -| | -| Client A | -|__________| - - - - Network Layout - - - - A setup like this is commonly used to share an Internet - connection. One of the LAN machines is - connected to the Internet and the rest of the machines access - the Internet through that gateway - machine. - - - - Boot Loader Configuration - - - boot loader - configuration - - - The kernel features for &man.natd.8; are not enabled in - the GENERIC kernel, but they can be - loaded at boot time by adding a couple of options to - /boot/loader.conf: - - ipfw_load="YES" -ipdivert_load="YES" - - Additionally, the - net.inet.ip.fw.default_to_accept tunable - option should be set to 1: - - net.inet.ip.fw.default_to_accept="1" - - - It is a good idea to set this option during the first - attempts to setup a firewall and NAT - gateway. This sets the default policy of &man.ipfw.8; to - be more permissive than the default deny ip from - any to any, making it slightly more difficult - to get locked out of the system right after a reboot. - - - - - Kernel Configuration - - - kernel - configuration - - - When modules are not an option or if it is preferable to - build all the required features into a custom kernel, the - following options must be in the custom kernel configuration - file: - - options IPFIREWALL -options IPDIVERT - - Additionally, the following may also be suitable: - - options IPFIREWALL_DEFAULT_TO_ACCEPT -options IPFIREWALL_VERBOSE - - - - System Startup Configuration - - To enable firewall and NAT support at - boot time, the following must be in - /etc/rc.conf: - - gateway_enable="YES" -firewall_enable="YES" -firewall_type="OPEN" -natd_enable="YES" -natd_interface="fxp0" -natd_flags="" - - - - Sets up the machine to act as a gateway. Running - sysctl net.inet.ip.forwarding=1 would - have the same effect. - - - - Enables the firewall rules in - /etc/rc.firewall at boot. - - - - This specifies a predefined firewall ruleset that - allows anything in. See - /etc/rc.firewall for additional - types. - - - - Indicates which interface to forward packets through. - This is the interface that is connected to the - Internet. - - - - Any additional configuration options passed to - &man.natd.8; on boot. - - - - These - /etc/rc.conf options will run - natd -interface fxp0 at boot. This can - also be run manually after boot. - - - It is also possible to use a configuration file for - &man.natd.8; when there are too many options to pass. In - this case, the configuration file must be defined by adding - the following line to - /etc/rc.conf: - - natd_flags="-f /etc/natd.conf" - - A list of configuration options, one per line, can be - added to /etc/natd.conf. For - example: - - redirect_port tcp 192.168.0.2:6667 6667 -redirect_port tcp 192.168.0.3:80 80 - - For more information about this configuration file, - consult &man.natd.8;. - - - Each machine and interface behind the - LAN should be assigned - IP addresses in the private network space, - as defined by RFC - 1918, and have a default gateway of the - &man.natd.8; machine's internal IP - address. - - For example, client A and - B behind the LAN - have IP addresses of 192.168.0.2 and 192.168.0.3, while the - &man.natd.8; machine's LAN interface has an - IP address of 192.168.0.1. The default - gateway of clients A and - B must be set to that of the - &man.natd.8; machine, 192.168.0.1. The - &man.natd.8; machine's external Internet interface does not - require any special modification for &man.natd.8; to - work. - - - - Port Redirection - - The drawback with &man.natd.8; is that the - LAN clients are not accessible from the - Internet. Clients on the LAN can make - outgoing connections to the world but cannot receive incoming - ones. This presents a problem if trying to run Internet - services on one of the LAN client machines. - A simple way around this is to redirect selected Internet - ports on the &man.natd.8; machine to a LAN - client. - - For example, an IRC server runs on - client A and a web server runs on - client B. For this to work properly, - connections received on ports 6667 (IRC) - and 80 (HTTP) must be redirected to the - respective machines. - - The syntax for is as - follows: - - -redirect_port proto targetIP:targetPORT[-targetPORT] - [aliasIP:]aliasPORT[-aliasPORT] - [remoteIP[:remotePORT[-remotePORT]]] - - In the above example, the argument should be: - - -redirect_port tcp 192.168.0.2:6667 6667 - -redirect_port tcp 192.168.0.3:80 80 - - This redirects the proper TCP ports - to the LAN client machines. - - Port ranges over individual ports can be indicated with - . For example, - tcp 192.168.0.2:2000-3000 2000-3000 - would redirect all connections received on ports 2000 to 3000 - to ports 2000 to 3000 on client - A. - - These options can be used when directly running - &man.natd.8;, placed within the - natd_flags="" option in - /etc/rc.conf, or passed via a - configuration file. - - For further configuration options, consult - &man.natd.8; - - - - Address Redirection - - - address redirection - - - Address redirection is useful if more than one - IP address is available. Each - LAN client can be assigned its own - external IP address by &man.natd.8;, - which will then rewrite outgoing packets from the - LAN clients with the proper external - IP address and redirects all traffic - incoming on that particular IP address - back to the specific LAN client. This is - also known as static NAT. For example, - if IP addresses 128.1.1.1, 128.1.1.2, and 128.1.1.3 are available, - 128.1.1.1 can be - used as the &man.natd.8; machine's external - IP address, while 128.1.1.2 and 128.1.1.3 are forwarded back - to LAN clients A - and B. - - The syntax is as - follows: - - -redirect_address localIP publicIP - - - - - - - localIP - The internal IP address of - the LAN client. - - - - publicIP - The external IP address - corresponding to the LAN - client. - - - - - - In the example, this argument would read: - - -redirect_address 192.168.0.2 128.1.1.2 --redirect_address 192.168.0.3 128.1.1.3 - - Like , these arguments are - placed within the natd_flags="" option - of /etc/rc.conf, or passed via a - configuration file. With address redirection, there is no - need for port redirection since all data received on a - particular IP address is redirected. - - The external IP addresses on the - &man.natd.8; machine must be active and aliased to the - external interface. Refer to &man.rc.conf.5; for - details. - - - <acronym>IPv6</acronym> Aaron Kaplan Originally Written by Tom Rhodes Restructured and Added by Brad Davis Extended by IPv6, also known as IPng IP next generation, is the new version of the well known IP protocol, also known as IPv4. &os; includes the KAME IPv6 reference implementation. &os; comes with everything needed to use IPv6. This section focuses on getting IPv6 configured and running. In the early 1990s, people became aware of the rapidly diminishing address space of IPv4. Given the expansion rate of the Internet, there were two major concerns: Running out of addresses. For years the use of RFC1918 private address space (10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16) and NAT has slowed down the exhaustion. Even though, there are very few remaining IPv4 addresses. The Internet Assigned Numbers Authority (IANA) has issued the last of the available major blocks to the Regional Registries. Once each Regional Registry runs out, there will be no more available and switching to IPv6 will be critical. Every block of IPv4 addresses allocated required routing information to be exchanged between many routers on the Internet, and these routing tables were getting too large to allow efficient routing. IPv6 deals with these and many other issues by providing the following: 128 bit address space which allows for 340,282,366,920,938,463,463,374,607,431,768,211,456 addresses. This means there are approximately 6.67 * 10^27 IPv6 addresses per square meter on the planet. Routers only store network aggregation addresses in their routing tables, thus reducing the average space of a routing table to 8192 entries. There are many other useful features of IPv6: Address autoconfiguration (RFC2462). Anycast addresses (one-out-of many). Mandatory multicast addresses. IPsec (IP security). Simplified header structure. Mobile IP. IPv6-to-IPv4 transition mechanisms. For more information see: KAME.net Background on <acronym>IPv6</acronym> Addresses There are different types of IPv6 addresses: unicast, anycast, and multicast. Unicast addresses are the well known addresses. A packet sent to a unicast address arrives at the interface belonging to the address. Anycast addresses are syntactically indistinguishable from unicast addresses but they address a group of interfaces. The packet destined for an anycast address will arrive at the nearest (in router metric) interface. Anycast addresses may only be used by routers. Multicast addresses identify a group of interfaces. A packet destined for a multicast address will arrive at all interfaces belonging to the multicast group. The IPv4 broadcast address, usually xxx.xxx.xxx.255, is expressed by multicast addresses in IPv6. Reserved <acronym>IPv6</acronym> Addresses IPv6 address Prefixlength (Bits) Description Notes :: 128 bits unspecified Equivalent to 0.0.0.0 in IPv4. ::1 128 bits loopback address Equivalent to 127.0.0.1 in IPv4. ::00:xx:xx:xx:xx 96 bits embedded IPv4 The lower 32 bits are the compatible IPv4 address. ::ff:xx:xx:xx:xx 96 bits IPv4 mapped IPv6 address The lower 32 bits are the IPv4 address for hosts which do not support IPv6. fe80:: - feb:: 10 bits link-local Equivalent to the loopback address in IPv4. fec0:: - fef:: 10 bits site-local   ff:: 8 bits multicast   001 (base 2) 3 bits global unicast All global unicast addresses are assigned from this pool. The first 3 bits are 001.
Reading <acronym>IPv6</acronym> Addresses The canonical form is represented as: x:x:x:x:x:x:x:x, with each x being a 16 bit hex value. For example: FEBC:A574:382B:23C1:AA49:4592:4EFE:9982. Often an address will have long substrings of all zeros. One such substring per address can be abbreviated by ::. Also, up to three leading 0s per hex quad can be omitted. For example, fe80::1 corresponds to the canonical form fe80:0000:0000:0000:0000:0000:0000:0001. A third form is to write the last 32 bit part in the well known (decimal) IPv4 style with dots (.) as separators. For example, 2002::10.0.0.1 corresponds to the hexadecimal canonical representation 2002:0000:0000:0000:0000:0000:0a00:0001, which in turn is equivalent to 2002::a00:1. Here is a sample entry from &man.ifconfig.8;: &prompt.root; ifconfig rl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 inet 10.0.0.10 netmask 0xffffff00 broadcast 10.0.0.255 inet6 fe80::200:21ff:fe03:8e1%rl0 prefixlen 64 scopeid 0x1 ether 00:00:21:03:08:e1 media: Ethernet autoselect (100baseTX ) status: active fe80::200:21ff:fe03:8e1%rl0 is an auto configured link-local address. It is generated from the MAC address as part of the auto configuration. For further information on the structure of IPv6 addresses, see RFC3513. Getting Connected Currently, there are four ways to connect to other IPv6 hosts and networks: Contact an Internet Service Provider to see if they offer IPv6. SixXS offers tunnels with end-points all around the globe. Hurricane Electric offers tunnels with end-points all around the globe. Tunnel via 6-to-4 as described in RFC3068. Use the net/freenet6 port for a dial-up connection. Applying the Needed Changes to <filename>/etc/rc.conf</filename> <acronym>IPv6</acronym> Client Auto-Configuration To automatically configure a machine on a LAN which acts as a client, not a router, two items are required. First to enable the em0 to receive the router solicitation messages, add this line to rc.conf: ifconfig_em0_ipv6="inet6 accept_rtadv" Secondly, the router solicitation daemon, &man.rtsol.8;, should be enabled by adding the following to rc.conf: rtsold_enable="YES" For &os; 8.x, add: ipv6_enable="YES" <acronym>IPv6</acronym> Client Static Configuration To statically assign the IPv6 address, 2001:db8:4672:6565:2026:5043:2d42:5344, to fxp0, add the following for &os; 9.x: ifconfig_fxp0_ipv6="inet6 2001:db8:4672:6565:2026:5043:2d42:5344 prefixlen 64" Be sure to change prefixlen 64 to the appropriate value for the subnet. For &os; 8.x, add: ipv6_ifconfig_fxp0="2001:db8:4672:6565:2026:5043:2d42:5344" To assign a default router of 2001:db8:4672:6565::1, add the following to /etc/rc.conf: ipv6_defaultrouter="2001:db8:4672:6565::1" <acronym>IPv6</acronym> Router/Gateway Settings This section demonstrates how to take the directions from a tunnel provider and convert it into settings that will persist through reboots. To restore the tunnel on startup, add the following lines to /etc/rc.conf. The first entry lists the generic tunneling interfaces to be configured. This example configures one interface, gif0: gif_interfaces="gif0" To configure that interface with a local endpoint of MY_IPv4_ADDR to a remote endpoint of REMOTE_IPv4_ADDR: gifconfig_gif0="MY_IPv4_ADDR REMOTE_IPv4_ADDR" To apply the IPv6 address that has been assigned for use as the IPv6 tunnel endpoint, add the following line for &os; 9.x and later: ifconfig_gif0_ipv6="inet6 MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" For &os; 8.x, add: ipv6_ifconfig_gif0="MY_ASSIGNED_IPv6_TUNNEL_ENDPOINT_ADDR" Then, set the default route for IPv6. This is the other side of the IPv6 tunnel: ipv6_defaultrouter="MY_IPv6_REMOTE_TUNNEL_ENDPOINT_ADDR" <acronym>IPv6</acronym> Tunnel Settings If the server is to route IPv6 between the rest of the network and the world, the following /etc/rc.conf setting will also be needed: ipv6_gateway_enable="YES" Router Advertisement and Host Auto Configuration This section demonstrates how to setup &man.rtadvd.8; to advertise the IPv6 default route. To enable &man.rtadvd.8;, add the following to /etc/rc.conf: rtadvd_enable="YES" It is important to specify the interface on which to do IPv6 router solicitation. For example, to tell &man.rtadvd.8; to use fxp0: rtadvd_interfaces="fxp0" Next, create the configuration file, /etc/rtadvd.conf as seen in this example: fxp0:\ :addrs#1:addr="2001:471:1f11:246::":prefixlen#64:tc=ether: Replace fxp0 with the interface to be used and 2001:471:1f11:246:: with the prefix of the allocation. For a dedicated /64 subnet, nothing else needs to be changed. Otherwise, change the prefixlen# to the correct value. <acronym>IPv6</acronym> and <acronym>IPv6</acronym> Address Mapping When IPv6 is enabled on a server, there may be a need to enable IPv4 mapped IPv6 address communication. This compatibility option allows for IPv4 addresses to be represented as IPv6 addresses. Permitting IPv6 applications to communicate with IPv4 and vice versa may be a security issue. This option may not be required in most cases and is available only for compatibility. This option will allow IPv6-only applications to work with IPv4 in a dual stack environment. This is most useful for third party applications which may not support an IPv6-only environment. To enable this feature, add the following to /etc/rc.conf: ipv6_ipv4mapping="YES" Reviewing the information in RFC 3493, section 3.6 and 3.7 as well as RFC 4038 section 4.2 may be useful to some adminstrators. Application Use of <acronym>IPv6</acronym> Currently IPv6 support for many applications and services is very good, though for some software it still needs work. For authoritative information about the support of IPv6, please consult the Official Documentation for the software in question. Web, DNS and Mail applications and servers have the best support for IPv6 because they are the most common use case. Other applications may have varying degrees of IPv6 support.
Common Address Redundancy Protocol (<acronym>CARP</acronym>) Tom Rhodes Contributed by Allan Jude Updated by CARP Common Address Redundancy Protocol The Common Address Redundancy Protocol (CARP) allows multiple hosts to share the same IP address and provide high availability. One or more hosts can fail, and the others will take over for the failed system transparently. In addition to the shared IP address, hosts also have a unique IP address for management and configuration, as in the example provided here. Using <acronym>CARP</acronym> for High Availability CARP is often used to provide high availability for one or more services. This example configures failover support with three hosts, all with unique IP addresses, but providing the same web content. These machines are load balanced with a Round Robin DNS configuration. The master and backup machines are configured identically except for their hostnames and management IP addresses. These servers must have the same configuration and run the same services. When the failover occurs, requests to the service on the shared IP address can only be answered correctly if the backup server has access to the same content. The backup machine has two additional CARP interfaces, one for each of the master content server's IP addresses. When a failure occurs, the backup server will pick up the failed master machine's IP address. Users will not see a service failure at all. This example has two different masters named hosta.example.org and hostb.example.org, with a shared backup named hostc.example.org. Each virtual IP address has a unique identification number known as a Virtual Host Identification (VHID). All of the machines that share an IP address have the same VHID. The VHID for each virtual IP address must be unique across the broadcast domain of the network interface. Using <acronym>CARP</acronym> on &os; 10 and Later Enable support for CARP by loading the carp.ko kernel module in /boot/loader.conf: carp_load="YES" The CARP module can also be built into the &os; kernel as described in : device carp The hostname, management IP address, CARP configuration, and the IP address to be shared are all set by adding entries to /etc/rc.conf. This example is for hosta.example.org: hostname="hosta.example.org" ifconfig_em0="inet 192.168.1.3 netmask 255.255.255.0" ifconfig_em0_alias0="vhid 1 pass testpass alias 192.168.1.50/32" On hostb.example.org: hostname="hostb.example.org" ifconfig_em0="inet 192.168.1.4 netmask 255.255.255.0" ifconfig_em0_alias0="vhid 2 pass testpass alias 192.168.1.51/32" The passwords specified with &man.ifconfig.8; must be identical. CARP will only listen to and accept advertisements from machines with the correct password. The third machine, hostc.example.org, is prepared to handle failover from either of the previous hosts. This machine is configured with two CARP VHIDs, one to handle the virtual IP address of each of the master hosts. , the CARP advertising skew, is set to ensure that the backup host advertises later than the master. controls the order of precedence when there are multiple backup servers. Set the configuration in /etc/rc.conf: hostname="hostc.example.org" ifconfig_em0="inet 192.168.1.5 netmask 255.255.255.0" ifconfig_em0_alias0="vhid 1 advskew 100 pass testpass alias 192.168.1.50/32" ifconfig_em0_alias1="vhid 2 advskew 100 pass testpass alias 192.168.1.51/32" Having two CARP VHIDs configured means that hostc.example.org will notice if either of the master servers becomes unavailable. If a master fails to advertise before the backup server, the backup server will pick up the shared IP address until the master becomes available again. Preemption is disabled by default. If preemption has been enabled, hostc.example.org might not release the virtual IP address back to the original master server. The administrator can force the backup server to return the IP address to the master with the command: &prompt.root; ifconfig em0 vhid 1 state backup At this point, either networking must be restarted or the machine rebooted, then CARP is enabled. CARP functionality can be controlled via several &man.sysctl.8; variables documented in the &man.carp.4; manual pages. Other actions can be triggered from CARP events by using &man.devd.8;. Using <acronym>CARP</acronym> on &os; 9 and Earlier Enable support for CARP by loading the if_carp.ko kernel module in /boot/loader.conf: if_carp_load="YES" CARP can also be built into the &os; kernel as described in : device carp The CARP devices themselves may be created using &man.ifconfig.8;: &prompt.root; ifconfig carp0 create Set the hostname, configure the management IP address, then configure CARP and the IP address to be shared by adding the required lines to /etc/rc.conf. Here are example lines for hosta.example.org: hostname="hosta.example.org" ifconfig_fxp0="inet 192.168.1.3 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 1 pass testpass 192.168.1.50/24" On hostb.example.org: hostname="hostb.example.org" ifconfig_fxp0="inet 192.168.1.4 netmask 255.255.255.0" cloned_interfaces="carp0" ifconfig_carp0="vhid 2 pass testpass 192.168.1.51/24" The passwords specified with &man.ifconfig.8; must be identical. CARP will only listen to and accept advertisements from machines with the correct password. The VHID must also be unique for each virtual IP address. The third machine, hostc.example.org, is prepared to handle failover from either of the previous hosts. This machine is configured with two CARP devices, one to handle each of the virtual IP address of each of the master hosts. Setting the controls the CARP advertising skew. The skew ensuring that the backup hosts advertises later than the master, and controls the order of precedence when there are multiple backup servers. Set the configuration in /etc/rc.conf: hostname="hostc.example.org" ifconfig_fxp0="inet 192.168.1.5 netmask 255.255.255.0" cloned_interfaces="carp0 carp1" ifconfig_carp0="vhid 1 advskew 100 pass testpass 192.168.1.50/24" ifconfig_carp1="vhid 2 advskew 100 pass testpass 192.168.1.51/24" Having two CARP devices configured means that hostc.example.org will notice if either of the master servers becomes unavailable. If a master fails to advertise before the backup server, the backup server will pick up the shared IP address until the master becomes available again. Preemption is disabled in the GENERIC &os; kernel. If Preemption has been enabled with a custom kernel, hostc.example.org may not release the IP address back to the original content server. The administrator can force the backup server to return the IP address to the master with the command: &prompt.root; ifconfig carp0 down && ifconfig carp0 up This should be done on the carp interface which corresponds to the correct host. At this point, either networking must be restarted or the machine rebooted, then CARP is enabled. CARP functionality can be controlled via several &man.sysctl.8; variables documented in the &man.carp.4; manual pages. Other actions can be triggered from CARP events by using &man.devd.8;.
diff --git a/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml b/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml index 4311b79595..85d8c594b9 100644 --- a/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml +++ b/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml @@ -1,3744 +1,3743 @@ Firewalls Joseph J. Barbish Contributed by Brad Davis Converted to SGML and updated by firewall security firewalls Synopsis Firewalls make it possible to filter the incoming and outgoing traffic that flows through a system. A firewall can use one or more sets of rules to inspect network packets as they come in or go out of network connections and either allows the traffic through or blocks it. The rules of a firewall can inspect one or more characteristics of the packets such as the protocol type, source or destination host address, and source or destination port. Firewalls can enhance the security of a host or a network. They can be used to do one or more of the following: Protect and insulate the applications, services, and machines of an internal network from unwanted traffic from the public Internet. Limit or disable access from hosts of the internal network to services of the public Internet. Support network address translation (NAT), which allows an internal network to use private IP addresses and share a single connection to the public Internet using either a single IP address or a shared pool of automatically assigned public addresses. &os; has three firewalls built into the base system: PF, IPFW, and IPFILTER, also known as IPF. &os; also provides two traffic shapers for controlling bandwidth usage: &man.altq.4; and &man.dummynet.4;. ALTQ has traditionally been closely tied with PF and dummynet with IPFW. Each firewall uses rules to control the access of packets to and from a &os; system, although they go about it in different ways and each has a different rule syntax. &os; provides multiple firewalls in order to meet the different requirements and preferences for a wide variety of users. Each user should evaluate which firewall best meets their needs. After reading this chapter, you will know: How to define packet filtering rules. The differences between the firewalls built into &os;. How to use and configure the PF firewall. How to use and configure the IPFW firewall. How to use and configure the IPFILTER firewall. Before reading this chapter, you should: Understand basic &os; and Internet concepts. Since all firewalls are based on inspecting the values of selected packet control fields, the creator of the firewall ruleset must have an understanding of how TCP/IP works, what the different values in the packet control fields are, and how these values are used in a normal session conversation. For a good introduction, refer to Daryl's TCP/IP Primer. Firewall Concepts firewall rulesets A ruleset contains a group of rules which pass or block packets based on the values contained in the packet. The bi-directional exchange of packets between hosts comprises a session conversation. The firewall ruleset processes both the packets arriving from the public Internet, as well as the packets produced by the system as a response to them. Each TCP/IP service is predefined by its protocol and listening port. Packets destined for a specific service originate from the source address using an unprivileged port and target the specific service port on the destination address. All the above parameters can be used as selection criteria to create rules which will pass or block services. To lookup unknown port numbers, refer to /etc/services. Alternatively, visit http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers and do a port number lookup to find the purpose of a particular port number. Check out this link for port numbers used by Trojans http://www.sans.org/security-resources/idfaq/oddports.php. FTP has two modes: active mode and passive mode. The difference is in how the data channel is acquired. Passive mode is more secure as the data channel is acquired by the ordinal ftp session requester. For a good explanation of FTP and the different modes, see http://www.slacksite.com/other/ftp.html. A firewall ruleset can be either exclusive or inclusive. An exclusive firewall allows all traffic through except for the traffic matching the ruleset. An inclusive firewall does the reverse as it only allows traffic matching the rules through and blocks everything else. An inclusive firewall offers better control of the outgoing traffic, making it a better choice for systems that offer services to the public Internet. It also controls the type of traffic originating from the public Internet that can gain access to a private network. All traffic that does not match the rules is blocked and logged. Inclusive firewalls are generally safer than exclusive firewalls because they significantly reduce the risk of allowing unwanted traffic. Unless noted otherwise, all configuration and example rulesets in this chapter create inclusive firewall rulesets. Security can be tightened further using a stateful firewall. This type of firewall keeps track of open connections and only allows traffic which either matches an existing connection or opens a new, allowed connection. Stateful filtering treats traffic as a bi-directional exchange of packets comprising a session. When state is specified on a matching rule the firewall dynamically generates internal rules for each anticipated packet being exchanged during the session. It has sufficient matching capabilities to determine if a packet is valid for a session. Any packets that do not properly fit the session template are automatically rejected. When the session completes, it is removed from the dynamic state table. Stateful filtering allows one to focus on blocking/passing new sessions. If the new session is passed, all its subsequent packets are allowed automatically and any impostor packets are automatically rejected. If a new session is blocked, none of its subsequent packets are allowed. Stateful filtering provides advanced matching abilities capable of defending against the flood of different attack methods employed by attackers. NAT stands for Network Address Translation. NAT function enables the private LAN behind the firewall to share a single ISP-assigned IP address, even if that address is dynamically assigned. NAT allows each computer in the LAN to have Internet access, without having to pay the ISP for multiple Internet accounts or IP addresses. NAT will automatically translate the private LAN IP address for each system on the LAN to the single public IP address as packets exit the firewall bound for the public Internet. It also performs the reverse translation for returning packets. According to RFC 1918, the following IP address ranges are reserved for private networks which will never be routed directly to the public Internet, and therefore are available for use with NAT: 10.0.0.0/8. 172.16.0.0/12. 192.168.0.0/16. When working with the firewall rules, be very careful. Some configurations can lock the administrator out of the server. To be on the safe side, consider performing the initial firewall configuration from the local console rather than doing it remotely over ssh. PF John Ferrell Revised and updated by firewall PF Since &os; 5.3, a ported version of OpenBSD's PF firewall has been included as an integrated part of the base system. PF is a complete, full-featured firewall that has optional support for ALTQ (Alternate Queuing), which provides Quality of Service (QoS). The OpenBSD Project maintains the definitive reference for PF in the PF FAQ. Peter Hansteen maintains a thorough PF tutorial at http://home.nuug.no/~peter/pf/. When reading the PF FAQ, keep in mind that different versions of &os; contain different versions of PF. &os; 8.X uses the same version of PF as OpenBSD 4.1 and &os; 9.X and later uses the same version of PF as OpenBSD 4.5. The &a.pf; is a good place to ask questions about configuring and running the PF firewall. Check the mailing list archives before asking a question as it may have already been answered. More information about porting PF to &os; can be found at http://pf4freebsd.love2party.net/. This section of the Handbook focuses on PF as it pertains to &os;. It demonstrates how to enable PF and ALTQ. It then provides several examples for creating rulesets on a &os; system. Enabling <application>PF</application> In order to use PF, its kernel module must be first loaded. This section describes the entries that can be added to /etc/rc.conf in order to enable PF. Start by adding the following line to /etc/rc.conf: pf_enable="YES" Additional options, described in &man.pfctl.8;, can be passed to PF when it is started. Add this entry to /etc/rc.conf and specify any required flags between the two quotes (""): pf_flags="" # additional flags for pfctl startup PF will not start if it cannot find its ruleset configuration file. The default ruleset is already created and is named /etc/pf.conf. If a custom ruleset has been saved somewhere else, add a line to /etc/rc.conf which specifies the full path to the file: pf_rules="/path/to/pf.conf" Logging support for PF is provided by &man.pflog.4;. To enable logging support, add this line to /etc/rc.conf: pflog_enable="YES" The following lines can also be added in order to change the default location of the log file or to specify any additional flags to pass to &man.pflog.4; when it is started: pflog_logfile="/var/log/pflog" # where pflogd should store the logfile pflog_flags="" # additional flags for pflogd startup Finally, if there is a LAN behind the firewall and packets need to be forwarded for the computers on the LAN, or NAT is required, add the following option: gateway_enable="YES" # Enable as LAN gateway After saving the needed edits, PF can be started with logging support by typing: &prompt.root; service pf start &prompt.root; service pflog start By default, PF reads its configuration rules from /etc/pf.conf and modifies, drops, or passes packets according to the rules or definitions specified in this file. The &os; installation includes several sample files located in /usr/share/examples/pf/. Refer to the PF FAQ for complete coverage of PF rulesets. To control PF, use pfctl. summarizes some useful options to this command. Refer to &man.pfctl.8; for a description of all available options: Useful <command>pfctl</command> Options Command Purpose pfctl -e Enable PF. pfctl -d Disable PF. pfctl -F all -f /etc/pf.conf Flush all NAT, filter, state, and table rules and reload /etc/pf.conf. pfctl -s [ rules | nat state ] Report on the filter rules, NAT rules, or state table. pfctl -vnf /etc/pf.conf Check /etc/pf.conf for errors, but do not load ruleset.
security/sudo is useful for running commands like pfctl that require elevated privileges. It can be installed from the Ports Collection. To keep an eye on the traffic that passes through the PF firewall, consider installing the sysutils/pftop package or port. Once installed, pftop can be run to view a running snapshot of traffic in a format which is similar to &man.top.1;.
Enabling <application>ALTQ</application> On &os;, ALTQ can be used with PF to provide Quality of Service (QOS). Once ALTQ is enabled, queues can be defined in the ruleset which determine the processing priority of outbound packets. Before enabling ALTQ, refer to &man.altq.4; to determine if the drivers for the network cards installed on the system support it. ALTQ is not available as a loadable kernel module. If the system's interfaces support ALTQ, create a custom kernel using the instructions in . The following kernel options are available. The first is needed to enable ALTQ. At least one of the other options is necessary to specify the queueing scheduler algorithm: options ALTQ options ALTQ_CBQ # Class Based Queuing (CBQ) options ALTQ_RED # Random Early Detection (RED) options ALTQ_RIO # RED In/Out options ALTQ_HFSC # Hierarchical Packet Scheduler (HFSC) options ALTQ_PRIQ # Priority Queuing (PRIQ) The following scheduler algorithms are available: CBQ Class Based Queuing (CBQ) is used to divide a connection's bandwidth into different classes or queues to prioritize traffic based on filter rules. RED Random Early Detection (RED) is used to avoid network congestion by measuring the length of the queue and comparing it to the minimum and maximum thresholds for the queue. When the queue is over the maximum, all new packets are randomly dropped. RIO In Random Early Detection In and Out (RIO) mode, RED maintains multiple average queue lengths and multiple threshold values, one for each QOS level. HFSC Hierarchical Fair Service Curve Packet Scheduler (HFSC) is described in http://www-2.cs.cmu.edu/~hzhang/HFSC/main.html. PRIQ Priority Queuing (PRIQ) always passes traffic that is in a higher queue first. More information about the scheduling algorithms and example rulesets are available at http://www.openbsd.org/faq/pf/queueing.html. <application>PF</application> Rulesets Peter Hansteen N. M. Contributed by This section demonstrates how to create a customized ruleset. It starts with the simplest of rulesets and builds upon its concepts using several examples to demonstrate real-world usage of PF's many features. The simplest possible ruleset is for a single machine that does not run any services and which needs access to one network, which may be the Internet. To create this minimal ruleset, edit /etc/pf.conf so it looks like this: block in all pass out all keep state The first rule denies all incoming traffic by default. The second rule allows connections created by this system to pass out, while retaining state information on those connections. This state information allows return traffic for those connections to pass back and should only be used on machines that can be trusted. The ruleset can be loaded with: &prompt.root; pfctl -e ; pfctl -f /etc/pf.conf In addition to keeping state, PF provides lists and macros which can be defined for use when creating rules. Macros can include lists and need to be defined before use. As an example, insert these lines at the very top of the ruleset: tcp_services = "{ ssh, smtp, domain, www, pop3, auth, pop3s }" udp_services = "{ domain }" PF understands port names as well as port numbers, as long as the names are listed in /etc/services. This example creates two macros. The first is a list of seven TCP port names and the second is one UDP port name. Once defined, macros can be used in rules. In this example, all traffic is blocked except for the connections initiated by this system for the seven specified TCP services and the one specified UDP service: tcp_services = "{ ssh, smtp, domain, www, pop3, auth, pop3s }" udp_services = "{ domain }" block all pass out proto tcp to any port $tcp_services keep state pass proto udp to any port $udp_services keep state Even though UDP is considered to be a stateless protocol, PF is able to track some state information. For example, when a UDP request is passed which asks a name server about a domain name, PF will watch for the response in order to pass it back. Whenever an edit is made to a ruleset, the new rules must be loaded so they can be used: &prompt.root; pfctl -f /etc/pf.conf If there are no syntax errors, pfctl will not output any messages during the rule load. Rules can also be tested before attempting to load them: &prompt.root; pfctl -nf /etc/pf.conf Including causes the rules to be interpreted only, but not loaded. This provides an opportunity to correct any errors. At all times, the last valid ruleset loaded will be enforced until either PF is disabled or a new ruleset is loaded. Adding to a pfctl ruleset verify or load will display the fully parsed rules exactly the way they will be loaded. This is extremely useful when debugging rules. A Simple Gateway with NAT This section demonstrates how to configure a &os; system running PF to act as a gateway for at least one other machine. The gateway needs at least two network interfaces, each connected to a separate network. In this example, xl1 is connected to the Internet and xl0 is connected to the internal network. First, enable the gateway in order to let the machine forward the network traffic it receives on one interface to another interface. This sysctl setting will forward IPv4 packets: &prompt.root; sysctl net.inet.ip.forwarding=1 To forward IPv6 traffic, use: &prompt.root; sysctl net.inet6.ip6.forwarding=1 To enable these settings at system boot, add the following to /etc/rc.conf: gateway_enable="YES" #for ipv4 ipv6_gateway_enable="YES" #for ipv6 Verify with ifconfig that both of the interfaces are up and running. Next, create the PF rules to allow the gateway to pass traffic. While the following rule allows stateful traffic to pass from the Internet to hosts on the network, the to keyword does not guarantee passage all the way from source to destination: pass in on xl1 from xl1:network to xl0:network port $ports keep state That rule only lets the traffic pass in to the gateway on the internal interface. To let the packets go further, a matching rule is needed: pass out on xl0 from xl1:network to xl0:network port $ports keep state While these two rules will work, rules this specific are rarely needed. For a busy network admin, a readable ruleset is a safer ruleset. The remainder of this section demonstrates how to keep the rules as simple as possible for readability. For example, those two rules could be replaced with one rule: pass from xl1:network to any port $ports keep state The interface:network notation can be replaced with a macro to make the ruleset even more readable. For example, a $localnet macro could be defined as the network directly attached to the internal interface ($xl1:network). Alternatively, the definition of $localnet could be changed to an IP address/netmask notation to denote a network, such as 192.168.100.1/24 for a subnet of private addresses. If required, $localnet could even be defined as a list of networks. Whatever the specific needs, a sensible $localnet definition could be used in a typical pass rule as follows: pass from $localnet to any port $ports keep state The following sample ruleset allows all traffic initiated by machines on the internal network. It first defines two macros to represent the external and internal 3COM interfaces of the gateway. For dialup users, the external interface will use tun0. For an ADSL connection, specifically those using PPP over Ethernet (PPPoE), the correct external interface is tun0, not the physical Ethernet interface. ext_if = "xl0" # macro for external interface - use tun0 for PPPoE int_if = "xl1" # macro for internal interface localnet = $int_if:network # ext_if IP address could be dynamic, hence ($ext_if) nat on $ext_if from $localnet to any -> ($ext_if) block all pass from { lo0, $localnet } to any keep state This ruleset introduces the nat rule which is used to handle the network address translation from the non-routable addresses inside the internal network to the IP address assigned to the external interface. The parentheses surrounding the last part of the nat rule ($ext_if) is included when the IP address of the external interface is dynamically assigned. It ensures that network traffic runs without serious interruptions even if the external IP address changes. Note that this ruleset probably allows more traffic to pass out of the network than is needed. One reasonable setup could create this macro: client_out = "{ ftp-data, ftp, ssh, domain, pop3, auth, nntp, http, \ https, cvspserver, 2628, 5999, 8000, 8080 }" to use in the main pass rule: pass inet proto tcp from $localnet to any port $client_out \ flags S/SA keep state A few other pass rules may be needed. This one enables SSH on the external interface:: pass in inet proto tcp to $ext_if port ssh This macro definition and rule allows DNS and NTP for internal clients: udp_services = "{ domain, ntp }" pass quick inet proto { tcp, udp } to any port $udp_services keep state Note the quick keyword in this rule. Since the ruleset consists of several rules, it is important to understand the relationships between the rules in a ruleset. Rules are evaluated from top to bottom, in the sequence they are written. For each packet or connection evaluated by PF, the last matching rule in the ruleset is the one which is applied. However, when a packet matches a rule which contains the quick keyword, the rule processing stops and the packet is treated according to that rule. This is very useful when an exception to the general rules is needed. Creating an <acronym>FTP</acronym> Proxy Configuring working FTP rules can be problematic due to the nature of the FTP protocol. FTP pre-dates firewalls by several decades and is insecure in its design. The most common points against using FTP include: Passwords are transferred in the clear. The protocol demands the use of at least two TCP connections (control and data) on separate ports. When a session is established, data is communicated using randomly selected ports. All of these points present security challenges, even before considering any potential security weaknesses in client or server software. More secure alternatives for file transfer exist, such as &man.sftp.1; or &man.scp.1;, which both feature authentication and data transfer over encrypted connections.. For those situations when FTP is required, PF provides redirection of FTP traffic to a small proxy program called &man.ftp-proxy.8;, which is included in the base system of &os;. The role of the proxy is to dynamically insert and delete rules in the ruleset, using a set of anchors, in order to correctly handle FTP traffic. To enable the FTP proxy, add this line to /etc/rc.conf: ftpproxy_enable="YES" Then start the proxy by running service ftp-proxy start. For a basic configuration, three elements need to be added to /etc/pf.conf. First, the anchors which the proxy will use to insert the rules it generates for the FTP sessions: nat-anchor "ftp-proxy/*" rdr-anchor "ftp-proxy/*" Second, a pass rule is needed to allow FTP traffic in to the proxy. Third, redirection and NAT rules need to be defined before the filtering rules. Insert this rdr rule immediately after the nat rule: rdr pass on $int_if proto tcp from any to any port ftp -> 127.0.0.1 port 8021 Finally, allow the redirected traffic to pass: pass out proto tcp from $proxy to any port ftp where $proxy expands to the address the proxy daemon is bound to. Save /etc/pf.conf, load the new rules, and verify from a client that FTP connections are working: &prompt.root; pfctl -f /etc/pf.conf This example covers a basic setup where the clients in the local network need to contact FTP servers elsewhere. This basic configuration should work well with most combinations of FTP clients and servers. As shown in &man.ftp-proxy.8;, the proxy's behavior can be changed in various ways by adding options to the ftpproxy_flags= line. Some clients or servers may have specific quirks that must be compensated for in the configuration, or there may be a need to integrate the proxy in specific ways such as assigning FTP traffic to a specific queue. For ways to run an FTP server protected by PF and &man.ftp-proxy.8;, configure a separate ftp-proxy in reverse mode, using , on a separate port with its own redirecting pass rule. Managing <acronym>ICMP</acronym> Many of the tools used for debugging or troubleshooting a TCP/IP network rely on the Internet Control Message Protocol (ICMP), which was designed specifically with debugging in mind. The ICMP protocol sends and receives control messages between hosts and gateways, mainly to provide feedback to a sender about any unusual or difficult conditions enroute to the target host. Routers use ICMP to negotiate packet sizes and other transmission parameters in a process often referred to as path MTU discovery. From a firewall perspective, some ICMP control messages are vulnerable to known attack vectors. Also, letting all diagnostic traffic pass unconditionally makes debugging easier, but it also makes it easier for others to extract information about the network. For these reasons, the following rule may not be optimal: pass inet proto icmp from any to any One solution is to let all ICMP traffic from the local network through while stopping all probes from outside the network: pass inet proto icmp from $localnet to any keep state pass inet proto icmp from any to $ext_if keep state Additional options are available which demonstrate some of PF's flexibility. For example, rather than allowing all ICMP messages, one can specify the messages used by &man.ping.8; and &man.traceroute.8;. Start by defining a macro for that type of message: icmp_types = "echoreq" and a rule which uses the macro: pass inet proto icmp all icmp-type $icmp_types keep state If other types of ICMP packets are needed, expand icmp_types to a list of those packet types. Type more /usr/src/contrib/pf/pfctl/pfctl_parser.c to see the list of ICMP message types supported by PF. Refer to http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xhtml for an explanation of each message type. Since Unix traceroute uses UDP by default, another rule is needed to allow Unix traceroute: # allow out the default range for traceroute(8): pass out on $ext_if inet proto udp from any to any port 33433 >< 33626 keep state Since TRACERT.EXE on Microsoft Windows systems uses ICMP echo request messages, only the first rule is needed to allow network traces from those systems. Unix traceroute can be instructed to use other protocols as well, and will use ICMP echo request messages if is used. Check the &man.traceroute.8; man page for details. Path <acronym>MTU</acronym> Discovery Internet protocols are designed to be device independent, and one consequence of device independence is that the optimal packet size for a given connection cannot always be predicted reliably. The main constraint on packet size is the Maximum Transmission Unit (MTU) which sets the upper limit on the packet size for an interface. Type ifconfig to view the MTUs for a system's network interfaces. TCP/IP uses a process known as path MTU discovery to determine the right packet size for a connection. This process sends packets of varying sizes with the Do not fragment flag set, expecting an ICMP return packet of type 3, code 4 when the upper limit has been reached. Type 3 means destination unreachable, and code 4 is short for fragmentation needed, but the do-not-fragment flag is set. To allow path MTU discovery in order to support connections to other MTUs, add the destination unreachable type to the icmp_types macro: icmp_types = "{ echoreq, unreach }" Since the pass rule already uses that macro, it does not need to be modified in order to support the new ICMP type: pass inet proto icmp all icmp-type $icmp_types keep state PF allows filtering on all variations of ICMP types and codes. The list of possible types and codes are documented in &man.icmp.4; and &man.icmp6.4;. Using Tables Some types of data are relevant to filtering and redirection at a given time, but their definition is too long to be included in the ruleset file. PF supports the use of tables, which are defined lists that can be manipulated without needing to reload the entire ruleset, and which can provide fast lookups. Table names are always enclosed within < >, like this: table <clients> { 192.168.2.0/24, !192.168.2.5 } In this example, the 192.168.2.0/24 network is part of the table, except for the address 192.168.2.5, which is excluded using the ! operator. It is also possible to load tables from files where each item is on a separate line, as seen in this example /etc/clients: 192.168.2.0/24 !192.168.2.5 To refer to the file, define the table like this: table <clients> persist file "/etc/clients" Once the table is defined, it can be referenced by a rule: pass inet proto tcp from <clients> to any port $client_out flags S/SA keep state A table's contents can be manipulated live, using pfctl. This example adds another network to the table: &prompt.root; pfctl -t clients -T add 192.168.1.0/16 Note that any changes made this way will take affect now, making them ideal for testing, but will not survive a power failure or reboot. To make the changes permanent, modify the definition of the table in the ruleset or edit the file that the table refers to. One can maintain the on-disk copy of the table using a &man.cron.8; job which dumps the table's contents to disk at regular intervals, using a command such as pfctl -t clients -T show >/etc/clients. Alternatively, /etc/clients can be updated with the in-memory table contents: &prompt.root; pfctl -t clients -T replace -f /etc/clients Using Overload Tables to Protect <acronym>SSH</acronym> Those who run SSH on an external interface have probably seen something like this in the authentication logs: Sep 26 03:12:34 skapet sshd[25771]: Failed password for root from 200.72.41.31 port 40992 ssh2 Sep 26 03:12:34 skapet sshd[5279]: Failed password for root from 200.72.41.31 port 40992 ssh2 Sep 26 03:12:35 skapet sshd[5279]: Received disconnect from 200.72.41.31: 11: Bye Bye Sep 26 03:12:44 skapet sshd[29635]: Invalid user admin from 200.72.41.31 Sep 26 03:12:44 skapet sshd[24703]: input_userauth_request: invalid user admin Sep 26 03:12:44 skapet sshd[24703]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2 This is indicative of a brute force attack where somebody or some program is trying to discover the user name and password which will let them into the system. If external SSH access is needed for legitimate users, changing the default port used by SSH can offer some protection. However, PF provides a more elegant solution. Pass rules can contain limits on what connecting hosts can do and violators can be banished to a table of addresses which are denied some or all access. It is even possible to drop all existing connections from machines which overreach the limits. To configure this, create this table in the tables section of the ruleset: table <bruteforce> persist Then, somewhere early in the ruleset, add rules to block brute access while allowing legitimate access: block quick from <bruteforce> pass inet proto tcp from any to $localnet port $tcp_services \ flags S/SA keep state \ (max-src-conn 100, max-src-conn-rate 15/5, \ overload <bruteforce> flush global) The part in parentheses defines the limits and the numbers should be changed to meet local requirements. It can be read as follows: max-src-conn is the number of simultaneous connections allowed from one host. max-src-conn-rate is the rate of new connections allowed from any single host (15) per number of seconds (5). overload <bruteforce> means that any host which exceeds these limits gets its address added to the bruteforce table. The ruleset blocks all traffic from addresses in the bruteforce table. Finally, flush global says that when a host reaches the limit, that all (global) of that host's connections will be terminated (flush). These rules will not block slow bruteforcers, as described in http://home.nuug.no/~peter/hailmary2013/. This example ruleset is intended mainly as an illustration. For example, if a generous number of connections in general are wanted, but the desire is to be more restrictive when it comes to ssh, supplement the rule above with something like the one below, early on in the rule set: pass quick proto { tcp, udp } from any to any port ssh \ flags S/SA keep state \ (max-src-conn 15, max-src-conn-rate 5/3, \ overload <bruteforce> flush global) It May Not be Necessary to Block All Overloaders It is worth noting that the overload mechanism is a general technique which does not apply exclusively to SSH, and it is not always optimal to entirely block all traffic from offenders. For example, an overload rule could be used to protect a mail service or a web service, and the overload table could be used in a rule to assign offenders to a queue with a minimal bandwidth allocation or to redirect to a specific web page. Over time, tables will be filled by overload rules and their size will grow incrementally, taking up more memory. Sometimes an IP address that is blocked is a dynamically assigned one, which has since been assigned to a host who has a legitimate reason to communicate with hosts in the local network. For situations like these, pfctl provides the ability to expire table entries. For example, this command will remove <bruteforce> table entries which have not been referenced for 86400 seconds: &prompt.root; pfctl -t bruteforce -T expire 86400 Similar functionality is provided by security/expiretable, which removes table entries which have not been accessed for a specified period of time. Once installed, expiretable can be run to remove <bruteforce> table entries older than a specified age. This example removes all entries older than 24 hours: /usr/local/sbin/expiretable -v -d -t 24h bruteforce Protecting Against <acronym>SPAM</acronym> Not to be confused with the spamd daemon which comes bundled with spamassassin, mail/spamd can be configured with PF to provide an outer defense against SPAM. This spamd hooks into the PF configuration using a set of redirections. Spammers tend to send a large number of messages, and SPAM is mainly sent from a few spammer friendly networks and a large number of hijacked machines, both of which are reported to blacklists fairly quickly. When an SMTP connection from an address in a blacklist is received, spamd presents its banner and immediately switches to a mode where it answers SMTP traffic one byte at a time. This technique, which is intended to waste as much time as possible on the spammer's end, is called tarpitting. The specific implementation which uses one byte SMTP replies is often referred to as stuttering. This example demonstrates the basic procedure for setting up spamd with automatically updated blacklists. Refer to the man pages which are installed with mail/spamd for more information. Configuring <application>spamd</application> Install the mail/spamd package or port. In order to use spamd's greylisting features, &man.fdescfs.5; must be mounted at /dev/fd. Add the following line to /etc/fstab: fdescfs /dev/fd fdescfs rw 0 0 Then, mount the filesystem: &prompt.root; mount fdescfs Next, edit the PF ruleset to include: table <spamd> persist table <spamd-white> persist rdr pass on $ext_if inet proto tcp from <spamd> to \ { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025 rdr pass on $ext_if inet proto tcp from !<spamd-white> to \ { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025 The two tables <spamd> and <spamd-white> are essential. SMTP traffic from an address listed in <spamd> but not in <spamd-white> is redirected to the spamd daemon listening at port 8025. The next step is to configure spamd in /usr/local/etc/spamd.conf and to add some rc.conf parameters. The installation of mail/spamd includes a sample configuration file (/usr/local/etc/spamd.conf.sample) and a man page for spamd.conf. Refer to these for additional configuration options beyond those shown in this example. One of the first lines in the configuration file that does not begin with a # comment sign contains the block which defines the all list, which specifies the lists to use: all:\ :traplist:whitelist: This entry adds the desired blacklists, separated by colons (:). To use a whitelist to subtract addresses from a blacklist, add the name of the whitelist immediately after the name of that blacklist. For example: :blacklist:whitelist:. This is followed by the specified blacklist's definition: traplist:\ :black:\ :msg="SPAM. Your address %A has sent spam within the last 24 hours":\ :method=http:\ :file=www.openbsd.org/spamd/traplist.gz where the first line is the name of the blacklist and the second line specifies the list type. The msg field contains the message to display to blacklisted senders during the SMTP dialogue. The method field specifies how spamd-setup fetches the list data; supported methods are http, ftp, from a file in a mounted file system, and via exec of an external program. Finally, the file field specifies the name of the file spamd expects to receive. The definition of the specified whitelist is similar, but omits the msg field since a message is not needed: whitelist:\ :white:\ :method=file:\ :file=/var/mail/whitelist.txt Choose Data Sources with Care Using all the blacklists in the sample spamd.conf will blacklist large blocks of the Internet. Administrators need to edit the file to create an optimal configuration which uses applicable data sources and, when necessary, uses custom lists. Next, add this entry to /etc/rc.conf. Additional flags are described in the man page specified by the comment: spamd_flags="-v" # use "" and see spamd-setup(8) for flags When finished, reload the ruleset, start spamd by typing service start obspamd, and complete the configuration using spamd-setup. Finally, create a &man.cron.8; job which calls spamd-setup to update the tables at reasonable intervals. On a typical gateway in front of a mail server, hosts will soon start getting trapped within a few seconds to several minutes. PF also supports greylisting, which temporarily rejects messages from unknown hosts with 45n codes. Messages from greylisted hosts which try again within a reasonable time are let through. Traffic from senders which are set up to behave within the limits set by RFC 1123 and RFC 2821 are immediately let through. More information about greylisting as a technique can be found at the greylisting.org web site. The most amazing thing about greylisting, apart from its simplicity, is that it still works. Spammers and malware writers have been very slow to adapt in order to bypass this technique. The basic procedure for configuring greylisting is as follows: Configuring Greylisting Make sure that &man.fdescfs.5; is mounted as described in Step 1 of the previous Procedure. To run spamd in greylisting mode, add this line to /etc/rc.conf: spamd_grey="YES" # use spamd greylisting if YES Refer to the spamd man page for descriptions of additional related parameters. To complete the greylisting setup: &prompt.root; service restart obspamd &prompt.root; service start spamlogd Behind the scenes, the spamdb database tool and the spamlogd whitelist updater perform essential functions for the greylisting feature. spamdb is the administrator's main interface to managing the black, grey, and white lists via the contents of the /var/db/spamdb database. Network Hygiene This section describes how block-policy, scrub, and antispoof can be used to make the ruleset behave sanely. The block-policy is an option which can be set in the options part of the ruleset, which precedes the redirection and filtering rules. This option determines which feedback, if any, PF sends to hosts that are blocked by a rule. The option has two possible values: drop drops blocked packets with no feedback, and return returns a status code such as Connection refused. If not set, the default policy is drop. To change the block-policy, specify the desired value: set block-policy return In PF, scrub is a keyword which enables network packet normalization. This process reassembles fragmented packets and drops TCP packets that have invalid flag combinations. Enabling scrub provides a measure of protection against certain kinds of attacks based on incorrect handling of packet fragments. A number of options are available, but the simplest form is suitable for most configurations: scrub in all Some services, such as NFS, require specific fragment handling options. Refer to http://www.openbsd.gr/faq/pf/scrub.html for more information. This example reassembles fragments, clears the do not fragment bit, and sets the maximum segment size to 1440 bytes: scrub in all fragment reassemble no-df max-mss 1440 The antispoof mechanism protects against activity from spoofed or forged IP addresses, mainly by blocking packets appearing on interfaces and in directions which are logically not possible. These rules weed out spoofed traffic coming in from the rest of the world as well as any spoofed packets which originate in the local network: antispoof for $ext_if antispoof for $int_if Handling Non-Routable Addresses Even with a properly configured gateway to handle network address translation, one may have to compensate for other people's misconfigurations. A common misconfiguration is to let traffic with non-routable addresses out to the Internet. Since traffic from non-routeable addresses can play a part in several DoS attack techniques, consider explicitly blocking traffic from non-routeable addresses from entering the network through the external interface. In this example, a macro containing non-routable addresses is defined, then used in blocking rules. Traffic to and from these addresses is quietly dropped on the gateway's external interface. martians = "{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \ 10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \ 0.0.0.0/8, 240.0.0.0/4 }" block drop in quick on $ext_if from $martians to any block drop out quick on $ext_if from any to $martians
<application>IPFW</application> firewall IPFW IPFW is a stateful firewall written for &os; which supports both IPv4 and IPv6. It is comprised of several components: the kernel firewall filter rule processor and its integrated packet accounting facility, the logging facility, NAT, the &man.dummynet.4; traffic shaper, a forward facility, a bridge facility, and an ipstealth facility. &os; provides a sample ruleset in /etc/rc.firewall which defines several firewall types for common scenarios to assist novice users in generating an appropriate ruleset. IPFW provides a powerful syntax which advanced users can use to craft customized rulesets that meet the security requirements of a given environment. This section describes how to enable IPFW, provides an overview of its rule syntax, and demonstrates several rulesets for common configuration scenarios. Enabling <application>IPFW</application> IPFW enabling IPFW is included in the basic &os; install as a kernel loadable module, meaning that a custom kernel is not needed in order to enable IPFW. kernel options IPFIREWALL kernel options IPFIREWALL_VERBOSE kernel options IPFIREWALL_VERBOSE_LIMIT IPFW kernel options For those users who wish to statically compile IPFW support into a custom kernel, refer to the instructions in . The following options are available for the custom kernel configuration file: options IPFIREWALL # enables IPFW options IPFIREWALL_VERBOSE # enables logging for rules with log keyword options IPFIREWALL_VERBOSE_LIMIT=5 # limits number of logged packets per-entry options IPFIREWALL_DEFAULT_TO_ACCEPT # sets default policy to pass what is not explicitly denied options IPDIVERT # enables NAT To configure the system to enable IPFW at boot time, add the following entry to /etc/rc.conf: firewall_enable="YES" To use one of the default firewall types provided by &os;, add another line which specifies the type: firewall_type="open" The available types are: open: passes all traffic. client: protects only this machine. simple: protects the whole network. closed: entirely disables IP traffic except for the loopback interface. workstation: protects only this machine using stateful rules. UNKNOWN: disables the loading of firewall rules. filename: full path of the file containing the firewall ruleset. If firewall_type is set to either client or simple, modify the default rules found in /etc/rc.firewall to fit the configuration of the system. Note that the filename type is used to load a custom ruleset. An alternate way to load a custom ruleset is to set the firewall_script variable to the absolute path of an executable script that includes IPFW commands. The examples used in this section assume that the firewall_script is set to /etc/ipfw.rules: firewall_script="/etc/ipfw.rules" To enable logging, include this line: firewall_logging="YES" There is no /etc/rc.conf variable to set logging limits. To limit the number of times a rule is logged per connection attempt, specify the number using this line in /etc/sysctl.conf: net.inet.ip.fw.verbose_limit=5 After saving the needed edits, start the firewall. To enable logging limits now, also set the sysctl value specified above: &prompt.root; service ipfw start &prompt.root; sysctl net.inet.ip.fw.verbose_limit=5 <application>IPFW</application> Rule Syntax IPFW rule processing order When a packet enters the IPFW firewall, it is compared against the first rule in the ruleset and progresses one rule at a time, moving from top to bottom in sequence. When the packet matches the selection parameters of a rule, the rule's action is executed and the search of the ruleset terminates for that packet. This is referred to as first match wins. If the packet does not match any of the rules, it gets caught by the mandatory IPFW default rule number 65535, which denies all packets and silently discards them. However, if the packet matches a rule that contains the count, skipto, or tee keywords, the search continues. Refer to &man.ipfw.8; for details on how these keywords affect rule processing. IPFW rule syntax When creating an IPFW rule, keywords must be written in the following order. Some keywords are mandatory while other keywords are optional. The words shown in uppercase represent a variable and the words shown in lowercase must precede the variable that follows it. The # symbol is used to mark the start of a comment and may appear at the end of a rule or on its own line. Blank lines are ignored. CMD RULE_NUMBER set SET_NUMBER ACTION log LOG_AMOUNT PROTO from SRC SRC_PORT to DST DST_PORT OPTIONS This section provides an overview of these keywords and their options. It is not an exhaustive list of every possible option. Refer to &man.ipfw.8; for a complete description of the rule syntax that can be used when creating IPFW rules. CMD Every rule must start with ipfw add. RULE_NUMBER Each rule is associated with a number in the range of 1 to 65534. The number is used to indicate the order of rule processing. Multiple rules can have the same number, in which case they are checked according to the order in which they have been added. SET_NUMBER Each rule is associated with a set number in the range of 0 to 31. Sets can be individually disabled or enabled, making it possible to quickly add or delete a set of rules. If a SET_NUMBER is not specified, the rule will be added to set 0. ACTION A rule can be associated with one of the following actions. The specified action will be executed when the packet matches the selection criterion of the rule. allow | accept | pass | permit: these keywords are equivalent and allow packets that match the rule. check-state: checks the packet against the dynamic state table. If a match is found, execute the action associated with the rule which generated this dynamic rule, otherwise move to the next rule. A check-state rule does not have selection criterion. If no check-state rule is present in the ruleset, the dynamic rules table is checked at the first keep-state or limit rule. count: updates counters for all packets that match rule. The search continues with the next rule. deny | drop: either word discards packets that match this rule. Additional actions are available. Refer to &man.ipfw.8; for details. LOG_AMOUNT When a packet matches a rule with the log keyword, a message will be logged to &man.syslogd.8; with a facility name of SECURITY. Logging only occurs if the number of packets logged for that particular rule does not exceed the optional specified LOG_AMOUNT. If no LOG_AMOUNT is specified, the limit is taken from the value of net.inet.ip.fw.verbose_limit. A value of zero removes the logging limit. Once the limit is reached, logging can be re-enabled by clearing the logging counter or the packet counter for that rule, using ipfw reset log. Logging is done after all other packet matching conditions have been met, and before performing the final action on the packet. The administrator decides which rules to enable logging on. PROTO This optional value can be used to specify any protocol name or number found in /etc/protocols. SRC The from keyword must be followed by the source address or a keyword that represents the source address. An address can be represented by the any, me (any address configured on an interface on this system), me6, (any IPv6 address configured on an interface on this system), or table followed by the number of a lookup table which contains a list of addresses. When specifying an IP address, it can be optionally followed by its CIDR mask or subnet mask. For example, 1.2.3.4/25 or 1.2.3.4:255.255.255.128. SRC_PORT An optional source port can be specified using the port number or name from /etc/services. DST The to keyword must be followed by the destination address or a keyword that represents the destination address. The same keywords and addresses described in the SRC section can be used to describe the destination. DST_PORT An optional destination port can be specified using the port number or name from /etc/services. OPTIONS Several keywords can follow the source and destination. As the name suggests, OPTIONS are optional. Commonly used options include in or out, which specify the direction of packet flow, icmptypes followed by the type of ICMP message, and keep-state. When a keep-state rule is matched, the firewall will create a dynamic rule which matches bidirectional traffic between the source and destination addresses and ports using the same protocol. The dynamic rules facility is vulnerable to resource depletion from a SYN-flood attack which would open a huge number of dynamic rules. To counter this type of attack with IPFW, use limit. This option limits the number of simultaneous sessions by checking the open dynamic rules, counting the number of times this rule and IP address combination occurred. If this count is greater than the value specified by limit, the packet is discarded. Dozens of OPTIONS are available. Refer to &man.ipfw.8; for a description of each available option. Example Ruleset This section demonstrates how to create an example stateful firewall ruleset script named /etc/ipfw.rules. In this example, all connection rules use in or out to clarify the direction. They also use via interface-name to specify the interface the packet is traveling over. The firewall script begins by indicating that it is a Bourne shell script and flushes any existing rules. It then creates the cmd variable so that ipfw add does not have to be typed at the beginning of every rule. It also defines the pif variable which represents the name of the interface that is attached to the Internet. #!/bin/sh # Flush out the list before we begin. ipfw -q -f flush # Set rules command prefix cmd="ipfw -q add" pif="dc0" # interface name of NIC attached to Internet The first two rules allow all traffic on the trusted internal interface and on the loopback interface: # Change xl0 to LAN NIC interface name $cmd 00005 allow all from any to any via xl0 # No restrictions on Loopback Interface $cmd 00010 allow all from any to any via lo0 The next rule allows the packet through if it matches an existing entry in the dynamic rules table: $cmd 00015 check-state The next set of rules defines which stateful connections internal systems can create to hosts on the Internet: # Allow access to public DNS # Replace x.x.x.x with the IP address of a public DNS server # and repeat for each DNS server in /etc/resolv.conf $cmd 00110 allow tcp from any to x.x.x.x 53 out via $pif setup keep-state $cmd 00111 allow udp from any to x.x.x.x 53 out via $pif keep-state # Allow access to ISP's DHCP server for cable/DSL configurations. # Use the first rule and check log for IP address. # Then, uncomment the second rule, input the IP address, and delete the first rule $cmd 00120 allow log udp from any to any 67 out via $pif keep-state #$cmd 00120 allow udp from any to x.x.x.x 67 out via $pif keep-state # Allow outbound HTTP and HTTPS connections $cmd 00200 allow tcp from any to any 80 out via $pif setup keep-state $cmd 00220 allow tcp from any to any 443 out via $pif setup keep-state # Allow outbound email connections $cmd 00230 allow tcp from any to any 25 out via $pif setup keep-state $cmd 00231 allow tcp from any to any 110 out via $pif setup keep-state # Allow outbound ping $cmd 00250 allow icmp from any to any out via $pif keep-state # Allow outbound NTP $cmd 00260 allow tcp from any to any 37 out via $pif setup keep-state # Allow outbound SSH $cmd 00280 allow tcp from any to any 22 out via $pif setup keep-state # deny and log all other outbound connections $cmd 00299 deny log all from any to any out via $pif The next set of rules controls connections from Internet hosts to the internal network. It starts by denying packets typically associated with attacks and then explicitly allows specific types of connections. All the authorized services that originate from the Internet use limit to prevent flooding. # Deny all inbound traffic from non-routable reserved address spaces $cmd 00300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 00301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 00302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 00303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 00304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 00305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 00306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 00307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster interconnect $cmd 00308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Deny public pings $cmd 00310 deny icmp from any to any in via $pif # Deny ident $cmd 00315 deny tcp from any to any 113 in via $pif # Deny all Netbios services. $cmd 00320 deny tcp from any to any 137 in via $pif $cmd 00321 deny tcp from any to any 138 in via $pif $cmd 00322 deny tcp from any to any 139 in via $pif $cmd 00323 deny tcp from any to any 81 in via $pif # Deny fragments $cmd 00330 deny all from any to any frag in via $pif # Deny ACK packets that did not match the dynamic rule table $cmd 00332 deny tcp from any to any established in via $pif # Allow traffic from ISP's DHCP server. # Replace x.x.x.x with the same IP address used in rule 00120. #$cmd 00360 allow udp from any to x.x.x.x 67 in via $pif keep-state # Allow HTTP connections to internal web server $cmd 00400 allow tcp from any to me 80 in via $pif setup limit src-addr 2 # Allow inbound SSH connections $cmd 00410 allow tcp from any to me 22 in via $pif setup limit src-addr 2 # Reject and log all other incoming connections $cmd 00499 deny log all from any to any in via $pif The last rule logs all packets that do not match any of the rules in the ruleset: # Everything else is denied and logged $cmd 00999 deny log all from any to any - - - The <application>IPFW</application> Command - - ipfw - - ipfw can be used to make manual, - single rule additions or deletions to the active firewall - while it is running. The problem with using this method is - that all the changes are lost when the system reboots. It is - recommended to instead write all the rules in a file and to - use that file to load the rules at boot time and to replace - the currently running firewall rules whenever that file - changes. - - ipfw is a useful way to display the - running firewall rules to the console screen. The - IPFW accounting facility - dynamically creates a counter for each rule that counts each - packet that matches the rule. During the process of testing a - rule, listing the rule with its counter is one way to - determine if the rule is functioning as expected. - - To list all the running rules in sequence: - - &prompt.root; ipfw list - - To list all the running rules with a time stamp of when - the last time the rule was matched: - - &prompt.root; ipfw -t list - - The next example lists accounting information and the - packet count for matched rules along with the rules - themselves. The first column is the rule number, followed by - the number of matched packets and bytes, followed by the rule - itself. - - &prompt.root; ipfw -a list - - To list dynamic rules in addition to static rules: - - &prompt.root; ipfw -d list - To also show the expired dynamic rules: - - &prompt.root; ipfw -d -e list - - To zero the counters: - - &prompt.root; ipfw zero - - To zero the counters for just the rule with number - NUM: - - &prompt.root; ipfw zero NUM - - - Logging Firewall Messages - - - IPFW - - logging - - - Even with the logging facility enabled, - IPFW will not generate any rule - logging on its own. The firewall administrator decides - which rules in the ruleset will be logged, and adds the - log keyword to those rules. Normally - only deny rules are logged. It is customary to duplicate - the ipfw default deny everything rule with - the log keyword included as the last rule - in the ruleset. This way, it is possible to see all the - packets that did not match any of the rules in the - ruleset. - - Logging is a two edged sword. If one is not careful, - an over abundance of log data or a DoS attack can fill the - disk with log files. Log messages are not only written to - syslogd, but also are displayed - on the root console screen and soon become annoying. - - The IPFIREWALL_VERBOSE_LIMIT=5 - kernel option limits the number of consecutive messages - sent to &man.syslogd.8;, concerning the packet matching of a - given rule. When this option is enabled in the kernel, the - number of consecutive messages concerning a particular rule - is capped at the number specified. There is nothing to be - gained from 200 identical log messages. With this option - set to five, - five consecutive messages concerning a particular rule - would be logged to syslogd and - the remainder identical consecutive messages would be - counted and posted to syslogd - with a phrase like the following: - - last message repeated 45 times - - All logged packets messages are written by default to - /var/log/security, which is - defined in /etc/syslog.conf. - - - - Building a Rule Script - - Most experienced IPFW users - create a file containing the rules and code them in a manner - compatible with running them as a script. The major benefit - of doing this is the firewall rules can be refreshed in mass - without the need of rebooting the system to activate them. - This method is convenient in testing new rules as the - procedure can be executed as many times as needed. Being a - script, symbolic substitution can be used for frequently - used values to be substituted into multiple rules. - - This example script is compatible with the syntax used - by the &man.sh.1;, &man.csh.1;, and &man.tcsh.1; shells. - Symbolic substitution fields are prefixed with a dollar sign - ($). Symbolic fields do not have the $ - prefix. The value to populate the symbolic field must be - enclosed in double quotes (""). - - Start the rules file like this: - - ############### start of example ipfw rules script ############# -# -ipfw -q -f flush # Delete all rules -# Set defaults -oif="tun0" # out interface -odns="192.0.2.11" # ISP's DNS server IP address -cmd="ipfw -q add " # build rule prefix -ks="keep-state" # just too lazy to key this each time -$cmd 00500 check-state -$cmd 00502 deny all from any to any frag -$cmd 00501 deny tcp from any to any established -$cmd 00600 allow tcp from any to any 80 out via $oif setup $ks -$cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks -$cmd 00611 allow udp from any to $odns 53 out via $oif $ks -################### End of example ipfw rules script ############ - - The rules are not important as the focus of this example - is how the symbolic substitution fields are - populated. - - If the above example was in - /etc/ipfw.rules, the rules could be - reloaded by the following command: - - &prompt.root; sh /etc/ipfw.rules - - /etc/ipfw.rules can be located - anywhere and the file can have any name. - - The same thing could be accomplished by running these - commands by hand: - - &prompt.root; ipfw -q -f flush -&prompt.root; ipfw -q add check-state -&prompt.root; ipfw -q add deny all from any to any frag -&prompt.root; ipfw -q add deny tcp from any to any established -&prompt.root; ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state -&prompt.root; ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state -&prompt.root; ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state - - - - An Example <acronym>NAT</acronym> and Stateful - Ruleset + + Configuring <acronym>NAT</acronym> NAT and IPFW There are some additional configuration statements that need to be enabled to activate the NAT function of IPFW. For a customized kernel, the kernel configuration file needs option IPDIVERT added to the other IPFIREWALL options. In addition to the normal IPFW options in /etc/rc.conf, the following are needed: natd_enable="YES" # Enable NATD function natd_interface="rl0" # interface name of public Internet NIC natd_flags="-dynamic -m" # -m = preserve port numbers if possible Utilizing stateful rules with a divert natd rule complicates the ruleset logic. The positioning of the check-state, and divert natd rules in the ruleset is critical and a new action type is used, called skipto. When using skipto, it is mandatory that each rule is numbered, so that the skipto rule knows which rule to jump to. The following is an uncommented example of a ruleset which explains the sequence of the packet flow. The processing flow starts with the first rule from the top of the ruleset and progresses one rule at a time until the end is reached or the packet matches and the packet is released out of the firewall. Take note of the location of rule numbers 100 101, 450, 500, and 510. These rules control the translation of the outbound and inbound packets so that their entries in the dynamic keep-state table always register the private LAN IP address. All the allow and deny rules specify the direction of the packet and the interface. All start outbound session requests will skipto rule 500 to undergo NAT. Consider a web browser which initializes a new HTTP session over port 80. When the first outbound packet enters the firewall, it does not match rule 100 because it is headed out rather than in. It passes rule 101 because this is the first packet, and it has not been posted to the dynamic keep-state table yet. The packet finally matches rule 125 as it is outbound through the NIC facing the Internet and has a source IP address as a private LAN IP address. On matching this rule, two actions take place. keep-state adds this rule to the dynamic keep-state rules table and the specified action is executed and posted as part of the info in the dynamic table. In this case, the action is skipto rule 500. Rule 500 NATs the packet IP address and sends it out to the Internet. This packet makes its way to the destination web server, where a response packet is generated and sent back. This new packet enters the top of the ruleset. It matches rule 100 and has it destination IP address mapped back to the corresponding LAN IP address. It then is processed by the check-state rule, is found in the table as an existing session, and is released to the LAN. It goes to the LAN system that sent it and a new packet is sent requesting another segment of the data from the remote server. This time it matches the check-state rule, its outbound entry is found, and the associated action, skipto 500, is executed. The packet jumps to rule 500, gets NATed, and is released to the Internet. On the inbound side, everything coming in that is part of an existing session is automatically handled by the check-state rule and the properly placed divert natd rules. The ruleset only has to deny bad packets and allow only authorized services. Consider a web server running on the firewall where web requests from the Internet should have access to the local web site. An inbound start request packet will match rule 100 and its IP address will be mapped to the LAN IP address of the firewall. The packet is then matched against all the nasty things that need to be checked and finally matches rule 425 where two actions occur. The packet rule is posted to the dynamic keep-state table but this time, any new session requests originating from that source IP address are limited to 2. This defends against DoS attacks against the service running on the specified port number. The action is allow, so the packet is released to the LAN. The packet generated as a response is recognized by the check-state as belonging to an existing session. It is then sent to rule 500 for NATing and released to the outbound interface. Example Ruleset #1: #!/bin/sh cmd="ipfw -q add" skip="skipto 500" pif=rl0 ks="keep-state" good_tcpo="22,25,37,43,53,80,443,110,119" ipfw -q -f flush $cmd 002 allow all from any to any via xl0 # exclude LAN traffic $cmd 003 allow all from any to any via lo0 # exclude loopback traffic $cmd 100 divert natd ip from any to any in via $pif $cmd 101 check-state # Authorized outbound packets $cmd 120 $skip udp from any to xx.168.240.2 53 out via $pif $ks $cmd 121 $skip udp from any to xx.168.240.5 53 out via $pif $ks $cmd 125 $skip tcp from any to any $good_tcpo out via $pif setup $ks $cmd 130 $skip icmp from any to any out via $pif $ks $cmd 135 $skip udp from any to any 123 out via $pif $ks # Deny all inbound traffic from non-routable reserved address spaces $cmd 300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster $cmd 308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Authorized inbound packets $cmd 400 allow udp from xx.70.207.54 to any 68 in $ks $cmd 420 allow tcp from any to me 80 in via $pif setup limit src-addr 1 $cmd 450 deny log ip from any to any # This is skipto location for outbound stateful rules $cmd 500 divert natd ip from any to any out via $pif $cmd 510 allow ip from any to any ######################## end of rules ################## The next example is functionally equivalent, but uses descriptive comments to help the inexperienced IPFW rule writer to better understand what the rules are doing. Example Ruleset #2: #!/bin/sh ################ Start of IPFW rules file ############################### # Flush out the list before we begin. ipfw -q -f flush # Set rules command prefix cmd="ipfw -q add" skip="skipto 800" pif="rl0" # public interface name of NIC # facing the public Internet ################################################################# # No restrictions on Inside LAN Interface for private network # Change xl0 to your LAN NIC interface name ################################################################# $cmd 005 allow all from any to any via xl0 ################################################################# # No restrictions on Loopback Interface ################################################################# $cmd 010 allow all from any to any via lo0 ################################################################# # check if packet is inbound and nat address if it is ################################################################# $cmd 014 divert natd ip from any to any in via $pif ################################################################# # Allow the packet through if it has previous been added to the # the "dynamic" rules table by a allow keep-state statement. ################################################################# $cmd 015 check-state ################################################################# # Interface facing Public Internet (Outbound Section) # Check session start requests originating from behind the # firewall on the private network or from this gateway server # destined for the public Internet. ################################################################# # Allow out access to my ISP's Domain name server. # x.x.x.x must be the IP address of your ISP's DNS # Dup these lines if your ISP has more than one DNS server # Get the IP addresses from /etc/resolv.conf file $cmd 020 $skip tcp from any to x.x.x.x 53 out via $pif setup keep-state # Allow out access to my ISP's DHCP server for cable/DSL configurations. $cmd 030 $skip udp from any to x.x.x.x 67 out via $pif keep-state # Allow out non-secure standard www function $cmd 040 $skip tcp from any to any 80 out via $pif setup keep-state # Allow out secure www function https over TLS SSL $cmd 050 $skip tcp from any to any 443 out via $pif setup keep-state # Allow out send & get email function $cmd 060 $skip tcp from any to any 25 out via $pif setup keep-state $cmd 061 $skip tcp from any to any 110 out via $pif setup keep-state # Allow out FreeBSD (make install & CVSUP) functions # Basically give user root "GOD" privileges. $cmd 070 $skip tcp from me to any out via $pif setup keep-state uid root # Allow out ping $cmd 080 $skip icmp from any to any out via $pif keep-state # Allow out Time $cmd 090 $skip tcp from any to any 37 out via $pif setup keep-state # Allow out nntp news (i.e., news groups) $cmd 100 $skip tcp from any to any 119 out via $pif setup keep-state # Allow out secure FTP, Telnet, and SCP # This function is using SSH (secure shell) $cmd 110 $skip tcp from any to any 22 out via $pif setup keep-state # Allow out whois $cmd 120 $skip tcp from any to any 43 out via $pif setup keep-state # Allow ntp time server $cmd 130 $skip udp from any to any 123 out via $pif keep-state ################################################################# # Interface facing Public Internet (Inbound Section) # Check packets originating from the public Internet # destined for this gateway server or the private network. ################################################################# # Deny all inbound traffic from non-routable reserved address spaces $cmd 300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP $cmd 301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP $cmd 302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP $cmd 303 deny all from 127.0.0.0/8 to any in via $pif #loopback $cmd 304 deny all from 0.0.0.0/8 to any in via $pif #loopback $cmd 305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config $cmd 306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs $cmd 307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster $cmd 308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast # Deny ident $cmd 315 deny tcp from any to any 113 in via $pif # Deny all Netbios service. 137=name, 138=datagram, 139=session # Netbios is MS/Windows sharing services. # Block MS/Windows hosts2 name server requests 81 $cmd 320 deny tcp from any to any 137 in via $pif $cmd 321 deny tcp from any to any 138 in via $pif $cmd 322 deny tcp from any to any 139 in via $pif $cmd 323 deny tcp from any to any 81 in via $pif # Deny any late arriving packets $cmd 330 deny all from any to any frag in via $pif # Deny ACK packets that did not match the dynamic rule table $cmd 332 deny tcp from any to any established in via $pif # Allow traffic in from ISP's DHCP server. This rule must contain # the IP address of your ISP's DHCP server as it is the only # authorized source to send this packet type. # Only necessary for cable or DSL configurations. # This rule is not needed for 'user ppp' type connection to # the public Internet. This is the same IP address you captured # and used in the outbound section. $cmd 360 allow udp from x.x.x.x to any 68 in via $pif keep-state # Allow in standard www function because I have Apache server $cmd 370 allow tcp from any to me 80 in via $pif setup limit src-addr 2 # Allow in secure FTP, Telnet, and SCP from public Internet $cmd 380 allow tcp from any to me 22 in via $pif setup limit src-addr 2 # Allow in non-secure Telnet session from public Internet # labeled non-secure because ID & PW are passed over public # Internet as clear text. # Delete this sample group if you do not have telnet server enabled. $cmd 390 allow tcp from any to me 23 in via $pif setup limit src-addr 2 # Reject & Log all unauthorized incoming connections from the public Internet $cmd 400 deny log all from any to any in via $pif # Reject & Log all unauthorized out going connections to the public Internet $cmd 450 deny log all from any to any out via $pif # This is skipto location for outbound stateful rules $cmd 800 divert natd ip from any to any out via $pif $cmd 801 allow ip from any to any # Everything else is denied by default # deny and log all packets that fell through to see what they are $cmd 999 deny log all from any to any ################ End of IPFW rules file ############################### + + + + The <application>IPFW</application> Command + + ipfw + + ipfw can be used to make manual, + single rule additions or deletions to the active firewall + while it is running. The problem with using this method is + that all the changes are lost when the system reboots. It is + recommended to instead write all the rules in a file and to + use that file to load the rules at boot time and to replace + the currently running firewall rules whenever that file + changes. + + ipfw is a useful way to display the + running firewall rules to the console screen. The + IPFW accounting facility + dynamically creates a counter for each rule that counts each + packet that matches the rule. During the process of testing a + rule, listing the rule with its counter is one way to + determine if the rule is functioning as expected. + + To list all the running rules in sequence: + + &prompt.root; ipfw list + + To list all the running rules with a time stamp of when + the last time the rule was matched: + + &prompt.root; ipfw -t list + + The next example lists accounting information and the + packet count for matched rules along with the rules + themselves. The first column is the rule number, followed by + the number of matched packets and bytes, followed by the rule + itself. + + &prompt.root; ipfw -a list + + To list dynamic rules in addition to static rules: + + &prompt.root; ipfw -d list + + To also show the expired dynamic rules: + + &prompt.root; ipfw -d -e list + + To zero the counters: + + &prompt.root; ipfw zero + + To zero the counters for just the rule with number + NUM: + + &prompt.root; ipfw zero NUM + + + Logging Firewall Messages + + + IPFW + + logging + + + Even with the logging facility enabled, + IPFW will not generate any rule + logging on its own. The firewall administrator decides + which rules in the ruleset will be logged, and adds the + log keyword to those rules. Normally + only deny rules are logged. It is customary to duplicate + the ipfw default deny everything rule with + the log keyword included as the last rule + in the ruleset. This way, it is possible to see all the + packets that did not match any of the rules in the + ruleset. + + Logging is a two edged sword. If one is not careful, + an over abundance of log data or a DoS attack can fill the + disk with log files. Log messages are not only written to + syslogd, but also are displayed + on the root console screen and soon become annoying. + + The IPFIREWALL_VERBOSE_LIMIT=5 + kernel option limits the number of consecutive messages + sent to &man.syslogd.8;, concerning the packet matching of a + given rule. When this option is enabled in the kernel, the + number of consecutive messages concerning a particular rule + is capped at the number specified. There is nothing to be + gained from 200 identical log messages. With this option + set to five, + five consecutive messages concerning a particular rule + would be logged to syslogd and + the remainder identical consecutive messages would be + counted and posted to syslogd + with a phrase like the following: + + last message repeated 45 times + + All logged packets messages are written by default to + /var/log/security, which is + defined in /etc/syslog.conf. + + + + Building a Rule Script + + Most experienced IPFW users + create a file containing the rules and code them in a manner + compatible with running them as a script. The major benefit + of doing this is the firewall rules can be refreshed in mass + without the need of rebooting the system to activate them. + This method is convenient in testing new rules as the + procedure can be executed as many times as needed. Being a + script, symbolic substitution can be used for frequently + used values to be substituted into multiple rules. + + This example script is compatible with the syntax used + by the &man.sh.1;, &man.csh.1;, and &man.tcsh.1; shells. + Symbolic substitution fields are prefixed with a dollar sign + ($). Symbolic fields do not have the $ + prefix. The value to populate the symbolic field must be + enclosed in double quotes (""). + + Start the rules file like this: + + ############### start of example ipfw rules script ############# +# +ipfw -q -f flush # Delete all rules +# Set defaults +oif="tun0" # out interface +odns="192.0.2.11" # ISP's DNS server IP address +cmd="ipfw -q add " # build rule prefix +ks="keep-state" # just too lazy to key this each time +$cmd 00500 check-state +$cmd 00502 deny all from any to any frag +$cmd 00501 deny tcp from any to any established +$cmd 00600 allow tcp from any to any 80 out via $oif setup $ks +$cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks +$cmd 00611 allow udp from any to $odns 53 out via $oif $ks +################### End of example ipfw rules script ############ + + The rules are not important as the focus of this example + is how the symbolic substitution fields are + populated. + + If the above example was in + /etc/ipfw.rules, the rules could be + reloaded by the following command: + + &prompt.root; sh /etc/ipfw.rules + + /etc/ipfw.rules can be located + anywhere and the file can have any name. + + The same thing could be accomplished by running these + commands by hand: + + &prompt.root; ipfw -q -f flush +&prompt.root; ipfw -q add check-state +&prompt.root; ipfw -q add deny all from any to any frag +&prompt.root; ipfw -q add deny tcp from any to any established +&prompt.root; ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state +&prompt.root; ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state +&prompt.root; ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state IPFILTER (IPF) firewall IPFILTER IPFILTER, also known as IPF, is a cross-platform, open source firewall which has been ported to several operating systems, including &os;, NetBSD, OpenBSD, and &solaris;. IPFILTER is a kernel-side firewall and NAT mechanism that can be controlled and monitored by userland programs. Firewall rules can be set or deleted using ipf, NAT rules can be set or deleted using ipnat, run-time statistics for the kernel parts of IPFILTER can be printed using ipfstat, and ipmon can be used to log IPFILTER actions to the system log files. IPF was originally written using a rule processing logic of the last matching rule wins and only used stateless rules. Since then, IPF has been enhanced to include the quick and keep state options. For a detailed explanation of the legacy rules processing method, refer to http://coombs.anu.edu.au/~avalon/ip-filter.html. The IPF FAQ is at http://www.phildev.net/ipf/index.html. A searchable archive of the IPFilter mailing list is available at http://marc.info/?l=ipfilter. This section of the Handbook focuses on IPF as it pertains to FreeBSD. It provides examples of rules that contain the quick and keep state options. Enabling <application>IPF</application> IPFILTER enabling IPF is included in the basic &os; install as a kernel loadable module, meaning that a custom kernel is not needed in order to enable IPF. kernel options IPFILTER kernel options IPFILTER_LOG kernel options IPFILTER_DEFAULT_BLOCK IPFILTER kernel options For users who prefer to statically compile IPF support into a custom kernel, refer to the instructions in . The following kernel options are available: options IPFILTER options IPFILTER_LOG options IPFILTER_LOOKUP options IPFILTER_DEFAULT_BLOCK where options IPFILTER enables support for IPFILTER, options IPFILTER_LOG enables IPF logging using the ipl packet logging pseudo-device for every rule that has the log keyword, IPFILTER_LOOKUP enables IP pools in order to speed up IP lookups, and options IPFILTER_DEFAULT_BLOCK changes the default behavior so that any packet not matching a firewall pass rule gets blocked. To configure the system to enable IPF at boot time, add the following entries to /etc/rc.conf. These entries will also enable logging and default pass all. To change the default policy to block all without compiling a custom kernel, remember to add a block all rule at the end of the ruleset. ipfilter_enable="YES" # Start ipf firewall ipfilter_rules="/etc/ipf.rules" # loads rules definition text file ipmon_enable="YES" # Start IP monitor log ipmon_flags="-Ds" # D = start as daemon # s = log to syslog # v = log tcp window, ack, seq # n = map IP & port to names If NAT functionality is needed, also add these lines: gateway_enable="YES" # Enable as LAN gateway ipnat_enable="YES" # Start ipnat function ipnat_rules="/etc/ipnat.rules" # rules definition file for ipnat Then, to start IPF now: &prompt.root; service ipfilter start To load the firewall rules, specify the name of the ruleset file using ipf. The following command can be used to replace the currently running firewall rules: &prompt.root; ipf -Fa -f /etc/ipf.rules where flushes all the internal rules tables and specifies the file containing the rules to load. This provides the ability to make changes to a custom ruleset and update the running firewall with a fresh copy of the rules without having to reboot the system. This method is convenient for testing new rules as the procedure can be executed as many times as needed. Refer to &man.ipf.8; for details on the other flags available with this command. <application>IPF</application> Rule Syntax IPFILTER rule syntax This section describes the IPF rule syntax used to create stateful rules. When creating rules, keep in mind that unless the quick keyword appears in a rule, every rule is read in order, with the last matching rule being the one that is applied. This means that even if the first rule to match a packet is a pass, if there is a later matching rule that is a block, the packet will be dropped. Sample rulesets can be found in /usr/share/examples/ipfilter. When creating rules, a # character is used to mark the start of a comment and may appear at the end of a rule, to explain that rule's function, or on its own line. Any blank lines are ignored. The keywords which are used in rules must be written in a specific order, from left to right. Some keywords are mandatory while others are optional. Some keywords have sub-options which may be keywords themselves and also include more sub-options. The keyword order is as follows, where the words shown in uppercase represent a variable and the words shown in lowercase must precede the variable that follows it: ACTION DIRECTION OPTIONS proto PROTO_TYPE from SRC_ADDR SRC_PORT to DST_ADDR DST_PORT TCP_FLAG|ICMP_TYPE keep state STATE This section describes each of these keywords and their options. It is not an exhaustive list of every possible option. Refer to &man.ipf.5; for a complete description of the rule syntax that can be used when creating IPF rules and examples for using each keyword. ACTION The action keyword indicates what to do with the packet if it matches that rule. Every rule must have an action. The following actions are recognized: block: drops the packet. pass: allows the packet. log: generates a log record. count: counts the number of packets and bytes which can provide an indication of how often a rule is used. auth: queues the packet for further processing by another program. call: provides access to functions built into IPF that allow more complex actions. decapsulate: removes any headers in order to process the contents of the packet. DIRECTION Next, each rule must explicitly state the direction of traffic using one of these keywords: in: the rule is applied against an inbound packet. out: the rule is applied against an outbound packet. all: the rule applies to either direction. If the system has multiple interfaces, the interface can be specified along with the direction. An example would be in on fxp0. OPTIONS Options are optional. However, if multiple options are specified, they must be used in the order shown here. log: when performing the specified ACTION, the contents of the packet's headers will be written to the &man.ipl.4; packet log pseudo-device. quick: if a packet matches this rule, the ACTION specified by the rule occurs and no further processing of any following rules will occur for this packet. on: must be followed by the interface name as displayed by &man.ifconfig.8;. The rule will only match if the packet is going through the specified interface in the specified direction. When using the log keyword, the following qualifiers may be used in this order: body: indicates that the first 128 bytes of the packet contents will be logged after the headers. first: if the log keyword is being used in conjunction with a keep state option, this option is recommended so that only the triggering packet is logged and not every packet which matches the stateful connection. Additional options are available to specify error return messages. Refer to &man.ipf.5; for more details. PROTO_TYPE The protocol type is optional. However, it is mandatory if the rule needs to specify a SRC_PORT or a DST_PORT as it defines the type of protocol. When specifying the type of protocol, use the proto keyword followed by either a protocol number or name from /etc/protocols. Example protocol names include tcp, udp, or icmp. If PROTO_TYPE is specified but no SRC_PORT or DST_PORT is specified, all port numbers for that protocol will match that rule. SRC_ADDR The from keyword is mandatory and is followed by a keyword which represents the source of the packet. The source can be a hostname, an IP address followed by the CIDR mask, an address pool, or the keyword all. Refer to &man.ipf.5; for examples. There is no way to match ranges of IP addresses which do not express themselves easily using the dotted numeric form / mask-length notation. The net-mgmt/ipcalc package or port may be used to ease the calculation of the CIDR mask. Additional information is available at the utility's web page: http://jodies.de/ipcalc. SRC_PORT The port number of the source is optional. However, if it is used, it requires PROTO_TYPE to be first defined in the rule. The port number must also be preceded by the proto keyword. A number of different comparison operators are supported: = (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to). To specify port ranges, place the two port numbers between <> (less than and greater than ), >< (greater than and less than ), or : (greater than or equal to and less than or equal to). DST_ADDR The to keyword is mandatory and is followed by a keyword which represents the destination of the packet. Similar to SRC_ADDR, it can be a hostname, an IP address followed by the CIDR mask, an address pool, or the keyword all. DST_PORT Similar to SRC_PORT, the port number of the destination is optional. However, if it is used, it requires PROTO_TYPE to be first defined in the rule. The port number must also be preceded by the proto keyword. TCP_FLAG|ICMP_TYPE If tcp is specifed as the PROTO_TYPE, flags can be specified as letters, where each letter represents one of the possible TCP flags used to determine the state of a connection. Possible values are: S (SYN), A (ACK), P (PSH), F (FIN), U (URG), R (RST), C (CWN), and E (ECN). If icmp is specifed as the PROTO_TYPE, the ICMP type to match can be specified. Refer to &man.ipf.5; for the allowable types. STATE If a pass rule contains keep state, IPF will add an entry to its dynamic state table and allow subsequent packets that match the connection. IPF can track state for TCP, UDP, and ICMP sessions. Any packet that IPF can be certain is part of an active session, even if it is a different protocol, will be allowed. In IPF, packets destined to go out through the interface connected to the public Internet are first checked against the dynamic state table. If the packet matches the next expected packet comprising an active session conversation, it exits the firewall and the state of the session conversation flow is updated in the dynamic state table. Packets that do not belong to an already active session are checked against the outbound ruleset. Packets coming in from the interface connected to the public Internet are first checked against the dynamic state table. If the packet matches the next expected packet comprising an active session, it exits the firewall and the state of the session conversation flow is updated in the dynamic state table. Packets that do not belong to an already active session are checked against the inbound ruleset. Several keywords can be added after keep state. If used, these keywords set various options that control stateful filtering, such as setting connection limits or connection age. Refer to &man.ipf.5; for the list of available options and their descriptions. Example Ruleset This section demonstrates how to create an example ruleset which only allows services matching pass rules and blocks all others. &os; uses the loopback interface (lo0) and the IP address 127.0.0.1 for internal communication. The firewall ruleset must contain rules to allow free movement of these internally used packets: # no restrictions on loopback interface pass in quick on lo0 all pass out quick on lo0 all The public interface connected to the Internet is used to authorize and control access of all outbound and inbound connections. If one or more interfaces are cabled to private networks, those internal interfaces may require rules to allow packets originating from the LAN to flow between the internal networks or to the interface attached to the Internet. The ruleset should be organized into three major sections: any trusted internal interfaces, outbound connections through the public interface, and inbound connections through the public interface. These two rules allow all traffic to pass through a trusted LAN interface named xl0: # no restrictions on inside LAN interface for private network pass out quick on xl0 all pass in quick on xl0 all The rules for the public interface's outbound and inbound sections should have the most frequently matched rules placed before less commonly matched rules, with the last rule in the section blocking and logging all packets for that interface and direction. This set of rules defines the outbound section of the public interface named dc0. These rules keep state and identify the specific services that internal systems are authorized for public Internet access. All the rules use quick and specify the appropriate port numbers and, where applicable, destination addresses. # interface facing Internet (outbound) # Matches session start requests originating from or behind the # firewall, destined for the Internet. # Allow outbound access to public DNS servers. # Replace x.x.x. with address listed in /etc/resolv.conf. # Repeat for each DNS server. pass out quick on dc0 proto tcp from any to x.x.x. port = 53 flags S keep state pass out quick on dc0 proto udp from any to xxx port = 53 keep state # Allow access to ISP's specified DHCP server for cable or DSL networks. # Use the first rule, then check log for the IP address of DHCP server. # Then, uncomment the second rule, replace z.z.z.z with the IP address, # and comment out the first rule pass out log quick on dc0 proto udp from any to any port = 67 keep state #pass out quick on dc0 proto udp from any to z.z.z.z port = 67 keep state # Allow HTTP and HTTPS pass out quick on dc0 proto tcp from any to any port = 80 flags S keep state pass out quick on dc0 proto tcp from any to any port = 443 flags S keep state # Allow email pass out quick on dc0 proto tcp from any to any port = 110 flags S keep state pass out quick on dc0 proto tcp from any to any port = 25 flags S keep state # Allow NTP pass out quick on dc0 proto tcp from any to any port = 37 flags S keep state # Allow FTP pass out quick on dc0 proto tcp from any to any port = 21 flags S keep state # Allow SSH pass out quick on dc0 proto tcp from any to any port = 22 flags S keep state # Allow ping pass out quick on dc0 proto icmp from any to any icmp-type 8 keep state # Block and log everything else block out log first quick on dc0 all This example of the rules in the inbound section of the public interface blocks all undesirable packets first. This reduces the number of packets that are logged by the last rule. # interface facing Internet (inbound) # Block all inbound traffic from non-routable or reserved address spaces block in quick on dc0 from 192.168.0.0/16 to any #RFC 1918 private IP block in quick on dc0 from 172.16.0.0/12 to any #RFC 1918 private IP block in quick on dc0 from 10.0.0.0/8 to any #RFC 1918 private IP block in quick on dc0 from 127.0.0.0/8 to any #loopback block in quick on dc0 from 0.0.0.0/8 to any #loopback block in quick on dc0 from 169.254.0.0/16 to any #DHCP auto-config block in quick on dc0 from 192.0.2.0/24 to any #reserved for docs block in quick on dc0 from 204.152.64.0/23 to any #Sun cluster interconnect block in quick on dc0 from 224.0.0.0/3 to any #Class D & E multicast # Block fragments and too short tcp packets block in quick on dc0 all with frags block in quick on dc0 proto tcp all with short # block source routed packets block in quick on dc0 all with opt lsrr block in quick on dc0 all with opt ssrr # Block OS fingerprint attempts and log first occurrence block in log first quick on dc0 proto tcp from any to any flags FUP # Block anything with special options block in quick on dc0 all with ipopts # Block public pings and ident block in quick on dc0 proto icmp all icmp-type 8 block in quick on dc0 proto tcp from any to any port = 113 # Block incoming Netbios services block in log first quick on dc0 proto tcp/udp from any to any port = 137 block in log first quick on dc0 proto tcp/udp from any to any port = 138 block in log first quick on dc0 proto tcp/udp from any to any port = 139 block in log first quick on dc0 proto tcp/udp from any to any port = 81 Any time there are logged messages on a rule with the log first option, run ipfstat -hio to evaluate how many times the rule has been matched. A large number of matches may indicate that the system is under attack. The rest of the rules in the inbound section define which connections are allowed to be initiated from the Internet. The last rule denies all connections which were not explicitly allowed by previous rules in this section. # Allow traffic in from ISP's DHCP server. Replace z.z.z.z with # the same IP address used in the outbound section. pass in quick on dc0 proto udp from z.z.z.z to any port = 68 keep state # Allow public connections to specified internal web server pass in quick on dc0 proto tcp from any to x.x.x.x port = 80 flags S keep state # Block and log only first occurrence of all remaining traffic. block in log first quick on dc0 all Configuring <acronym>NAT</acronym> NAT IP masquerading NAT network address translation NAT ipnat To enable NAT, add these statements to /etc/rc.conf and specify the name of the file containing the NAT rules: gateway_enable="YES" ipnat_enable="YES" ipnat_rules="/etc/ipnat.rules" NAT rules are flexible and can accomplish many different things to fit the needs of both commercial and home users. The rule syntax presented here has been simplified to demonstrate common usage. For a complete rule syntax description, refer to &man.ipnat.5;. The basic syntax for a NAT rule is as follows, where map starts the rule and IF should be replaced with the name of the external interface: map IF LAN_IP_RANGE -> PUBLIC_ADDRESS The LAN_IP_RANGE is the range of IP addresses used by internal clients. Usually, it is a private address range such as 192.168.1.0/24. The PUBLIC_ADDRESS can either be the static external IP address or the keyword 0/32 which represents the IP address assigned to IF. In IPF, when a packet arrives at the firewall from the LAN with a public destination, it first passes through the outbound rules of the firewall ruleset. Then, the packet is passed to the NAT ruleset which is read from the top down, where the first matching rule wins. IPF tests each NAT rule against the packet's interface name and source IP address. When a packet's interface name matches a NAT rule, the packet's source IP address in the private LAN is checked to see if it falls within the IP address range specified in LAN_IP_RANGE. On a match, the packet has its source IP address rewritten with the public IP address specified by PUBLIC_ADDRESS. IPF posts an entry in its internal NAT table so that when the packet returns from the Internet, it can be mapped back to its original private IP address before being passed to the firewall rules for further processing. For networks that have large numbers of internal systems or multiple subnets, the process of funneling every private IP address into a single public IP address becomes a resource problem. Two methods are available to relieve this issue. The first method is to assign a range of ports to use as source ports. By adding the portmap keyword, NAT can be directed to only use source ports in the specified range: map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp 20000:60000 Alternately, use the auto keyword which tells NAT to determine the ports that are available for use: map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp auto The second method is to use a pool of public addresses. This is useful when there are too many LAN addresses to fit into a single public address and a block of public IP addresses is available. These public addresses can be used as a pool from which NAT selects an IP address as a packet's address is mapped on its way out. The range of public IP addresses can be specified using a netmask or CIDR notation. These two rules are equivalent: map dc0 192.168.1.0/24 -> 204.134.75.0/255.255.255.0 map dc0 192.168.1.0/24 -> 204.134.75.0/24 A common practice is to have a publically accessible web server or mail server segregated to an internal network segment. The traffic from these servers still has to undergo NAT, but port redirection is needed to direct inbound traffic to the correct server. For example, to map a web server using the internal address 10.0.10.25 to its public IP address of 20.20.20.5, use this rule: rdr dc0 20.20.20.5/32 port 80 -> 10.0.10.25 port 80 If it is the only web server, this rule would also work as it redirects all external HTTP requests to 10.0.10.25: rdr dc0 0.0.0.0/0 port 80 -> 10.0.10.25 port 80 IPF has a built in FTP proxy which can be used with NAT. It monitors all outbound traffic for active or passive FTP connection requests and dynamically creates temporary filter rules containing the port number used by the FTP data channel. This eliminates the need to open large ranges of high order ports for FTP connections. In this example, the first rule calls the proxy for outbound FTP traffic from the internal LAN. The second rule passes the FTP traffic from the firewall to the Internet, and the third rule handles all non-FTP traffic from the internal LAN: map dc0 10.0.10.0/29 -> 0/32 proxy port 21 ftp/tcp map dc0 0.0.0.0/0 -> 0/32 proxy port 21 ftp/tcp map dc0 10.0.10.0/29 -> 0/32 The FTP map rules go before the NAT rule so that when a packet matches an FTP rule, the FTP proxy creates temporary filter rules to let the FTP session packets pass and undergo NAT. All LAN packets that are not FTP will not match the FTP rules but will undergo NAT if they match the third rule. Without the FTP proxy, the following firewall rules would instead be needed. Note that without the proxy, all ports above 1024 need to be allowed: # Allow out LAN PC client FTP to public Internet # Active and passive modes pass out quick on rl0 proto tcp from any to any port = 21 flags S keep state # Allow out passive mode data channel high order port numbers pass out quick on rl0 proto tcp from any to any port > 1024 flags S keep state # Active mode let data channel in from FTP server pass in quick on rl0 proto tcp from any to any port = 20 flags S keep state Whenever the file containing the NAT rules is edited, run ipnat with to delete the current NAT rules and flush the contents of the dynamic translation table. Include and specify the name of the NAT ruleset to load: &prompt.root; ipnat -CF -f /etc/ipnat.rules To display the NAT statistics: &prompt.root; ipnat -s To list the NAT table's current mappings: &prompt.root; ipnat -l To turn verbose mode on and display information relating to rule processing and active rules and table entries: &prompt.root; ipnat -v Viewing <application>IPF</application> Statistics ipfstat IPFILTER statistics IPF includes &man.ipfstat.8; which can be used to retrieve and display statistics which are gathered as packets match rules as they go through the firewall. Statistics are accumulated since the firewall was last started or since the last time they were reset to zero using ipf -Z. The default ipfstat output looks like this: input packets: blocked 99286 passed 1255609 nomatch 14686 counted 0 output packets: blocked 4200 passed 1284345 nomatch 14687 counted 0 input packets logged: blocked 99286 passed 0 output packets logged: blocked 0 passed 0 packets logged: input 0 output 0 log failures: input 3898 output 0 fragment state(in): kept 0 lost 0 fragment state(out): kept 0 lost 0 packet state(in): kept 169364 lost 0 packet state(out): kept 431395 lost 0 ICMP replies: 0 TCP RSTs sent: 0 Result cache hits(in): 1215208 (out): 1098963 IN Pullups succeeded: 2 failed: 0 OUT Pullups succeeded: 0 failed: 0 Fastroute successes: 0 failures: 0 TCP cksum fails(in): 0 (out): 0 Packet log flags set: (0) Several options are available. When supplied with either for inbound or for outbound, the command will retrieve and display the appropriate list of filter rules currently installed and in use by the kernel. To also see the rule numbers, include . For example, ipfstat -on displays the outbound rules table with rule numbers: @1 pass out on xl0 from any to any @2 block out on dc0 from any to any @3 pass out quick on dc0 proto tcp/udp from any to any keep state Include to prefix each rule with a count of how many times the rule was matched. For example, ipfstat -oh displays the outbound internal rules table, prefixing each rule with its usage count: 2451423 pass out on xl0 from any to any 354727 block out on dc0 from any to any 430918 pass out quick on dc0 proto tcp/udp from any to any keep state To display the state table in a format similar to &man.top.1;, use ipfstat -t. When the firewall is under attack, this option provides the ability to identify and see the attacking packets. The optional sub-flags give the ability to select the destination or source IP, port, or protocol to be monitored in real time. Refer to &man.ipfstat.8; for details. <application>IPF</application> Logging ipmon IPFILTER logging IPF provides ipmon, which can be used to write the firewall's logging information in a human readable format. It requires that options IPFILTER_LOG be first added to a custom kernel using the instructions in . This command is typically run in daemon mode in order to provide a continuous system log file so that logging of past events may be reviewed. Since &os; has a built in &man.syslogd.8; facility to automatically rotate system logs, the default rc.conf ipmon_flags statement uses : ipmon_flags="-Ds" # D = start as daemon # s = log to syslog # v = log tcp window, ack, seq # n = map IP & port to names Logging provides the ability to review, after the fact, information such as which packets were dropped, what addresses they came from, and where they were going. This information is useful in tracking down attackers. Once the logging facility is enabled in rc.conf and started with service ipmon start, IPF will only log the rules which contain the log keyword. The firewall administrator decides which rules in the ruleset should be logged and normally only deny rules are logged. It is customary to include the log keyword in the last rule in the ruleset. This makes it possible to see all the packets that did not match any of the rules in the ruleset. By default, ipmon -Ds mode uses local0 as the logging facility. The following logging levels can be used to further segregate the logged data: LOG_INFO - packets logged using the "log" keyword as the action rather than pass or block. LOG_NOTICE - packets logged which are also passed LOG_WARNING - packets logged which are also blocked LOG_ERR - packets which have been logged and which can be considered short due to an incomplete header In order to setup IPF to log all data to /var/log/ipfilter.log, first create the empty file: &prompt.root; touch /var/log/ipfilter.log Then, to write all logged messages to the specified file, add the following statement to /etc/syslog.conf: local0.* /var/log/ipfilter.log To activate the changes and instruct &man.syslogd.8; to read the modified /etc/syslog.conf, run service syslogd reload. Do not forget to edit /etc/newsyslog.conf to rotate the new log file. Messages generated by ipmon consist of data fields separated by white space. Fields common to all messages are: The date of packet receipt. The time of packet receipt. This is in the form HH:MM:SS.F, for hours, minutes, seconds, and fractions of a second. The name of the interface that processed the packet. The group and rule number of the rule in the format @0:17. The action: p for passed, b for blocked, S for a short packet, n did not match any rules, and L for a log rule. The addresses written as three fields: the source address and port separated by a comma, the -> symbol, and the destination address and port. For example: 209.53.17.22,80 -> 198.73.220.17,1722. PR followed by the protocol name or number: for example, PR tcp. len followed by the header length and total length of the packet: for example, len 20 40. If the packet is a TCP packet, there will be an additional field starting with a hyphen followed by letters corresponding to any flags that were set. Refer to &man.ipf.5; for a list of letters and their flags. If the packet is an ICMP packet, there will be two fields at the end: the first always being icmp and the next being the ICMP message and sub-message type, separated by a slash. For example: icmp 3/3 for a port unreachable message.