- Интернет-шлюз на базе Ubuntu Server 18.04 LTS
- Настройка сети для router
- Настройка сети для pc-1, pc-2 и server
- Настройка интернет-шлюза
- Доступ внутрь сети
- Сохранение правил netfilter
- Домашний интернет-шлюз. Начальная настройка 6-портового мини-компьютера на Ubuntu Server 20.04 LTS
- Введение
- Netplan
- DHCP-сервер
- Заключение
- Ubuntu Documentation
- 1. Setting up an Ubuntu Wired/Wireless Router
- 1.1. Preface
- 1.2. Scripted wired:wired router
- 1.3. Network Manager
- 1.3.1. Typical Example
- 1.3.1.1. Quick and Dirty
- 1.4. Technical Overview
- 2. Prerequisites
- 2.1. Internet Connection
- 2.2. Router Hardware
- 2.2.1. Use your desktop PC
- 2.2.2. Dedicated Hardware
- 2.2.3. Terminology
- 3. Internal Network Information
- 4. Setting Up Your Network Interfaces
- 4.1. Device Naming Overview
- 4.2. Taking a Backup
- 4.3. Configuring the External Network Interface
- 4.3.1. Setting up External Network Interface
- 4.3.1.1. For Dynamic IP Addresses (DHCP) Only
- 4.3.1.2. For PPPoE connection with dynamic IP address only
- 4.3.1.3. For Static IP Address Only
- 4.3.2. Testing Connectivity
- 4.4. Configuring the Internal Network Interfaces
- 4.4.1. Wired Only
- 4.4.2. Wireless Only
- 4.4.3. Both Wired and Wireless
- 4.5. Enable IP forwarding and Masquerading
Интернет-шлюз на базе Ubuntu Server 18.04 LTS
Небольшой эксперимент создания интернет-шлюза на Ubuntu Server. У меня дома компьютер с установленной Windows 10 и VirtualBox. Давайте создадим четыре виртуальные машины router , pc-1 , pc-2 и server . Все виртуальные машины находятся в одной сети 192.168.30.0/24 . При этом у виртуальной машины router два сетевых интерфейса:
- enp0s3 (сетевой мост) — смотрит в домашнюю сеть, получает ip-адрес 192.168.110.8 от роутера
- enp0s8 (внутренняя сеть) — смотрит в одну сеть с виртуальными машинами pc-1 , pc-2 и server
Тут надо сказать несколько слов о настройке сети в VirtualBox. Существует несколько способов, рассмотрим два из них:
- Сетевой мост — при таком подключении виртуальная машина становится полноценным членом локальной сети, к которой подключена основная система. Виртуальная машина получает адрес у роутера и становится доступна для других устройств, как и основной компьютер, по своему ip-адресу.
- Внутренняя сеть — тип подключения симулирует закрытую сеть, доступную только для входящих в ее состав машин. Поскольку виртуальные машины не имеет прямого доступа к физическому сетевому адаптеру основной системы, то сеть получается полностью закрытой, снаружи и изнутри.
Как нетрудно догадаться, у виртуальных машин pc-1 , pc-2 и server будет по одному интерфейсу (внутренняя сеть). У виртуальной машины router два интерфейса и она будет обеспечивать выход в интернет для pc-1 , pc-2 и server .
Настройка сети для router
Сначала нужно посмотреть, как называются сетевые интерфейсы в системе:
Теперь редактируем файл /etc/netplan/01-netcfg.yaml
Применяем настройки и смотрим сетевые интерфейсы:
Первый сетевой интерфейс enp0s3 получил ip-адрес 192.168.110.8 от домашнего роутера (этот адрес закреплен постоянно для router ). Второму сетевому интерфейсу enp0s8 мы назначили ip-адрес 192.168.30.1 .
Настройка сети для pc-1, pc-2 и server
Сначала для виртуальной машины pc-1 . Смотрим, как называются сетевые интерфейсы в системе:
Открываем на редактирование файл /etc/netplan/01-netcfg.yaml :
Применяем настройки и смотрим сетевые интерфейсы:
Для виртуальных машин pc-2 и server все будет аналогично, так что не буду описывать подробно. Для примера — виртуальной машине pc-2 мы назначили ip-адрес 192.168.30.3/24 :
Настройка интернет-шлюза
Виртуальная машина router должна обеспечивать выход в интернет для всех компьютеров из локальной сети 192.168.30.0/24 . По умолчанию транзитный трафик отключен, так что редактируем файл /etc/sysctl.conf :
Чтобы внесенные изменения вступили в силу:
После этого настраиваем netfilter с помощью утилиты iptables :
И смотрим, что получилось:
Мы разрешили ходить транзитным пакетам для нашего диапазона ip-адресов, а всё остальное запретили. Теперь настроим SNAT (подмена адреса источника), что позволит всем компьютерам сети выходить в интернет, используя единственный ip-адрес 192.168.110.8 .
И смотрим, что получилось:
Теперь проверяем наличие интернета на виртуальных машинах pc-1 , pc-2 и server :
Доступ внутрь сети
Давайте теперь посмотрим, как получить доступ извне к компьютеру внутри сети 192.168.30.0/24 . Установим на виртуальную машину server SSH-сервер:
А на виртуальной машине router будем отбирать tcp-пакеты, которые приходят на интерфейс enp0s3 на порт 2222 и отправлять эти пакеты виртуальной машине server на порт 22, заменяя в пакетах пункт назначения на 192.168.30.254 :
Смотрим, что получилось:
Теперь попробуем с физического компьютера установить ssh-соединение с виртуальной машиной server . Открываем PowerShell и выполняем команду:
Мы в команде указываем порт 2222 и ip-адрес виртуальной машины router — 192.168.110.8 , которая находится в одной сети 192.168.110.0/24 с физическим компьютером. А виртуальная машина router пробрасывает это соединение с интерфейса enp0s3 на интерфейс enp0s8 и дальше — виртуальной машине server , но уже на порт 22.
Сохранение правил netfilter
Созданные с помощью утилиты iptables правила пропадут при перезагрузке. Так что их нужно сохранить и восстанавливать при перезагрузке. В этом нам поможет пакет iptables-persistent :
При установке пакета будет предложено сохранить текущие правила iptables :
- в файл /etc/iptables/rules.v4 для протокола IPv4
- в файл /etc/iptables/rules.v6 для протокола IPv6
После установки пакета будет добавлена новая служба netfilter-persistent.service , которая при загрузке системы будет восстанавливать созданные нами правила:
При добавлении новых правил, надо сохранить конфигурацию с помощью команды
Восстановить ранее сохраненную конфигурацию можно с помощью команды
Источник
Домашний интернет-шлюз. Начальная настройка 6-портового мини-компьютера на Ubuntu Server 20.04 LTS
Введение
Обновил я интернет до 500 Мбит/с, и пришло время заняться 100 Мбитным сервером, который работал на Pentium 3 и был уже на грани. Выбор пал на китайского зверя. Все, что нужно — имеется, потребление в обычном режиме не превышает 15W, запас производительности для дополнительных задач есть.
Установку ОС расписывать не буду («ОК — Далее — Далее»), отмечу только, что при установке требуется сконфигурировать хотя бы один сетевой интерфейс для доступа в интернет.
Для удобства я использую Midnight Commander и его текстовый редактор. Работать будем от root-пользователя:
Итак, у нас есть установленная Ubuntu Server, начнем с конфигурации остальных сетевых интерфейсов.
Netplan
В последних версиях Ubuntu появилась утилита Netplan, позволяющая настроить сеть в унифицированном формате и выбирать сетевой менеджер для работы. По умолчанию используется Systemd-networkd, я же выбрал NetworkManager, так как установил Web-интерфейс Cockpit, который использует именно NM для отображения части информации.
Синтаксис конфигурации Netplan очень строгий и лишний пробел или табуляция может вызвать ошибку.
Подробнее о функционале уже расписывали habr.com/ru/post/448400, так же различные примеры есть на сайте netplan.io/examples.
Посмотрим названия интерфейсов:
Перейдем в директорию /etc/netplan и откроем (F4 для МС) файл 50-cloud-init.yaml. Для сетевого интерфейса, который будет использоваться для подключения к интернету, определим получение настроек по dhcp (dhcp4: true). В моем случае это enp6s0. Для остальных укажем false и добавим параметр optional: true, т.к. интерфейс может быть ни к чему не подключен.
Для объединения интерфейсов в локальную сеть я использовал bridge, но, возможно, правильнее было бы использовать vlan. Создадим мост lan-br, зададим общий IP-адрес, DNS-сервер и пропишем объединяемые интерфейсы:
У меня будет собственный DNS-сервер, поэтому указываю адрес своего сервера в поле nameservers, можно указать например 8.8.8.8 (Google). Указываем версию и менеджер. В итоге должно получиться примерно так:
Сохраняем файл и проверяем/применяем конфигурацию:
DHCP-сервер
Настроим DHCP-сервер для того, чтобы клиенты могли получать IP-адреса автоматически.
В файле /etc/default/isc-dhcp-server правим строчку:
Переходим в /etc/dhcp, открываем dhcpd.conf и прописываем настройки:
Теперь клиенты должны получать адреса автоматически.
UFW (Uncomplicated Firewall) — инструмент для более легкой настройки iptables. Настроим фаервол и пересылку пакетов между интерфейсами. Переходим в/etc/ufw и в файле sysctl.conf раскомментируем строку:
Если Вы подключены через ssh перед началом откройте 22 порт:
Включим UFW, проверим состояние:
Зададим политики по умолчанию:
Разрешим доступ из локальной сети:
Настроим NAT. Откроем файл before.rules и пишем следующее перед блоком *filter:
Сохраняемся и перезапускаем ufw:
Проверим iptables, должна появиться наша строчка:
На этом базовую настройку сервера можно считать законченной.
Заключение
Я не поднимал вопрос настройки DNS-сервера, так как планирую выпустить вторую часть, где будет изложена настройка Dnscrypt-proxy в роли DNS-сервера для локальной сети.
Источник
Ubuntu Documentation
1. Setting up an Ubuntu Wired/Wireless Router
1.1. Preface
This article is intended for intermediate and advanced users who would like to set up an Ubuntu installation acting as a router at home or in their office. The end result is a powerful router that can provide functionality similar to popular products (for example, the Linksys WRT54G).
1.2. Scripted wired:wired router
I (user id Snake_Byte) created a python script a while back that sets up a wired router for you given some basic info (check the readme).
Tested on Karmic and Lucid, let me know if you have any problems. I want to start a GUI project to make this simpler, and incorporate wireless features if anyone is interested, we can get a repo going.
[Note added: The script included in this page at the link below assumes different addresses than on the rest of the page and MUST BE EDITED to replace the assumed IP address and range for your private network, and to remover the examples, before use. Furthermore, for recent versions of Debian and Ubuntu, the assumed dhcp3-server must be replaced by a more modern server, such as isc-dhcp-server, and all references to dhcp3 and dhcp3 should be replaced by just dhcp once you do so. Thus you should LOOK OVER ALL OF THE CONTENTS of the directory tree after unpacking the tar file — so not just blindly execute it before doing so.]
You can get it here:
1.3. Network Manager
This tool is perfect for simple networking problems, especially for laptop users. It is not appropriate for setting up a router, even though it does have a very basic internet connection sharing capability.
1.3.1. Typical Example
Home Office
The basis is one PC connected to a broadband internet connection. Additional devices:
- network printer
- wifi PDA
- laptop
Some of these devices should be able to communicate with each other, some should be allowed to communicate with the internet. Some are wired, and some are wireless. With this guide, your PC can share the internet over additional network interfaces, such as wireless cards and ethernet cards.
University
Single PC on a university LAN. Additional devices:
- X-Box running mythbuntu
- Wifi mobile phone
- laptops
1.3.1.1. Quick and Dirty
If you would like to try to do the same thing the ‘quick and dirty’ way, see EasyRouter, a much quicker method with much less flexibility.
1.4. Technical Overview
The router that will be created is an Internet gateway for wired and/or wireless clients to share an internet connection with one IP address.
The essential components are:
routing of packets from your local networks to the internet, with IP_masquerading
This router can also provide:
- A firewall
- port forwarding
2. Prerequisites
2.1. Internet Connection
This is not strictly necessary, but is probably the reason you are following this article. You can set up a router in an isolated network using these instructions, but you will likely have specialist requirements, and need to make changes.
2.2. Router Hardware
2.2.1. Use your desktop PC
If you have a recent PC, bought in the last two years, it probably has enough horsepower to run all your normal applications and act as a router at the same time.
2.2.2. Dedicated Hardware
You’ll need a dedicated computer to act as the router. The computer can use old hardware and having the minimum requirements to install Ubuntu should suffice. The author of this article runs his router on a P3 600mhz processor with 256MB of RAM. You are encouraged use this as a server for other applications perhaps by installing postfix, apache, mysql, and/or samba. This guide recommends a server installation of Ubuntu, but there’s no reason why a desktop installation wouldn’t work. If you plan to be able to access the router remotely, install ssh before proceeding.
The following needs to be physically installed and recognized by the kernel on your router:
- A network adapter
For a wired network,
- Another network adapter, typically an ethernet port on a motherboard, or PCI card.
For a wireless network,
- A wireless network adapter
Ideally it should be able run in «master» mode, although «ad-hoc» mode might be good enough. Cards and chipsets which can work in master mode (otherwise known as access point or ap mode), are listed at the Linux Wireless Project.
sudo ip link set dev down && sudo iwconfig mode master should not return an error; but some cards take extra commands to set master mode. mac80211 compatible drivers can run cards in master mode. Pay careful attention to what hardware you buy.
If your wireless network adapter is not recognized by your server installation of Ubuntu, it may use the madwifi chipset (like the D-Link DWL-G520). Please visit Router/Madwifi for more information.
Running ip addr will show you what network interfaces are available.
2.2.3. Terminology
interface is used to mean the operating system’s name for a place which sends or receives data packets. It is often, but not necessarily, the same as a device. An interface may have several devices associated (e.g. a bridge), or a single device may have several interfaces. device will refer here to the bit of hardware dealing with your network connections.
3. Internal Network Information
Here are the values we’ll use to set up your internal network. Advanced users use caution when changing them as the changes will need to be reflected in all further router configuration.
Firstly, discover the IP address of your internet-connected interface. If you are plugged into a business or academic LAN, this is very likely to be given by:
ip addr show eth0
For a home broadband user, it may be a ppp interface; and a wireless user could have any number of interface names, such as ethX, wlanX, athX, where X is a digit.
Be aware that it is important to use different numbers below to the one given to your internet device. This is probably the case already, but if you are not directly connected to the internet, you may be on a LAN with the same address range. If you already have a broadband router, for example, it might have given you the 192.168.0.2 address, and kept 192.168.0.1 for itself. If so, change the third digit (0) to another number (and do so throughout the rest of this tutorial).
Router
192.168.0.1
192.168.0.0/24
Broadcast
192.168.0.255
Clients
Addresses
192.168.0.2 — 192.168.0.254
Prefix length
Broadcast
192.168.0.255
192.168.0.1
4. Setting Up Your Network Interfaces
4.1. Device Naming Overview
Network Device
Internal or External Network
Description
eth0
External
Network adapter connected to an external network (your broadband connection)
eth1
Internal
Network adapter connected to a hub or switch
wlan0
Internal
Wireless network adapter
br0
Internal
Network bridge between eth1 and wlan0 that will treat the two like one device
It is important to note that the names of the network interfaces above ( eth0 , eth1 , and wlan0 ) are used as convention. It is very likely that your router will recognize its devices under different names (for example, madwifi calls its wireless device ath0 ). Please substitute the names of your device accordingly. For information about how to change the names of your network devices, try man iftab.
4.2. Taking a Backup
Issue the following command to take a backup of your current network configuration:
4.3. Configuring the External Network Interface
4.3.1. Setting up External Network Interface
Here, we configure the Ubuntu networking system to bring the the local loopback and external network interfaces up by editing /etc/networking/interfaces. The primary goal here is to set up your external network interface ( eth0 , or whatever you’re using in place of it) to be brought up by the networking subsystem. The examples below are only for the most basic setups. If your setup requires additional configuration, for example you need to setup ADSL with PPPoE, adapt the following examples so that the end result is your external network interface connected to the Internet.
4.3.1.1. For Dynamic IP Addresses (DHCP) Only
Open /etc/network/interfaces with your favourite editor. Delete everything and paste in what is below. Follow the commented out instructions carefully.
4.3.1.2. For PPPoE connection with dynamic IP address only
4.3.1.3. For Static IP Address Only
Open /etc/network/interfaces with your favourite editor. Delete everything and paste in what is below. Follow the commented out instructions carefully.
Now, set up your DNS servers as given to you by your service provider in /etc/resolv.conf, which should look something like this
You can visit the Ubuntu Server Guide — Network Configuration documentation for more information
4.3.2. Testing Connectivity
Reload the network configuration and test for connectivity,
And if all goes well something similar should return:
4.4. Configuring the Internal Network Interfaces
4.4.1. Wired Only
Append the following to /etc/network/interfaces and follow the commented out instructions carefully.
Your internal network interface is: eth1 (or whatever you’re using in place of it)
4.4.2. Wireless Only
If you plan on using WEP, generate a network key,
Append the following to /etc/network/interfaces and follow the commented out instructions carefully.
Your internal network interface is: wlan0 (or whatever you’re using in place of it)
4.4.3. Both Wired and Wireless
First install the necessary tools to create a network bridge,
If you plan on using WEP, generate a network key,
Append the following to /etc/network/interfaces and follow the commented out instructions carefully.
Your internal network interface is: br0
4.5. Enable IP forwarding and Masquerading
Doing the above might not be enough to make the Ubuntu machine a real router which does NAT (Network Address Translation) and IP Forwarding. The following script configures the Kernel IPTable and IP forwarding. You will have to configure at least the script’s 2 variables; the 1st is the external network interface; the 2nd is the internal network interface.
The script was originally from a Ubuntu router guide forum article which has 2 internal network interfaces. What’s showing below uses only 1 internal network interface. You will have to modify the script manually or use the script in the Ubuntu router guide forum article if you need to configure 2 internal network interfaces.
After configuring the 2 variables, save the script below as nat.sh and make it executable by doing
Now, test the script by running as root
Investigate the messages from the console output to see if any error happened. If everything looks fine, use another host in the internal network to test if it can access the external network (presumably the Internet). A quick way to test is pinging Google public DNS from the console.
If ping responds, make our new script bootable so we don’t have to run the script every time we restart.
As a final test, restart your computer and test to see if you still have the same functionality. If so then congratulations! If not then make sure you followed the above correctly so the script is bootable.
Источник