Как закрыть все порты linux

Закрыть все кроме 22, 80, 5432 портов через iptables?

Подскажите пожалуйста команды в iptables, для того что бы:

1. закрыть все входящие порты, кроме 22, 80, 5432

2. открыть все исходящие порты

3. открыть порт 80 для всех входящих соединений

4. открыть 22 и 5432 порты только для конкретного IP

1. закрыть все входящие порты
iptables -P INPUT DROP
2. открыть все исходящие порты
iptables -P OUTPUT ACCEPT
3. открыть порт 80 для всех входящих соединений
iptables -A INPUT —dport 80 -j ACCEPT
4. открыть 22 и 5432 порты только для конкретного IP
iptables -A INPUT -m multiport —dports 22,5432 -s IP_ADDRESS -j ACCEPT

И сохранить настройки вроде так: //sbin/iptables-save. Помнится вроде так и делал, но что-то не всё выходило. Отпишитесь, если всё получится (и скрипт тоже)).

iptables-save выдает список правил в формате, который можно скормить iptables-restore.
Можно это вручную, сохранять в файл, на автозапуск настроить iptables-restore < file, либо init-скрипты дистрибутивов это обычно умеют:
service iptables save в федоре
/etc/init.d/iptables save в gentoo

ГЛАВНОЕ не выполнять это по ssh, иначе после первой строчки настройка закончится.
Дополнительно советую сначала отправлять «остальные» пакеты не в дроп, а в лог — так можно обнаружить порты, которые изначально забыли открыть.

Не закончиться, если делать через &&…
Для пущей безопасности можно подстаховаться и сделать (sleep 120 && reboot) &

Ну, ты пишешь в консоле «iptables -P INPUT DROP» и отрубаешься от своего сервера до тех пор, пока он не перезапуститься =) VPS можно из панели управления перезапустить, а если сервер физический… придеться звонить ребятам тех. поддержки =)

При настройке через ssh лучше сначала сделать разрешающее правило на порт ssh, после чего убедиться что оно работает (посмотреть счетчик пакетов по нему). Если всё сделать с первого раза правильно, то проблем, конечно, не будет, однако береженого бог бережет. У меня поначалу случались такие ошибки.
И еще раз повторюсь про трюк с отправкой в лог по-умолчанию, пару раз это помогало найти порты, которые изначально открыть забыл.

Читайте также:  Являются ли имена файлов фс linux регистрозависимыми

С вашим конфигом исходящие соединения работать не будут. Необходимо ещё правило, разрешающее прохождение ответных пакетов (что-то вроде «iptables -A INPUT -i eth0 —match state —state ESTABLISHED,RELATED -j ACCEPT»). Ниже есть правильное решение.

cjey

должно получиться что-то вроде этого
# Настраиваем политики по умолчанию
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# удаляем все имеющиеся правила
iptables -F
iptables -t nat -F
iptables -t mangle -F

iptables -X
iptables -t nat -X
iptables -t mangle -X

# правила входящих соединений
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -i eth0 —match state —state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i eth0 -p tcp —dport 80 —match state —state NEW -j ACCEPT
iptables -A INPUT -i eth0 —source 192.168.0.10 -p tcp —dport 22 —match state —state NEW -j ACCEPT
iptables -A INPUT -i eth0 —source 192.168.0.10 -p tcp —dport 5432 —match state —state NEW -j ACCEPT

# Правила исходящих соединений
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -o eth0 —match state —state NEW, ESTABLISHED, RELATED -j ACCEPT

Источник

How to Find Open Ports and Close Them in Linux

Troubleshooting networks? Here’s how to find the open ports and close those open ports in the Linux command line.

So you are dealing with a critical server where you have to maintain security at any cost. And closing ports to block unwanted traffic is the first step you’d take.

Find open ports in Linux

In this tutorial, I am going to use the ss command to find open ports.

You can use the -l option with the ss command to get listening ports. But to be more specific, I’m going with -lt to get listening TCP ports:

list listening tcp ports in linux

Similarly, if you want to have a list of both TCP and UDP in the listening state, you can use the given command:

list of both TCP and UDP ports in the listening state

And to get the listening port of each service, you can use -n and for more fine-tuned results, you can always use the grep command:

Читайте также:  Linux как расшарить папку

get listening port of currently running service

Enough of finding open ports, let’s jump to how you can close them.

Close open ports in Linux

To close the port, first, you will need to stop the service and to find the service name, you can use the same ss command with -p option:

sudo ss -tulnp | grep LISTEN

find open ports with service names attactched to it

As you can see, the NGINX is utilizing port number 80. So let’s stop it using the given command:

sudo systemctl stop nginx

As it will enable itself on every boot and you can alter this behavior using the given command:

sudo systemctl disable nginx

For better results, I would recommend changing firewall rules.

Here, I’m going to block port no 80 (used by NGINX) in UFW (which is pre-installed in Ubuntu).

First, let’s check the status of UFW:

check status of ufw

And if it shows inactive , you can use the given command to enable it:

Now, you just have to pair the deny option with the port number :

deny nginx server from ufw

close port no 80

Wrapping Up

This was my take on how you can find and close open ports in Linux. I hope you will find this helpful.

And if you have any queries, let me know in the comments.

Источник

How to close ports in Linux?

it show that 23/tcp port is closed. Which of them is true? I want to close this port on my whole system, how can I do it?

they are both true. TCP ports aren’t associated with hosts. they are associated with network interfaces. the difference is subtle but important. interfaces are often the same as hosts, but not always. in this case (as stated in answers) localhost is accessing the lo (loopback) interface. the IP Address is accesing your real interface, probably eth0 or wlan0 or somesuch.

5 Answers 5

Nmap is a great port scanner, but sometimes you want something more authoritative. You can ask the kernel what processes have which ports open by using the netstat utility:

me@myhost:~$ sudo netstat -tlnp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 1004/dnsmasq tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 380/sshd tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 822/cupsd tcp6 0 0 . 22 . * LISTEN 380/sshd tcp6 0 0 ::1:631 . * LISTEN 822/cupsd

The options I have given are:

  • -t TCP only
  • -l Listening ports only
  • -n Don’t look up service and host names, just display numbers
  • -p Show process information (requires root privilege)
Читайте также:  Linux монтирование от имени пользователя

In this case, we can see that sshd is listening on any interface ( 0.0.0.0 ) port 22, and cupsd is listening on loopback ( 127.0.0.1 ) port 631. Your output may show that telnetd has a local address of 192.168.1.1:23 , meaning it will not answer to connections on the loopback adapter (e.g. you can’t telnet 127.0.0.1 ).

There are other tools that will show similar information (e.g. lsof or /proc ), but netstat is the most widely available. It even works on Windows ( netstat -anb ). BSD netstat is a little different: you’ll have to use sockstat(1) to get the process information instead.

Once you have the process ID and program name, you can go about finding the process and killing it if you wish to close the port. For finer-grained control, you can use a firewall (iptables on Linux) to limit access to only certain addresses. You may need to disable a service startup. If the PID is «-» on Linux, it’s probably a kernel process (this is common with NFS for instance), so good luck finding out what it is.

Note: I said «authoritative» because you’re not being hindered by network conditions and firewalls. If you trust your computer, that’s great. However, if you suspect that you’ve been hacked, you may not be able to trust the tools on your computer. Replacing standard utilities (and sometimes even system calls) with ones that hide certain processes or ports (a.k.a. rootkits) is a standard practice among attackers. Your best bet at this point is to make a forensic copy of your disk and restore from backup; then use the copy to determine the way they got in and close it off.

Источник

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