Как закрыть порт linux
Перейти к содержимому

Как закрыть порт linux

  • автор:

IptablesHowTo

Iptables is a firewall, installed by default on all official Ubuntu distributions (Ubuntu, Kubuntu, Xubuntu). When you install Ubuntu, iptables is there, but it allows all traffic by default. Ubuntu comes with ufw — a program for managing the iptables firewall easily.

There is a wealth of information available about iptables, but much of it is fairly complex, and if you want to do a few basic things, this How To is for you.

Basic Commands

lists your current rules in iptables. If you have just set up your server, you will have no rules, and you should see

Basic Iptables Options

  • NEW — The connection has not yet been seen.
  • RELATED — The connection is new, but is related to another connection already permitted.
  • ESTABLISHED — The connection is already established.
  • INVALID — The traffic couldn’t be identified for some reason.

Allowing Established Sessions

  • The above rule has no spaces either side of the comma in ESTABLISHED,RELATED

If the line above doesn’t work, you may be on a castrated VPS whose provider has not made available the extension, in which case an inferior version can be used as last resort:

Allowing Incoming Traffic on Specific Ports

You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.

To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in.

  • append this rule to the input chain (-A INPUT) so we look at incoming traffic
  • check to see if it is TCP (-p tcp).
  • if so, check to see if the input goes to the SSH port (—dport ssh).
  • if so, accept the input (-j ACCEPT).

Lets check the rules: (only the first few lines shown, you will see more)

Now, let’s allow all incoming web traffic

Checking our rules, we have

We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.

Blocking Traffic

Once a decision is made to accept a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end.

Because we didn’t specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh.

Editing iptables

The only problem with our setup so far is that even the loopback port is blocked. We could have written the drop rule for just eth0 by specifying -i eth0, but we could also add a rule for the loopback. If we append this rule, it will come too late — after all the traffic has been dropped. We need to insert this rule before that. Since this is a lot of traffic, we’ll insert it as the first rule so it’s processed first.

The first and last lines look nearly the same, so we will list iptables in greater detail.

You can now see a lot more information. This rule is actually very important, since many programs use the loopback interface to communicate with each other. If you don’t allow them to talk, you could break those programs!

Logging

In the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way:

See Tips section for more ideas on logging.

Saving iptables

If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can use iptables-save and iptables-restore.

Configuration on startup

WARNING: Iptables and NetworkManager can conflict. Also if you are concerned enough about security to install a firewall you might not want to trust NetworkManager. Also note NetworkManager and iptables have opposite aims. Iptables aims to keep any questionable network traffic out. NetworkManager aims to keep you connected at all times. Therefore if you want security all the time, run iptables at boot time. If you want security some of the time then NetworkManager might be the right choice.

WARNING: If you use NetworkManager (installed by default on Feisty and later) these steps will leave you unable to use NetworkManager for the interfaces you modify. Please follow the steps in the next section instead.

NOTE: It appears on Hardy, NetworkManager has an issue with properly on saving and restoring the iptable rules when using the method in the next section. Using this first method appears to work. If you find otherwise, please update this note.

Save your firewall rules to a file

At this point you have several options. You can make changes to /etc/network/interfaces or add scripts to /etc/network/if-pre-up.d/ and /etc/network/if-post-down.d/ to achieve similar ends. The script solution allows for slightly more flexibility.

Solution #1 — /etc/network/interfaces

(NB: be careful — entering incorrect configuration directives into the interface file could disable all interfaces, potentially locking you out of a remote machine.)

Modify the /etc/network/interfaces configuration file to apply the rules automatically. You will need to know the interface that you are using in order to apply the rules — if you do not know, you are probably using the interface eth0, although you should check with the following command first to see if there are any wireless cards:

If you get output similar to the following, then you do not have any wireless cards at all and your best bet is probably eth0.

When you have found out the interface you are using, edit (using sudo) your /etc/network/interfaces:

When in the file, search for the interface you found, and at the end of the network related lines for that interface, add the line:

You can also prepare a set of down rules, save them into second file /etc/iptables.downrules and apply it automatically using the above steps:

A fully working example using both from above:

You may also want to keep information from byte and packet counters.

The above command will save the whole rule-set to a file called /etc/iptables.rules with byte and packet counters still intact.

Solution #2 /etc/network/if-pre-up.d and ../if-post-down.d

NOTE: This solution uses iptables-save -c to save the counters. Just remove the -c to only save the rules.

Alternatively you could add the iptables-restore and iptables-save to the if-pre-up.d and if-post-down.d directories in the /etc/network directory instead of modifying /etc/network/interface directly.

NOTE: Scripts in if-pre-up.d and if-post-down.d must not contain dot in their names.

The script /etc/network/if-pre-up.d/iptablesload will contain:

and /etc/network/if-post-down.d/iptablessave will contain:

Then be sure to give both scripts execute permissions:

Solution #3 iptables-persistent

Install and use the iptables-persistent package.

Configuration on Startup for NetworkManager

NetworkManager includes the ability to run scripts when it activates or deactivates an interface. To save iptables rules on shutdown, and to restore them on startup, we are going to create such a script. To begin, press Alt+F2 and enter this command:

Then, paste this script into your editor, save, and exit the editor.

Finally, we need to make sure NetworkManager can execute this script. In a terminal window, enter this command:

If you manually edit iptables on a regular basis

The above steps go over how to setup your firewall rules and presume they will be relatively static (and for most people they should be). But if you do a lot of development work, you may want to have your iptables saved everytime you reboot. You could add a line like this one in /etc/network/interfaces:

The line «post-down iptables-save > /etc/iptables.rules» will save the rules to be used on the next boot.

Using iptables-save/restore to test rules

If you edit your iptables beyond this tutorial, you may want to use the iptables-save and iptables-restore feature to edit and test your rules. To do this open the rules file in your favorite text editor (in this example gedit).

You will have a file that appears similiar to (following the example above):

Notice that these are iptables commands minus the iptable command. Feel free to edit this to file and save when complete. Then to test simply:

NOTE: With iptables 1.4.1.1-1 and above, a script allow you to test your new rules without risking to brick your remote server. If you are applying the rules on a remote server, you should consider testing it with:

After testing, if you have not added the iptables-save command above to your /etc/network/interfaces remember not to lose your changes:

More detailed Logging

For further detail in your syslog you may want create an additional Chain. This will be a very brief example of my /etc/iptables.rules showing how I setup my iptables to log to syslog:

Disabling the firewall

If you need to disable the firewall temporarily, you can flush all the rules using

or create a script using text editor such as nano

Make sure you can execute the script

You can run the script

Easy configuration via GUI

UFW & GUFW

GUFW — Gufw is a graphical frontend to UFW (Uncomplicated Firewall).

Further Information

Shoreline Firewall, a.k.a. Shorewall, is a firewall generator for iptables which allows advanced configuration with simple configuration files. It is available from the Ubuntu repositories via apt-get.

Credits

Thanks to Rusty Russell and his How-To, as much of this is based off that.

IptablesHowTo (последним исправлял пользователь gunnarhj 2020-04-11 23:42:18)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

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

Успешно применять этот инструмент могут не только продвинутые пользователи Linux, но и новички. В этом руководстве представлено описание базовых настроек конфигурации этого мощного файрвола.

Что такое iptables

Как сказано выше, iptables является утилитой, выполняющей функции межсетевого экрана. Настройка iptables производится в командной строке, с помощью правил iptables можно разрешать или блокировать прохождение трафика. Когда происходит попытка установления соединения с текущей машиной, iptables просматривает список правил в списке, чтобы понять, как нужно поступить в этом случае. Если правила нет, то выполняется действие по умолчанию.

Как правило, itpables предустанавливается на всех Linux-дистрибутивах. Чтобы обновить утилиту, или установить ее, если по каким-то причинам она отсутствует в базовой поставке, нужно воспользоваться следующей командой:

Существует три типа правил iptables — input, forward и output.

Input — Такие цепочки используются для контроля поведения входящих соединений. К примеру, если пользователь попробует подключиться к серверу по SSH, то iptables сравнит его IP-адрес со своим списком, чтобы разрешить или запретить доступ.

Forward — Правила этого типа используются для обработки входящих сообщений, конечный пункт назначения которых не является текущим сервером. К примеру, в случае маршрутизатора, к нему подключаются многие пользователи и приложения, но данные не посылаются на сам маршрутизатор, они лишь передаются ему, чтобы он мог перенаправить их адресату. Если вы не занимаетесь настройкой маршрутизации или NAT, то правила этого типа использовать в работе не будете.

Output — Такие цепочки используются для исходящих соединений. К прмиеру, если пользователь пытается отправинг запрос ping к сайту 1cloud.ru, iptables изучит цепочку правил, чтобы понять, что нужно делать в случае ping и этого сайт, и только потом разрешит или запретит соединение.

Важный момент

Даже в случае пинга внешних хостов, нужно не только отправить пакеты к ним, но и получить ответ. При работе с iptables важно помнить, что многие протоколы передачи данных требуют двусторонней коммуникации. Поэтому нужно настраивать правила соответствующим образом — случаи, когда новички забывают разрешить работу с сервером по SSH случаются очень часто.

Рассмотрим вариант закрытия всех портов на сервере minecraft

Скопируйте и вставьте следующее содержимое (подсказка: чтобы вставить в терминал, используйте Ctrl + Shift + V):

Измените права доступа к файлу, чтобы только пользователь root мог запускать скрипт:

Вот и все! Теперь, когда вам нужно настроить iptables, просто запустите скрипт:

Когда вам нужно изменить правила брандмауэра, отредактируйте скрипт и запустите его снова.

Запуск iptables при загрузке

Чтобы наш брандмауэр был идеальным, не хватает только одного: правила должны быть установлены во время загрузки вместе с операционной системой, сетью и службами.

В дистрибутивах systemd, таких как openSUSE и Linux Kamarada, лучший способ запустить сценарий, такой как my-firewall.sh, во время загрузки — это создать службу.

Например, создайте службу systemd с именем my-firewall.service в папке /etc/systemd/system/ с помощью вашего любимого текстового редактора:

Скопируйте и вставьте следующее содержимое:

Настройте права доступа к файлам:

Установите и включите службу, чтобы она запускалась при следующей загрузке:

Если вы хотите протестировать свою службу перед перезагрузкой, запустите:

Вот и все! В следующий раз, когда вы перезагрузите систему, systemd запустит службу, которая запускает скрипт, настраивающий iptables.

Как закрыть порт iptables

Серверы и компьютеры, подключенные к интернету подвержены атакам и сканированию различных скриптов, программ и злоумышленников. А поскольку известно, что во всех системах могут быть уязвимости, то лучше, чтобы извне было видно минимум портов.

Некоторые порты должны быть видны постоянно, например, порт веб-сервера, другие используются только системными администраторами, а еще одни, вообще, должны быть доступны только локально. Несмотря на то что все сервисы имеют методы авторизации, и не позволят подключиться кому попало, они могут быть уязвимы, поэтому все лишнее лучше закрыть. В этой статье мы рассмотрим как закрыть порт iptables. Мы закроем нужные порты полностью, а также сделаем некоторые из них доступными на время, после попытки подключения к определенному порту.

Как закрыть порт Iptables

В этой статье я не стану подробно рассматривать все возможности Iptables, виды цепочек и как работает эта служба. Все это мы рассмотрели в статье настройка Iptables для начинающих. Вместо этого, перейдем ближе к делу. Чтобы заблокировать порт нам сначала нужно понять какие порты открыты в Linux и за что они отвечают. Чтобы посмотреть какие порты слушаются локально, можно использовать утилиту netstat:

sudo netstat -ntulp

Для анализа портов, доступных извне используется программа nmap:

Как видите, извне у нас, кроме стандартных портов веб-сервера, доступны mysql, ftp, dns и другие сервисы. Некоторые из них не должны быть доступны публично. Это не критично, но и нежелательно. Мы можем очень просто закрыть такие порты с помощью iptables. Общий синтаксис команды для блокировки порта будет выглядеть вот так:

$ iptables -A INPUT -p tcp —dport номер_порта -j DROP

Например, если мы хотим заблокировать порт iptables mysql, то необходимо выполнить:

sudo iptables -A INPUT -p tcp —dport 3306 -j DROP

Можно закрыть порт для определенного интерфейса, например, eth1:

sudo iptables -A INPUT -i eth1 -p tcp —dport 3306 -j DROP

Или даже для ip и целой подсети. Например, закрыть все подключения к порту 22 SSH кроме IP адреса 1.2.3.4:

sudo iptables -A INPUT -i eth1 -p tcp -s !1.2.3.4 —dport 22 -j DROP

Здесь знак восклицания означает инверсию, то есть применить ко всем кроме этого. Можно убрать этот знак и указать только IP, к которым нужно применить запрет. Мы рассмотрели как закрыть порт iptables в цепочке INPUT, которая отвечает за входящие соединения, это более применимо к серверам. Но что, если нужно закрыть подключение к удаленному порту из этого компьютера или нашей сети? Для этого существует цепочка OUTPUT.

Например, заблокируем попытки отправки почты подключением к любой машине по порту 25:

sudo iptables -A OUTPUT -p tcp —dport 25 -j DROP

Также, как и раньше, вы можете указать исходящий сетевой интерфейс, только теперь он указывается опцией -o:

sudo iptables -A OUTPUT -o eth1 -p tcp —dport 25 -j DROP

После того как вы завершите с настройкой портов нужно сохранить все созданные правила, чтобы они остались активными даже после перезагрузки. Для этого выполните:

Чтобы посмотреть текущие правила для каждой из цепочек выполните:

sudo iptables -L -n -v

Такая команда покажет все правила, а если вы хотите только информацию о заблокированных портах, выполните:

sudo iptables -L -n -v | grep -i DROP

Очистить все правила в случае возникновения проблем можно командой:

sudo iptables -F

Закрыть порты iptables, кроме разрешенных

По умолчанию политика для цепочек INPUT и OUTPUT — разрешать все подключения, а уже с помощью правил мы указываем какие подключения стоит запретить. Но если вы хотите закрыть все порты кроме разрешенных iptables. То нужно поступить по-другому. Мы поменяем политику по умолчанию, так чтобы она запрещала все и разрешим только доступ к нужным портам.

Например, меняем политику для цепочки INPUT:

sudo iptables -P INPUT DROP

Затем разрешаем все входящие соединения от локального интерфейса:

sudo iptables -A INPUT -i lo -j ACCEPT

Затем разрешаем доступ к портам 80 и 22:

sudo iptables -A INPUT -i eth0 -p tcp —dport 80 —match state —state NEW -j ACCEPT $ sudo iptables -A INPUT -i eth0 -p tcp —dport 80 —match state —state NEW -j ACCEPT

Как скрыть порт iptables?

Закрыть порт, это очень хорошо, но что если он нужен нам открытым и желательно, чтобы для других этот же порт был недоступен. Существует такая технология, как Port Knocking, которая позволяет открывать нужный порт только для определенного ip адреса и только после обращения его к нужному порту. Например, нам нужно защитить SSH от перебора паролей и несанкционированного доступа. Для этого все пакеты, которые будут приходить на порт 22, 111 и 112 мы будем перенаправлять в цепочку SSH.

Как вы уже догадались, порт 22 нам непосредственно нужен, на порты 111 и 112 будут включать его и отключать соответственно. Когда пользователь обратится к порту 111 мы укажем системе, что нужно присвоить всем его пакетам имя ssh, при обращении к порту 112 уберем этот флаг. А если пользователь решит зайти на 22 порт, то проверим присвоено ли этому пакету имя SSH, если да, то пропустим, в противном случае — отбросим.

Сначала создаем цепочку SSH:

sudo iptables -N SSH

sudo iptables -A INPUT -p tcp —dport 22 -j SSH $ sudo iptables -A INPUT -p tcp —dport 111 -j SSH $ sudo iptables -A INPUT -p tcp —dport 112 -j SSH

При обращении к порту 111 присваиваем IP адресу имя, сам пакет дальше не пускаем:

sudo iptables -A SSH -p tcp -m state —state NEW -m tcp —dport 111 -m recent —set —name SSH —rsource -j DROP

При обращении к 112 убираем имя у IP:

sudo iptables -A SSH -p tcp -m state —state NEW -m tcp —dport 112 -m recent —remove —name SSH —rsource -j DROP

И нам осталось только проверить имеет ли наш пакет, который пытается обратиться к 22 порту имя SSH и если да, то мы его одобряем:

sudo iptables -A SSH -p tcp -m state —state NEW -m tcp —dport 22 -m recent —rcheck —name SSH —rsource -j ACCEPT

Вот и все. Теперь для того чтобы открыть наш SSH порт будет достаточно попытаться подключиться к порту 111 с помощью telnet. Утилита сообщит, что произошла ошибка во время подключения, поскольку мы отбросили пакет:

telnet ip_адрес 111

Но зато теперь вы можете получить доступ к сервису SSH на порту 22. Чтобы снова закрыть порт выполните:

telnet ip_адрес 112

Даже при открытии, этот порт доступен только вашему ip адресу и больше никому другому. Но нужно заметить, что это не панацея. Кто-либо может случайно запросить порт, который предназначен для активации, и таким образом, открыть себе доступ к службе SSH. Так что надежные пароли и ключи шифрования это не отменяет.

Выводы

В этой статье мы рассмотрели как закрыть порт iptables, а также как его скрыть с возможностью подключения, когда это будет необходимо. Надеюсь, эта информация была для вас полезной.

How to close an open port in Ubuntu?

I need a command to list all open ports in my PC, and another command to close a port.

I need to close some applications’ port.

uzaif's user avatar

nux's user avatar

7 Answers 7

netstat can be used to see the ports stat.

To list all Listening ports Numbers with the Process responsible on each one. Terminate or kill the process to close port. ( kill , pkill . )

Without process termination, It is not possible! . See Manually closing a port from command line. Other way you may look for a firewall solution (as isolating that port from network)

user.dz's user avatar

for closing open port in ubuntu you can use below command

in place of 3000 you can specify your port number

lsof command will give information about file opened by process

-t : This flag specifies that lsof should produce terse output with process identifiers only and no header — e.g., so that the output may be piped to kill(1). This option selects the -w option.

-i : This flag selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *