User:Intelminer/Drafts/Home Router

From Gentoo Wiki
Jump to:navigation Jump to:search

I didn't want to flood the Home Router page with edits and revisions so this is my draft copy to hack on :)

This document details how to turn an old Gentoo machine into a router or gateway for connecting a home network to the Internet.


Building a personal router out of old spare parts has many advantages over buying a pre-made router built by big companies (Linksys, D-Link, Netgear, etc). The biggest advantage by far is control over the connection. The other advantages can be left up to the user's imagination; just about anything can be done in this scenario, it is simply a matter of need.

This guide will provide instructions on how to setup Network Address Translation (NAT) on a custom router (kernel and iptables), add and configure common services (Domain Name System (DNS) via net-dns/bind and DHCP via net-misc/dhcp), and offer some more advanced features for a rainy day (Port Fowarding/UPnP, WireGuard etc).

Before getting started, review the list of basic requirements:

  1. A computer that has at least 2 Network Interface Cards (NICs) installed.
  2. The configuration settings for an Internet connection (may include things like IP/DNS/Gateway/username/password).
  3. (Optionally) a Wi-Fi card that supports master mode. Master mode is recommended to avoid NICs with a bypass feature since some NICs require proprietary drivers. Without access to the proprietary driver the card will remain in bypass mode permanently and will not be usable. (be warned that as of 2021 it is difficult to obtain modern Wi-Fi cards that fill this requirement. Atheros devices are currently the best supported in Linux for this task, but may not support newer standards like Wi-Fi 6)
  4. Some spare time, trial and error and a love of Gentoo and projects to tinker with on a rainy day :)

The basic conventions used in this guide include:

  • eth0 - NIC connected to the Local Area Network (LAN)
  • eth1 - NIC connected to the Wide Area Network (WAN)
  • LAN utilizes the private 10.1.1.X network
  • Router is hardcoded to the standard IP address
Due to the way systemd handles interface names, your ifaces WILL look different (unless you disable predictable interface names or use OpenRC). Remember to check your configuration before hitting save!

Kernel setup (lay the groundwork)

The kernel needs to have the drivers installed for both NICs present on the system. To see if the cards are already setup use the ip link command. The output may differ slightly from the following example. What matters is that the interfaces exist.

root #ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:60:F5:07:07:B8 brd ff:ff:ff:ff:ff:ff
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT group default qlen 1000
    link/ether 00:60:F5:07:07:B9 brd ff:ff:ff:ff:ff:ff

If only one (or none) of the two cards show up try running lspci | grep Ethernet.

The lspci utility is part of the sys-apps/pciutils package and can be installed by running emerge sys-apps/pciutils.

Once the make(s)/model(s) of the NIC(s) has been obtained, configure the kernel with support for the correct drivers. For more information on kernel configuration see the Kernel Configuration Guide.

The next thing needed is support for iptables and NAT (and packet shaping if desired). The following list is split up into always required (*), required only for ADSL via PPPoE (a), suggested for everyone (x), and only for shaper (s) features. It does not matter whether the features are built into the kernel or as modules as long as when the feature is needed, the correct module(s) are loaded. For more information on loading modules see the Kernel Modules Guide.

KERNEL Enabling the necessary networking options
-*- Networking support  --->
   Networking options  --->
      [*] TCP/IP networking
         [*] IP: advanced router
      [*] Network packet filtering framework (Netfilter)  --->
         [*]   Advanced netfilter configuration
            IPv6: Netfilter Configuration  ---> 
               <*> IPv6 connection tracking support
               <*> IP6 tables support (required for filtering)

Those who would rather search for these features directly in menuconfig can find them under the following names: CONFIG_INET, CONFIG_IP_ADVANCED_ROUTER, and CONFIG_NETFILTER, CONFIG_NETFILTER_ADVANCED, CONFIG_NF_CONNTRACK_IPV6, and CONFIG_IP6_NF_IPTABLES.

KERNEL Network Options
[*] Socket Filtering
   IP: Netfilter Configuration  --->
      [*] Connection tracking (required for masq/NAT)
         [x] FTP protocol support
         [x] IRC protocol support
      [*] IP tables support (required for filtering/masq/NAT)
         [*] IP range match support
         [x] MAC address match support
         [*] Multiple port match support
         [*] Packet filtering
            [*] REJECT target support
            [x] REDIRECT target support
         [*] Full NAT
            [*] MASQUERADE target support
         [s] Packet mangling
            [s] MARK target support
         [x] LOG target support
   QoS and/or fair queueing  --->
      [s] QoS and/or fair queueing
         [s] HTB packet scheduler
         [s] Ingress Qdisc
   [a] PPP (point-to-point protocol) support
      [a] PPP filtering
      [a] PPP support for async serial ports
      [a] PPP support for sync tty ports
      [a] PPP Deflate compression
      [a] PPP BSD-Compress compression
      [a] PPP over Ethernet
Some things may be slightly different in the menuconfig interface on newer kernels (EG: enabling nftables), however things should not be too difficult to figure out. Good luck!

Hello, World! (WAN configuration)


There are many ways to connect to the internet. The two most popular kinds are Cable/Dynamic IP (DOCSIS, Fiber-Optic and others) and PPPoE (ADSL, VDSL, "Fiber-To-The-Curb" and others) this document currently only specifies Cable configuration due to a lack of access to PPPoE services to verify configuration. (If you have a PPPoE service and would like to add it, please do!)

Cable and/or dynamic/static IP

If a static IP is necessary then additional configuration details will be required. Static IP users will need to add the IP address, gateway address, and DNS server addresses.

Dynamic IP Users:

FILE /etc/systemd/network/wan.networkDynamic IP addresses


Static IP Users:

FILE /etc/systemd/network/lan.networkStatic IP address configuration

We don't want to set up DNS yet since we'll be using BIND as a DNS server. We will set up DNS later when we add that

Dynamic and Static Setup:

root #systemctl enable systemd-networkd
root #systemctl start systemd-networkd

After working through the changes above the system should be ready to continue.

Hug the LAN (let's share some internet)

This step is a breeze compared to the previous one. To use more than two devices (more than the one for LAN and the one for WAN), a Network bridge will need to be setup between all NICs using the LAN. This will allow multiple NICs to be reached by the same IP address. This is outside the scope of this article, but is documented in Network bridge

LAN Services ("hey, listen!")

DHCP server

DHCP is the first thing we need if we're going to bring everyone else along through our gateway. It lets everyone on our LAN know we exist and where to send their packets to reach the internet. For more information about DHCP, visit Wikipedia's DHCP article.

This section will use the net-misc/dhcp package which will provide DHCP. An alternative option if you would like both DHCP and DNS is the net-dns/dnsmasq package

FILE /etc/dhcpd.conf
option domain-name

<div class="alert alert-warning gw-box" style="padding-top: 8px; padding-bottom: 8px;"><strong><i class="fa fa-exclamation-circle"></i> Important</strong><br />Do not use TLD's like .local or .lan. This can cause undesired behaviour, [ see ICANN report]</div>

default-lease-time 43200
max-lease-time 129600


option domain-name-servers;
option subnet-mask;
option routers;
subnet netmask {

{{RootCmd |cp /lib/systemd/system/dhcpd4.service /etc/systemd/system/dhcpd4@.service

FILE /etc/systemd/system/dhcpd4@.service

Setting the interface is very important. Using default dnsmasq settings will open the router to DNS amplification attacks which could create some scary email from the ISP providing the connection. Check to make sure the router is not allowing for DNS amplification attacks by using [1].

Now the little router is a bona-fide DHCP server. Plug in those computers and watch them work! With Windows systems navigate to the TCP/IP Properties and select the Obtain an IP address automatically and Obtain DNS server address automatically options. Sometimes the changes are not instantaneous, so opening a command prompt and running ipconfig /release and ipconfig /renew might be necessary. Enough about Windows, time to get back to everyone's favorite penguin!

DNS server

When people want to visit a place on the Internet, they remember names, not a string of funky numbers. After all, what is easier to remember, or This is where the DNS steps in. DNS servers run all over the Internet, and whenever someone wants to visit, these servers turn the text "" (what we understand) into IP address "" (what computers understand). For more information about DNS visit Wikipedia.

Since dnsmasq is being used for the DHCP server, and it includes a DNS server, there is nothing left to do here! The little router is already providing DNS to its DHCP clients. Shouldn't everything be this easy? ;)

It is possible to choose other DNS servers if they are more comfortable to setup. dnsmasq is used in this article because it was designed to do exactly what this guide required. It is a little DNS caching/forwarding server for local networks. The scope of this howto is not to provide DNS for a domain; but it does offer simple DNS services to every user of a home-based LAN.

NAT (a.k.a. IP-masquerading)

At this point, people on the network can talk to each other and look up hostnames via DNS, but they still ca not actually connect to the Internet. While the network administrator (the person reading this) may think it is great (more bandwidth for the Admin!), the other users are probably not very happy without an Internet connection.

This is where Network Address Translation (NAT) steps in. NAT is a way of connecting multiple computers in a private LAN to the Internet when a small number of public IP addresses are available. Typically a home Internet user is provided with 1 public IP address by an ISP for the whole house to connect to the Internet. NAT is the magic that makes this possible. For more information about NAT, please visit Wikipedia.

Before getting started, make sure IPtables has been installed on the system. If it is not installed, install it: emerge iptables

After IPtables is installed, flush the current rules:

root #iptables -F
root #iptables -t nat -F

Setup default policies to handle unmatched traffic:

root #iptables -P INPUT ACCEPT
root #iptables -P OUTPUT ACCEPT
root #iptables -P FORWARD DROP

Copy and paste the following:

root #export LAN=eth0
root #export WAN=eth1

The next step locks the services so they only work from the LAN:

root #iptables -I INPUT 1 -i ${LAN} -j ACCEPT
root #iptables -I INPUT 1 -i lo -j ACCEPT
root #iptables -A INPUT -p UDP --dport bootps ! -i ${LAN} -j REJECT
root #iptables -A INPUT -p UDP --dport domain ! -i ${LAN} -j REJECT

(Optional) Allow access to the ssh server from the WAN:

root #iptables -A INPUT -p TCP --dport ssh -i ${WAN} -j ACCEPT

Drop TCP / UDP packets to privileged ports:

root #iptables -A INPUT -p TCP ! -i ${LAN} -d 0/0 --dport 0:1023 -j DROP
root #iptables -A INPUT -p UDP ! -i ${LAN} -d 0/0 --dport 0:1023 -j DROP

Finally add the rules for NAT:

root #iptables -I FORWARD -i ${LAN} -d -j DROP
root #iptables -A FORWARD -i ${LAN} -s -j ACCEPT
root #iptables -A FORWARD -i ${WAN} -d -j ACCEPT
root #iptables -t nat -A POSTROUTING -o ${WAN} -j MASQUERADE

Inform the kernel that IP forwarding is OK:

root #echo 1 > /proc/sys/net/ipv4/ip_forward
root #for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done

Instruct the IPtables daemon to save the changes to the rules, then add IPtables to the default runlevel:

root #/etc/init.d/iptables save
root #rc-update add iptables default
FILE /etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.conf.default.rp_filter = 1

For dynamic Internet the following setting should be enabled:

FILE /etc/sysctl.conf
net.ipv4.ip_dynaddr = 1

Once the above text has been entered the rest of the network users should now be able to use the Internet as if they were directly connected themselves.

The ip_dynaddr option is useful for dial on demand systems or when the ISP gives out dynamic addresses. This works around the problem where a connection is attempted before the Internet interface is fully setup. This provides a smoother network experience for users behind the router.

Fun things (for a rainy day)


Believe it or not, it is done! From here on out, some other common topics that may interest will be covered. Everything in the following sections are completely optional.

Port forwarding

Sometimes users need to be able to host services on a computer behind the router, or need to be able to connect remotely to a computer behind the router. Perhaps a FTP, HTTP, SSH, or VNC server is needed on one or more machines behind the router and outsiders need to connect to them all. The only caveat to Port Forwarding is only one service/machine combo can be established per port. For example, there is no practical way to setup three FTP servers behind the router and connect to them all through port 21; only one system can be on port 21 while the others would need to be on other ports (port 123 and port 567 would be fine options).

All the port forwarding rules are of the form iptables -t nat -A PREROUTING -p [protocol] --dport [external port on router] -i ${WAN} -j DNAT --to [ip/port to forward to]. Unfortunately, iptables does not accept hostnames when port forwarding. When forwarding an external port to the same port on the internal machine, omit the destination port. See the iptables(8) man page for more information.

root #export LAN=eth0
root #export WAN=eth1

Forward port 2 to ssh on an internal host:

root #iptables -t nat -A PREROUTING -p tcp --dport 2 -i ${WAN} -j DNAT --to

FTP forwarding to an internal host:

root #iptables -t nat -A PREROUTING -p tcp --dport 21 -i ${WAN} -j DNAT --to

HTTP forwarding to an internal host:

root #iptables -t nat -A PREROUTING -p tcp --dport 80 -i ${WAN} -j DNAT --to

VNC forwarding for internal hosts:

root #iptables -t nat -I PREROUTING -p tcp --dport 5900 -i ${WAN} -j DNAT --to
root #iptables -t nat -I PREROUTING -p tcp --dport 5901 -i ${WAN} -j DNAT --to
VNC clients by default connect to port 5900. If a different port needs to be selected, most VNC clients use a suffix to the connection address which will be added to 5900 to find the final port. So, in the above case, to VNC in to, add :1 to the target IP address (which is the WAN address of the router) so that the VNC client connects to port 5901.

SAMBA forwarding to an internal host (excess ports to cover Windows):

root #iptables -t nat -I PREROUTING -p tcp --dport 135 -i ${WAN} -j DNAT --to
root #iptables -t nat -I PREROUTING -p tcp --dport 139 -i ${WAN} -j DNAT --to
root #iptables -t nat -I PREROUTING -p tcp --dport 445 -i ${WAN} -j DNAT --to
root #iptables -t nat -I PREROUTING -p udp --dport 137:138 -i ${WAN} -j DNAT --to
root #iptables -t nat -I PREROUTING -p udp --dport 445 -i ${WAN} -j DNAT --to

Bittorrent forwarding:

root #iptables -t nat -A PREROUTING -p tcp --dport 6881:6889 -i ${WAN} -j DNAT --to

eDonkey/eMule forwarding:

root #iptables -t nat -A PREROUTING -p tcp --dport 4662 -i ${WAN} -j DNAT --to

Game Cube Warp Pipe support:

root #iptables -t nat -A PREROUTING -p udp --dport 4000 -i ${WAN} -j DNAT --to

Playstation 2 Online support:

root #iptables -t nat -A PREROUTING -p tcp --dport 10070:10080 -i ${WAN} -j DNAT --to
root #iptables -t nat -A PREROUTING -p udp --dport 10070:10080 -i ${WAN} -j DNAT --to

Xbox Live:

root #iptables -t nat -A PREROUTING -p tcp --dport 3074 -i ${WAN} -j DNAT --to
root #iptables -t nat -A PREROUTING -p udp --dport 3074 -i ${WAN} -j DNAT --to
root #iptables -t nat -A PREROUTING -p udp --dport 88 -i ${WAN} -j DNAT --to

Identd (for IRC)

Internet Relay Chat utilizes the ident service pretty heavily. Now that the IRC clients are behind the router, a way to host ident for both the router and the clients is needed. A server has been created for this purpose. It is called net-misc/midentd.

root #emerge --ask net-misc/midentd
root #rc-update add midentd default
root #service midentd start

There are a few other ident servers in the Portage tree. Other viable options are net-misc/oidentd and net-misc/fakeidentd.

Time server

Keeping the system time correct is essential to maintaining a healthy system. One of the most common ways of accomplishing this is with the Network Time Protocol (NTP) and the net-misc/ntp package (which provides implementations for both server and client).

Many users run ntp clients on their computers. Obviously, the more clients in the world, the larger the load ntp servers need to shoulder. In environments like home networks an NTP server can be setup locally to help keep the load down on public servers while still providing the proper time to local systems. As an added bonus, private updates will be a lot faster for the local clients! The setup is simple: run a NTP server on the router that synchronizes itself with the public Internet servers while, at the same time, providing the time to the rest of the computers in the network. To get started, simply emerge ntp on the router and edit /etc/conf.d/ntp-client as desired.

root #rc-update add ntp-client default
FILE /etc/ntp.conf
restrict default ignore
restrict mask notrust nomodify notrap

These will allow only NTP clients with an IP address in the range to use the NTP server.

root #rc-update add ntpd default
root #service ntpd start
Make sure to allow inbound and outbound communication on the NTP port (123/udp) when setting up the server. The client just needs outbound access on port 123 over UDP.

Now, on the clients, run emerge ntp. By running the NTP client setup is a lot simpler.

In /etc/conf.d/ntp-client, change the server in the NTPCLIENT_OPTS variable to

root #rc-update add ntp-client default
root #service ntp-client start

Rsync server

For those who run multiple Gentoo boxes on the same LAN, it is wise to prevent every machine running emerge --sync with remote servers. By setting up a local rsync, both personal bandwidth and the Gentoo rsync servers' bandwidth is saved. The process is relatively simple.

For a much more in-depth rsync guide, please see the official rsync guide.

Since every Gentoo machine requires rsync, there is no need to emerge it. Edit the default /etc/rsyncd.conf config file, uncomment the [gentoo-portage] section, and make sure to add an address option. All other defaults should be already set correctly.

FILE /etc/rsyncd.conf
pid file = /var/run/
use chroot = yes
read only = yes
address =
  path = /mnt/space/portage
  comment = Gentoo Linux Repository
  exclude = /distfiles /packages

The service then needs to be started (again, the defaults are OK).

root #service rsyncd start
root #rc-update add rsyncd default

Only thing left is to set tell the clients to sync against the router. Edit the /etc/portage/repos.conf/gentoo.conf config file. If this file does not exist, make a directory under /etc/portage called repos.conf and copy the /usr/share/portage/config/repos.conf file into this directory. Then update this file accordingly - don't forget to set sync-uri to match the address of the server (the home router).

FILE /etc/portage/repos.conf/gentoo.confSetup client to new rsync server
main-repo = gentoo
location = /var/db/repos/gentoo
sync-type = rsync
sync-uri = rsync://
auto-sync = yes

Mail server

Sometimes it is nice to run a Simple Mail Transfer Protocol (SMTP) server on the router. Each user may have their own reason for wanting to do so, however one advantage to running SMTP on the router is the users see mail as being sent instantly and the work of retrying/routing is left up to the mail server. Some ISPs do not allow for mail relaying for accounts that are not part of their network (like Verizon). Also, throttling the delivery of mail may be needed so that large attachments will not seriously lag the Internet connection.

root #emerge --ask mail-mta/netqmail

Make sure the output of the hostname command is correct:

root #emerge --config netqmail
root #iptables -I INPUT -p tcp --dport smtp ! -i ${LAN} -j REJECT
root #ln -s /var/qmail/supervise/qmail-send /service/qmail-send
root #ln -s /var/qmail/supervise/qmail-smtpd /service/qmail-smtpd
root #cd /etc/tcprules.d

Edit tcp.qmail-smtp and add an entry like so to the allow section:

FILE niltcp.qmail-smtp
root #make
root #rc-update add svscan default
root #service svscan start

When e-mail is setup on the hosts in the network, tell them the SMTP server is Visit the netqmail homepage for more documentation on netqmail usage.

Full DHCP server

Earlier dnsmasq was used to provide DHCP service to all DHCP clients. For most people with a simple small LAN, this is perfect, however there may needs something with more features. Thus a full-featured DHCP server is provided by the ISC folks for users who crave the maximum.

root #emerge --ask net-misc/dhcp
FILE /etc/dhcp/dhcpd.confHere is a simple configuration file
ddns-update-style interim;
subnet netmask {
    pool {
        default-lease-time 259200;
        max-lease-time 518400;
        option subnet-mask;
        option broadcast-address;
        option routers;
        option domain-name-servers;

In /etc/conf.d/dhcpd set IFACE to "eth0".

root #rc-update add dhcpd default
root #service dhcpd start

This is the minimal setup required to replace the dnsmasq DHCP functionality used earlier. The DHCP features in dnsmasq should be disabled? If not, comment out the dhcp-range setting in /etc/dnsmasq.conf and restart the service.

Connect another LAN (or two or three)

Sometimes the router must be connected to another LAN. This can be done to hook up a group of friends temporarily or to section off different groups of computers. Whatever the reason, extending the router to other LAN networks should is straightforward. In the following examples, This article presumes that the new network is connected via a third ethernet card, namely eth2.

First configure the interface. Take the instructions in this section and replace config_eth0="" with config_eth2="".

Tweak dnsmasq to service the new interface. Edit the /etc/conf.d/dnsmasq file again and append -i eth2 to DNSMASQ_OPTS; using -i multiple times is OK. Then edit /etc/dnsmasq.conf and add another line like the dhcp-range line in this section, replacing dhcp-range=eth0,,,72h with dhcp-range=eth2,,,72h and replace interface=eth0 with interface=eth2. Having multiple dhcp-range and interface lines is OK too.

Finally, see the rules in this section and duplicate the rules that have -i ${LAN} in them. Another variable may need to be created, say LAN2, to make things easier.


Useful tools

When having trouble getting computers to communicate try out the following tools (they can all be found in the net-analyzer Portage category):

Utility Description
net-analyzer/wireshark GUI tool to view all raw network data according to filters
net-analyzer/tcpdump Console tool to dump all raw network data according to filters
net-analyzer/iptraf-ng ncurses based IP LAN monitor
net-analyzer/ettercap ncurses based network monitor/control

DHCP fails to start

When starting the dhcp init.d script for the first time, it may fail to load but neglect to provide any useful information.

root #service dhcp start
 * Setting ownership on dhcp.leases ...          [ ok ]
 * Starting dhcpd ...                            [ !! ]

The trick is used to know where dhcpd is sending its output. Browse to /var/log and read the log files. Since the exact log file depends on the package using a syslog, try running grep -Rl dhcpd /var/log to narrow down the possibilities. Chances are a typo was made in the configuration file. Another command to try running: dhcpd -d -f (short for debug / foreground). This aids in debugging the errors based upon the output.

Incorrect MTU value

If odd errors are experienced (such as not being able to access some webpages while others load fine), it might be Path MTU Discovery trouble. The quick way to test for this is to run the following iptables command:

root #iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu

This will affect all new connections; refresh the problematic website in order to test the fix. In case it helps, the standard MTU value for 100mbit ethernet connections is 1500; this value also applies to PPPoA. For PPPoE connections it is 1492. For more info, read Chapter 15 of the Linux Advanced Routing & Traffic Control HOWTO.

If the above command does not work, consider putting the rule into the mangle table. Simply add -t mangle to the command.

Unable to connect two machines directly

If (for whatever reason) connecting two machines directly together without a hub or switch is required, a regular ethernet cable will likely not work, unless an Auto MDI/MDI-X (also known as "autosensing") capable network adapter is available. A different cable called a crossover cable will be needed for direct NIC to NIC connections. This Wikipedia page explains the low level details.

Final notes

There are no other final notes. If any troubles with this guide are experienced either update this article with the correct information or leave a brief message on this article's talk page with a summary of what is broken. Eventually someone should be able to correct any issue(s). It is also possible to file a bug on Gentoo's Bugtracking Website. If there are any other interesting bits that would enhance this guide, by all means include them! The worst that could happen is they could be removed.

This page is based on a document formerly found on our main website
The following people contributed to the original document: Mike Frysinger (vapier)
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.