Home router/ru

В этом документе подробно рассказывается, как превратить старый компьютер с системой Gentoo в маршрутизатор для соединения домашней сети с интернетом.

Введение
Создание собственного маршрутизатора из старых компонентов имеет массу преимуществ по сравнению с покупкой уже собранного и запечатанного на заводе (Linksys, D-Link, Netgear и т.д.). Самое большое преимущество, безусловно, является контроль над соединением. Остальные преимущества можно оставить на пользовательское воображение. Можно сделать буквально все что угодно; дело лишь в том, действительно ли это нужно.

Это руководство рассказывает, как настроить преобразование сетевых адресов (NAT) на пользовательском маршрутизаторе (ядро и iptables), как добавить и настроить распространённые сервисы (вроде системы доменных имён (DNS) с помощью, DHCP через , ADSL через ). Статья завершается более сложными и интересными вещами на которые способен пользовательский маршрутизатор (проброс портов (port forwarding), шейпинг (traffic shaping), прокси/кэширование и т.д.).

Перед началом, пожалуйста ознакомьтесь со списком основных требований:
 * 1) в компьютере должны быть установлены как минимум две сетевые платы (NIC).
 * 2) будут нужны настройки для соединения с интернетом (такие вещи как IP/DNS/шлюз/имя пользователя/пароль).
 * 3) нужно будет немного свободного времени, и любовь к Gentoo для того, чтобы прочитать эту статью и успешно настроить многофункциональный домашний маршрутизатор.

В руководстве используются следующие оговорки:


 * eth0 - сетевая плата, подключенная к локальной сети (LAN) или сетевой мост, состоящий из нескольких сетевых карт
 * eth1 - сетевая плата, подключенная к глобальной сети (WAN)
 * LAN использует частную сеть вида 192.168.0.xxx
 * Маршрутизатор жестко привязан к IP-адресу 192.168.0.1
 * Маршрутизатор работает на ядре Linux 2.4 или 2.6; другие версии ядра не поддерживаются в этом руководстве&#41;.

Настройка ядра (сначала познай себя)
Ядру необходимы драйверы для обеих сетевых плат, установленных в компьютере. Возможно, сетевые платы уже настроены — чтобы проверить это, используйте. Вывод может немного отличаться примера ниже, ничего страшного. Самое главное, присутствует ли интерфейс в списке.

Если видна только одна (или ни одной) из двух карт, то попробуйте запустить.

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.

Далее, необходима поддержка iptables и NAT (а также, по желанию, шейпинга (packet shaping)). Нижеследующий список разделён на всегда необходимое (*), нужное только для ADSL через PPPoE (a), предлагаемое для всех (x), и только для shaping'a (s). Не имеет значения, встраивается ли функцию в ядро, или компилируется как модуль, когда нужна какая-либо функция, нужные модули загружаются автоматически. Более подробную информацию о загрузке модулей можно найти в статье Kernel Modules Guide.

Для работы DHCP необходимо включить следующее, если используется ядро 2.4.x :

Введение
There are many ways to connect to the Internet, however there are generally only a couple of ways that are used by most of the public. ADSL (PPPoE) and cable modems (static/dynamic) are the two most common methods ISP (Internet Service Providers) provide. If there are other methods available, feel free to add them to this wiki article. Skip any of the following sections in this chapter that are not applicable to the needed use case. This chapter addresses getting the router connected to the Internet via eth1.

ADSL и PPPoE
Всевозможное программное обеспечение PPPoE, которое обеспечивалось пакетом rp-pppoe (Roaring Penguin) было включено в стандартный пакет PPP. Просто выполните для установки PPPoE. Помните, что были необходимы логин и пароль в списке выше? Откройте файл в любимом текстовом редакторе и настройте его соответствующим образом.

Замените  и   в примере ниже необходимым именем пользователя и паролем:

Cable and/or dynamic/static IP
Если необходим статический IP, то потребуется немного больше информации. Пользователям со статическим IP-адресом потребуются добавить IP, шлюз (gateway) и DNS-сервера.

Пользователи с динамическим IP:

Пользователи со статическим IP:

Как для динамического, так и для статического варианта:

После изменений выше система должна быть готова к продолжению.

Настройка LAN (приведем своих друзей)
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.

If a network bridge will be necessary, follow the instructions to set up a Network bridge. The name of the bridge (default br0) will then replace eth0 for the LAN device in the steps in this wiki. If a large number of network devices in the home router, consider renaming them via udev to make administration easier. Setting up a bridge and renaming devices is completely optional but recommended for larger home networks.

When creating a Wi-Fi access point make sure the Wi-Fi card supports master mode and set up Hostapd.

DHCP сервер
Было бы отлично, если любой желающий в доме просто бы мог подключить свои компьютеры к сети, после чего всё сразу бы заработало. Без необходимости помнить сбивающие с толку данные, или заставлять пялиться на запутанные окна настройки. Жизнь была бы прекрасна, не так ли? Познакомьтесь с протоколом динамической настройки узла (DHCP), и с тем, почему о нём действительно стоит позаботиться.

DHCP — вещь, соответствующая своему названию. Это протокол, который позволяет настроить другие узлы автоматически, прямо во время работы. Запустите DHCP-сервер на маршрутизаторе, снабдив его данными о сети (правильные IP, сервера DNS, шлюзы и т. п.), и как только другие компьютеры включаются, они запускают DHCP-клиен, чтобы автоматически настроиться. Ни забот, ни хлопот! За дополнительными сведениями о DHCP всегда можно обратиться к DHCP статье на Википедии.

This section will use the package which will provide both DHCP and DNS services. For now lets focus on the DHCP aspect. Note: to run a different DHCP server, another example can be found in the Fun Things section below. Also, to tinker with the DHCP server settings read the comments in the file.

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.

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

DNS сервер
Когда человек хочет посетить место в интернете, он помнит его название, но не строку страшных цифр. Действительно, что легче запомнить, eBay.com, или 66.135.192.87? Именно в этом замешан DNS. Сервера DNS работают по всему интернету, и когда кто-то хочет посетить eBay.com, эти сервера преобразовывают текст "eBay.com" (что нам понятно) в IP-адрес "66.135.192.87" (что понятно нашим компьютерам). За дополнительными сведениями о DNS можно обратиться к Википедии.

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 (или IP-маскарадинг)
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.

After IPtables is installed, flush the current rules:

Setup default policies to handle unmatched traffic:

Скопируйте и вставьте следующее:

Далее заблокируйте службы, чтобы они были доступны только из локальной сети.

(Необязательно) Разрешите доступ к ssh серверу из WAN:

Drop TCP / UDP packets to privileged ports:

Наконец, добавьте правила для NAT:

Сообщим ядру, что IP-форвардинг настроен:

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

For dynamic Internet the following setting should be enabled:

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  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.

Введение
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. 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.

Forward port 2 to ssh on an internal host:

FTP forwarding to an internal host:

HTTP forwarding to an internal host:

VNC forwarding for internal hosts:

To VNC in to 192.168.0.3, then add  to the router's hostname.

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

Bittorrent forwarding:

eDonkey/eMule forwarding:

Game Cube Warp Pipe support:

Playstation 2 Online support:

Xbox Live:

Identd (для 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.

There are a few other ident servers in the Portage tree. Other viable options are and.

Сервер времени
Забота о точности установленного времени необходима для поддержки работающей системы. Самый распространенный способ достигнуть этого — использовать Network Time Protocol (NTP), и пакет (который включает в себя как серверную, так и клиентскую реализации).

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 on the router and edit  as desired.

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

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

In, change the  server in the   variable to

Rsync сервер
For those who run multiple Gentoo boxes on the same LAN, it is wise to prevent every machine running 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.

Since every Gentoo machine requires rsync, there is no need to emerge it. Edit the default config file, uncomment the   section, and make sure to add an   option. All other defaults should be already set correctly.

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

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

Почтовый сервер
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.

Make sure the output of the command is correct:

Edit and add an entry like so to the allow section:

When e-mail is setup on the hosts in the network, tell them the SMTP server is 192.168.0.1. 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.

В установите значение   равным "eth0".

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  setting in  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.

First configure the interface. Take the instructions in this section and replace  with   and   with.

Tweak dnsmasq to service the new interface. Edit the file again and append   to  ; using -i multiple times is OK. Then edit and add another line like the dhcp-range line in this section, replacing   with. Having multiple dhcp-range lines is OK too.

Finally, see the rules in this section and duplicate the rules that have  in them. Another variable may need to be created, say, to make things easier.

Полезные инструменты
When having trouble getting computers to communicate try out the following tools (they can all be found in the net-analyzer Portage category):

DHCP не запускается
When starting the dhcp init.d script for the first time, it may fail to load but neglect to provide any useful information.

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

Неправильное значение MTU
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:

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 ; this value also applies to PPPoA. For PPPoE connections it is. 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  to the command.

Невозможно соединить два компьютера напрямую
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.

Завершающие заметки
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.