- 25 Useful IPtable Firewall Rules Every Linux Administrator Should Know
- 1. Start/Stop/Restart Iptables Firewall
- On SystemD based Linux Distributions
- On SysVinit based Linux Distributions
- 2. Check all IPtables Firewall Rules
- 3. Block Specific IP Address in IPtables Firewall
- 4. Unblock IP Address in IPtables Firewall
- 5. Block Specific Port on IPtables Firewall
- 6. Allow Multiple Ports on IPtables using Multiport
- 7. Allow Specific Network Range on Particular Port on IPtables
- 8. Block Facebook on IPtables Firewall
- 9. Setup Port Forwarding in IPtables
- 10. Block Network Flood on Apache Port with IPtables
- 11. Block Incoming Ping Requests on IPtables
- 12. Allow loopback Access
- 13. Keep a Log of Dropped Network Packets on IPtables
- 14. Block Access to Specific MAC Address on IPtables
- 15. Limit the Number of Concurrent Connections per IP Address
- 16. Search within IPtables Rule
- 17. Define New IPTables Chain
- 18. Flush IPtables Firewall Chains or Rules
- 19. Save IPtables Rules to a File
- 20. Restore IPtables Rules from a File
- 21. Setup IPtables Rules for PCI Compliance
- 22. Allow Established and Related Connections
- 23. Drop Invalid Packets in IPtables
- 24. Block Connection on Network Interface
- 25. Disable Outgoing Mails through IPTables
- Conclusion
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Создание и тестирование Firewall в Linux, Часть 1.1 Виртуальная лаборатория
- Введение
- Создание виртуальной среды. Теория
- Создание виртуальной среды. Практика
- Проверка
25 Useful IPtable Firewall Rules Every Linux Administrator Should Know
Managing network traffic is one of the toughest jobs a system administrators has to deal with. He must configure the firewall in such a way that it will meet the system and users requirements for both incoming and outgoing connections, without leaving the system vulnerable to attacks.
25 IPtables Firewall Rules for Linux
This is where iptables come in handy. Iptables is a Linux command line firewall that allows system administrators to manage incoming and outgoing traffic via a set of configurable table rules.
Iptables uses a set of tables which have chains that contain set of built-in or user defined rules. Thanks to them a system administrator can properly filter the network traffic of his system.
Per iptables manual, there are currently 3 types of tables:
- FILTER – this is the default table, which contains the built in chains for:
- INPUT – packages destined for local sockets
- FORWARD – packets routed through the system
- OUTPUT – packets generated locally
- NAT – a table that is consulted when a packet tries to create a new connection. It has the following built-in:
- PREROUTING – used for altering a packet as soon as it’s received
- OUTPUT – used for altering locally generated packets
- POSTROUTING – used for altering packets as they are about to go out
- MANGLE – this table is used for packet altering. Until kernel version 2.4 this table had only two chains, but they are now 5:
- PREROUTING – for altering incoming connections
- OUTPUT – for altering locally generated packets
- INPUT – for incoming packets
- POSTROUTING – for altering packets as they are about to go out
- FORWARD – for packets routed through the box
In this article, you will see some useful commands that will help you manage your Linux box firewall through iptables. For the purpose of this article, I will start with simpler commands and go to more complex to the end.
1. Start/Stop/Restart Iptables Firewall
First, you should know how to manage iptables service in different Linux distributions. This is fairly easy:
On SystemD based Linux Distributions
On SysVinit based Linux Distributions
2. Check all IPtables Firewall Rules
If you want to check your existing rules, use the following command:
This should return output similar to the one below:
If you prefer to check the rules for a specific table, you can use the -t option followed by the table which you want to check. For example, to check the rules in the NAT table, you can use:
3. Block Specific IP Address in IPtables Firewall
If you find an unusual or abusive activity from an IP address you can block that IP address with the following rule:
Where you need to change «xxx.xxx.xxx.xxx» with the actual IP address. Be very careful when running this command as you can accidentally block your own IP address. The -A option appends the rule in the end of the selected chain.
In case you only want to block TCP traffic from that IP address, you can use the -p option that specifies the protocol. That way the command will look like this:
4. Unblock IP Address in IPtables Firewall
If you have decided that you no longer want to block requests from specific IP address, you can delete the blocking rule with the following command:
The -D option deletes one or more rules from the selected chain. If you prefer to use the longer option you can use —delete .
5. Block Specific Port on IPtables Firewall
Sometimes you may want to block incoming or outgoing connections on a specific port. It’s a good security measure and you should really think on that matter when setting up your firewall.
To block outgoing connections on a specific port use:
To allow incoming connections use:
In both examples change «xxx» with the actual port you wish to allow. If you want to block UDP traffic instead of TCP, simply change «tcp» with «udp» in the above iptables rule.
6. Allow Multiple Ports on IPtables using Multiport
You can allow multiple ports at once, by using multiport, below you can find such rule for both incoming and outgoing connections:
7. Allow Specific Network Range on Particular Port on IPtables
You may want to limit certain connections on specific port to a given network. Let’s say you want to allow outgoing connections on port 22 to network 192.168.100.0/24 .
You can do it with this command:
8. Block Facebook on IPtables Firewall
Some employers like to block access to Facebook to their employees. Below is an example how to block traffic to Facebook.
Note: If you are a system administrator and need to apply these rules, keep in mind that your colleagues may stop talking to you 🙂
First find the IP addresses used by Facebook:
You can then block that Facebook network with:
Keep in mind that the IP address range used by Facebook may vary in your country.
9. Setup Port Forwarding in IPtables
Sometimes you may want to forward one service’s traffic to another port. You can achieve this with the following command:
The above command forwards all incoming traffic on network interface eth0 , from port 25 to port 2525 . You may change the ports with the ones you need.
10. Block Network Flood on Apache Port with IPtables
Sometimes IP addresses may requests too many connections towards web ports on your website. This can cause number of issues and to prevent such problems, you can use the following rule:
The above command limits the incoming connections from per minute to 100 and sets a limit burst to 200 . You can edit the limit and limit-burst to your own specific requirements.
11. Block Incoming Ping Requests on IPtables
Some system administrators like to block incoming ping requests due to security concerns. While the threat is not that big, it’s good to know how to block such request:
12. Allow loopback Access
Loopback access (access from 127.0.0.1 ) is important and you should always leave it active:
13. Keep a Log of Dropped Network Packets on IPtables
If you want to log the dropped packets on network interface eth0 , you can use the following command:
You can change the value after «—log-prefix» with something by your choice. The messages are logged in /var/log/messages and you can search for them with:
14. Block Access to Specific MAC Address on IPtables
You can block access to your system from specific MAC address by using:
Of course, you will need to change «00:00:00:00:00:00» with the actual MAC address that you want to block.
15. Limit the Number of Concurrent Connections per IP Address
If you don’t want to have too many concurrent connection established from single IP address on given port you can use the command below:
The above command allows no more than 3 connections per client. Of course, you can change the port number to match different service. Also the —connlimit-above should be changed to match your requirement.
16. Search within IPtables Rule
Once you have defined your iptables rules, you will want to search from time to time and may need to alter them. An easy way to search within your rules is to use:
In the above example, you will need to change $table with the actual table within which you wish to search and $string with the actual string for which you are looking for.
Here is an example:
17. Define New IPTables Chain
With iptables, you can define your own chain and store custom rules in it. To define a chain, use:
Now you can check if your new filter is there:
Sample Output
18. Flush IPtables Firewall Chains or Rules
If you want to flush your firewall chains, you can use:
You can flush chains from specific table with:
You can change «nat» with the actual table which chains you wish to flush.
19. Save IPtables Rules to a File
If you want to save your firewall rules, you can use the iptables-save command. You can use the following to save and store your rules in a file:
It’s up to you where will you store the file and how you will name it.
20. Restore IPtables Rules from a File
If you want to restore a list of iptables rules, you can use iptables-restore . The command looks like this:
Of course the path to your rules file might be different.
21. Setup IPtables Rules for PCI Compliance
Some system administrators might be required to configure their servers to be PCI compiliant. There are many requirements by different PCI compliance vendors, but there are few common ones.
In many of the cases, you will need to have more than one IP address. You will need to apply the rules below for the site’s IP address. Be extra careful when using the rules below and use them only if you are sure what you are doing:
If you use cPanel or similar control panel, you may need to block it’s’ ports as well. Here is an example:
Note: To make sure you meet your PCI vendor’s requirements, check their report carefully and apply the required rules. In some cases you may need to block UDP traffic on certain ports as well.
22. Allow Established and Related Connections
As the network traffic is separate on incoming and outgoing, you will want to allow established and related incoming traffic. For incoming connections do it with:
For outgoing use:
23. Drop Invalid Packets in IPtables
It’s possible to have some network packets marked as invalid. Some people may prefer to log those packages, but others prefer to drop them. To drop invalid the packets, you can use:
24. Block Connection on Network Interface
Some systems may have more than one network interface. You can limit the access to that network interface or block connections from certain IP address.
Change “xxx.xxx.xxx.xxx” with the actual IP address (or network) that you wish to block.
25. Disable Outgoing Mails through IPTables
If your system should not be sending any emails, you can block outgoing ports on SMTP ports. For example you can use this:
Conclusion
Iptables is a powerful firewall that you can easily benefit from. It is vital for every system administrator to learn at least the basics of iptables. If you want to find more detailed information about iptables and its options it is highly recommend to read it’s manual:
If you think we should add more commands to this list, please share them with us, by submitting them in the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Создание и тестирование Firewall в Linux, Часть 1.1 Виртуальная лаборатория
Решил написать статью по следам курса, который я делал в прошлом семестре в институте. Конечно, тут я опишу лишь самые главные основы и максимально все упрощу. Постараюсь дать немного теоритической информации, но в основном больше ссылок, картинок и практики.
Итак, речь пойдет о написании firewall в среде Linux. Всю статью я поделю на несколько частей. То, что вы читаете сейчас – первая часть, она поделена еще на три части. Некоторые темы хорошо известны и задокументированы, поэтому я постараюсь отдельно давать минимум теории по ним и отдельно практику. Чтобы всем было интересно. А также ссылки для углубления (часто это будут английские статьи).
Содержание первой части:
Содержание второй части:
Часть 2. Еще не готова, но думаю затронуть следующие темы: краткое введение в таблицы firewall. Stateless vs statefull firewall. Добавление еще одного модуля для загрузки таблиц правил (через виртуальную файловую систему sysfs из первой части, может быть тут я просто дам исходный код, потому что принципиально ничего нового тут нет). Добавим небольшую прокси-программу в user space и пошлем нужный траффик из kernel в прокси, поработаем с содержанием траффика и на этой основе примем решения о его дальнейшей судьбе (добавим возможность блокировать отдельные сайты). А так же возьмем реальную известную атаку основанную на buffer overflow, захватим управление над удаленным компьютером с ее помощью и посмотрим как наш firewall может защитить от этого.
Возможно вторая часть будет разбита на две, или изменена. Буду очень рад вашим комментариям и пожеланиям как по первой части так и по второй.
Введение
Наша цель в этой части – написание программы, которая будет на очень простом уровне контролировать весь траффик. А именно – мы определим какие пакеты можно пропускать, а какие удалять. Создадим простую систему логов, для отслеживания результатов, а так же программу для конечно пользователя, через которую можно будет читать эти результаты и немного управлять программой. Такой вот тривиальный firewall или на русском языке — Межсетево́й экра́н, сетево́й экра́н — это комплекс аппаратных и программных средств в компьютерной сети, осуществляющий контроль и фильтрацию проходящих через негосетевых пакетов в соответствии с заданными правилами. (Wikipedia).
В нашем случае, функцию firewall будет выполнять отдельный компьютер. Выглядить это будет так:
Давайте смотреть. Мы сделаем сеть, в которой будет три виртуальных компьютера – host1, host2, fw и соединим их как на картинке выше.
host1 — получит статичный IP address – 10.0.1.1. Его мы будем защищать.
host2 — который будет в последней части аттакующим и будет иметь статичный IP – 10.0.2.2
fw — будет отслеживать весь трафик, сконфигурируем ему так же интерфейс для выхода в интернет, чтобы можно было при (читать ВК и новости) необходимости скачивать нужный софт.
В двух словах про DHCP (англ. Dynamic Host Configuration Protocol — протокол динамической настройки узла) —сетевой протокол, позволяющий компьютерам автоматически получать IP-адрес и другие параметры, необходимые для работы в сети TCP/IP. (Wikipedia).
То есть он будет сам получать различные настройки, включая IP, для того чтобы иметь возможность через этот сетевой интерфейс, выходить без лишней головной боли в интернет.
Создание виртуальной среды. Теория
Немного про виртуальные машины. В нашем случае, виртуальная машина – это программа, которая будет эмулировать копьютер, благодаря чему, мы сможем запустить на нашем компьютере сразу три операционные системы. Для тех кто совсем не знаком с темой, могут начать тут.
Мы воспользуемся бесплатной программой VirtualBox, которая позволяет создавать виртуальные сети на одном компьютере. Конечно же не принципиально чем именно пользоваться, главное иметь возможность сконфигурировать сеть. Программа бесплатна, ищем, качаем, ставим.
Следующим шагом будет добавить виртуальные машины. Я буду работать с Linux Ubuntu 12, по «историческим причинам». Вы можете скачать последнюю версию. Тем более если ваш копьютер достаточно мощный. Образ Ubuntu можно найти тут.
Я надеюсь, что читающий справится с добавление образа в virtualbox и теперь у вас есть что-то похожее на картинку. Я советую воспользоваться функцией “clone” в virtualbox, для быстрого создания еще двух машин. У меня в роли host1, host2 специально урезанные «легкие» версии ubuntu, без графического интерфейса (не хватает RAM для полноценных).
Примерно так это должно выглядеть в конце
Создание виртуальной среды. Практика
И так, я предполагаю, что у Вас уже есть три виртуальных linux машины, которые мы сейчас сконфигурирует в одну сеть и проверим, что все работает, прежде чем начать писать программу.
Идем в settings и конфигурируем как на фото:
Добавляем сетевое устройство:
Теперь, linux «будет думать», что у нашего компьютера, есть сетевая карта, а если вы посмотрите в Advanced, то увидите, что в нее еще и вставлен кабель. Отлично. Теперь надо сконфигурировать этк карту в операционной системе. Для этого запускаем host1.
На данном этапе, я предполагаю, что читателю ивестно, что такое IP адресс как он выгледит и зачем он нужен. Я буду редактировать в vi, вы можете в любом другом редакторе, но не забываем давать права администратора (запускать с sudo), чтобы иметь возможность сохранить.
«Просим» систему заново прочитать файл конфигурации (чтобы не перезагружать машину):
Запускаем ifconfig и проверяем, что у нас есть сетевая карта под именем eth0, с IP == 10.0.1.1, маской и тд и тп.
То же самое делаем с host2, только IP установить в 10.0.2.2, gateway 10.0.2.3 и не забыть «добавить» сетевую карту в настройках машины в virtualbox (у меня после изменений настроек в virtualbox, машина при загрузке подвисала на пару минут и писала waiting for network configuration… Это связано с тем, что по умолчанию, сетевой интерфейс сконфигурирован как dhcp, то есть, операционная система ждет динамически получить сетевые настройки, но в virtualbox, для этого она должна быть сконфигурирована как NAT, но мы это поменяли, поэтому ОС пытается понять, что не так. Можно сначало загрузить ОС, отредактировать interfaces, потом выключить компьютер, изменить настройки и запустить заново).
Теперь пришла очередь главной машины, которая будет выполнять роль firewall. Напоминаю, что нам понадобятся три сетевые карты, через одну мы сможем выходить в интернет в случае необходимости поэтому она будет определена как NAT. Остальные две будут ответственны пересылать трафик с host1 -> host2 и обратно с host2 -> host1.
Adapter1 – должен быть выставлен как NAT. Настройки Adapter2, Adapter3, такие же как и в предыдущих примерах (Internal network). Запускаем, начинаем конфигурировать сетевые карты. Так должен выглядеть файл interfaces.
А вот – конечный результат конфигурации, после перезапуска:
Последнее, что осталось сделать — это разрешить packet forwarding, для того чтобы компьютер мог брать пакеты с одного сетевого интерфейса(10.0.2.3) на который приходят пакеты от host2 и передать их на другой сетевой интерфейс 10.0.1.3 связннаый соответственно с host1.
Тут все подробно описано. Чтобы настройка была постоянной, нужно изменить следующую строчку в /etc/sysctl.conf:
Сделать это можно любым удобным способом, не забываем sudo. Много информации про конфигурацию интерфесов можно почитать тут.
Проверка
Осталось проверить, что все связно друг с другом и работает. Проверять будем классическим ping
Как видно на картинке, ping «прошел» с host1 -> host2, host2 -> host1, fw -> host1, fw -> host2. Готово, «лаборатория» для будущих экспериментов настроена.
Источник