Sorry, you have been blocked
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7a24f7e00ecb2d7f • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Как отключить / включить переадресацию IP в Linux
Может потребоваться настроить переадресацию IP на Система Linux в определенных сценариях. Если сервер Linux действует как брандмауэр, маршрутизатор или устройство NAT, он должен быть способен пересылать пакеты, предназначенные для других пунктов назначения (кроме него самого).
И наоборот, переадресацию IP обычно следует отключать, если вы не используете одну из вышеупомянутых конфигураций. Обычно вы не хотите, чтобы ваша система тратила впустую полосу пропускания или ресурсы для пересылки пакетов в другое место, если только она не предназначена для этой работы.
В этом руководстве мы рассмотрим пошаговые инструкции по включению или отключению переадресации IP через командная строка Примеры. Вы можете применить эти команды к любым основным Дистрибутив Linux , включая популярные варианты, такие как Ubuntu и Красная Шапка .
В этом уроке вы узнаете:
- Как проверить текущий статус IP-переадресации
- Как включить или отключить переадресацию IP
- Общие шаги по устранению неполадок при переадресации IP
Проверка статуса переадресации IP и включение настройки
Категория | Требования, условные обозначения или используемая версия программного обеспечения |
---|---|
Система | Любой Дистрибутив Linux |
Программного обеспечения | N / A |
Другой | Привилегированный доступ к вашей системе Linux с правами root или через судо команда. |
Условные обозначения | # — требует данных команды linux для выполнения с привилегиями root либо непосредственно как пользователь root, либо с использованием судо команда $ — требует данных команды linux будет выполняться как обычный непривилегированный пользователь |
Проверить текущий статус переадресации IP
Большинство систем смогут использовать sysctl команда, которая может применять переменные ядра. Следовательно, вы можете использовать следующие sysctl команда, чтобы проверить, включена или отключена переадресация IP.
В приведенном выше примере net.ipv4.ip_forward настройка ядра — 0. Значит, выключено. Если бы он был установлен на 1, это означало бы, что он включен.
Этот параметр также можно просмотреть внутри /proc/sys/net/ipv4/ip_forward файл в системах с systemd или любой другой системой инициализации.
Включение или отключение переадресации IP
Вы можете использовать следующие sysctl команда, чтобы включить или отключить переадресацию IP в вашей системе.
Вы также можете изменить настройку внутри /proc/sys/net/ipv4/ip_forward , чтобы включить или выключить настройку.
Использование любого из описанных выше методов не сделает изменение постоянным. Чтобы новый параметр сохранился после перезагрузки, необходимо отредактировать /etc/sysctl.conf файл.
Добавьте одну из следующих строк в конец файла, в зависимости от того, хотите ли вы, чтобы переадресация IP была отключена или включена соответственно. Затем сохраните изменения в этом файле. Параметр будет постоянным после перезагрузки.
После редактирования файла вы можете запустить следующую команду, чтобы изменения сразу вступили в силу.
Поиск проблемы
Обратите внимание, что sysctl команда, если служба в данный момент не запущена. Проверить статус sysctl с помощью этой команды.
Сервис должен сказать, что он активен. Если нет, запустите службу с помощью этой команды:
При установке Linux без systemd проверка статуса sysctl будет другим. Например, OpenRC использует эту команду:
Если вы успешно включили переадресацию IP (проверено проверкой переменной ядра после перезагрузка), но вы по-прежнему не получаете трафик в целевых системах, проверьте правила FORWARD для iptables.
Ваша цепочка FORWARD должна быть либо установлена на ACCEPT, либо иметь список правил, разрешающих определенные соединения. Вы можете увидеть, достигает ли трафик цепочки FORWARD iptables, проверив количество пакетов и байтов, попавших в цепочку. Если их нет, то, возможно, в вашей цепочке есть правила более высокого уровня, которые блокируют трафик.
Заключительные мысли
В этом руководстве мы увидели, как включить или отключить переадресацию IP в системах Linux, отредактировав переменную ядра. Методы здесь относятся к системам, использующим systemd или какую-либо другую систему инициализации. Мы также узнали, как сделать изменения постоянными, и узнать общие шаги по устранению неполадок в случае, если переадресация IP-адресов по-прежнему не работает после изменения.
Подпишитесь на новостную рассылку Linux Career Newsletter, чтобы получать последние новости, вакансии, советы по карьере и рекомендуемые руководства по настройке.
LinuxConfig ищет технических писателей, специализирующихся на технологиях GNU / Linux и FLOSS. В ваших статьях будут представлены различные руководства по настройке GNU / Linux и технологии FLOSS, используемые в сочетании с операционной системой GNU / Linux.
Ожидается, что при написании статей вы сможете идти в ногу с технологическим прогрессом в вышеупомянутой технической области. Вы будете работать независимо и сможете выпускать не менее 2 технических статей в месяц.
- 08/08/2021
- 0
- СетиБезопасностьСерверКоманды
Генерация случайных чисел в Bash с примерами
- 09/08/2021
- 0
- БашСценарииАдминистрацияКомандыРазработка
При написании сценариев Bash — особенно при разработке сценариев для тестирования функциональности — нам иногда необходимо сгенерировать случайное число или случайный ввод. Эти числа также могут быть в определенном диапазоне. Эта статья научит вас.
Как взломать zip-пароль в Kali Linux
- 08/08/2021
- 0
- Файловая системаКалиБезопасностьКоманды
Цель этого руководства — показать, как взломать пароль для zip файл на Kali Linux.По умолчанию Kali включает инструменты для взлома паролей для этих сжатых архивов, а именно утилиту fcrackzip, Джон Потрошитель и список слов. Следуйте вместе с нами.
Как делать скриншоты с помощью maim в Linux
- 08/08/2021
- 0
- ПриложенияМультимедиаКомандыРабочий стол
В Linux есть множество утилит, которые можно использовать для создания снимков экрана. Каждая полная среда рабочего стола, такая как GNOME, KDE или XFCE, имеет свое интегрированное приложение, специально разработанное для этой задачи, но многие др.
Enabling IP-Forwarding for IPv4 in Debian GNU/Linux
The term IP Forwarding describes sending a network package from one network interface to another one on the same device. It should be enabled when you want your system to act as a router that transfers IP packets from one network to another.
On a Linux system the Linux kernel has a variable named `ip_forward` that keeps this value. It is accessible using the file `/proc/sys/net/ipv4/ip_forward`. The default value is 0 which means no IP Forwarding, because a regular user who runs a single computer without further components is not in need of that, usually. In contrast, for routers, gateways and VPN servers it is quite an essential feature.
Next, we will explain to you how to enable IP Forwarding temporarily, and permanently.
IP Forwarding As A Temporary Solution
In order to enable this kernel parameter on the fly you have two options. Option 1 simply stores the value of 1 in the variable from above as follows:
Option 2 uses the `sysctl` command that allows you to adjust different kernel parameters at runtime, too [2]. As an administrative user run the following command:
Keep in mind that this setting is changed instantly. Also, the result will not be preserved after rebooting the system.
You can query the stored value as follows:
This command returns a value of 0 for no IP Forwarding, and a value of 1 for IP Forwarding enabled. As an alternative, using `sysctl` also shows you the current status:
Enabling IP Forwarding Permanently
In order to achieve this some other steps have to be done. First, edit the file `/etc/sysctl.conf`. Search for a line containing the entry “#net.ipv4.ip_forward=1”, and remove the # at the beginning of the line.
Then, save the file, and run the `sysctl` command in order to enable the adjusted settings:
The option `-p` is short for `–load`, and requires a name for the configuration file to be followed.
Next, restart the proc file system that provides information about the status of the Linux kernel using the following command:
In about 2015 the file name was shortened from `procps.sh` to `procps`. So, on elderly Debian systems the script that you have to invoke is named `procps.sh`, instead.
Dealing With Systemd
The next hurdle came with the release of Systemd version 221. IP Forwarding is disabled by default, and enabling requires an additional file to be there. If it is not there yet, just add it. The file name consists of the name of the network interface followed by the suffix `.network`, for example `eth0.network` for the network interface `/dev/eth0`. As stated in the documentation [4], other extensions are ignored.
The following code snippet shows the setup for the network interface `/dev/tun0`. It contains of two sections — `Match` and `Network`. In the Match section define the name of the network interface, and in the network section enable IP Forwarding.
Conclusion
Activating IP Forwarding for IPv4 is not a mystery. Just a few steps, and your are there. Happy hacking!
Explanation
In the rest of this document, we will be discussing the following configuration:
This information was obtained using the RH5.1 official bluebox Linux distribution:
All netmasks are 255.255.255.0
192.168.200.110 thru 149 are used for virtual web hosting — they represent different websites.
The object here is to allow the Windows 98 machine to access IP addresses 192.168.200.110-149, either through the IP address or through DNS, without the Windows 98 machine knowing details of the network or various subnets.
Preparing Your System to Forward
/etc/sysconfig/network-scripts/ifcfg-eth1
I think it’s pretty self-explanatory why.
/etc/sysconfig/network-scripts/ifcfg-eth1:0
/etc/sysconfig/network
Of course, you’ll use your domain name and your host.domain. CAUTION. WARNING. Note the 254 on the end of the gateway address. USE IT. 254 is a magic number that does the right things. DO NOT user 192.168.100.3 here — it will appear to work but will cause IP forwarding failure.
CAUTION. WARNING. Even though you define the gateway in /etc/sysconfig/network as 192.168.100.254, on the Windows machine you must define it as 192.168.100.3. It’s the gateway combination of 192.168.100.3 in Windows and 192.168.100.254 that allows IP forwarding. 254 is a magic number.
Check IP Forwarding Tables
If you see anything in the output of the commands that seems to preclude any communication to or from 192.168.200, ESPECIALLY a default policy of deny or reject in the IP firewall forward rules, you must add ipfwadm commands to /etc/rc.d/rc.local to enable forwarding to and from that subnet.
NOTE: A default policy of accept is a security risk that’s acceptable for tutorial purposes only. For an actual functioning network it’s far better to default to deny, then individually enable ip forwarding on a subnet by subnet basis.
False Fixes
Routing on the Windows Machine
Special Routing Table Tweeks on the Linux Machine
Reboot the Linux Box
General IP Forwarding Troubleshooting Tips
Quick Checks
- Make sure you’ve restarted the necessary processes. Sometimes the safest thing (and sometimes the quickest in the long run) is reboot the Linux box.
- If you can’t ping 192.168.100.3 from your Linux machine, fix that problem before going on. It’s not a forwarding problem.
- If you can’t ping 192.168.100.3 from your Windows machine, fix that problem before going on. It’s not a forwarding problem.
- If you can’t ping 192.168.200.3 from your Linux machine, fix that problem before going on. It’s not a forwarding problem.
- Verify that the Windows gateway is set to the address of eth0 (192.168.100.3), and that the gateway address in /etc/sysconfig/network is set to the magic number 192.168.100.254.
Forwarding at a Higher Level
Telling Windows where DNS is located:
- Host: The name of the Windows machine. Should be the same as the name on the identification tab.
- Domain: Identifies the domain your computer belongs to.
- DNS Server Search Order: This must contain a reference to 192.168.100.3 (though not necessarily the first), because that machine is serving as a DNS server with authority over the 192.168.100 and 192.168.200 subnets, and the mydomain.cxm domain in general.
- Domain Suffix Search Order: Put a reference to the domain containing the Windows machine, which we’d assume would be the same domain as the Linux machine (192.168.100 subnet, after all).
Configure Your DNS Files
This section contains only ip-forwarding dns info. For a complete tutoral of DNS, click here. We’ll assume the following DNS config files:
/etc/named.boot | Starting point. Must contain a reference for each domain name, telling what file contains its DNS info. As a practical matter, usually all will point to file /var/named/named.forward. |
/var/named/named.forward | This contains the SOA statement, and other statements that map domain names to ip addresses. |
/var/named/named.reverse | This is the reverse DNS file. It maps IP addresses to domain names. |
/etc/named.boot
/var/named/named.forward
Be sure to increase the serial number (yyyymmdd##) in the IN SOA statement before exiting the editor.
/var/named/named.reverse
For each 192.168.200 subnet domain name in named.forward, both canonical and aliased (IN A and IN CNAME), add a line below the 192.168.200 IN SOA. Here are 2 examples: Once again, be sure to increase the serial number (yyyymmdd##) in every IN SOA statement in named.reverse before exiting the editor.
Letting DHCP Do Your Windows Client Admin For You
You must change /etc/dhcpd.conf, adding a dummy entry for the 192.168.200 subnet, and upgrading your existing entry for the 192.168.100 subnet (the one your Windows clients are actually on) to feed them information like default gateway, dns, etc. Here’s an example of /etc/dhcpd.conf:
Note that the subnet 192.168.200.0 entry has less information because it’s not expected to be used. If it were expected to be used, it would contain the same info as the 192.168.100 entry.
Most contents of the subnet 192.168.100.0 entry are self-explanatory. Note that the option routers is the Windows machine’s default gateway (overriding whatever’s on Windows’ gateway tab, while the option domain-name-servers is the DNS list, overriding or adding to (I’m not sure) the contents of Windows’ DNS tab.