Where is iptables in linux

How to configure iptables on Ubuntu

The user-space application program iptables allows configuring the tables provided by the Linux kernel firewall, as well as the chains and rules it stores. The kernel module currently used for iptables only applies to IPv4 traffic, to configure firewall rules for IPv6 connections instead use ip6tables, which respond to the same command structures as iptables.

Listing current rules

Ubuntu servers do not implement any restrictions by default, but for future reference, check the current iptable rules using the following command.

This will print out a list of three chains, input, forward and output, like the empty rules table example output below.

Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination

The chain names indicate which traffic the rules in each list will be applied to, input is for any connections coming to your cloud server, output is any leaving traffic and forward for any pass through. Each chain also has its policy setting which determines how the traffic is handled if it doesn’t match any specific rules, by default it’s set to accept.

Adding rules

Firewalls can commonly be configured in one of two ways, either set the default rule to accept and then block any unwanted traffic with specific rules, or by using the rules to define allowed traffic and blocking everything else. The latter is often the recommended approach, as it allows pre-emptively blocking traffic, rather than having to reactively reject connections that should not be attempting to access your cloud server.

To begin using iptables, you should first add the rules for allowed inbound traffic for the services you require. Iptables can track the state of the connection, so use the command below to allow established connections to continue.

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

You can check that the rule was added using the same sudo iptables -L as before.

Next, allow traffic to a specific port to enable SSH connections with the following.

sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT

The ssh in the command translates to port number 22, which the protocol uses by default. The same command structure can be used to allow traffic to other ports as well. To enable access to an HTTP web server, use the following command.

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

After adding all the allowed rules you require, change the input policy to drop.

Читайте также:  Winehq установка astra linux

Warning: Changing the default rule to drop will permit only specifically accepted connection. Make sure you’ve enabled at least SSH as shown above before changing the default rule.

sudo iptables -P INPUT DROP

The same policy rules can be defined to other chains as well by entering the chain name and selecting either DROP or ACCEPT.

Saving and restoring rules

Now if you were to restart your cloud server all of these iptables configurations would be wiped. To prevent this, save the rules to a file.

sudo iptables-save > /etc/iptables/rules.v4

You can then simply restore the saved rules by reading the file you saved.

# Overwrite the current rules sudo iptables-restore < /etc/iptables/rules.v4 # Add the new rules keeping the current ones sudo iptables-restore -n < /etc/iptables/rules.v4

You can automate the restore process at reboot by installing an additional package for iptables which takes over the loading of the saved rules. To this with the following command.

sudo apt-get install iptables-persistent

After the installation the initial setup will ask to save the current rules for IPv4 and IPv6, just select Yes and press enter for both.

If you make further changes to your iptables rules, remember to save them again using the same command as above. The iptables-persistent looks for the files rules.v4 and rules.v6 under /etc/iptables.

These are just a few simple commands you can use with iptables, which is capable of much more. Read on to check on some of the other options available for more advanced control over iptable rules.

Advanced rule setup

As per basic firewall behaviour, the rules are read in the order they are listed on each chain, which means you’ll need to put the rules in the correct order. Appending new rules adds them to the end of the list. You can add new rules to a specific position of the list by inserting them using iptables -I -command, where the is the order number you wish to insert the rule. To know which index number to enter, use the following command.

sudo iptables -L --line-numbers
Chain INPUT (policy DROP) num target prot opt source destination 1 ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED 2 ACCEPT tcp -- anywhere anywhere , dpt:ssh 3 ACCEPT tcp -- anywhere anywhere tcp dpt:http

The number at the beginning of each rule line indicates the position in the chain. To insert a new rule above a specific existing rule, simply use the index number of that existing rule. For example to insert a new rule to the top of the chain, use the following command with index number 1.

sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

If you wish to remove an existing rule from a certain chain, use the delete command with the parameter -D. The easiest way to select the rule for deletion is to use the index numbers explained above. For example to delete the second rule on the input chain, use this command.

Читайте также:  Linux servers monitoring tools

It’s also possible to flush all rules of a specific chain or even the whole iptables using the -F -parameter. This is useful if you suspect iptables is interfering with your attempted network traffic, or you simply wish to start configuring again from a clean table.

Warning: Make sure you set the default rule to ACCEPT before flushing any chain.

sudo iptables -P INPUT ACCEPT

Afterwards, you can go ahead with clearing other rules. Remember to save the rules to a file before flushing the table in case you want to restore the configuration later.

# Clear input chain sudo iptables -F INPUT # Flush the whole iptables sudo iptables -F

With the iptable flushed, your server could be vulnerable to attacks. Make sure to secure your system with an alternative method while disabling iptables even temporarily.

Источник

How do I find out where my IPTables rules are being stored?

I working on a Debian server and I'm trying to figure out where my IPTable rules are being stored. From looking around on the internet I've found there is generally two locations were these are usually saved. http://major.io/2009/11/16/automatically-loading-iptables-on-debianubuntu/ suggests /etc/network/if-up.d/iptables but that file does not exist in that directory. http://beginlinux.wordpress.com/2009/05/26/saving-changes-for-iptables/ /etc/sysconfig/iptables but the /etc/sysconfig directory doesn't even exist. From what I know it isn't to uncommon for the previous administrator to save common files to a different location for security purposes and I was wondering if there was a way for me to find out where the rules are being saved when the iptables-save command is used. This page also states that the file is restored using the script located at /etc/init.d/iptables but this also does not exist. Any help or suggestions as far as how to proceed to find out where the rules are being saved? I know I can try and use grep to find a rare string which would be located in the rules, but I feel there has to be a simpler and more direct method. Update: Thank you for all of your help. I tried using grep to search the /etc directory but it took a very long time and I didn't want to risk running out of memory, so I stopped it. I figured I'd try using strace as a less intensive method. From looking through the strace I've come to the lines (I changed the IP addess to 1.1.1.1):

`open("/etc/protocols", O_RDONLY|O_CLOEXEC) = 5 fstat64(5, ) = 0 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7747000 read(5, "# Internet (IP) protocols\n#\n# Up". 4096) = 2859 close(5) = 0 munmap(0xb7747000, 4096) = 0 write(1, "-A net2fw -s 1.1.1.1/32 -p t". 66) = 66` 

I'm not 100% sure what this is doing, but it looks like to me that this is where it uses protocol #5 from the file /etc/protocols which would be: st 5 ST # ST datagram mode reading the file stats of some file and then mapping what it reads to a memory location 0xb7747000 . I'm unsure where it is reading from but then it closes the protocol, unmaps from memory and then writes the rule to file descriptor 1 . How close am I to reading this correctly? and how would I find out the file represented by 1 ?

Читайте также:  Линукс команды какие диски есть

Red Hat Linux and descendants from that uses /etc/sysconfig/iptables , I am not aware of any distributions in the Debian family using that path.

I would probably cd into /etc , and run commands like grep -R -l 'iptables-save' , and grep -R -l 'iptables' . If you know a specific address used in a rule, you might also try grepping for that particular rule.

Источник

Как найти конфиг, который использует iptables?

На сайте настроен iptables. Разрешает коннект к порту 3306 только для одного IP. IP сменился, нужно открыть конфиг фаервола и сменить IP.
Гуглю где находится его конфиг, гугль говорит, смотреть в /etc/sysconfig/iptables.old и в /etc/sysconfig/iptables-config.
Ага, думаю я, то что мне нужно, открываю эти конфиги, в них нет записи с нужным IP. Видимо iptables использует кастомный конфиг. Как узнать где он находится?

littleguga

Выведите список через iptables -L
и удалите старое, добавьте новое

Если я не ошибаюсь, конфиг можно сохранить куда угодно.

In CentOS you have the file /etc/sysconfig/iptables
если его там нет, вы можете его создать, используя iptables-save, чтобы записать текущие правила в файл

iptables-save > /etc/sysconfig/iptables
чтобы загрузить файл, Вам не нужно перезагружать сервер, просто используйте iptables-restore

# iptables -A INPUT -i ens192 -p tcp -s x.x.x.x --dport 3306 -j ACCEPT

так добавить разрешение для подключения определенного IP? какую нибудь еще команду нужно вводить или что нибудь перезагружать?

littleguga

mr_blond97: на счет этого, к сожалению помочь не могу. По умолчанию - все подключения разрешены. Надо смотреть, какое правило у Вас запрещало подключаться со всех ip, кроме старого и его менять.
ps
Если ответ помог, отметьте решением, пожалуйста.

iptables -S выведет список правил
=========
/etc/sysconfig/iptables-config
Не тот файл вы открываете.
mcedit /etc/sysconfig/iptables
меняете правило и
/etc/init.d/iptables restart

Disen

Итак, шаг номер раз:
iptables -L -n --line-numbers
эта команда выведет список всех имеющихся у Вас правил с номерами.

шаг номер 2:
iptables -D INPUT num, где num - номер запрещающего правила.
этой командой мы удаляем запрещающее правило

наг номер 3:
iptables -I INPUT 1 -p tcp -s x.x.x.x --dport 3306 -j ACCEPT
этой командой мы добавляем новое разрешающее правило в цепочку INPUT и ставим его первым. На случай, если у Вас в конце цепочки написано что-то типа -A INPUT -j REJECT --reject-with icmp-host-prohibited

если что-то не получается - пришлите вывод iptables -L -n --line-numbers, бум думать.

Источник

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