Как закрыть порты на windows server

Рассмотрим как можно закрыть порты 135 и 445 в версиях Windows 2008/2012.
В связи с тем что в начале апреля в сеть были выложены инструменты для обхода защиты Windows, в частности по портам 445 и 135.
Подробнее в новости xakep.ru/2017/04/24/doublepulsar/

Исправление уязвимости доступно установкой обновлений MS17-010, CVE-2017-0146, и CVE-2017
Более подробно по ссылке geektimes.ru/post/288148/

Рассмотрим 2 варианта создания правил в брандмауере, через командную строку и через графический интерфейс.
Инструкция для настройки разрешения подключения только с доверенных адресов находится после Windows 2012

Windows 2008

Первый вариант, через командную строку

1. Через меню «Пуск» находим приложение cmd

2. Вводим или вставляем команду

netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=135 name="Block_TCP-135

Нажимаем Enter, ждём сообщения Ok

Вводим или вставляем вторую команду

netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=445 name="Block_TCP-445"

Нажимаем Enter, ждём сообщения Ok

Второй вариант, через графический интерфейс

1. В меню «Пуск» находим — панель управления

2. Заходим в панель управления, в поиск вводим «брандмауер» и запускаем панель управления брандмауером Windows

3. Входим в «Дополнительные параметры»

4. Выбираем строку «Правила входящих подключений» и нажимаем на «Создать новое правило»

5. Устанавливаем отметку «Для порта», нажимаем далее

6. Выбираем «Протокол TCP» и «определенные локальные порты», вводим в поле 135 и 445 через запятую, нажимаем далее

7. Выбираем блокировать «Блокировать», нажимаем далее

8. Оставляем все отметки, нажимаем далее

9. Вводим имя правила, нажимаем «Готово»

Windows 2012

Шаги по настройке для Windows 2012 не отключаются от 2008, отличия только в интерфейсе.

Отличия при настройке через командную строку

1. Найдем приложение cmd

2. Вводим команду, нажимаем Enter, ждем сообщения Ok

netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=135,445 name="Block_TCP-135,445"

Отличия при настройке через графический интерфейс

1. Кнопка запуска панели управления находится на стартовом экране, так же Вы можете найти панель управления через поиск на стартовом экране.

Остальные шаги идентичны Windows 2008

Настройка на Windows 2016 идентична Windows 2012

По указанным шагам возможна блокировка любых TCP/UDP портов.

Настройка доступа по портам 135 и 445 только доверенным адресам

1. Отключим системные разрешающие правила для портом 135 и 445
Выберем правила: Управление DFS (входящий трафик SMB) и Управление DFS (входящий трафик DCOM)
Нажимаем «Отключить правило»

2. Создадим новое правило, выберем тип правила «настраиваемое»

3. Выбираем «все программы»

4. Выбираем тип протокола TCP, локальный порт указываем «специальные порты», в поле вводим 135 и 445 через запятую

5. Укажем удаленный доверенный адрес, к примеру это может быть ip адрес Вашего офиса, выбираем «указанные адреса», нажимаем «добавить»

6. Вводим адрес в строку, если у Вас подсеть или диапазон, их требуется вводить в указанном в окне виде

7. Проверяем введенный адрес, нажимаем далее

8. Выбираем «разрешить подключение»

9. Оставляем все отмеченное, нажимаем далее

10. Даём название, нажимаем «готово»

What is Windows Firewall?

How to Open Ports in Windows Firewall

Step 1: Open the Control Panel

Step 2: Select System and Security

Step 3: Choose Windows Defender Firewall

Step 4: Select Advanced Settings

Step 5: Create a New Rule

Step 6: Select Port

Step 7: Choose TCP or UDP

Step 8: Allow or Block the Connection

Step 9: Specify Rule Options

Step 10: Name and Finish

How to Block a Port

Step 1: Select the Rule

Step 2: Access the Rule’s Properties

Step 3: Choose Block the Connection

How to Disable or Delete a Firewall Rule

Step 1: Open the Control Panel

Step 2: Select System and Security

Step 3: Open Windows Defender Firewall:

Step 4: Select Advanced Settings

Step 5: Navigate to Inbound or Outbound Rules

Step 6: Find the Rule

Step 7: Disable or Delete the Rule

Tags: Windows,  Firewall 

Table of Contents

What is Windows Firewall?

How to Open Ports in Windows Firewall

Step 1: Open the Control Panel

Step 2: Select System and Security

Step 3: Choose Windows Defender Firewall

Step 4: Select Advanced Settings

Step 5: Create a New Rule

Step 6: Select Port

Step 7: Choose TCP or UDP

Step 8: Allow or Block the Connection

Step 9: Specify Rule Options

Step 10: Name and Finish

How to Block a Port

Step 1: Select the Rule

Step 2: Access the Rule’s Properties

Step 3: Choose Block the Connection

How to Disable or Delete a Firewall Rule

Step 1: Open the Control Panel

Step 2: Select System and Security

Step 3: Open Windows Defender Firewall:

Step 4: Select Advanced Settings

Step 5: Navigate to Inbound or Outbound Rules

Step 6: Find the Rule

Step 7: Disable or Delete the Rule

What is Windows Firewall?

Windows Firewall is a security feature built into Windows that helps protect your system by filtering incoming and outgoing network traffic. It does this by allowing or blocking specific traffic based on a set of rules you define. For example, when a program needs access to the internet, you might see a pop-up asking you to allow or deny the connection. This is Windows Firewall working to ensure you’re aware of what’s trying to connect to your computer.

By default, Windows Firewall focuses on external connections and unknown networks. Local connections, such as those to your printer, are not typically blocked unless you manually set rules to do so.

How to Open Ports in Windows Firewall

The following guide explains how to open firewall ports on Windows 10 and Windows Server 2016. Steps for other versions of Windows should be quite similar.

Step 1: Open the Control Panel

  • Search for «Control Panel« in the Windows search bar.

Step 2: Select System and Security

  • Click on System and Security.

Step 3: Choose Windows Defender Firewall

  • Click on Windows Defender Firewall from the list of options.

Step 4: Select Advanced Settings

  • On the left side, find and click on Advanced Settings.

Step 5: Create a New Rule

  • Depending on your needs, choose either Inbound Rules (regulating incoming traffic) or Outbound Rules (regulating outgoing traffic).

  • Right-click on the rule you want to edit and click New Rule.

Note: it is suggested to create the same rule for the opposite option for simplicity and security.

Step 6: Select Port

  • Choose Port to create a rule for a specific port.

Step 7: Choose TCP or UDP

  • Most ports use TCP, but some may use UDP. Select the type of connection you want to control.

  • Add the port manually in the text box and click «Next» when you have specified this to fit your needs.

Step 8: Allow or Block the Connection

  • Decide whether you want to allow or block the connection through this port.

Step 9: Specify Rule Options

  • Choose the profiles to which the rule applies. You can select all profiles, but typically you want to ensure the Public profile is checked

Step 10: Name and Finish

  • Give the rule a name and optional description, then click Finish.

Your new rule should now be active and the port open according to your settings.

How to Block a Port

Step 1: Select the Rule

  • In the Advanced Settings, locate and click the rule (inbound or outbound) you want to block.

Step 2: Access the Rule’s Properties

  • Locate the rule name you want to block, Right-click it and select Properties.

Step 3: Choose Block the Connection

  • In the General tab, select Block the connection and click Apply.

The rule should now be updated to block the connection, and you may see a red circle or other indicator showing the rule has been changed.

How to Disable or Delete a Firewall Rule

You can disable or delete firewall rules within your Windows Firewall by following these steps.

Step 1: Open the Control Panel

  • Search for «Control Panel» in the Windows search bar.

Step 2: Select System and Security

  • Choose System and Security from the options.

Step 3: Open Windows Defender Firewall:

  • Click on Windows Defender Firewall.

Step 4: Select Advanced Settings

  • Locate and click on Advanced Settings on the left side of the window.

Step 5: Navigate to Inbound or Outbound Rules

  • Depending on the rule you want to adjust, select either Inbound Rules or Outbound Rules.

Step 6: Find the Rule

  • Locate the rule you want to disable or delete.

Step 7: Disable or Delete the Rule

  • Right-click the rule and choose either Disable Rule or Delete.

Disabling a rule keeps it inactive but available for future use (Reenable by right-clicking the rule and selecting Enable Rule), while deleting a rule removes it permanently. Only delete a rule if you’re sure you no longer need it.

Remember, when making changes to firewall rules, proceed with caution to avoid unintended disruptions in your network traffic. Always double-check your choices before applying changes.

Содержание

  1. Самые уязвимые порты Windows 7 – 10
  2. Как проверить, какие порты открыты
  3. Как закрыть порты с 135 по 139 и 445 в Windows?
  4. Инструкция по работе с программой, закрывающей порты
  5. Заключение

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

Чаще всего вирусы атакуют компьютеры с операционной системой Windows. Это объясняется тем, что большинство вирусов проникают в операционную систему через определенные входящие соединения, называемые «портами», которые, к сожалению, обычно активированы по умолчанию.

Простыми словами, «порт» — это номер входящего соединения, через которое внешние программы (включая вирусы) могут связаться с вашим компьютером через сеть IP. Каждому порту присваивается уникальный номер, который определяет, какому приложению в операционной системе предназначены входящие данные.

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

Самые уязвимые порты Windows 7 – 10

Изучение крупных случаев вирусных атак показывает, что 80% вредоносного трафика проходят через четыре порта, используемые для обмена данными между разными версиями операционной системы Windows. Среди наиболее уязвимых открытых портов Windows можно выделить следующие:

  • TCP порт 445 (применяется для обмена файлами).
  • TCP порт 139 (предназначен для удаленного подключения к компьютеру).
  • UDP порт 137 (используется для поиска информации на других компьютерах).
  • TCP порт 135 (через него выполняются команды и задания).

Как проверить, какие порты открыты

Для определения наличия открытых уязвимых портов на вашем устройстве, вы можете воспользоваться сканером портов от Whoer.net. Путем идентификации вашего IP-адреса и использования инструмента nmap, этот сервис проверки открытых портов предоставит вам информацию о том, какие порты открыты на вашем устройстве и какие программы ими пользуются. Это даст вам возможность оценить уровень уязвимости вашего устройства и насколько оно подвержено потенциальным угрозам в сети Интернет.

Как закрыть порты с 135 по 139 и 445 в Windows?

Существует множество методов, которые могут быть использованы для блокировки портов в операционной системе Windows, но в данной статье мы сосредоточимся на наиболее простых способах этого достичь.

Первый способ — использование командной строки

Командная строка в операционной системе Windows предназначена для настройки параметров, которые не имеют графического интерфейса. К одним из таких функций относится контроль за открытыми портами подключений.

Для запуска командной строки можно выполнить следующие шаги:

  • Нажмите комбинацию клавиш Win+R.
  • В появившемся окне «Выполнить» введите «CMD».
  • Нажмите «ОК».

Вы увидите окно с черным фоном. Поступите следующим образом: последовательно скопируйте строки, представленные ниже, и нажмите клавишу «Enter»:

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=135 name=“Block1_TCP-135”

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=137 name=“Block1_TCP-137”

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=138 name=“Block1_TCP-138”

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=139 name=“Block_TCP-139” (команда помогает закрыть порт 139)

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=445 name=“Block_TCP-445” (команда помогает закрыть порт 445)

netsh advfirewall firewall add rule dir=in action=block protocol=tcp localport=5000 name=“Block_TCP-5000”

Эти шесть команд блокируют четыре из перечисленных выше наиболее уязвимых открытых портов Windows, а также порт 5000, который отвечает за обнаружение доступных служб, и UDP порт 138 для разрешения имен NetBIOS.

Способ 2 – использование сторонних программ

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

Рекомендуется использовать программу Windows Doors Cleaner, которая упрощает процесс закрытия портов на компьютере (поддерживается на Windows 10-7, но не на старых версиях ОС).

Инструкция по работе с программой, закрывающей порты

  1. Сначала загрузите и установите программу.
  2. После установки, запустите программу с правами администратора.
  3. В окне программы, нажмите кнопки «Закрыть» или «Отключить» для блокировки всех уязвимых портов Windows.

  4. После внесения необходимых изменений, перезагрузите операционную систему Windows.

Важно отметить, что с помощью этой программы также можно открыть порты, если это потребуется.

Заключение

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

Для обеспечения максимальной безопасности Windows необходимо устанавливать критические обновления, предоставляемые Microsoft, использовать антивирусное программное обеспечение, выбирать безопасные веб-браузеры и другие инструменты, способствующие укреплению безопасности и анонимности.

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

Простой способ закрыть все порты в Windows при помощи Брандмауэра Windows (Windows Firewall) и оставить только нужные

Проблема

Проблема Брандмауэра Windows (Windows Firewall) заключается не в том как закрыть все порты, а в том, как открыть только необходимые. И главное, что сходу хрен поймешь, каким образом ограничить подключение к некоторым портам по IP адресам клиентов. По отдельности решить эти задачи не сложно, но чтобы было вместе — не встретил ни одного толкового руководства, поэтому и написана данная заметка. Так же, найденное решение не предполагает установки стороннего фаервола.

Недостатки Брандмауэра Windows:
— Если создать запрещающее правило для всех портов, а потом разрешающие для необходимых, то они не попадают в белый список, т.к. запрещающие правила приоритетнее разрешающих. Т.е. если запрет на подключение по порту существует, то разрешение на этот порт работать уже не будет.
— Нет приоритетов правил, как в нормальных фаерволах, чтобы сначала указать открытые порты, а последним задать запрещающее правило для всех остальных.

Допустим, есть VPS на винде, но у хостера нет внешнего фаервола, которым можно прикрыться. Свежеустановленная винда торчит наружу как минимум 135/tcp, 445/tcp, 49154/tcp и 3389/tcp (если включен RDP) портами даже в публичной сети (Public network), что требует исправления.

Алгоритм

Есть три типа портов, это:
— Общедоступные порты, которые должны быть открыты для всего интернета. Пусть будут 80 и 443 (http и https)
— Фильтруемые порты, доступные только с определенных IP адресов. Возьмем 3389 (RDP)
— Все остальные, должны быть закрыты
Требуется:
1. Создать правило, запрещающее всё, кроме трех вышеобозначенных портов.
2. Для общедоступных больше делать ни чего не требуется.
3. Для фильтруемого создать разрешающее правило, указав белые адреса.

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

Пример

Задача 1: оставить открытыми для всего интернета 80, 443 и 3389 порты. Все остальные закрыть.
1. Создать новое правило для входящих подключений
2. Тип правила (Rule Type). Настраиваемые (Custom)
3. Программа (Program). Все программы (All programs)
4. Протокол и порты (Protocol and Ports). Тип протокола (Protocol type) — TCP. Локальный порт (Local port) — Специальные порты (Specific Ports). В поле вписать диапазон портов, за исключением 80, 443 и 3389. Должно выглядеть так — 1-79, 81-442, 444-3388, 3390-65535
5. Область (Scope). Локальный (local) — Любой IP-адрес (Any IP address). Удаленный (remote) — Любой IP-адрес (Any IP address).
6. Действие (Action). Блокировать подключение (Block the connection).
7. Профиль (Profile). Выбрать на свое усмотрение. Если не уверен, то выбрать все.
8. Имя (Name). Назвать его, например, Block_TCP.

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

Задача 2: оставить открытыми для всего интернета 80 и 443 порты. Ограничить подключение на порт 3389 только с разрешенных IP адресов. Все остальные закрыть.
Шаги 1-8 аналогичны предыдущей задаче, т.е. создается правило, разрешающее коннект по трем указанным портам.
Для фильтрации по IP надо создать второе правило:
9. Создать новое правило для входящих подключений
10. Тип правила. Настраиваемые
11. Программа. Все программы
12. Протокол и порты. Тип протокола — TCP. Локальный порт — специальные порты. Вписать порт 3389
13. Область. Локальный — Любой IP-адрес. Удаленный — Указанные IP-адреса. Сюда вписать белый список IPшников или подсетей, которым разрешен коннект по данному порту
14. Действие. Разрешить подключение.
15. Профиль. Выбрать на свое усмотрение. Если не уверен, то выбрать все.
16. Имя. Назвать его, например, RDP.

Если фильтруемых портов несколько, то создается по одному правилу на каждый порт.

Ну и чтобы стать совсем защищенным — создать правило, блокирующее все UDP соединения.

Задача 2 из консоли

Для хардcoreщиков приведу вторую задачу в виде консольных команд:

netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=1-79,81-442,444-3388,3390-65535 name="Block_TCP"
netsh advfirewall firewall add rule dir=in action=allow protocol=TCP localport=3389 remoteip=192.168.0.0/24,x.x.x.x name="RDP"
netsh advfirewall firewall add rule dir=in action=block protocol= UDP name="Block_All_UDP"

В конечном итоге, в гуёвине должно выглядеть так:
Для правила RDP:

rdp

rdp3

rdp2

Для правила Block_TCP:

block_tcp_2

block_tcp

 


UPDATE

Выяснилось, что приведенный выше синтаксис командной строки не работает на WS2008R2, а конкретно — перечисления в любом параметре, поэтому пришлось разбивать два правила на восемь:

netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=1-79 name="Block_TCP-1"
netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=81-442 name="Block_TCP-2"
netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=444-3388 name="Block_TCP-3"
netsh advfirewall firewall add rule dir=in action=block protocol=TCP localport=3390-65535 name="Block_TCP-4"

netsh advfirewall firewall add rule dir=in action=allow protocol=TCP localport=80 name="HTTP"
netsh advfirewall firewall add rule dir=in action=allow protocol=TCP  localport=443 name="HTTPS"

netsh advfirewall firewall add rule dir=in action=allow protocol=TCP localport=3389 remoteip=192.168.0.0/24 name="RDP-1"
netsh advfirewall firewall add rule dir=in action=allow protocol=TCP localport=3389 remoteip=x.x.x.x name="RDP-2"

Open ports in Windows 10 are often deemed dangerous because hackers can exploit them if the service or application the ports are associated with are unpatched or lack basic security protocols. Therefore, it is recommended to close any listening network ports that your system isn’t using.

Let us brief you on what ports are and why they can be dangerous.

Table of Contents

What are network ports?

Network ports are used by Windows services and applications to send and receive data over the network. If you wonder if this is what the IP address is used for, then you are absolutely correct. However, a unique IP address defines the path to a specific device, whereas a port defines what application or service on that particular device to send that information to.

Just like the IP addresses, a port is also unique within its ecosystem. Meaning, the same port cannot be used by two different services/applications. Therefore, both of these unique identifiers, the IP address, and the port number, are used to send and receive information from a computer.

A port number can be found suffixed to an IP address, as in the example below:

xxx.xxx.xxx.xxx:80

Here, the numbers followed by the colon denote the port number. Below are a few ports used by certain services and applications by default:

  • FTP – 21
  • SSH – 22
  • Telnet – 23
  • SMTP – 25
  • DNS – 53
  • DHCP – 67 & 68
  • HTTP – 80 & 8080
  • HTTPS – 443
  • SNMP – 161
  • RDP – 3389

A single IP address can have 65535 TCP and 65535 UDP ports in total.

Are open network ports dangerous?

Not all ports that are listening are dangerous. Sometimes an application opens the ports automatically without informing the users. If the application is poorly constructed and the security protocols lack the basic infrastructure, an attacker might exploit those and infiltrate your PC.

An open networking port is not always dangerous, but it is always better to keep your guard up and close any ports that are not required.

2 ways to check which ports are open/listening in Windows 10

You can figure out which ports are currently open on your computer, even if the installed applications did not inform you that they are using them. Here are 2 ways to check which ports are open and which service/application uses them on your local computer before you proceed to block them.

Here is a guide to check if a remote network port is open.

Determine open ports with process name using Command Prompt

Some applications give out the name of the application/service associated with a port number. You can use the below-given command in Command Prompt to determine which ports are open and what are the names of the associated applications.

  1. Open Command Prompt with administrative privileges.
  2. Enter the following command:
    netstat -ab
  3. Command Prompt will now display the output of open network ports with their associated application/service names, as in the image below:
    cmd 1 1

Since the IP address assigned to our computer is 10.0.0.31, it displays different ports used by various applications suffixed to the IP address. However, as you may notice, some of the names of the services and applications are unidentifiable. For that, we shall adopt the second method.

Determine open ports with process ID using Command Prompt

In this approach, we shall be comparing the process IDs of the running applications and services associated with the ports and then determining the name of the process using the Task Manager. Here is how to do so:

  1. Open Command Prompt with administrative privileges.
  2. Enter the following command:
    netstat -aon
  3. Command Prompt will now display a list of TCP and UDP ports currently listening on your computer. Note the associated PIDs to compare from the Task Manager.
    PID

  4. Now open the Task Manager by right-clicking on the Taskbar and clicking on Task Manager. Or, you may use the Ctrl + Shift + Esc shortcut keys.
  5. Now switch to the Details tab within the Task Manager and match the PID with the associated name of the process/application.
    task manager

Now you have sufficient information on the ports you would like to close, if any. Proceed to the next step to block/close any listening ports on your computer.

How to close an open port

If you have found a port that you are no longer using or are not sure if it is secure to keep open, you should preferably block it. If you wish to close an open port, you can do so with Windows Firewall  or Windows Defender in case of Windows 10.

  1. Open the Windows Firewall by going to Start –> Control Panel –> Windows Firewall. If you are using Windows 10, you can open the Windows Defender Firewall by going to Run –> firewall.cpl.
  2. From the left side menu, click on Advanced settings.
  3. From the right side menu of the new window, select Inbound Rules.
    New Rule

  4. Then click New rule in the right pane.
  5. On the Rule type screen in New inbound rule wizard, select Port and then click Next.
    port

  6. On the next screen, select the type of port as determined through the Command Prompt earlier, and then enter the port number you want to close in front of Specific local ports. Click Next when done.
    local port

  7. On the next screen, select Block the connection and then click Next.
  8. On the Profile screen, select All Profiles and click Next.
    profiles

  9. Now set a name for the rule and click Finish.

You have now successfully disabled the port. You can repeat the steps to block additional ports or delete this one by navigating to the Inbound rules and removing the respective rules.

How to quickly close ports using Command Prompt

A couple of commands can be used to identify the processes that have opened the ports and then close the ports by killing the process.

  1. Open Command Prompt and run the command: netstat -a -o -n. This will show all the open ports in your system along with their current state and the process ID that have opened the ports.
  2. If you want to find a specific port, you should run the command: netstat -a -o -n | findstr “993”. Replace 993 with the port number you want to find.
    Find open ports in cmd

  3. The last column on the list is the Process ID or PID number. Killing the process will automatically close the listening port. To kill the process, run the command: taskkill /pid 993.
    Kill the process to close ports

Please note that this is a quick and temporary way of closing the port using the command prompt. If you want to permanently block the port from opening again, you should follow the first method given above.

How to block network ports in Windows Firewall using Command Prompt

Block port in Windows Firewall using command line

You can also permanently block ports in Windows Defender Firewall using the Command Prompt.

To create a block port rule in Windows Firewall, run the following command in Command Prompt:

netsh advfirewall firewall add rule name="Rule Name" protocol=TCP dir=out remoteport=993 action=block

Replace Rule Name with your own rule name, for example, since I’m blocking IMAP port, I’ll name the rule as Block IMAP. Replace TCP with either RCP or UDP, whichever port you want to block. Replace 993 with the actual port number you want to block.

Unblock/Open port in Windows Firewall using command line

To open the port again, simply run the following command in CMD:

netsh advfirewall firewall delete rule name="Rule Name"

Replace Rule Name with the actual rule name, Block IMAP in my case. This will delete the rule that we created above.

Closing words

Listening ports are not always dangerous, as it is very much dependent on what application/service it is open through. Nonetheless, it is still important not to give the attacker any chance to exploit your system’s vulnerabilities and wise to close any ports that are not being used.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • 0x80042468 при установке windows
  • Служба узла журнал событий windows 10 грузит процессор
  • Как удалить обновление windows 10 через cmd
  • Windows xp error 0x0000007b
  • Virtualbox общие папки для windows