Index: head/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml =================================================================== --- head/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml (revision 46057) +++ head/en_US.ISO8859-1/books/handbook/firewalls/chapter.xml (revision 46058) @@ -1,3758 +1,3758 @@ 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 from 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 applied according to the order in which they have been added. SET_NUMBER Each rule is associated with a set number from 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 the rule. The search continues with the next rule. deny | drop: either word silently 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 a 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 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. When first creating or testing a firewall ruleset, consider temporarily setting this tunable: net.inet.ip.fw.default_to_accept="1" 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. 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 00101 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 Configuring <acronym>NAT</acronym> Chern Lee Contributed by NAT and IPFW &os;'s built-in NAT daemon, &man.natd.8;, works in conjunction with IPFW to provide network address translation. This can be used to provide an Internet Connection Sharing solution so that several internal computers can connect to the Internet using a single IP address. To do this, the &os; machine connected to the Internet must act as a gateway. This system must have two NICs, where one is connected to the Internet and the other is connected to the internal LAN. Each machine connected to the LAN should be assigned an IP address in the private network space, as defined by RFC 1918, and have the default gateway set to the &man.natd.8; system's internal IP address. Some additional configuration is needed in order to activate the NAT function of IPFW. If the system has a custom kernel, the kernel configuration file needs to include option IPDIVERT along with the other IPFIREWALL options described in . To enable NAT support at boot time, the following must be in /etc/rc.conf: gateway_enable="YES" # enables the gateway natd_enable="YES" # enables NAT natd_interface="rl0" # specify interface name of NIC attached to Internet natd_flags="-dynamic -m" # -m = preserve port numbers; additional options are listed in &man.natd.8; It is also possible to specify a configuration file which contains the options to pass to &man.natd.8;: natd_flags="-f /etc/natd.conf" The specified file must contain a list of configuration options, one per line. 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;. Next, add the NAT rules to the firewall ruleset. When the rulest contains stateful rules, the positioning of the NAT rules is critical and the skipto action is used. The skipto action requires a rule number so that it knows which rule to jump to. The following example builds upon the firewall ruleset shown in the previous section. It adds some additional entries and modifies some existing rules in order to configure the firewall for NAT. It starts by adding some additional variables which represent the rule number to skip to, the keep-state option, and a list of TCP ports which will be used to reduce the number of rules: #!/bin/sh ipfw -q -f flush cmd="ipfw -q add" skip="skipto 500" pif=dc0 ks="keep-state" good_tcpo="22,25,37,53,80,443,110" The inbound NAT rule is inserted after the two rules which allow all traffic on the trusted internal interface and on the loopback interface and before the check-state rule. It is important that the rule number selected for this NAT rule, in this example 100, is higher than the first two rules and lower than the check-state rule: $cmd 005 allow all from any to any via xl0 # exclude LAN traffic $cmd 010 allow all from any to any via lo0 # exclude loopback traffic $cmd 100 divert natd ip from any to any in via $pif # NAT any inbound packets # Allow the packet through if it has an existing entry in the dynamic rules table $cmd 101 check-state The outbound rules are modified to replace the allow action with the $skip variable, indicating that rule processing will continue at rule 500. The seven tcp rules have been replaced by rule 125 as the $good_tcpo variable contains the seven allowed outbound ports. # Authorized outbound packets $cmd 120 $skip udp from any to x.x.x.x 53 out via $pif $ks $cmd 121 $skip udp from any to x.x.x.x 67 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 The inbound rules remain the same, except for the very last rule which removes the via $pif in order to catch both inbound and outbound rules. The NAT rule must follow this last outbound rule, must have a higher number than that last rule, and the rule number must be referenced by the skipto action. In this ruleset, rule number 500 diverts all packets which match the outbound rules to &man.natd.8; for NAT processing. The next rule allows any packet which has undergone NAT processing to pass. $cmd 499 deny log all from any to any $cmd 500 divert natd ip from any to any out via $pif # skipto location for outbound stateful rules $cmd 510 allow ip from any to any In this example, rules 100, 101, 125, 500, and 510 control the address translation of the outbound and inbound packets so that the entries in the dynamic state table always register the private LAN IP address. Consider an internal web browser which initializes a new outbound 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 state table yet. The packet finally matches rule 125 as it is outbound on an allowed port and has a source IP address from the internal LAN. On matching this rule, two actions take place. First, the keep-state action adds an entry to the dynamic state table and the specified action, skipto rule 500, is executed. Next, the packet undergoes NAT and is sent 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 its destination IP address mapped back to the original internal 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. On the inbound side, the ruleset has to deny bad packets and allow only authorized services. A packet which matches an inbound rule is posted to the dynamic state table and the - packet is released to the LAN. The packet + packet is released to the LAN. The packet generated as a response is recognized by the check-state rule as belonging to an existing session. It is then sent to rule 500 to undergo NAT before being released to the outbound interface. 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. 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.
Index: head/en_US.ISO8859-1/books/handbook/ppp-and-slip/chapter.xml =================================================================== --- head/en_US.ISO8859-1/books/handbook/ppp-and-slip/chapter.xml (revision 46057) +++ head/en_US.ISO8859-1/books/handbook/ppp-and-slip/chapter.xml (revision 46058) @@ -1,1679 +1,1679 @@ <acronym>PPP</acronym> Synopsis PPP &os; supports the Point-to-Point (PPP) protocol which can be used to establish a network or Internet connection using a dial-up modem. This chapter describes how to configure modem-based communication services in &os;. After reading this chapter, you will know: How to configure, use, and troubleshoot a PPP connection. How to set up PPP over Ethernet (PPPoE). How to set up PPP over ATM (PPPoA). PPP PPP over Ethernet Before reading this chapter, you should: Be familiar with basic network terminology. Understand the basics and purpose of a dial-up connection and PPP. Configuring <acronym>PPP</acronym> &os; provides built-in support for managing dial-up PPP connections using &man.ppp.8;. The default &os; kernel provides support for tun which is used to interact with a modem hardware. Configuration is performed by editing at least one configuration file, and configuration files containing examples are provided. Finally, ppp is used to start and manage connections. In order to use a PPP connection, the following items are needed: A dial-up account with an Internet Service Provider (ISP). A dial-up modem. The dial-up number for the ISP. The login name and password assigned by the ISP. The IP address of one or more DNS servers. Normally, the ISP provides these addresses. If it did not, &os; can be configured to use DNS negotiation. If any of the required information is missing, contact the ISP. The following information may be supplied by the ISP, but is not necessary: The IP address of the default gateway. If this information is unknown, the ISP will automatically provide the correct value during connection setup. When configuring PPP on &os;, this address is referred to as HISADDR. The subnet mask. If the ISP has not provided one, 255.255.255.255 will be used in the &man.ppp.8; configuration file. static IP address If the ISP has assigned a static IP address and hostname, it should be input into the configuration file. Otherwise, this information will be automatically provided during connection setup. The rest of this section demonstrates how to configure &os; for common PPP connection scenarios. The required configuration file is /etc/ppp/ppp.conf and additional files and examples are available in /usr/share/examples/ppp/. Throughout this section, many of the file examples display line numbers. These line numbers have been added to make it easier to follow the discussion and are not meant to be placed in the actual file. When editing a configuration file, proper indentation is important. Lines that end in a : start in the first column (beginning of the line) while all other lines should be indented as shown using spaces or tabs. Basic Configuration PPP with static IP addresses In order to configure a PPP connection, first edit /etc/ppp/ppp.conf with the - dial-in information for the ISP. This file + dial-in information for the ISP. This file is described as follows: 1 default: 2 set log Phase Chat LCP IPCP CCP tun command 3 ident user-ppp VERSION 4 set device /dev/cuau0 5 set speed 115200 6 set dial "ABORT BUSY ABORT NO\\sCARRIER TIMEOUT 5 \ 7 \"\" AT OK-AT-OK ATE1Q0 OK \\dATDT\\T TIMEOUT 40 CONNECT" 8 set timeout 180 9 enable dns 10 11 provider: 12 set phone "(123) 456 7890" 13 set authname foo 14 set authkey bar 15 set timeout 300 16 set ifaddr x.x.x.x/0 y.y.y.y/0 255.255.255.255 0.0.0.0 17 add default HISADDR Line 1: Identifies the default entry. Commands in this entry (lines 2 through 9) are executed automatically when ppp is run. Line 2: Enables verbose logging parameters for testing the connection. Once the configuration is working satisfactorily, this line should be reduced to: set log phase tun Line 3: Displays the version of &man.ppp.8; to the PPP software running on the other side of the connection. Line 4: Identifies the device to which the modem is connected, where COM1 is /dev/cuau0 and COM2 is /dev/cuau1. Line 5: Sets the connection speed. If 115200 does not work on an older modem, try 38400 instead. Lines 6 & 7: The dial string written as an expect-send syntax. Refer to &man.chat.8; for more information. Note that this command continues onto the next line for readability. Any command in ppp.conf may do this if the last character on the line is \. Line 8: Sets the idle timeout for the link in seconds. Line 9: Instructs the peer to confirm the DNS settings. If the local network is running its own DNS server, this line should be commented out, by adding a # at the beginning of the line, or removed. Line 10: A blank line for readability. Blank lines are ignored by &man.ppp.8;. Line 11: Identifies an entry called provider. This could be changed to the name of the ISP so that can be used to start the connection. Line 12: Use the phone number for the ISP. Multiple phone numbers may be specified using the colon (:) or pipe character (|) as a separator. To rotate through the numbers, use a colon. To always attempt to dial the first number first and only use the other numbers if the first number fails, use the pipe character. Always enclose the entire set of phone numbers between quotation marks (") to prevent dialing failures. Lines 13 & 14: Use the user name and password for the ISP. Line 15: Sets the default idle timeout in seconds for the connection. In this example, the connection will be closed automatically after 300 seconds of inactivity. To prevent a timeout, set this value to zero. Line 16: Sets the interface addresses. The values used depend upon whether a static IP address has been obtained from the ISP or if it instead negotiates a dynamic IP address during connection. If the ISP has allocated a static IP address and default gateway, replace x.x.x.x with the static IP address and replace y.y.y.y with the IP address of the default gateway. If the ISP has only provided a static IP address without a gateway address, replace y.y.y.y with 10.0.0.2/0. If the IP address changes whenever a connection is made, change this line to the following value. This tells &man.ppp.8; to use the IP Configuration Protocol (IPCP) to negotiate a dynamic IP address: set ifaddr 10.0.0.1/0 10.0.0.2/0 255.255.255.255 0.0.0.0 Line 17: Keep this line as-is as it adds a default route to the gateway. The HISADDR will automatically be replaced with the gateway address specified on line 16. It is important that this line appears after line 16. Depending upon whether &man.ppp.8; is started manually or automatically, a /etc/ppp/ppp.linkup may also need to be created which contains the following lines. This file is required when running ppp in mode. This file is used after the connection has been established. At this point, the IP address will have been assigned and it is now be possible to add the routing table entries. When creating this file, make sure that provider matches the value demonstrated in line 11 of ppp.conf. provider: add default HISADDR This file is also needed when the default gateway address is guessed in a static IP address configuration. In this case, remove line 17 from ppp.conf and create /etc/ppp/ppp.linkup with the above two lines. More examples for this file can be found in /usr/share/examples/ppp/. By default, the ppp command must be run as the root user. To change this default, add the account of the user who should run ppp to the network group in /etc/group. Then, give the user access to one or more entries in /etc/ppp/ppp.conf using the allow command. For example, to give fred and mary permission to only the provider: entry, add this line to the provider: section: allow users fred mary To give the specified users access to all entries, put that line in the default section instead. Receiving Incoming Calls PPP receiving incoming calls When configuring &man.ppp.8; to receive incoming calls on a machine connected to a Local Area Network (LAN), decide if packets should be forwarded to the LAN. If so, allocate the connecting system an IP address from the LAN's subnet, and add the enable proxy line to /etc/ppp/ppp.conf. Also, confirm that /etc/rc.conf contains the following line: gateway_enable="YES" Refer to &man.ppp.8; and /usr/share/examples/ppp/ppp.conf.sample for more details. The following steps will also be required: Create an entry in /etc/passwd (using the &man.vipw.8; program). Create a profile in this users home directory that runs ppp -direct direct-server or similar. Create an entry in /etc/ppp/ppp.conf. The direct-server example should suffice. Create an entry in /etc/ppp/ppp.linkup. <acronym>PPP</acronym> Shells for Dynamic <acronym>IP</acronym> Users PPP shells Create a file called /etc/ppp/ppp-shell containing the following: #!/bin/sh IDENT=`echo $0 | sed -e 's/^.*-\(.*\)$/\1/'` CALLEDAS="$IDENT" TTY=`tty` if [ x$IDENT = xdialup ]; then IDENT=`basename $TTY` fi echo "PPP for $CALLEDAS on $TTY" echo "Starting PPP for $IDENT" exec /usr/sbin/ppp -direct $IDENT This script should be executable. Now make a symbolic link called ppp-dialup to this script using the following commands: &prompt.root; ln -s ppp-shell /etc/ppp/ppp-dialup Use this script as the shell for all of dial-up users. This is an example from /etc/passwd for a dial-up PPP: pchilds:*:1011:300:Peter Childs PPP:/home/ppp:/etc/ppp/ppp-dialup Create a /home/ppp directory that is world readable containing the following 0 byte files: -r--r--r-- 1 root wheel 0 May 27 02:23 .hushlogin -r--r--r-- 1 root wheel 0 May 27 02:22 .rhosts which prevents /etc/motd from being displayed. <acronym>PPP</acronym> Shells for Static <acronym>IP</acronym> Users PPP shells Create the ppp-shell file as above, and for each account with statically assigned IPs create a symbolic link to ppp-shell. For example, to route /24 CIDR networks for the dial-up customers fred, sam, and mary, type: &prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-fred &prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-sam &prompt.root; ln -s /etc/ppp/ppp-shell /etc/ppp/ppp-mary Each of these users dial-up accounts should have their shell set to the symbolic link created above (for example, mary's shell should be /etc/ppp/ppp-mary). Setting Up <filename>ppp.conf</filename> for Dynamic <acronym>IP</acronym> Users The /etc/ppp/ppp.conf file should contain something along the lines of: default: set debug phase lcp chat set timeout 0 ttyu0: set ifaddr 203.14.100.1 203.14.100.20 255.255.255.255 enable proxy ttyu1: set ifaddr 203.14.100.1 203.14.100.21 255.255.255.255 enable proxy The indenting is important. The default: section is loaded for each session. For each dial-up line enabled in /etc/ttys create an entry similar to the one for ttyu0: above. Each line should get a unique IP address from the pool of IP addresses for dynamic users. Setting Up <filename>ppp.conf</filename> for Static <acronym>IP</acronym> Users Along with the contents of the sample /usr/share/examples/ppp/ppp.conf above, add a section for each of the statically assigned dial-up users:. fred: set ifaddr 203.14.100.1 203.14.101.1 255.255.255.255 sam: set ifaddr 203.14.100.1 203.14.102.1 255.255.255.255 mary: set ifaddr 203.14.100.1 203.14.103.1 255.255.255.255 The file /etc/ppp/ppp.linkup should also contain routing information for each static IP user if required. The line below would add a route for the 203.14.101.0/24 network via the client's ppp link. fred: add 203.14.101.0 netmask 255.255.255.0 HISADDR sam: add 203.14.102.0 netmask 255.255.255.0 HISADDR mary: add 203.14.103.0 netmask 255.255.255.0 HISADDR ?> Advanced Configuration DNS NetBIOS PPP Microsoft extensions It is possible to configure PPP to supply DNS and NetBIOS nameserver addresses on demand. To enable these extensions with PPP version 1.x, the following lines might be added to the relevant section of /etc/ppp/ppp.conf. enable msext set ns 203.14.100.1 203.14.100.2 set nbns 203.14.100.5 And for PPP version 2 and above: accept dns set dns 203.14.100.1 203.14.100.2 set nbns 203.14.100.5 This will tell the clients the primary and secondary name server addresses, and a NetBIOS nameserver host. In version 2 and above, if the set dns line is omitted, PPP will use the values found in /etc/resolv.conf. PAP and CHAP Authentication PAP CHAP Some ISPs set their system up so that the authentication part of the connection is done using either of the PAP or CHAP authentication mechanisms. If this is the case, the ISP will not give a login: prompt at connection, but will start talking PPP immediately. PAP is less secure than CHAP, but security is not normally an issue here as passwords, although being sent as plain text with PAP, are being transmitted down a serial line only. There is not much room for crackers to eavesdrop. The following alterations must be made: 13 set authname MyUserName 14 set authkey MyPassword 15 set login Line 13: This line specifies the PAP/CHAP user name. Insert the correct value for MyUserName. Line 14: This line specifies the PAP/CHAP passwordpassword. Insert the correct value for MyPassword. You may want to add an additional line, such as: 16 accept PAP or 16 accept CHAP to make it obvious that this is the intention, but PAP and CHAP are both accepted by default. Line 15: The ISP will not normally require a login to the server when using PAP or CHAP. Therefore, disable the set login string. Using <acronym>PPP</acronym> Network Address Translation Capability PPPNAT PPP has ability to use internal NAT without kernel diverting capabilities. This functionality may be enabled by the following line in /etc/ppp/ppp.conf: nat enable yes Alternatively, NAT may be enabled by command-line - option -nat. There is also + option -nat. There is also /etc/rc.conf knob named ppp_nat, which is enabled by default. When using this feature, it may be useful to include the following /etc/ppp/ppp.conf options to enable incoming connections forwarding: nat port tcp 10.0.0.2:ftp ftp nat port tcp 10.0.0.2:http http or do not trust the outside at all nat deny_incoming yes Final System Configuration PPPconfiguration While ppp is now configured, some edits still need to be made to /etc/rc.conf. Working from the top down in this file, make sure the hostname= line is set: hostname="foo.example.com" If the ISP has supplied a static IP address and name, use this name as the host name. Look for the network_interfaces variable. To configure the system to dial the ISP on demand, make sure the tun0 device is added to the list, otherwise remove it. network_interfaces="lo0 tun0" ifconfig_tun0= The ifconfig_tun0 variable should be empty, and a file called /etc/start_if.tun0 should be created. This file should contain the line: ppp -auto mysystem This script is executed at network configuration time, starting the ppp daemon in automatic mode. If this machine acts as a gateway, consider including . Refer to the manual page for further details. Make sure that the router program is set to NO with the following line in /etc/rc.conf: router_enable="NO" routed It is important that the routed daemon is not started, as routed tends to delete the default routing table entries created by ppp. It is probably a good idea to ensure that the sendmail_flags line does not include the option, otherwise sendmail will attempt to do a network lookup every now and then, possibly causing your machine to dial out. You may try: sendmail_flags="-bd" sendmail The downside is that sendmail is forced to re-examine the mail queue whenever the ppp link. To automate this, include !bg in ppp.linkup: 1 provider: 2 delete ALL 3 add 0 0 HISADDR 4 !bg sendmail -bd -q30m SMTP An alternative is to set up a dfilter to block SMTP traffic. Refer to the sample files for further details. Using <command>ppp</command> All that is left is to reboot the machine. After rebooting, either type: &prompt.root; ppp and then dial provider to start the PPP session, or, to configure ppp to establish sessions automatically when there is outbound traffic and start_if.tun0 does not exist, type: &prompt.root; ppp -auto provider It is possible to talk to the ppp program while it is running in the background, but only if a suitable diagnostic port has been set up. To do this, add the following line to the configuration: set server /var/run/ppp-tun%d DiagnosticPassword 0177 This will tell PPP to listen to the specified &unix; domain socket, asking clients for the specified password before allowing access. The %d in the name is replaced with the tun device number that is in use. Once a socket has been set up, the &man.pppctl.8; program may be used in scripts that wish to manipulate the running program. Configuring Dial-in Services mgetty AutoPPP LCP provides a good description on enabling dial-up services using &man.getty.8;. An alternative to getty is comms/mgetty+sendfax port), a smarter version of getty designed with dial-up lines in mind. The advantages of using mgetty is that it actively talks to modems, meaning if port is turned off in /etc/ttys then the modem will not answer the phone. Later versions of mgetty (from 0.99beta onwards) also support the automatic detection of PPP streams, allowing clients scriptless access to the server. Refer to http://mgetty.greenie.net/doc/mgetty_toc.html for more information on mgetty. By default the comms/mgetty+sendfax port comes with the AUTO_PPP option enabled allowing mgetty to detect the LCP phase of PPP connections and automatically spawn off a ppp shell. However, since the default login/password sequence does not occur it is necessary to authenticate users using either PAP or CHAP. This section assumes the user has successfully compiled, and installed the comms/mgetty+sendfax port on his system. Ensure that /usr/local/etc/mgetty+sendfax/login.config has the following: /AutoPPP/ - - /etc/ppp/ppp-pap-dialup This tells mgetty to run ppp-pap-dialup for detected PPP connections. Create an executable file called /etc/ppp/ppp-pap-dialup containing the following: #!/bin/sh exec /usr/sbin/ppp -direct pap$IDENT For each dial-up line enabled in /etc/ttys, create a corresponding entry in /etc/ppp/ppp.conf. This will happily co-exist with the definitions we created above. pap: enable pap set ifaddr 203.14.100.1 203.14.100.20-203.14.100.40 enable proxy Each user logging in with this method will need to have a username/password in /etc/ppp/ppp.secret file, or alternatively add the following option to authenticate users via PAP from the /etc/passwd file. enable passwdauth To assign some users a static IP number, specify the number as the third argument in /etc/ppp/ppp.secret. See /usr/share/examples/ppp/ppp.secret.sample for examples. Troubleshooting <acronym>PPP</acronym> Connections PPP troubleshooting This section covers a few issues which may arise when using PPP over a modem connection. Some ISPs present the ssword prompt while others present password. If the ppp script is not written accordingly, the login attempt will fail. The most common way to debug ppp connections is by connecting manually as described in this section. Check the Device Nodes When using a custom kernel, make sure to include the following line in the kernel configuration file: device uart The uart device is already included in the GENERIC kernel, so no additional steps are necessary in this case. Just check the dmesg output for the modem device with: &prompt.root; dmesg | grep uart This should display some pertinent output about the uart devices. These are the COM ports we need. If the modem acts like a standard serial port, it should be listed on uart1, or COM2. If so, a kernel rebuild is not required. When matching up, if the modem is on uart1, the modem device would be /dev/cuau1. Connecting Manually Connecting to the Internet by manually controlling ppp is quick, easy, and a great way to debug a connection or just get information on how the ISP treats ppp client connections. Lets start PPP from the command line. Note that in all of our examples we will use example as the hostname of the machine running PPP. To start ppp: &prompt.root; ppp ppp ON example> set device /dev/cuau1 This second command sets the modem device to cuau1. ppp ON example> set speed 115200 This sets the connection speed to 115,200 kbps. ppp ON example> enable dns This tells ppp to configure the resolver and add the nameserver lines to /etc/resolv.conf. If ppp cannot determine the hostname, it can manually be set later. ppp ON example> term This switches to terminal mode in order to manually control the modem. deflink: Entering terminal mode on /dev/cuau1 type '~h' for help at OK atdt123456789 Use at to initialize the modem, then use atdt and the number for the ISP to begin the dial in process. CONNECT Confirmation of the connection, if we are going to have any connection problems, unrelated to hardware, here is where we will attempt to resolve them. ISP Login:myusername At this prompt, return the prompt with the username that was provided by the ISP. ISP Pass:mypassword At this prompt, reply with the password that was provided by the ISP. Just like logging into &os;, the password will not echo. Shell or PPP:ppp Depending on the ISP, this prompt might not appear. If it does, it is asking whether to use a shell on the provider or to start ppp. In this example, ppp was selected in order to establish an Internet connection. Ppp ON example> Notice that in this example the first has been capitalized. This shows that we have successfully connected to the ISP. PPp ON example> We have successfully authenticated with our ISP and are waiting for the assigned IP address. PPP ON example> We have made an agreement on an IP address and successfully completed our connection. PPP ON example>add default HISADDR Here we add our default route, we need to do this before we can talk to the outside world as currently the only established connection is with the peer. If this fails due to existing routes, put a bang character ! in front of the . Alternatively, set this before making the actual connection and it will negotiate a new route accordingly. If everything went good we should now have an active connection to the Internet, which could be thrown into the background using CTRL z If PPP returns to ppp then the connection has bee lost. This is good to know because it shows the connection status. Capital P's represent a connection to the ISP and lowercase p's show that the connection has been lost. Debugging If a connection cannot be established, turn hardware flow CTS/RTS to off using . This is mainly the case when connected to some PPP-capable terminal servers, where PPP hangs when it tries to write data to the communication link, and waits for a Clear To Send (CTS) signal which may never come. When using this option, include as it may be required to defeat hardware dependent on passing certain characters from end to end, most of the time XON/XOFF. Refer to &man.ppp.8; for more information on this option and how it is used. An older modem may need . Parity is set at none be default, but is used for error checkingm with a large increase in traffic, on older modems. PPP may not return to the command mode, which is usually a negotiation error where the ISP is waiting for negotiating to begin. At this point, using ~p will force ppp to start sending the configuration information. If a login prompt never appears, PAP or CHAP authentication is most likely required. To use PAP or CHAP, add the following options to PPP before going into terminal mode: ppp ON example> set authname myusername Where myusername should be replaced with the username that was assigned by the ISP. ppp ON example> set authkey mypassword Where mypassword should be replaced with the password that was assigned by the ISP. If a connection is established, but cannot seem to find any domain name, try to &man.ping.8; an IP address. If there is 100 percent (100%) packet loss, it is likely that a default route was not assigned. Double check that was set during the connection. If a connection can be made to a remote IP address, it is possible that a resolver address has not been added to /etc/resolv.conf. This file should look like: domain example.com nameserver x.x.x.x nameserver y.y.y.y Where x.x.x.x and y.y.y.y should be replaced with the IP address of the ISP's DNS servers. To configure &man.syslog.3; to provide logging for the PPP connection, make sure this line exists in /etc/syslog.conf: !ppp *.* /var/log/ppp.log Using <acronym>PPP</acronym> over Ethernet (PPPoE) PPP over Ethernet This section describes how to set up PPP over Ethernet (PPPoE). Here is an example of a working ppp.conf: default: set log Phase tun command # you can add more detailed logging if you wish set ifaddr 10.0.0.1/0 10.0.0.2/0 name_of_service_provider: set device PPPoE:xl1 # replace xl1 with your Ethernet device set authname YOURLOGINNAME set authkey YOURPASSWORD set dial set login add default HISADDR As root, run: &prompt.root; ppp -ddial name_of_service_provider Add the following to /etc/rc.conf: ppp_enable="YES" ppp_mode="ddial" ppp_nat="YES" # if you want to enable nat for your local network, otherwise NO ppp_profile="name_of_service_provider" Using a PPPoE Service Tag Sometimes it will be necessary to use a service tag to establish the connection. Service tags are used to distinguish between different PPPoE servers attached to a given network. Any required service tag information should be in the documentation provided by the ISP. As a last resort, one could try installing the net/rr-pppoe package or port. Bear in mind however, this may de-program your modem and render it useless, so think twice before doing it. Simply install the program shipped with the modem. Then, access the System menu from the program. The name of the profile should be listed there. It is usually ISP. The profile name (service tag) will be used in the PPPoE configuration entry in ppp.conf as the provider part of the set device command (see the &man.ppp.8; manual page for full details). It should look like this: set device PPPoE:xl1:ISP Do not forget to change xl1 to the proper device for the Ethernet card. Do not forget to change ISP to the profile. For additional information, refer to Cheaper Broadband with &os; on DSL by Renaud Waldura. PPPoE with a &tm.3com; <trademark class="registered">HomeConnect</trademark> ADSL Modem Dual Link This modem does not follow the PPPoE specification defined in RFC 2516. In order to make &os; capable of communicating with this device, a sysctl must be set. This can be done automatically at boot time by updating /etc/sysctl.conf: net.graph.nonstandard_pppoe=1 or can be done immediately with the command: &prompt.root; sysctl net.graph.nonstandard_pppoe=1 Unfortunately, because this is a system-wide setting, it is not possible to talk to a normal PPPoE client or server and a &tm.3com; HomeConnect ADSL Modem at the same time. Using <application>PPP</application> over <acronym>ATM</acronym> (PPPoA) PPP over ATM PPPoA The following describes how to set up PPP over ATM (PPPoA). PPPoA is a popular choice among European DSL providers. Using mpd The mpd application can be used to connect to a variety of services, in particular PPTP services. It can be installed using the net/mpd5 package or port. Many ADSL modems require that a PPTP tunnel is created between the modem and computer. Once installed, configure mpd to suit the provider's settings. The port places a set of sample configuration files which are well documented in /usr/local/etc/mpd/. A complete guide to configure mpd is available in HTML format in /usr/ports/share/doc/mpd/. Here is a sample configuration for connecting to an ADSL - service with mpd. The configuration - is spread over two files, first the + service with mpd. The + configuration is spread over two files, first the mpd.conf: This example of the mpd.conf file only works with mpd 4.x. default: load adsl adsl: new -i ng0 adsl adsl set bundle authname username set bundle password password set bundle disable multilink set link no pap acfcomp protocomp set link disable chap set link accept chap set link keep-alive 30 10 set ipcp no vjcomp set ipcp ranges 0.0.0.0/0 0.0.0.0/0 set iface route default set iface disable on-demand set iface enable proxy-arp set iface idle 0 open The username used to authenticate with your ISP. The password used to authenticate with your ISP. The mpd.links file contains information about the link, or links, to establish. An example mpd.links to accompany the above example is given beneath: adsl: set link type pptp set pptp mode active set pptp enable originate outcall set pptp self 10.0.0.1 set pptp peer 10.0.0.138 The IP address of &os; computer running mpd. The IP address of the ADSL modem. The Alcatel &speedtouch; Home defaults to 10.0.0.138. It is possible to initialize the connection easily by issuing the following command as root: &prompt.root; mpd -b adsl To view the status of the connection: &prompt.user; ifconfig ng0 ng0: flags=88d1<UP,POINTOPOINT,RUNNING,NOARP,SIMPLEX,MULTICAST> mtu 1500 inet 216.136.204.117 --> 204.152.186.171 netmask 0xffffffff Using mpd is the recommended way to connect to an ADSL service with &os;. Using pptpclient It is also possible to use &os; to connect to other PPPoA services using net/pptpclient. To use net/pptpclient to connect to a DSL service, install the port or package, then edit /etc/ppp/ppp.conf. An example section of ppp.conf is given below. For further information on ppp.conf options consult &man.ppp.8;. adsl: set log phase chat lcp ipcp ccp tun command set timeout 0 enable dns set authname username set authkey password set ifaddr 0 0 add default HISADDR The username for the DSL provider. The password for your account. Since the account's password is added to ppp.confin plain text form, make sure nobody can read the contents of this file: &prompt.root; chown root:wheel /etc/ppp/ppp.conf &prompt.root; chmod 600 /etc/ppp/ppp.conf This will open a tunnel for a PPP session to the DSL router. Ethernet DSL modems have a preconfigured LAN IP address to connect to. In the case of the Alcatel &speedtouch; Home, this address is - 10.0.0.138. The + 10.0.0.138. The router's documentation should list the address the device uses. To open the tunnel and start a PPP session: &prompt.root; pptp address adsl If an ampersand (&) is added to the end of this command, pptp will return the prompt. A tun virtual tunnel device will be created for interaction between the pptp and ppp processes. Once the prompt is returned, or the pptp process has confirmed a connection, examine the tunnel: &prompt.user; ifconfig tun0 tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500 inet 216.136.204.21 --> 204.152.186.171 netmask 0xffffff00 Opened by PID 918 If the connection fails, check the configuration of the router, which is usually accessible using a web browser. Also, examine the output of pptp and the contents of the log file, /var/log/ppp.log for clues. Index: head/en_US.ISO8859-1/books/handbook/x11/chapter.xml =================================================================== --- head/en_US.ISO8859-1/books/handbook/x11/chapter.xml (revision 46057) +++ head/en_US.ISO8859-1/books/handbook/x11/chapter.xml (revision 46058) @@ -1,1524 +1,1524 @@ The X Window System Synopsis An installation of &os; using bsdinstall does not automatically install a graphical user interface. This chapter describes how to install and configure &xorg;, which provides the open source X Window System used to provide a graphical environment. It then describes how to find and install a desktop environment or window manager. Users who prefer an installation method that automatically configures the &xorg; and offers a choice of window managers during installation should refer to the pcbsd.org website. For more information on the video hardware that &xorg; supports, refer to the x.org website. After reading this chapter, you will know: The various components of the X Window System, and how they interoperate. How to install and configure &xorg;. How to install and configure several window managers and desktop environments. How to use &truetype; fonts in &xorg;. How to set up your system for graphical logins (XDM). Before reading this chapter, you should: Know how to install additional third-party software as described in . Terminology While it is not necessary to understand all of the details of the various components in the X Window System and how they interact, some basic knowledge of these components can be useful: X server X was designed from the beginning to be network-centric, and adopts a client-server model. In this model, the X server runs on the computer that has the keyboard, monitor, and mouse attached. The server's responsibility includes tasks such as managing the display, handling input from the keyboard and mouse, and handling input or output from other devices such as a tablet or a video projector. This confuses some people, because the X terminology is exactly backward to what they expect. They expect the X server to be the big powerful machine down the hall, and the X client to be the machine on their desk. X client Each X application, such as XTerm or Firefox, is a client. A client sends messages to the server such as Please draw a window at these coordinates, and the server sends back messages such as The user just clicked on the OK button. In a home or small office environment, the X server and the X clients commonly run on the same computer. It is also possible to run the X server on a less powerful computer and to run the X applications on a more powerful system. In this scenario, the communication between the X client and server takes place over the network. window manager X does not dictate what windows should look like on screen, how to move them around with the mouse, which keystrokes should be used to move between windows, what the title bars on each window should look like, whether or not they have close buttons on them, and so on. Instead, X delegates this responsibility to a separate window manager application. There are dozens of window managers available. Each window manager provides a different look and feel: some support virtual desktops, some allow customized keystrokes to manage the desktop, some have a Start button, and some are themeable, allowing a complete change of the desktop's look-and-feel. Window managers are available in the x11-wm category of the Ports Collection. Each window manager uses a different configuration mechanism. Some expect configuration file written by hand while others provide graphical tools for most configuration tasks. desktop environment KDE and GNOME are considered to be desktop environments as they include an entire suite of applications for performing common desktop tasks. These may include office suites, web browsers, and games. focus policy The window manager is responsible for the mouse focus policy. This policy provides some means for choosing which window is actively receiving keystrokes and it should also visibly indicate which window is currently active. One focus policy is called click-to-focus. In this model, a window becomes active upon receiving a mouse click. In the focus-follows-mouse policy, the window that is under the mouse pointer has focus and the focus is changed by pointing at another window. If the mouse is over the root window, then this window is focused. In the sloppy-focus model, if the mouse is moved over the root window, the most recently used window still has the focus. With sloppy-focus, focus is only changed when the cursor enters a new window, and not when exiting the current window. In the click-to-focus policy, the active window is selected by mouse click. The window may then be raised and appear in front of all other windows. All keystrokes will now be directed to this window, even if the cursor is moved to another window. Different window managers support different focus models. All of them support click-to-focus, and the majority of them also support other policies. Consult the documentation for the window manager to determine which focus models are available. widgets Widget is a term for all of the items in the user interface that can be clicked or manipulated in some way. This includes buttons, check boxes, radio buttons, icons, and lists. A widget toolkit is a set of widgets used to create graphical applications. There are several popular widget toolkits, including Qt, used by KDE, and GTK+, used by GNOME. As a result, applications will have a different look and feel, depending upon which widget toolkit was used to create the application. Installing <application>&xorg;</application> &xorg; is the implementation of the open source X Window System released by the X.Org Foundation. In &os;, it can be installed as a package or port. The meta-port for the complete distribution which includes X servers, clients, libraries, and fonts is located in x11/xorg. A minimal distribution is located in x11/xorg-minimal, with separate ports available for docs, libraries, and apps. The examples in this section install the complete &xorg; distribution. To build and install &xorg; from the Ports Collection: &prompt.root; cd /usr/ports/x11/xorg &prompt.root; make install clean To build &xorg; in its entirety, be sure to have at least 4 GB of free disk space available. Alternatively, &xorg; can be installed directly from packages with this command: &prompt.root; pkg install xorg Quick Start In most cases, &xorg; is self-configuring. When started without any configuration file, the video card and input devices are automatically detected and used. Autoconfiguration is the preferred method, and should be tried first. Check if HAL is used by the X server: &prompt.user; pkg info xorg-server | grep HAL If the output shows HAL is off, skip to the next step. If HAL is on, enable needed services by adding two entries to /etc/rc.conf. Then start the services: hald_enable="YES" dbus_enable="YES" &prompt.root; service hald start ; service dbus start Rename or delete old versions of xorg.conf: &prompt.root; mv /etc/X11/xorg.conf ~/xorg.conf.etc &prompt.root; mv /usr/local/etc/X11/xorg.conf ~/xorg.conf.localetc Start the X system: &prompt.user; startx Test the system by moving the mouse and typing text into the windows. If both mouse and keyboard work as expected, see and . If the mouse or keyboard do not work, continue with . <application>&xorg;</application> Configuration &xorg; &xorg; Those with older or unusual equipment may find it helpful to gather some hardware information before beginning configuration. Monitor sync frequencies Video card chipset Video card memory horizontal sync frequency horizontal scan rate horizontal sync frequency refresh rate vertical sync frequency refresh rate vertical scan rate refresh rate Screen resolution and refresh rate are determined by the monitor's horizontal and vertical sync frequencies. Almost all monitors support electronic autodetection of these values. A few monitors do not provide these values, and the specifications must be determined from the printed manual or manufacturer web site. The video card chipset is also autodetected, and used to select the proper video driver. It is beneficial for the user to be aware of which chipset is installed for when autodetection does not provide the desired result. Video card memory determines the maximum resolution and color depth which can be displayed. Caveats The ability to configure optimal resolution is dependent upon the video hardware and the support provided by its driver. At this time, driver support includes: Intel: as of &os; 9.3 and &os; 10.1, 3D acceleration on most Intel graphics, including IronLake, SandyBridge, and IvyBridge, is supported. Support for switching between X and virtual consoles is provided by &man.vt.4;. ATI/Radeon: 2D and 3D acceleration is supported on most Radeon cards up to the HD6000 series. NVIDIA: several NVIDIA drivers are available in the x11 category of the Ports Collection. Install the driver that matches the video card. Optimus: currently there is no switching support between the two graphics adapters provided by Optimus. Optimus implementations vary, and &os; will not be able to drive all versions of the hardware. Some computers provide a BIOS option to disable one of the graphics adapters or select a discrete mode. Configuring <application>&xorg;</application> By default, &xorg; uses HAL to autodetect keyboards and mice. The sysutils/hal and devel/dbus ports are automatically installed as dependencies of x11/xorg, but must be enabled by adding these entries to /etc/rc.conf: hald_enable="YES" dbus_enable="YES" Start these services before configuring &xorg;: &prompt.root; service hald start &prompt.root; service dbus start Once the services have been started, check whether &xorg; auto-configures itself by typing: &prompt.root; Xorg -configure This will generate a file named /root/xorg.conf.new which attempts to load the proper drivers for the detected hardware. Next, test that the automatically generated configuration file works with the graphics hardware by typing: &prompt.root; Xorg -config xorg.conf.new -retro If a black and grey grid and an X mouse cursor appear, the configuration was successful. To exit the test, switch to the virtual console used to start it by pressing Ctrl Alt Fn (F1 for the first virtual console) and press Ctrl C . The Ctrl Alt Backspace key combination may also be used to break out of &xorg;. To enable it, you can either type the following command from any X terminal emulator: &prompt.user; setxkbmap -option terminate:ctrl_alt_bksp or create a keyboard configuration file for hald called x11-input.fdi and saved in the /usr/local/etc/hal/fdi/policy directory. This file should contain the following lines: <?xml version="1.0" encoding="iso-8859-1"?> <deviceinfo version="0.2"> <device> <match key="info.capabilities" contains="input.keyboard"> <merge key="input.x11_options.XkbOptions" type="string">terminate:ctrl_alt_bksp</merge> </match> </device> </deviceinfo> You will have to reboot your machine to force hald to read this file. The following line will also have to be added to xorg.conf.new, in the ServerLayout or ServerFlags section: Option "DontZap" "off" If the test is unsuccessful, skip ahead to . Once the test is successful, + linkend="x11-understanding"/>. Once the test is successful, copy the configuration file to /etc/X11/xorg.conf: &prompt.root; cp xorg.conf.new /etc/X11/xorg.conf Desktop environments like GNOME, KDE or Xfce provide graphical tools to set parameters such as video resolution. If the default configuration works, skip to for examples on how to install a desktop environment. Using Fonts in <application>&xorg;</application> Type1 Fonts The default fonts that ship with &xorg; are less than ideal for typical desktop publishing applications. Large presentation fonts show up jagged and unprofessional looking, and small fonts are almost completely unintelligible. However, there are several free, high quality Type1 (&postscript;) fonts available which can be readily used with &xorg;. For instance, the URW font collection (x11-fonts/urwfonts) includes high quality versions of standard type1 fonts (Times Roman, Helvetica, Palatino and others). The Freefonts collection (x11-fonts/freefonts) includes many more fonts, but most of them are intended for use in graphics software such as the Gimp, and are not complete enough to serve as screen fonts. In addition, &xorg; can be configured to use &truetype; fonts with a minimum of effort. For more details on this, see the &man.X.7; manual page or . To install the above Type1 font collections from the Ports Collection, run the following commands: &prompt.root; cd /usr/ports/x11-fonts/urwfonts &prompt.root; make install clean And likewise with the freefont or other collections. To have the X server detect these fonts, add an appropriate line to the X server configuration file (/etc/X11/xorg.conf), which reads: FontPath "/usr/local/lib/X11/fonts/URW/" Alternatively, at the command line in the X session run: &prompt.user; xset fp+ /usr/local/lib/X11/fonts/URW &prompt.user; xset fp rehash This will work but will be lost when the X session is closed, unless it is added to the startup file (~/.xinitrc for a normal startx session, or ~/.xsession when logging in through a graphical login manager like XDM). A third way is to use the new /usr/local/etc/fonts/local.conf as demonstrated in . &truetype; Fonts TrueType Fonts fonts TrueType &xorg; has built in support for rendering &truetype; fonts. There are two different modules that can enable this functionality. The freetype module is used in this example because it is more consistent with the other font rendering back-ends. To enable the freetype module just add the following line to the "Module" section of /etc/X11/xorg.conf. Load "freetype" Now make a directory for the &truetype; fonts (for example, /usr/local/lib/X11/fonts/TrueType) and copy all of the &truetype; fonts into this directory. Keep in mind that &truetype; fonts cannot be directly taken from an &apple; &mac;; they must be in &unix;/&ms-dos;/&windows; format for use by &xorg;. Once the files have been copied into this directory, use ttmkfdir to create a fonts.dir, so that the X font renderer knows that these new files have been installed. ttmkfdir is available from the FreeBSD Ports Collection as x11-fonts/ttmkfdir. &prompt.root; cd /usr/local/lib/X11/fonts/TrueType &prompt.root; ttmkfdir -o fonts.dir Now add the &truetype; directory to the font path. This is just the same as described in : &prompt.user; xset fp+ /usr/local/lib/X11/fonts/TrueType &prompt.user; xset fp rehash or add a FontPath line to xorg.conf. That's it. Now Gimp, Apache OpenOffice, and all of the other X applications should now recognize the installed &truetype; fonts. Extremely small fonts (as with text in a high resolution display on a web page) and extremely large fonts (within &staroffice;) will look much better now. Anti-Aliased Fonts anti-aliased fonts fonts anti-aliased All fonts in &xorg; that are found in /usr/local/lib/X11/fonts/ and ~/.fonts/ are automatically made available for anti-aliasing to Xft-aware applications. Most recent applications are Xft-aware, including KDE, GNOME, and Firefox. In order to control which fonts are anti-aliased, or to configure anti-aliasing properties, create (or edit, if it already exists) the file /usr/local/etc/fonts/local.conf. Several advanced features of the Xft font system can be tuned using this file; this section describes only some simple possibilities. For more details, please see &man.fonts-conf.5;. XML This file must be in XML format. Pay careful attention to case, and make sure all tags are properly closed. The file begins with the usual XML header followed by a DOCTYPE definition, and then the <fontconfig> tag: <?xml version="1.0"?> <!DOCTYPE fontconfig SYSTEM "fonts.dtd"> <fontconfig> As previously stated, all fonts in /usr/local/lib/X11/fonts/ as well as ~/.fonts/ are already made available to Xft-aware applications. If you wish to add another directory outside of these two directory trees, add a line similar to the following to /usr/local/etc/fonts/local.conf: <dir>/path/to/my/fonts</dir> After adding new fonts, and especially new font directories, you should run the following command to rebuild the font caches: &prompt.root; fc-cache -f Anti-aliasing makes borders slightly fuzzy, which makes very small text more readable and removes staircases from large text, but can cause eyestrain if applied to normal text. To exclude font sizes smaller than 14 point from anti-aliasing, include these lines: <match target="font"> <test name="size" compare="less"> <double>14</double> </test> <edit name="antialias" mode="assign"> <bool>false</bool> </edit> </match> <match target="font"> <test name="pixelsize" compare="less" qual="any"> <double>14</double> </test> <edit mode="assign" name="antialias"> <bool>false</bool> </edit> </match> fonts spacing Spacing for some monospaced fonts may also be inappropriate with anti-aliasing. This seems to be an issue with KDE, in particular. One possible fix for this is to force the spacing for such fonts to be 100. Add the following lines: <match target="pattern" name="family"> <test qual="any" name="family"> <string>fixed</string> </test> <edit name="family" mode="assign"> <string>mono</string> </edit> </match> <match target="pattern" name="family"> <test qual="any" name="family"> <string>console</string> </test> <edit name="family" mode="assign"> <string>mono</string> </edit> </match> (this aliases the other common names for fixed fonts as "mono"), and then add: <match target="pattern" name="family"> <test qual="any" name="family"> <string>mono</string> </test> <edit name="spacing" mode="assign"> <int>100</int> </edit> </match> Certain fonts, such as Helvetica, may have a problem when anti-aliased. Usually this manifests itself as a font that seems cut in half vertically. At worst, it may cause applications to crash. To avoid this, consider adding the following to local.conf: <match target="pattern" name="family"> <test qual="any" name="family"> <string>Helvetica</string> </test> <edit name="family" mode="assign"> <string>sans-serif</string> </edit> </match> Once you have finished editing local.conf make sure you end the file with the </fontconfig> tag. Not doing this will cause your changes to be ignored. Finally, users can add their own settings via their personal .fonts.conf files. To do this, each user should simply create a ~/.fonts.conf. This file must also be in XML format. LCD screen Fonts LCD screen One last point: with an LCD screen, sub-pixel sampling may be desired. This basically treats the (horizontally separated) red, green and blue components separately to improve the horizontal resolution; the results can be dramatic. To enable this, add the line somewhere in local.conf: <match target="font"> <test qual="all" name="rgba"> <const>unknown</const> </test> <edit name="rgba" mode="assign"> <const>rgb</const> </edit> </match> Depending on the sort of display, rgb may need to be changed to bgr, vrgb or vbgr: experiment and see which works best. The X Display Manager Seth Kingsley Contributed by X Display Manager &xorg; provides an X Display Manager, XDM, which can be used for login session management. XDM provides a graphical interface for choosing which display server to connect to and for entering authorization information such as a login and password combination. This section demonstrates how to configure the X Display Manager on &os;. Some desktop environments provide their own graphical login manager. Refer to for instructions on how to configure the GNOME Display Manager and for instructions on how to configure the KDE Display Manager. Configuring <application>XDM</application> To install XDM, use the x11/xdm package or port. Once installed, XDM can be configured to run when the machine boots up by editing this entry in /etc/ttys: ttyv8 "/usr/local/bin/xdm -nodaemon" xterm off secure Change the off to on and save the edit. The ttyv8 in this entry indicates that XDM will run on the ninth virtual terminal. The XDM configuration directory is located in /usr/local/lib/X11/xdm. This directory contains several files used to change the behavior and appearance of XDM, as well as a few scripts and programs used to set up the desktop when XDM is running. summarizes the function of each of these files. The exact syntax and usage of these files is described in &man.xdm.1;. XDM Configuration Files File Description Xaccess The protocol for connecting to XDM is called the X Display Manager Connection Protocol (XDMCP) This file is a client authorization ruleset for controlling XDMCP connections from remote machines. By default, this file does not allow any remote clients to connect. Xresources This file controls the look and feel of the XDM display chooser and login screens. The default configuration is a simple rectangular login window with the hostname of the machine displayed at the top in a large font and Login: and Password: prompts below. The format of this file is identical to the app-defaults file described in the &xorg; documentation. Xservers The list of local and remote displays the chooser should provide as login choices. Xsession Default session script for logins which is run by XDM after a user has logged in. Normally each user will have a customized session script in ~/.xsession that overrides this script Xsetup_* Script to automatically launch applications before displaying the chooser or login interfaces. There is a script for each display being used, named Xsetup_*, where * is the local display number. Typically these scripts run one or two programs in the background such as xconsole. xdm-config Global configuration for all displays running on this machine. xdm-errors Contains errors generated by the server program. If a display that XDM is trying to start hangs, look at this file for error messages. These messages are also written to the user's ~/.xsession-errors on a per-session basis. xdm-pid The running process ID of XDM.
Configuring Remote Access By default, only users on the same system can login using XDM. To enable users on other systems to connect to the display server, edit the access control rules and enable the connection listener. To configure XDM to listen for any remote connection, comment out the DisplayManager.requestPort line in /usr/local/lib/X11/xdm/xdm-config by putting a ! in front of it: ! SECURITY: do not listen for XDMCP or Chooser requests ! Comment out this line if you want to manage X terminals with xdm DisplayManager.requestPort: 0 Save the edits and restart XDM. To restrict remote access, look at the example entries in /usr/local/lib/X11/xdm/Xaccess and refer to &man.xdm.1; for further information.
Desktop Environments Valentino Vaschetto Contributed by This section describes how to install three popular desktop environments on a &os; system. A desktop environment can range from a simple window manager to a complete suite of desktop applications. Over a hundred desktop environments are available in the x11-wm category of the Ports Collection. GNOME GNOME GNOME is a user-friendly desktop environment. It includes a panel for starting applications and displaying status, a desktop, a set of tools and applications, and a set of conventions that make it easy for applications to cooperate and be consistent with each other. More information regarding GNOME on &os; can be found at http://www.FreeBSD.org/gnome. That web site contains additional documentation about installing, configuring, and managing GNOME on &os;. This desktop environment can be installed from a package: &prompt.root; pkg install gnome2 To instead build GNOME from ports, use the following command. GNOME is a large application and will take some time to compile, even on a fast computer. &prompt.root; cd /usr/ports/x11/gnome2 &prompt.root; make install clean For proper operation, GNOME requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup: proc /proc procfs rw 0 0 Once GNOME is installed, configure &xorg; to start GNOME. The easiest way to do this is to enable the GNOME Display Manager, GDM, which is installed as part of the GNOME package or port. It can be enabled by adding this line to /etc/rc.conf: gdm_enable="YES" It is often desirable to also start all GNOME services. To achieve this, add a second line to /etc/rc.conf: gnome_enable="YES" GDM will now start automatically when the system boots. A second method for starting GNOME is to type startx from the command-line after configuring ~/.xinitrc. If this file already exists, replace the line that starts the current window manager with one that starts /usr/local/bin/gnome-session. If this file does not exist, create it with this command: &prompt.user; echo "exec /usr/local/bin/gnome-session" > ~/.xinitrc A third method is to use XDM as the display manager. In this case, create an executable ~/.xsession: &prompt.user; echo "#!/bin/sh" > ~/.xsession &prompt.user; echo "exec /usr/local/bin/gnome-session" >> ~/.xsession &prompt.user; chmod +x ~/.xsession KDE KDE KDE is another easy-to-use desktop environment. This desktop provides a suite of applications with a consistent look and feel, a standardized menu and toolbars, keybindings, color-schemes, internationalization, and a centralized, dialog-driven desktop configuration. More information on KDE can be found at http://www.kde.org/. For &os;-specific information, consult http://freebsd.kde.org. To install the KDE package, type: &prompt.root; pkg install x11/kde4 To instead build the KDE port, use the following command. Installing the port will provide a menu for selecting which components to install. KDE is a large application and will take some time to compile, even on a fast computer. &prompt.root; cd /usr/ports/x11/kde4 &prompt.root; make install clean KDE display manager KDE requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup: proc /proc procfs rw 0 0 The installation of KDE includes the KDE Display Manager, KDM. To enable this display manager, add this line to /etc/rc.conf: kdm4_enable="YES" A second method for launching KDE is to type startx from the command line. For this to work, the following line is needed in ~/.xinitrc: exec /usr/local/kde4/bin/startkde A third method for starting KDE is through XDM. To do so, create an executable ~/.xsession as follows: &prompt.user; echo "#!/bin/sh" > ~/.xsession &prompt.user; echo "exec /usr/local/kde4/bin/startkde" >> ~/.xsession &prompt.user; chmod +x ~/.xsession Once KDE is started, refer to its built-in help system for more information on how to use its various menus and applications. Xfce Xfce is a desktop environment based on the GTK+ toolkit used by GNOME. However, it is more lightweight and provides a simple, efficient, easy-to-use desktop. It is fully configurable, has a main panel with menus, applets, and application launchers, provides a file manager and sound manager, and is themeable. Since it is fast, light, and efficient, it is ideal for older or slower machines with memory limitations. More information on Xfce can be found at http://www.xfce.org. To install the Xfce package: &prompt.root; pkg install xfce Alternatively, to build the port: &prompt.root; cd /usr/ports/x11-wm/xfce4 &prompt.root; make install clean Unlike GNOME or KDE, Xfce does not provide its own login manager. In order to start Xfce from the command line by typing startx, first add its entry to ~/.xinitrc: &prompt.user; echo "exec /usr/local/bin/startxfce4" > ~/.xinitrc An alternate method is to use XDM. To configure this method, create an executable ~/.xsession: &prompt.user; echo "#!/bin/sh" > ~/.xsession &prompt.user; echo "exec /usr/local/bin/startxfce4" >> ~/.xsession &prompt.user; chmod +x ~/.xsession Troubleshooting If the mouse does not work, you will need to first configure it before proceeding. See in the &os; install chapter. In recent Xorg versions, the InputDevice sections in xorg.conf are ignored in favor of the autodetected devices. To restore the old behavior, add the following line to the ServerLayout or ServerFlags section of this file: Option "AutoAddDevices" "false" Input devices may then be configured as in previous versions, along with any other options needed (e.g., keyboard layout switching). As previously explained the hald daemon will, by default, automatically detect your keyboard. There are chances that your keyboard layout or model will not be correct, desktop environments like GNOME, KDE or Xfce provide tools to configure the keyboard. However, it is possible to set the keyboard properties directly either with the help of the &man.setxkbmap.1; utility or with a hald's configuration rule. For example if, one wants to use a PC 102 keys keyboard coming with a french layout, we have to create a keyboard configuration file for hald called x11-input.fdi and saved in the /usr/local/etc/hal/fdi/policy directory. This file should contain the following lines: <?xml version="1.0" encoding="iso-8859-1"?> <deviceinfo version="0.2"> <device> <match key="info.capabilities" contains="input.keyboard"> <merge key="input.x11_options.XkbModel" type="string">pc102</merge> <merge key="input.x11_options.XkbLayout" type="string">fr</merge> </match> </device> </deviceinfo> If this file already exists, just copy and add to your file the lines regarding the keyboard configuration. You will have to reboot your machine to force hald to read this file. It is possible to do the same configuration from an X terminal or a script with this command line: &prompt.user; setxkbmap -model pc102 -layout fr The /usr/local/share/X11/xkb/rules/base.lst file lists the various keyboard, layouts and options available. &xorg; tuning The xorg.conf.new configuration file may now be tuned to taste. Open the file in a text editor such as &man.emacs.1; or &man.ee.1;. If the monitor is an older or unusual model that does not support autodetection of sync frequencies, those settings can be added to xorg.conf.new under the "Monitor" section: Section "Monitor" Identifier "Monitor0" VendorName "Monitor Vendor" ModelName "Monitor Model" HorizSync 30-107 VertRefresh 48-120 EndSection Most monitors support sync frequency autodetection, making manual entry of these values unnecessary. For the few monitors that do not support autodetection, avoid potential damage by only entering values provided by the manufacturer. X allows DPMS (Energy Star) features to be used with capable monitors. The &man.xset.1; program controls the time-outs and can force standby, suspend, or off modes. If you wish to enable DPMS features for your monitor, you must add the following line to the monitor section: Option "DPMS" xorg.conf While the xorg.conf.new configuration file is still open in an editor, select the default resolution and color depth desired. This is defined in the "Screen" section: Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" DefaultDepth 24 SubSection "Display" Viewport 0 0 Depth 24 Modes "1024x768" EndSubSection EndSection The DefaultDepth keyword describes the color depth to run at by default. This can be overridden with the command line switch to &man.Xorg.1;. The Modes keyword describes the resolution to run at for the given color depth. Note that only VESA standard modes are supported as defined by the target system's graphics hardware. In the example above, the default color depth is twenty-four bits per pixel. At this color depth, the accepted resolution is 1024 by 768 pixels. Finally, write the configuration file and test it using the test mode given above. One of the tools available to assist you during troubleshooting process are the &xorg; log files, which contain information on each device that the &xorg; server attaches to. &xorg; log file names are in the format of /var/log/Xorg.0.log. The exact name of the log can vary from Xorg.0.log to Xorg.8.log and so forth. If all is well, the configuration file needs to be installed in a common location where &man.Xorg.1; can find it. This is typically /etc/X11/xorg.conf or /usr/local/etc/X11/xorg.conf. &prompt.root; cp xorg.conf.new /etc/X11/xorg.conf The &xorg; configuration process is now complete. &xorg; may be now started with the &man.startx.1; utility. The &xorg; server may also be started with the use of &man.xdm.1;. Configuration with &intel; <literal>i810</literal> Graphics Chipsets Intel i810 graphic chipset Configuration with &intel; i810 integrated chipsets requires the agpgart AGP programming interface for &xorg; to drive the card. See the &man.agp.4; driver manual page for more information. This will allow configuration of the hardware as any other graphics board. Note on systems without the &man.agp.4; driver compiled in the kernel, trying to load the module with &man.kldload.8; will not work. This driver has to be in the kernel at boot time through being compiled in or using /boot/loader.conf. Adding a Widescreen Flatpanel to the Mix widescreen flatpanel configuration This section assumes a bit of advanced configuration knowledge. If attempts to use the standard configuration tools above have not resulted in a working configuration, there is information enough in the log files to be of use in getting the setup working. Use of a text editor will be necessary. Current widescreen (WSXGA, WSXGA+, WUXGA, WXGA, WXGA+, et.al.) formats support 16:10 and 10:9 formats or aspect ratios that can be problematic. Examples of some common screen resolutions for 16:10 aspect ratios are: 2560x1600 1920x1200 1680x1050 1440x900 1280x800 At some point, it will be as easy as adding one of these resolutions as a possible Mode in the Section "Screen" as such: Section "Screen" Identifier "Screen0" Device "Card0" Monitor "Monitor0" DefaultDepth 24 SubSection "Display" Viewport 0 0 Depth 24 Modes "1680x1050" EndSubSection EndSection &xorg; is smart enough to pull the resolution information from the widescreen via I2C/DDC information so it knows what the monitor can handle as far as frequencies and resolutions. If those ModeLines do not exist in the drivers, one might need to give &xorg; a little hint. Using /var/log/Xorg.0.log one can extract enough information to manually create a ModeLine that will work. Simply look for information resembling this: (II) MGA(0): Supported additional Video Mode: (II) MGA(0): clock: 146.2 MHz Image Size: 433 x 271 mm (II) MGA(0): h_active: 1680 h_sync: 1784 h_sync_end 1960 h_blank_end 2240 h_border: 0 (II) MGA(0): v_active: 1050 v_sync: 1053 v_sync_end 1059 v_blanking: 1089 v_border: 0 (II) MGA(0): Ranges: V min: 48 V max: 85 Hz, H min: 30 H max: 94 kHz, PixClock max 170 MHz This information is called EDID information. Creating a ModeLine from this is just a matter of putting the numbers in the correct order: ModeLine <name> <clock> <4 horiz. timings> <4 vert. timings> So that the ModeLine in Section "Monitor" for this example would look like this: Section "Monitor" Identifier "Monitor1" VendorName "Bigname" ModelName "BestModel" ModeLine "1680x1050" 146.2 1680 1784 1960 2240 1050 1053 1059 1089 Option "DPMS" EndSection Now having completed these simple editing steps, X should start on your new widescreen monitor.