- Как настроить брандмауэр с UFW в Debian 10
- Подготовка
- Установка UFW
- Проверка статуса UFW
- Политики UFW по умолчанию
- Профили приложений
- Разрешить SSH-подключения
- Включить UFW
- Открытие портов
- Открытый порт 80 — HTTP
- Открытый порт 443 — HTTPS
- Открытый порт 8080
- Открытие портовых диапазонов
- Разрешение определенных IP-адресов
- Разрешение определенных IP-адресов на определенном порту
- Разрешение подсетей
- Разрешить подключения к определенному сетевому интерфейсу
- Запретить подключения
- Удалить правила UFW
- Отключить UFW
- Сбросить UFW
- Выводы
- как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- Re: как отключить iptables
- DebianFirewall
- Introduction
- Basic firewall software
- Basic software for network traffic manipulation
- Using iptables for IPv4 traffic
- Using ip6tables for IPv6 traffic
- Using ebtables for ARP traffic
- Application firewalls
- Troubleshooting software and tips
- Graphic applications and frontends
- Related articles
Как настроить брандмауэр с UFW в Debian 10
Правильно настроенный брандмауэр — один из наиболее важных аспектов общей безопасности системы.
UFW (несложный брандмауэр) — это удобный интерфейс для управления правилами брандмауэра iptables. Его основная цель — сделать управление iptables проще или, как следует из названия, несложным.
В этой статье описывается, как настроить брандмауэр с UFW в Debian 10.
Подготовка
Только root или пользователь с привилегиями sudo может управлять системным брандмауэром.
Установка UFW
Введите следующую команду, чтобы установить пакет ufw :
Проверка статуса UFW
Установка не активирует брандмауэр автоматически, чтобы избежать блокировки сервера. Вы можете проверить статус UFW, набрав:
Результат будет выглядеть так:
Если UFW активирован, вывод будет выглядеть примерно так:
Политики UFW по умолчанию
По умолчанию UFW блокирует все входящие соединения и разрешает все исходящие соединения. Это означает, что любой, кто пытается получить доступ к вашему серверу, не сможет подключиться, если вы специально не откроете порт. Приложения и службы, работающие на сервере, смогут получить доступ к внешнему миру.
Политики по умолчанию определены в /etc/default/ufw и могут быть изменены с помощью команды sudo ufw default
Политики брандмауэра являются основой для создания более подробных и определяемых пользователем правил. Как правило, исходные политики по умолчанию UFW являются хорошей отправной точкой.
Профили приложений
Большинство приложений поставляются с профилем приложения, который описывает службу и содержит настройки UFW. Профиль автоматически создается в каталоге /etc/ufw/applications.d во время установки пакета.
Чтобы вывести список всех профилей приложений, доступных в вашей системе, введите:
В зависимости от пакетов, установленных в вашей системе, вывод будет выглядеть следующим образом:
Чтобы найти дополнительную информацию о конкретном профиле и включенных правилах, используйте команду app info , после которой укажите имя профиля. Например, чтобы получить информацию о профиле OpenSSH, вы должны использовать:
Вывод включает имя профиля, заголовок, описание и правила брандмауэра.
Разрешить SSH-подключения
Перед включением брандмауэра UFW необходимо разрешить входящие соединения SSH.
Если вы подключаетесь к своему серверу из удаленного места и включаете брандмауэр UFW перед тем, как явно разрешить входящие соединения SSH, вы больше не сможете подключиться к своему серверу Debian.
Чтобы настроить брандмауэр UFW на прием SSH-подключений, выполните следующую команду:
Если SSH-сервер прослушивает порт, отличный от порта по умолчанию 22, вам нужно будет открыть этот порт.
Например, ваш ssh-сервер прослушивает порт 7722 , вы должны выполнить:
Включить UFW
Теперь, когда брандмауэр UFW настроен на разрешение входящих соединений SSH, включите его, запустив:
Вы будете предупреждены, что включение брандмауэра может нарушить существующие соединения ssh. Введите «y» и нажмите «Enter».
Открытие портов
В зависимости от приложений, которые работают на вашем сервере, вам необходимо открыть порты, на которых работают службы.
Ниже приведены несколько примеров того, как разрешить входящие соединения с некоторыми из наиболее распространенных служб:
Открытый порт 80 — HTTP
Вместо профиля http вы можете использовать номер порта 80 :
Открытый порт 443 — HTTPS
Вы также можете использовать номер порта 443 :
Открытый порт 8080
Если вы запустите Tomcat или любое другое приложение, которое прослушивает порт 8080 откройте порт с помощью:
Открытие портовых диапазонов
С помощью UFW вы также можете разрешить доступ к диапазонам портов. При открытии диапазона необходимо указать протокол порта.
Например, чтобы разрешить порты с 7100 по 7200 как на tcp и на udp , выполните следующую команду:
Разрешение определенных IP-адресов
Чтобы разрешить доступ ко всем портам с определенного IP-адреса, используйте команду ufw allow from за которой следует IP-адрес:
Разрешение определенных IP-адресов на определенном порту
Чтобы разрешить доступ к определенному порту, допустим, порт 22 с вашего рабочего компьютера с IP-адресом 64.63.62.61, используйте следующую команду:
Разрешение подсетей
Команда для разрешения подключения из подсети IP-адресов такая же, как и при использовании одного IP-адреса. Единственное отличие состоит в том, что вам нужно указать маску сети. Например, если вы хотите разрешить доступ для IP-адресов от 192.168.1.1 до 192.168.1.254 и до порта 3360 ( MySQL ), вы можете использовать эту команду:
Разрешить подключения к определенному сетевому интерфейсу
Чтобы разрешить доступ к определенному порту, скажем, порт 3360 только к определенному сетевому интерфейсу eth2 , используйте eth2 allow in on и имя сетевого интерфейса:
Запретить подключения
По умолчанию для всех входящих подключений задана политика deny , что означает, что UFW будет блокировать все входящие подключения, если вы специально не откроете подключение.
Допустим, вы открыли порты 80 и 443 , и ваш сервер подвергается атаке из сети 23.24.25.0/24 . Чтобы запретить все соединения с 23.24.25.0/24 , используйте следующую команду:
Если вы хотите запретить доступ только к портам 80 и 443 из 23.24.25.0/24 используйте:
Написание запрещающих правил аналогично написанию разрешающих правил. Вам нужно только заменить allow на deny .
Удалить правила UFW
Есть два разных способа удалить правила UFW. По номеру правила и указав фактическое правило.
Удаление правил UFW по номеру правила проще, особенно если вы новичок в UFW.
Чтобы сначала удалить правило по его номеру, вам нужно найти номер правила, которое вы хотите удалить. Для этого выполните следующую команду:
Чтобы удалить правило номер 3, правило, разрешающее подключения к порту 8080, вы можете использовать следующую команду:
Второй способ — удалить правило, указав фактическое правило. Например, если вы добавили правило для открытия порта 8069 вы можете удалить его с помощью:
Отключить UFW
Если по какой-либо причине вы хотите остановить UFW и деактивировать все правила, выполните:
Позже, если вы захотите снова включить UTF и активировать все правила, просто введите:
Сбросить UFW
Сброс UFW отключит UFW и удалит все активные правила. Это полезно, если вы хотите отменить все изменения и начать все заново.
Чтобы сбросить UFW, просто введите следующую команду:
Выводы
Вы узнали, как установить и настроить брандмауэр UFW на вашем компьютере с Debian 10. Обязательно разрешите все входящие соединения, которые необходимы для правильного функционирования вашей системы, ограничив при этом все ненужные соединения.
Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.
Источник
как отключить iptables
как их вырубить чтобы их небыло? (только на время этого сеанса конечно)
#sbin/iptables service stop
#rmmod ip_tables
#rmmof iptables
ну нихрена не срабатывает
Re: как отключить iptables
Сервис остарнавливается командой
service iptables stop
Re: как отключить iptables
bash: service: command not found
система debian 3.1
Re: как отключить iptables
А man iptables не пробовали?
удалит все цепочки, так что все пакеты пройдут.
Но это для моего дистрибутива.
для вашего не знаю, так как его название вы не умудрились сообщить.
Re: как отключить iptables
> #rmmod ip_tables
> #rmmof iptables
Смотреть lsmod и вырубать модули которые действительно активны.
Но на самом деле достаточно удалить все правила из всех таблиц:
# iptables -t nat -F
# iptables -t filter -F
# iptables -t mangle -F
Re: как отключить iptables
Потому что в debian нет такой команды.
Смотри в своем /etc/rc.d название и по названию:
Re: как отключить iptables
> а нафига
посмотри тему про proftpd — это тоже моя.
Я уже просто не знаю что бы такое сотворить.
аот и хочу iptables вырубить хотя 21 open
Re: как отключить iptables
в смысле тот который 2 темы назад
Re: как отключить iptables
iptables -A INPUT -p tcp -dport 20 -j ACCEPT
iptables -A INPUT -p tcp -dport 21 -j ACCEPT
iptables -A OUTPUT -p tcp -sport 20 -j ACCEPT
iptables -A OUTPUT -p tcp -sport 21 -j ACCEPT
iptables -A INPUT -p udp -dport 20 -j ACCEPT
iptables -A INPUT -p udp -dport 21 -j ACCEPT
iptables -A OUTPUT -p udp -sport 20 -j ACCEPT
iptables -A OUTPUT -p udp -sport 21 -j ACCEPT
P.S. Можно писать не так занудно, забыл -m multiport, что ли, и порты через запятую:
iptables -A INPUT -p udp -m multiport -dport 20,21 -j ACCEPT
Re: как отключить iptables
В Debian iptables по умолчанию вообще выключен, и инит-скриптов для него нету, самому надо делать.
Re: как отключить iptables
Не, так зачем мне его открывать? Он итак открыт. По крайней мере nmap говорит что 21 open
Re: как отключить iptables
все равно решил попробовать: #iptables -A INPUT -p tcp -dport 20 -j ACCEPT , а он мне: Bad argument `20′ Try `iptables -h’ or ‘iptables —help’ for more information.
Re: как отключить iptables
Сработало по примеру:
iptables -A INPUT -p tcp —dport 21 -j ACCEPT
Но все равно: с моего же компа (там где сам сервер работает) заходит, с остальных — ни гу-гу (timeout, типа нету такого).
Источник
- DebianFirewall
Introduction
WARNING: iptables is being replaced by nftables
A network firewall is a set of rules to allow or deny passage of network traffic, through one or more network devices. A network firewall may also perform more complex tasks, such as network address translation, bandwidth adjustment, provide encrypted tunnels and much more related to network traffic.
Prior to version 5 (Lenny), a default Debian installation, did not have a default firewall enabled. But provides the needed tools to configure it manually.
Basic firewall software
Network traffic has different components, layers and protocols. For more references, check out the links section.
The most known type of firewall, and the most initially implemented, are sets of rules based on netfilter software, based on a set of kernel modules and some user space tools.
Basic software for network traffic manipulation
The default Debian installation comes with the program iptables(8), configured to allow all traffic. This section briefly explains the different programs to handle network traffic manually, as well as two sample scripts.
You need to be root, or use sudo, to launch these programs.
You may find the iptables-persistent package useful.
Using iptables for IPv4 traffic
This is not an iptables manual, only a short introduction about the use of the program. For more extended explanations, see iptables(8)
Basic invocation to define rules is:
Tables and chains
All rules, are stored on different tables.
The default table is filter, which maintain the INPUT, OUTPUT and FORWARD chains, used for incoming, outgoing and redirected traffic respectively.
Other present tables are mangle, nat and raw. You can also create and delete custom tables.
Rules and program invocation may refer to a specific table using the -t table_name switch (or --table table_name).
If no table is specified, the default table is used (the filter table).
To list the ruleset of any table, the -L switch is used. For example:
As you can see, the default policy in a default installation is to ACCEPT all traffic. There are no rules on any chain.
Each of the default tables, contain different chains, to store rules for different points, in the kernel networking subsystem.
You can list other tables using -t, for example, to see the nat (Network Address Translation) table:
Matching and order
When a packet is inspected through the rulesets, matches are searched from top to bottom of tables and chains.
Into the rules, matches are searched from left to right, of the rule syntax used.
When a packet does not match a rule, the search jumps to the next rule. If no rules matches, then the default policy is applied to the packet.
If the packet matches any rule definition, then the target defined on the rule is applied (ACCEPT, REJECT, DROP, LOG, etc), and the following rules of the same chain are skipped.
It is very important to keep this in mind when designing a ruleset, to reach the desired functionality and because of its impact on performance, in large rulesets.
Policies and Targets
Default policy is to ACCEPT all traffic, but the most common practice, is to change policies to DROP all traffic but the allowed.
You have to be careful and sure that your rules are right, before put a policy to DROP, or you will lose connectivity.
See the troubleshooting section for tips about this issue.
Program switches
Most commonly used switches are:
-A Add this rule at the end of the defined chain.
-D Delete this rule definition from the ruleset.
-I Insert this rule at the beginning of the defined chain.
-P Change the default policy of a chain.
There are other switches, to handle chains, tables, clear rules, counters and other elements. See iptables(8) man page.
Modules
The iptables program has an extensive collection of modules, to use different criteria to evaluate packets.
There are modules for protocols, logging, states of the conection, etc. All compiled-in modules, are neatly explained in the man page.
Modules may have parameters (-m module_name --parameter_name parameter_arguments).
An example rule, using the state module, to drop incoming traffic with INVALID state (a parameter of the state module), defined in the headers of the packet, would be:
Example scripts
Installation
You can put this scripts at any place that run at boot time or network initialization.
Common places are:
/etc/rc.local
Before the exit 0. Will be launched at boot time.
/etc/network/interfaces
This is a more reasonable and standard place for networking related stuff.
For example, if eth0 is your main or uniq interface, using DHCP:
SystemD | firewall.service
Most Debian distributions now include systemd. In order to bring up the iptable rules using systemd at start:
Create a new file using any reasonable file text editor(I called mine firewall.service)
Then add the following:
Then enable the service:
Example: Basic standalone machine firewall
You can use this script in any stand-alone machine (for example a personal desktop) that does not need ports open to any place. Or see the final commented line, to open specific ports.
A simple script like the one below, will provide your host with a reasonable amount of security. Be aware that the following script drops all packets which do not match an allow rule, so normal network error messages will not be seen. All allow rules have been commented out to protect the uninitiated.
Example: Basic gateway machine firewall
Using ip6tables for IPv6 traffic
Because of growth, Internet is slowly switching to IPv6, that has a much larger address space than IPv4, and Debian is IPv6 capable.
If you have IPv6 addresses, networks and conections in your firewall, you’ve to be careful and configure your rulesets for each protocol.
To configure and manage IPv6 rulesets, you need to use ip6tables(8), which is provided by the default Debian install, in the package iptables.
The usage and functionality, is very similar to iptables, but oriented to IPv6 traffic.
For more references, see: ip6tables(8)
Using ebtables for ARP traffic
Ebtables (package ebtables) is used to set up, maintain, and inspect the tables of Ethernet frame rules in the Linux kernel. It is analogous to iptables, but operates at the MAC (ARP) layer, rather than the IP layer.
If you need to filter or translate ARP traffic (at link layer), your firewall has bridged interfaces (for example a transparent bridge between a OpenVPN tunneled VLAN and a local VLAN, or bridged interfaces for virtualization), ebtables(8) is your friend.
The design is very similar to netfilter’s iptables.
It manages rulesets in tables with chains and targets, using user space tools, but this time it’s not in the default Debian installation, and you need to add it:
For a more detailed explanation of its usage, look at the inevitable man page, and visit the official website (see links section).
There are documents that explain howto integrate ebtables and iptables, using the iptables module physdev.
Application firewalls
To go more up, and manipulate the Layer 7 of the OSI model, and be able to define rules at application level, you need other tools.
For example. you open the port 80 to your users, but you don’t want them to be able to download .exe files from internet. You need an application firewall or proxy.
The default kernel in Debian does not have layer 7 patches, but you can install user space proxys to manage this kind of filters.
There are options like squid, dans guardian, zorp, etc.
?Zorp is written in python and has been added to Debian with 5.0.
See also the links section for the l7-filter project.
Troubleshooting software and tips
Some helpful (and must-have) tools are:
ip(8): (package: iproute) to list interfaces, addresses, route tables, etc.
nc(1): (package: netcat) to test tcp and udp connections, open ports, etc.
ping(8): to test ICMP traffic ( not tcp or udp).
tail(1): and other tools to monitor logs.
tcpdump(8): (package: tcpdump) to monitor «raw» packets, traffic, etc. using filters and regular expresions.
It’s very easy to lose connectivity when initially configuring a firewall. And it’s easier the more complex the firewall is.
A basic skill for troubleshoot a firewall problem, is to know the points where the traffic passes, is turned, routed, can be rejected, etc. And to know how to monitor that points, and what is happening.
The most effective is to analyze the traffic from end to end, from the initial request, the DNS, the interfaces by which must pass, the translations that have to do, the rejected traffic logs, the routing rules, etc.
A common hack when doing ruleset designing, is to put a cron task, that flush rules every few minutes, in case you will make a mistake (working in remote).
Graphic applications and frontends
There are some tools, to configure firewalls using frontends and helpers.
Some of them are:
There are also command line «high level» tools, to avoid the «low level» syntax, or to simplify certain tasks. Anyway, the real power is in the large number of modules and options for basic command line programs, that often is not covered by frontends.
Related articles
HowTo/shorewall — Configuring your firewall
HowTo/dnsmasq — Adding DHCP and DNS to your firewall
?HowTo/dansguardian — Adding web content filtering
?HowTo/openvpn — Adding a SSL VPN server (my prefered VPN solution)
HowTo/openswan — Adding a IPSEC VPN server
?HOWTO/DynamicBlockSSHddos — Simple script to do dynamic ssh ddos attack blocking
Источник