Home router/ru

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

Введение
Создание собственного маршрутизатора из старых компонентов имеет массу преимуществ по сравнению с покупкой уже собранного и запечатанного на заводе: скажем, Linksys. Самое главное — управление соединением. Остальные преимущества вы сами можете придумать и воплотить в жизнь. Возможно сделать буквально все что угодно в случае собственного маршрутизатора, дело лишь в том, действительно ли вам это нужно.

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

Перед началом ознакомьтесь с некоторыми требованиями, которым необходимо соответствовать. Во-первых, вам понадобится такой компьютер, который имеет как минимум две сетевые платы (NIC). Во-вторых, вам будут нужны настройки провайдера для соединения с интернетом (такие вещи как IP/DNS/шлюз/имя пользователя/пароль). И наконец, нужно будет немного свободного времени, и любовь к Gentoo.

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


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

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

Если вы не видите обе свои платы, и не уверены, какого типа платы у вас установлены, попробуйте запустить. Вы получите такой вывод от. Как только вы получили эту информацию, зайдите в настройки ядра и включите поддержку нужных драйверов.

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

Введение
Существует настолько много способов соединения с интернетом, что я просто опишу некоторые, в которых разбираюсь. Таким образом, мы остались с ADSL (PPPoE) и кабельными модемами (статическими/динамическими). Если там есть другие способы, не стесняйтесь написать рекламку, и сообщить мне по эл. почте. Не бойтесь пропустить любой из разделов этой главы, который к вам не относится. Эта глава просто про подключение маршрутизатора к интернету через плату eth1.

ADSL и PPPoE
All the fancy PPPoE software that used to be provided by rp-pppoe (Roaring Penguin) has been integrated into the standard PPP package. Simply  and you'll be on your way. Remember how I said you'll need username/password information? Well I wasn't lying so I hope you have it now! Load up in your favorite editor and set it up.

Замените «vla9h924» в следующем примере своим именем пользователя, и «boogie» - паролем.

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

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

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

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

Вы все настроили для старта.

Настройка LAN (приведем своих друзей)
Этот шаг очень простой, по сравнению с предыдущим.

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

DHCP is exactly what its name implies. It's a protocol that allows you to dynamically configure other hosts automatically. You run a DHCP server on the router, give it all the information about your network (valid IPs, DNS servers, gateways, etc...), and then when the other hosts start up, they run a DHCP client to automatically configure themselves. No fuss, no muss! For more information about DHCP, you can always visit Wikipedia.

We'll use a package called dnsmasq which provides both DHCP and DNS services. For now lets just focus on the DHCP aspect. Note that if you want to run a different DHCP server, you can find another example in the Fun Things chapter. Also, if you wish to tinker with the DHCP server settings, just read the comments in. All the defaults should work fine though.

Now your little router is a bona-fide DHCP server! Plugin those computers and watch them work! With Windows systems you should go into the TCP/IP Properties and select the 'Obtain an IP address automatically' and 'Obtain DNS server address automatically' options. Sometimes the changes aren't instantaneous, so you may have to open a command prompt and run  and. But enough about Windows, let's get back to our favorite penguin.

Сервер DNS
When people want to visit a place on the internet, they remember names, not a string of funky numbers. After all, what's easier to remember, ebay.com or 66.135.192.87? This is where the DNS steps in. DNS servers run all over the internet, and whenever someone wants to visit 'ebay.com', these servers turn 'ebay.com' (what we understand) into '66.135.192.87' (what our computers understand). For more information about DNS, you can always visit Wikipedia.

Since we're using dnsmasq for our DHCP server, and it includes a DNS server, you've got nothing left to do here! Your little router is already providing DNS to its DHCP clients. Bet you wish everything was this easy ;).

You're welcome to choose other DNS servers if you're more comfortable with them, but the reason dnsmasq is great is because it was designed to do exactly what we want and nothing more. It's a little DNS caching/forwarding server for local networks. We're not looking to provide DNS for our own domain here, just offer simple DNS services to everyone else on our LAN.

NAT (или IP-маскарадинг)
At this point, people on your network can talk to each other and they can look up hostnames via DNS, but they still can't actually connect to the internet. While you may think that's great (more bandwidth for you!), I bet they're not too happy just yet.

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 you have a smaller number of public IP addresses available to you. Typically you are given 1 IP by your ISP, but you want to let your whole house connect to the internet. NAT is the magic that makes this possible. For more information about NAT, you can always visit Wikipedia.

First we flush our current rules

Setup default policies to handle unmatched traffic

Copy and paste these examples ...

Then we lock our services so they only work from the LAN:

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

Drop TCP / UDP packets to privileged ports:

Finally we add the rules for NAT:

Tell the kernel that ip forwarding is OK:

This is so when we boot we don't have to run the rules by hand.

If you have a dynamic internet address you probably want to enable this:

Once you've typed out all of that, the rest of your network 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 your ISP gives out dynamic addresses. This works around the problem where a connection is attempted before the internet interface is fully setup. Really this just provides for a smoother network experience for users behind your router.

Введение
Believe it or not, you're done :). From here on out, I'll cover a bunch of common topics that may interest you. Everything in this chapter is completely optional.

Port Forwarding
Sometimes you would like to be able to host services on a computer behind the router, or just to make your life easier when connecting remotely. Perhaps you want to run a FTP, HTTP, SSH, or VNC server on one or more machines behind your router and be able to connect to them all. The only caveat is that you can only have one service/machine combo per port. For example, there is no practical way to setup three FTP servers behind your router and then try to connect to them all through port 21; only one can be on port 21 while the others would have to be on say port 123 and port 567.

All the port forwarding rules are of the form. Unfortunately, iptables does not accept hostnames when port forwarding. If you are forwarding an external port to the same port on the internal machine, you can 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:

If you want to VNC in to 192.168.0.3, then just add ':1' 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 (for IRC)
Internet Relay Chat utilizes the ident service pretty heavily. Now that the IRC clients are behind the router, we need a way to host ident for both the router and the clients. One such server has been created called.

There are a few other ident servers in portage. Depending on your needs, I would recommend checking out  and.

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

Many people run ntp clients on their computers. Obviously, the more clients in the world, the larger the load the ntp servers need to shoulder. In environments like home networks though, we can help keep the load down on public servers while still providing the proper time to all our computers. As an added bonus, our private updates will be a lot faster for the clients too! All we have to do is run a ntp server on our router that synchronizes itself with the public internet servers while providing the time to the rest of the computers in the network. To get started, simply  on the router and edit  to your liking.

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

Now, on your clients, have them  also. However, we will just run the ntp client so setup is a lot simpler.

In, change the 'pool.ntp.org' server in the NTPCLIENT_OPTS variable to '192.168.0.1'.

Сервер Rsync
For those who run multiple Gentoo boxes on the same lan, you often want to keep from having every machine running  with remote servers. By setting up a local rsync, you save on both your bandwidth and the Gentoo rsync servers' bandwidth. It's pretty simple to do.

Since every Gentoo machine requires rsync, theres no need to emerge it. Edit the default config file, uncomment the   section, and make sure you add an   option. All the other defaults should be fine.

Then you need to start the service (again, the defaults are OK).

Only thing left is to set tell your clients to sync against the router.

Mail Server
Sometimes it's nice to run your own Simple Mail Transfer Protocol (SMTP) server on the router. You may have your own reason for wanting to do so, but I run it so that the users see mail as being sent instantly and the work of retrying/routing is left up to the mail server. Some ISPs also don't allow for mail relaying for accounts that aren't part of their network (like Verizon). Also, you can easily throttle the delivery of mail so that large attachments won't seriously lag your connection for half an hour.

Make sure the output of `hostname` is correct

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

I'm a huge fan of qmail, but you're free to use a different mta :). When you setup e-mail on the hosts in your network, tell them that their SMTP server is 192.168.0.1 and everything should be peachy. You might want to visit the netqmail homepage for more documentation.

Full DHCP Server
Earlier we used dnsmasq to provide DHCP service to all our clients. For most people with a simple small LAN, this is perfect. But you may need something with more features. Thus we turn to a full-featured DHCP server as provided by the ISC folks.

In set   to "eth0".

This is the minimal setup required to replace the dnsmasq DHCP functionality that we used earlier. Speaking of which, you did remember to disable the DHCP features in dnsmasq didn't you? If not, you should do so now (just comment out the  setting in  and restart the service).

Connect Another LAN (or two or three or ...)
Sometimes you have need of connecting the router to another LAN. Maybe you want to hook up a group of friends temporarily, or you're a neat freak and want to section off different groups of computers, or you're just really really bored. Whatever the reasons, extending the router to other LAN networks should be pretty straightforward. In the following examples, I will assume that this new network is connected via a third ethernet card, namely.

First you need to configure the interface. Just take the instructions in this section and replace  with   and   with.

Then you need to tweak dnsmasq to service the new interface. Just edit the file again and append   to DNSMASQ_OPTS; 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. You may want to create another variable, say, to make things easier.

Useful Tools
If you're having trouble getting your computers to communicate, you may way to try out the following tools (they can all be found in the  portage category):

DHCP Fails To Start
When starting the dhcp init.d script for the first time, it may fail to load but neglect to give you any useful info.

The trick is to know where dhcpd is sending its output. Simply browse to and read the log files. Since the exact log file depends on the package you are using as a syslog, try running  to narrow down the possibilities. Chances are you made a typo in your config file. You could also try running  (short for debug / foreground) and debug the error based upon the output.

Incorrect MTU Value
If you experience odd errors (such as not being able to access some webpages while others load fine), you may be having Path MTU Discovery trouble. The quick way to test is to run this iptables command:

This will affect all new connections, so just refresh the website you're having problems with in order to test. 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, you should read Chapter 15 of the Linux Advanced Routing & Traffic Control HOWTO.

If that command does not work for you, you may want to try putting the rule into the mangle table. Simply add  to the command.

Unable to connect two machines directly
If (for whatever reason) you want to connect two machines directly together without a hub or switch, a regular ethernet cable will likely not work, unless you have an Auto MDI/MDI-X (also known as "autosensing") capable network adapter. You will need a different cable called a crossover cable. This Wikipedia page explains the low level details.

Завершающие заметки
У меня нет завершающих заметок. Если у вас появятся проблемы со статьей, напишите пользователю (обратите внимание, что он знает только английский язык - прим. перев.), либо оформите баг на багтрекере Gentoo (опять же, на английском языке, прим. перев.). Если у вас есть некоторая информация, которая может улучшить данную статью, сразу же присылайте ее мне для включения.

Благодарности
Мы хотели бы поблагодарить следующих авторов и редакторов за их вклад в это руководство: