Linux as gateway server

Интернет шлюз на Ubuntu / Debian

Обновлено

Обновлено: 16.02.2023 Опубликовано: 23.01.2019

  1. Включение redirect на уровне ядра.
  2. Настройкой брандмауэра.
  3. Опционально, настройка проброса портов.

Настройка ядра системы

sysctl -p /etc/sysctl.d/gateway.conf

Если мы получим ошибку sysctl command not found, либо нужно установить пакет:

либо перезайти в режим суперпользователя с загрузкой его окружения:

В случае с единственным сетевым адаптером больше ничего делать не потребуется — Ubuntu начнет работать как Интернет-шлюз.

В случае с несколькими сетевыми адаптерами, настраиваем сетевой экран.

Настройка брандмауэра

Как правило, управление брандмауэром netfilter в Linux на базе Debian выполняется с помощью утилиты iptables.

Iptables

Предположим, что сеть Интернет настроена через интерфейс ens160, а локальная сеть доступна через ens32. Создадим правило:

iptables -t nat -I POSTROUTING -o ens160 -j MASQUERADE

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

iptables -I FORWARD -i ens32 -o ens160 -m state —state RELATED,ESTABLISHED -j ACCEPT

iptables -I FORWARD -i ens32 -o ens160 -j ACCEPT

* интерфейс ens160, как условились ранее, используется для доступа в Интернет. Интерфейс ens32 — локальная сеть.

Сохраняем настройки iptables:

apt install iptables-persistent

Проброс портов (Port Forwarding)

Необходим для перенаправление сетевых запросов на сервер, стоящий за NAT и не имеющий прямого выхода во внешнюю сеть.

Iptables

Настройка выполняется двумя командами:

iptables -t nat -A PREROUTING -p tcp -m tcp -d 10.8.232.111 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -t nat -A POSTROUTING -p tcp -m tcp -s 192.168.0.15 —sport 8025 -j SNAT —to-source 10.8.232.111:25

iptables -t nat -A PREROUTING -p tcp -i eth0 —dport 25 -j DNAT —to-destination 192.168.0.15:8025

iptables -A FORWARD -p tcp -d 192.168.0.15 —dport 8025 -m state —state NEW,ESTABLISHED,RELATED -j ACCEPT

* где eth0 — внешний сетевой интерфейс.

iptables -I INPUT 1 -p tcp —dport 8025 -j ACCEPT

* обратите внимание, что мы разрешаем порт, на который переводим запрос, так как цепочки POSTROUTING и PREROUTING работают до цепочки FILTER, а потому открывать нужно не входящий порт (25), а тот, на который назначается пакет (8025).

Не забываем сохранить правила:

Источник

How can I use Linux as a Gateway?

NOTE: If client devices ( computer B in this example) want to obtain internet through the gateway computer, maybe they still need to configure nameserver resolution. This is not explained here (a gateway does not necessarily serve internet).

I am trying to understand the fundamentals of networks routing.
So I am experimenting with my LAN (I don’t need internet for now, just LAN communications). I know the network configuration matters are a rather complex thing, but I am just trying to make a computer (say A) to act as a gateway for another (say B) (both running Ubuntu Linux).
I only need B to be capable to reach the router, that is only reachable for A. This is the case:

Router for computer A --> 192.168.0.1 Computer A - eth0 --> 192.168.0.2 Computer A - eth1 --> 192.168.1.1 Computer B - eth0 --> 192.168.1.2 

Computer A connects fine to router.
Computer A and B connect fine (ping, SSH. etc) between them.
Computer B can not reach the router for computer A. I was thinking that just adding on B Computer A as default gateway and activating IP Forwarding on A would make B to be able to reach the router for A:

luis@ComputerB:~$ sudo route add default gw 192.168.1.1 luis@ComputerB:~$ sudo routel target gateway source proto scope dev tbl 127.0.0.0 broadcast 127.0.0.1 kernel link lo local 127.0.0.0 8 local 127.0.0.1 kernel host lo local 127.0.0.1 local 127.0.0.1 kernel host lo local 127.255.255.255 broadcast 127.0.0.1 kernel link lo local 192.168.1.0 broadcast 192.168.1.2 kernel link eth0 local 192.168.1.2 local 192.168.1.2 kernel host eth0 local 192.168.1.255 broadcast 192.168.1.2 kernel link eth0 local default 192.168.1.1 eth0 169.254.0.0 16 link eth0 192.168.1.0 24 192.168.1.2 kernel link eth0 
root@ComputerA:~$ echo 1 > /proc/sys/net/ipv4/ip_forward 
luis@ComputerB:~$ ping 192.168.0.1 PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data. ^C 

(No ping response) Is this the correct procedure to make a computer running Linux to act as a gateway for another computer in a simple manner?

Читайте также:  Разгон видеокарты linux mint

Источник

Setup A Basic Gateway Server on Linux

This was tested on Ubuntu 14.04.1, items referenced below will be relative to locations in Ubuntu 14.04.1. The setup though across Linux distros should be the same other then paths. I will update this posting with location paths as they become known to me

-UPDATE: Additional notes added for Fedora 22
-UPDATE: This his now been tested on Ubuntu Server 14.04.1, 14.04.3 and Fedora 22. Documentation is complete to allow full setups on either of the 3 systems

This setup is a basic setup of a Gateway server. Note that this is not a tutorial on how to actually secure or properly secure the gateway. The intention of this tutorial is simply to get it working. It will allow anything to go through and work. The idea of this tutorial is to cator to first-time setups and people who would like to just tinker around.

Terminology

For this tutorial we have 2 devices — the Gateway Host and the Internal Host . The Internal Host being the machine behind the Gateway Host and relies on it in order to filter/forward/network all of the Internal Hosts traffic to the outside world

Setup the Gateway Host

Assumingly your Gateway Host has 2 network cards or connections of some kind. This is needed so that traffic from your Internal Host will come in one card of the Gateway Host and then sent out the other of the Gateway Host .

1. Configure Network Cards

Enter the following command:

This will display all enabled and disabled cards. Find the card that will service your Internal Host . This will likely have a name like eth0 or eth1 on Ubuntu.

Читайте также:  Редактор файлов linux windows

Then execute the following command. eth0 with the name of the card that services the Internal Host . Note also that as a newly enabled card we have statically assigned it an IP address 192.168.10.1 so that it can be routed to by the Internal Host .

ifconfig eth0 192.168.10.1 up 

2. Enable Kernel Forwarding

Kernel forwarding needs to be enabled in order for data to travel between your different network cards. This can be done as so on Ubuntu:

sudo cp /etc/sysctl.conf /etc/sysctl.conf.bak && sudo nano /etc/sysctl.conf 

This will create a backup and open the sysctl.conf file in nano. Within this conf file, search for and uncomment the following line:

This will enable Kernel Forwarding. On Ubuntu you will need to restart your Gateway Host now for the change to take effect.

On Fedora, you can enable kernel forwarding in a similar way, or use the shortcut command:

echo "1" >/proc/sys/net/ipv4/ip_forward 

On fedora this may or may not need a restart

3. Setup NAT Routing

NAT Routing takes a few special commands using iptables . These commands will let everything back and forth through your Gateway Host so it is important to note that this will not secure your Internal Host whatsoever

Enter the following iptables commands in order:

# flush all rules in fulter and nat tables iptables --flush iptables --table nat --flush iptables --delete-chain # delete all chains that are not in default filter and nat table iptables --table nat --delete-chain iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE iptables --append FORWARD --in-interface eth1 -j ACCEPT 

Note again in the above commands to replace eth0 and eth1 with the appropriate card names. eth1 in the above example is the card serving the Internal Host and eth0 is connected to the outside network.

It is also important to note that the above rules only allows the Internal Host to have access to the outside world. If your Internal Host is offering services through the Gateway Host , additional rules will be needed.
To allow external machines to connect to the Internal Host add the following rules:

iptables --table nat -A PREROUTING -i eth0 -j DNAT --to-destination 192.168.10.2 iptables --append FORWARD --in-interface eth0 -j ACCEPT #let everything through 

This will allow connections to come in to the Internal Host . For this example, our Internal Host ‘s IP is 192.168.10.2 which you can see in the first rule above is the —to-destination meaning all traffic directed at the Gateway Host will be redirected to the Internal Host .
NOTE: With the second command listed above will allow everything to be redirected to the internal host. For a more secure procedure, replace this rule with more finite FORWARD table rules using iptables.

Читайте также:  Linux создать файл большого размера

Setup the Internal Host

Now all we have to do is tell our Internal Host to resolve its IP’s with our configured Gateway Host .

1. Configure Network Cards

Again execute the following command to determine the name of your network card that is connected to the Gateway Host

Then execute the following command replacing eth0 with the name of the card connected to the Gateway Host

ifconfig eth0 192.168.10.2 up 

Note that the ip address we assigned here belongs to the subnet of our Gateway Host this is an important factor as our Gateway Host only knows how to route data from our 192.168.10.0 subnet to the outside world.

If your Internal Host only has a single network card, it may be already enabled and have an IP assigned to it. To change the IP to be part of the subnet run the following command

this will disable the network card. Use the command from earlier now to re-enable it and assign an IP.

If your Internal Host has multiple cards and some are connected to the internet, you will probably want to disable them so as to be able to test if your Gateway Host has been configured correctly. You can disable those cards with the ifconfig eth0 down command mentioned earlier, replacing the eth0 with the name of the card

2. Configure Routing

Now we want to route all traffic from our Internal Host to the Gateway Host . To do this we simply change the Internal Hosts default resolving IP to the Gateway Hosts IP. We do this with the following command:

route add default gw 192.168.10.1 

3. Check Nameserver Resolution Matches

Fedora 22

On Fedora you will need to make sure the Internal Host and the Gateway Host both have the same content written in the /etc/resolv.conf file. Most importantly you want to copy the contents of the Gateway Hosts resolve.conf into the Internal Hosts resolve.conf file. Otherwise you will have troubles making DNS calls from your Internal Host . A copy and paste and a possible reboot is all that is needed.

Ubuntu Server 14.04.1 — 14.04.3

On Ubuntu Server you will need to do the same as Fedora except Ubuntu automates the process more.
To view the nameservers on the Gateway Host enter the following command:

This will display the nameserver IP that needs to be copied to the Internal Host

To update the Internal Host ‘s nameservers, run the following commands

cd /etc/resolvconf/resolv.conf.d sudo cp -p head head.orig #create a backup copy sudo nano head 

In the now opened file type the following:

Hit Ctrl+X to save and then type:

This will cause Ubuntu to reload its nameservers from the file that was edited.

Ben Soer

Источник

Оцените статью
Adblock
detector