Red hat linux forward

18.5. FORWARD and NAT Rules

Most ISPs provide only a limited number of publicly routable IP addresses to the organizations they serve.

Administrators must, therefore, find alternative ways to share access to Internet services without giving public IP addresses to every node on the LAN. Using private IP addresses is the most common way of allowing all nodes on a LAN to properly access internal and external network services.

Edge routers (such as firewalls) can receive incoming transmissions from the Internet and route the packets to the intended LAN node. At the same time, firewalls/gateways can also route outgoing requests from a LAN node to the remote Internet service.

This forwarding of network traffic can become dangerous at times, especially with the availability of modern cracking tools that can spoof internal IP addresses and make the remote attacker’s machine act as a node on your LAN.

To prevent this, iptables provides routing and forwarding policies that can be implemented to prevent abnormal usage of network resources.

The FORWARD chain allows an administrator to control where packets can be routed within a LAN. For example, to allow forwarding for the entire LAN (assuming the firewall/gateway is assigned an internal IP address on eth1), use the following rules:

[root@myServer ~ ] # iptables -A FORWARD -i eth1 -j ACCEPT [root@myServer ~ ] # iptables -A FORWARD -o eth1 -j ACCEPT

This rule gives systems behind the firewall/gateway access to the internal network. The gateway routes packets from one LAN node to its intended destination node, passing all packets through its eth1 device.

By default, the IPv4 policy in Red Hat Enterprise Linux kernels disables support for IP forwarding. This prevents machines that run Red Hat Enterprise Linux from functioning as dedicated edge routers. To enable IP forwarding, use the following command:

[root@myServer ~ ] # sysctl -w net.ipv4.ip_forward=1

This configuration change is only valid for the current session; it does not persist beyond a reboot or network service restart. To permanently set IP forwarding, edit the /etc/sysctl.conf file as follows:

[root@myServer ~ ] # sysctl -p /etc/sysctl.conf

18.5.1. Postrouting and IP Masquerading

Accepting forwarded packets via the firewall’s internal IP device allows LAN nodes to communicate with each other; however they still cannot communicate externally to the Internet.

To allow LAN nodes with private IP addresses to communicate with external public networks, configure the firewall for IP masquerading, which masks requests from LAN nodes with the IP address of the firewall’s external device (in this case, eth0):

[root@myServer ~ ] # iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

This rule uses the NAT packet matching table ( -t nat ) and specifies the built-in POSTROUTING chain for NAT ( -A POSTROUTING ) on the firewall’s external networking device ( -o eth0 ).

Читайте также:  Linux mint блокировка экрана комбинация клавиш

The -j MASQUERADE target is specified to mask the private IP address of a node with the external IP address of the firewall/gateway.

Источник

Red hat linux forward

Многие организации получают у своих провайдеров лишь несколько маршрутизируемых в Интернете IP-адресов. Из-за этого ограничения администраторы вынуждены придумывать способы доступа к Интернет-службам, не требующие назначения реальных IP-адресов каждому узлу локальной сети. Использование частных IP-адресов — это распространенный способ обеспечить доступ к внешним и внутренним сетевым службам для всех узлов локальной сети. Пограничные маршрутизаторы (например, брандмауэры) могут получать данные, передаваемые из Интернета, и маршрутизировать пакеты к целевому узлу в локальной сети. В то же время, маршрутизаторы/брандмауэры также могут маршрутизировать исходящие запросы от локального узла к удалённой Интернет-службе. Такое перенаправление сетевого трафика иногда может быть опасным, особенно, учитывая возможности современных средств взлома, способных подменять внутренние IP-адреса и представлять компьютер злоумышленника узлом вашей сети. Чтобы предотвратить незаконное использование сетевых ресурсов таким образом, iptables предоставляет политики маршрутизации и пересылки пакетов.

Политика FORWARD позволяет администратору управлять тем, как пакеты маршрутизируются в локальной сети. Например, чтобы разрешить маршрутизацию для всей локальной сети (предположим, что брандмауэру/шлюзу назначен внутренний IP-адрес на интерфейсе eth1), можно задать такие правила:

iptables -A FORWARD -i eth1 -j ACCEPT iptables -A FORWARD -o eth1 -j ACCEPT

Это правило даёт компьютерам за брандмауэром/шлюзом доступ к внутренней сети. Шлюз маршрутизирует пакеты от одного узла в локальной сети к целевому узлу назначения, передавая все пакеты через устройство eth1 .

По умолчанию, политика IPv4 в ядре Red Hat Enterprise Linux отключает пересылку IP, что не даёт компьютерам с Red Hat Enterprise Linux выполнять функции маршрутизаторов. Чтобы включить пересылку IP, выполните следующую команду:

sysctl -w net.ipv4.ip_forward=1

Если эта команда исполняется в командной строке, она не будет действовать после перезагрузки. Чтобы пересылка работала постоянно, отредактируйте файл /etc/sysctl.conf . Найдите и отредактируйте следующую строку, заменив 0 на 1 :

Чтобы изменения в файле sysctl.conf вступили в силу, выполните следующую команду:

Разрешение принимать перенаправляемые пакеты через защищенный брандмауэром внутренний интерфейс позволяет узлам локальной сети взаимодействовать друг с другом, при этом обращаться к внешним узлам в Интернете они всё равно не смогут. Чтобы узлы локальной сети с частными IP-адресами могли связываться с внешними сетями, настройте на брандмауэре подмену IP , которая замаскирует узлы локальной сети под IP-адресом внешнего интерфейса брандмауэра (в данном случае, eth0):

Читайте также:  Oracle linux network restart

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Это правило использует таблицу сопоставления пакетов NAT ( -t nat ) и выбирает встроенную цепочку POSTROUTING для NAT ( -A POSTROUTING ) на внешнем сетевом интерфейсе брандмауэра ( -o eth0 ). Цепочка POSTROUTING позволяет изменить пакеты на выходе из внешнего устройства брандмауэра. Назначение -j MASQUERADE указывается, чтобы замаскировать частный IP-адрес узла за внешним IP-адресом брандмауэра/шлюза.

Если в вашей внутренней есть сервер, который вы хотите сделать доступным снаружи, вы можете, используя назначение -j DNAT цепочки PREROUTING в NAT, указать целевой IP-адрес и порт, входящие пакеты для которого будут перенаправляться внутренней службе. Например, если вы хотите перенаправить входящие HTTP-запросы выделенному HTTP-серверу Apache, работающему на компьютере 172.31.0.23, выполните следующую команду:

iptables -t nat -A PREROUTING -i eth0 -p tcp —dport 80 -j DNAT \ —to 172.31.0.23:80

Это правило определяет, что NAT-таблица использует встроенную цепочку PREROUTING для перенаправления входящих HTTP-запросов исключительно по указанному IP-адресу 172.31.0.23.

Если в вашей цепочке FORWARD политика по умолчанию DROP, вы должны добавить правило, перенаправляющее входящие HTTP-запросы с тем, чтобы была возможна NAT-маршрутизация к целевому узлу. Для этого выполните следующую команду:

iptables -A FORWARD -i eth0 -p tcp —dport 80 -d 172.31.0.23 -j ACCEPT

Это правило позволяет перенаправлять входящие HTTP-запросы от брандмауэра к целевому HTTP-серверу Apache, расположенному за брандмауэром.

Правила iptables также могут маршрутизировать трафик к определённым компьютерам, например, к выделенному HTTP или FTP-серверу в демилитаризованной зоне (DeMilitarized Zone, DMZ ) — специальной локальной подсети, выделенной для серверов, открытых для внешних сетей, таких как Интернет. Например, в следующем правиле, чтобы входящие HTTP-запросы маршрутизировались к выделенному HTTP-серверу с IP-адресом 10.0.4.2 (вне локальной сети 192.168.1.0/24), NAT обращается к таблице PREROUTING и передаёт пакеты по назначению:

iptables -t nat -A PREROUTING -i eth0 -p tcp —dport 80 -j DNAT \ —to-destination 10.0.4.2:80

Эта команда маршрутизирует все HTTP-соединения из внешней сети к HTTP-серверу, отделённому от остальной внутренней сети. Такое разделение сети может оказаться безопаснее, чем разрешение HTTP-соединений с компьютерами в локальной сети. Если HTTP-сервер настроен на защищённые соединения, также необходимо перенаправлять порт 443.

Источник

2.8.5. FORWARD and NAT Rules

Most ISPs provide only a limited number of publicly routable IP addresses to the organizations they serve.

Administrators must, therefore, find alternative ways to share access to Internet services without giving public IP addresses to every node on the LAN. Using private IP addresses is the most common way of allowing all nodes on a LAN to properly access internal and external network services.

Читайте также:  Android sdk command line tools linux

Edge routers (such as firewalls) can receive incoming transmissions from the Internet and route the packets to the intended LAN node. At the same time, firewalls/gateways can also route outgoing requests from a LAN node to the remote Internet service.

This forwarding of network traffic can become dangerous at times, especially with the availability of modern cracking tools that can spoof internal IP addresses and make the remote attacker’s machine act as a node on your LAN.

To prevent this, iptables provides routing and forwarding policies that can be implemented to prevent abnormal usage of network resources.

The FORWARD chain allows an administrator to control where packets can be routed within a LAN. For example, to allow forwarding for the entire LAN (assuming the firewall/gateway is assigned an internal IP address on eth1), use the following rules:

~]# iptables -A FORWARD -i eth1 -j ACCEPT ~]# iptables -A FORWARD -o eth1 -j ACCEPT

This rule gives systems behind the firewall/gateway access to the internal network. The gateway routes packets from one LAN node to its intended destination node, passing all packets through its eth1 device.

By default, the IPv4 policy in Red Hat Enterprise Linux kernels disables support for IP forwarding. This prevents machines that run Red Hat Enterprise Linux from functioning as dedicated edge routers. To enable IP forwarding, use the following command as the root user:

~]# sysctl -w net.ipv4.ip_forward=1 net.ipv4.ip_forward = 1

This configuration change is only valid for the current session; it does not persist beyond a reboot or network service restart. To permanently set IP forwarding, edit the /etc/sysctl.conf file as follows:

~]# sysctl -p /etc/sysctl.conf net.ipv4.ip_forward = 1 net.ipv4.conf.default.rp_filter = 1 net.ipv4.conf.default.accept_source_route = 0 [output truncated]

2.8.5.1. Postrouting and IP Masquerading

Accepting forwarded packets via the firewall’s internal IP device allows LAN nodes to communicate with each other; however they still cannot communicate externally to the Internet.

To allow LAN nodes with private IP addresses to communicate with external public networks, configure the firewall for IP masquerading, which masks requests from LAN nodes with the IP address of the firewall’s external device (in this case, eth0):

~]# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

This rule uses the NAT packet matching table ( -t nat ) and specifies the built-in POSTROUTING chain for NAT ( -A POSTROUTING ) on the firewall’s external networking device ( -o eth0 ).

The -j MASQUERADE target is specified to mask the private IP address of a node with the external IP address of the firewall/gateway.

Источник

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