Что такое firewalld
Программа представляет собой графическую оболочку для брандмауэра iptables и кроме интерфейса также отличается схемой взаимодействия:
- распределяет трафик не по зонам, а согласно правилам;
- содержит правила «белого» и «черного» списка, в соответствии с которыми работает на данной сетевой точке;
- может как ограничивать, так и блокировать трафик.
Облачные серверыIntel Xeon Gold 6254 3.
Изменение зоны интерфейса на постоянной основе
Если в настройках интерфейса не указана никакая другая зона, после перезапуска брандмауэра интерфейс будет снова привязан к зоне по умолчанию. В CentOS такие конфигурации хранятся в каталоге /etc/sysconfig/network-scripts, в файлах формата ifcfg-interface.
Чтобы определить зону интерфейса, откройте конфигурационный файл этого интерфейса, например:
sudo nano /etc/sysconfig/network-scripts/ifcfg-eth0
В конец файла добавьте переменную ZONE= и в качестве значения укажите другую зону, например, home:
. . .DNS1=2001:4860:4860::8844DNS2=2001:4860:4860::8888DNS3=8.8.8.8ZONE=home
Сохраните и закройте файл.
Чтобы обновить настройки, перезапустите сетевой сервис и брандмауэр:
sudo systemctl restart network.servicesudo systemctl restart firewalld.service
После перезапуска интерфейс eth0 будет привязан к зоне home.
firewall-cmd –get-active-zoneshomeinterfaces: eth0publicinterfaces: eth1
Введение
FirewallD — динамически управляемый брандмауэр с поддержкой зон, который определяет уровень доверия сетевых подключений или интерфейсов. Доступен для многих дистрибутивов Linux и выступает в качестве фронтенда для системы фильтрации сетевых пакетов Iptables ядра Linux.
Если у вас более новая версия FirewallD, чем та, что использовалась при написании этой статьи, или настройки вашего сервера отличаются от примера в статье, то некоторые приведенные в статье команды вам придется изменить в зависимости от используемых конфигураций.
Данная статья является переводом и адаптацией англоязычной статьи.
Changing the zone of an interface
You can transition an interface between zones during a session by using the –zone= parameter in combination with the –change-interface= parameter. As with all commands that modify the firewall, you will need to use sudo.
For instance, we can transition our eth0 interface to the “home” zone by typing this:
output
success
Note
Whenever you are transitioning an interface to a new zone, be aware that you are probably modifying the services that will be operational. For instance, here we are moving to the “home” zone, which has SSH available. This means that our connection shouldn’t drop. Some other zones do not have SSH enabled by default and if your connection is dropped while using one of these zones, you could find yourself unable to log back in.
We can verify that this was successful by asking for the active zones again:
output
home
interfaces: eth0
public
interfaces: eth1
Install and enable your firewall to start at boot
firewalld is installed by default on some Linux distributions, including many images of CentOS 7. However, it may be necessary for you to install firewalld yourself:
After you install firewalld, you can enable the service and reboot your server. Keep in mind that enabling firewalld will cause the service to start up at boot. It is best practice to create your firewall rules and take the opportunity to test them before configuring this behavior in order to avoid potential issues.
When the server restarts, your firewall should be brought up, your network interfaces should be put into the zones you configured (or fall back to the configured default zone), and any rules associated with the zone(s) will be applied to the associated interfaces.
We can verify that the service is running and reachable by typing:
output
running
This indicates that our firewall is up and running with the default configuration.
Iptables и другие
Проект iptables, разработанный Расти Расселом (Rusty Russell) в 1999 году для управления netfilter и заменивший в ядре 2.4 ipchains и ряд других инструментов вроде ipnatctl, предлагает более расширяемый способ фильтрации пакетов, обеспечивающий сисадмину больший контроль при упрощении самих правил.
Так, в ipchains нужно было создавать правило в каждой цепочке, прослеживая весь маршрут пакета, теперь достаточно одного. Появление модулей позволяло очень просто расширять возможности. В процессе развития проекта iptables был портирован для IPv6 (в 2021 году, ip6tables), добавлялись дополнительные модули (ULOG, nf_conntrack), он научился производить разные манипуляции с пакетами, классифицировать трафик (до седьмого уровня OSI), балансировать нагрузку и многое другое.
С ростом количества функций усложнились и настройки. При этом, даже несмотря на некоторую унификацию, каждое расширение имеет свой синтаксис, одни поддерживают диапазоны, отрицание, префиксы, другие — нет. Поначалу каждое изменение правил требовало полного перезапуска брандмауэра, включая выгрузку модулей, что приводило к разрыву установленных соединений. Сейчас такой проблемы нет.
Для простых случаев настройка при помощи iptables — дело нехитрое, но в сложных сетях управлять большим количеством правил становится тяжело; чтобы изучить все настройки и понять, как оно работает, нужно потратить время. Трудно с ходу разобраться, что делают все цепочки, правила начинают повторяться, их становится сложно обслуживать, обновлять и переносить на другие системы.
Неудивительно, что для решения этих проблем были придуманы разные надстройки. Так, в Ubuntu для простой настройки правил используется ufw (Uncomplicated Firewall — несложный файрвол). Например, чтобы открыть доступ к SSH-порту, достаточно ввести
$ sudo ufw allow 22
Разработчики приложений могут создавать готовые профили, которые активируются при установке пакета, избавляя пользователя от выдумывания и ввода правил.
Not using centos 7?
choose a different version or distribution.
Introduction
Firewalld is a firewall management solution available for many Linux distributions which acts as a frontend for the iptables packet filtering system provided by the Linux kernel. In this guide, we will cover how to set up a firewall for your server and show you the basics of managing the firewall with the firewall-cmd
administrative tool (if you’d rather use iptables
with CentOS, follow this guide).
Note: There is a chance that you may be working with a newer version of firewalld than was available at the time of this writing, or that your server was set up slightly differently than the example server used throughout this guide. Thus, the behavior of some of the commands explained in this guide may vary depending on your specific configuration.
Basic concepts in firewalld
Before we begin talking about how to actually use the firewall-cmd
utility to manage your firewall configuration, we should get familiar with a few basic concepts that the tool introduces.
Zones
The firewalld
daemon manages groups of rules using entities called “zones”. Zones are basically sets of rules dictating what traffic should be allowed depending on the level of trust you have in the networks your computer is connected to. Network interfaces are assigned a zone to dictate the behavior that the firewall should allow.
For computers that might move between networks frequently (like laptops), this kind of flexibility provides a good method of changing your rules depending on your environment. You may have strict rules in place prohibiting most traffic when operating on a public WiFi network, while allowing more relaxed restrictions when connected to your home network. For a server, these zones are not as immediately important because the network environment rarely, if ever, changes.
Regardless of how dynamic your network environment may be, it is still useful to be familiar with the general idea behind each of the predefined zones for firewalld
. In order from least trusted to most trusted, the predefined zones within firewalld
are:
To use the firewall, we can create rules and alter the properties of our zones and then assign our network interfaces to whichever zones are most appropriate.
Rule permanence
In firewalld, rules can be designated as either permanent or immediate. If a rule is added or modified, by default, the behavior of the currently running firewall is modified. At the next boot, the old rules will be reverted.
Most firewall-cmd
operations can take the --permanent
flag to indicate that the non-ephemeral firewall should be targeted. This will affect the rule set that is reloaded upon boot. This separation means that you can test rules in your active firewall instance and then reload if there are problems. You can also use the --permanent
flag to build out an entire set of rules over time that will all be applied at once when the reload command is issued.
Install and enable your firewall to start at boot
firewalld
is installed by default on some Linux distributions, including many images of CentOS 7. However, it may be necessary for you to install firewalld yourself:
After you install firewalld
, you can enable the service and reboot your server. Keep in mind that enabling firewalld will cause the service to start up at boot. It is best practice to create your firewall rules and take the opportunity to test them before configuring this behavior in order to avoid potential issues.
When the server restarts, your firewall should be brought up, your network interfaces should be put into the zones you configured (or fall back to the configured default zone), and any rules associated with the zone(s) will be applied to the associated interfaces.
We can verify that the service is running and reachable by typing:
output
running
This indicates that our firewall is up and running with the default configuration.
Getting familiar with the current firewall rules
Before we begin to make modifications, we should familiarize ourselves with the default environment and rules provided by the daemon.
Exploring the defaults
We can see which zone is currently selected as the default by typing:
output
public
Since we haven’t given firewalld
any commands to deviate from the default zone, and none of our interfaces are configured to bind to another zone, that zone will also be the only “active” zone (the zone that is controlling the traffic for our interfaces). We can verify that by typing:
output
public
interfaces: eth0 eth1
Here, we can see that our example server has two network interfaces being controlled by the firewall (eth0
and eth1
). They are both currently being managed according to the rules defined for the public zone.
How do we know what rules are associated with the public zone though? We can print out the default zone’s configuration by typing:
output
public (default, active)
target: default
icmp-block-inversion: no
interfaces: eth0 eth1
sources:
services: ssh dhcpv6-client
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
We can tell from the output that this zone is both the default and active and that the eth0
and eth1
interfaces are associated with this zone (we already knew all of this from our previous inquiries). However, we can also see that this zone allows for the normal operations associated with a DHCP client (for IP address assignment) and SSH (for remote administration).
Exploring alternative zones
Now we have a good idea about the configuration for the default and active zone. We can find out information about other zones as well.
To get a list of the available zones, type:
output
block dmz drop external home internal public trusted work
We can see the specific configuration associated with a zone by including the --zone=
parameter in our --list-all
command:
output
home
interfaces:
sources:
services: dhcpv6-client ipp-client mdns samba-client ssh
ports:
masquerade: no
forward-ports:
icmp-blocks:
rich rules:
You can output all of the zone definitions by using the --list-all-zones
option. You will probably want to pipe the output into a pager for easier viewing:
Selecting zones for your interfaces
Unless you have configured your network interfaces otherwise, each interface will be put in the default zone when the firewall is booted.
Changing the zone of an interface
You can transition an interface between zones during a session by using the --zone=
parameter in combination with the --change-interface=
parameter. As with all commands that modify the firewall, you will need to use sudo
.
For instance, we can transition our eth0
interface to the “home” zone by typing this:
output
success
Note
Whenever you are transitioning an interface to a new zone, be aware that you are probably modifying the services that will be operational. For instance, here we are moving to the “home” zone, which has SSH available. This means that our connection shouldn’t drop. Some other zones do not have SSH enabled by default and if your connection is dropped while using one of these zones, you could find yourself unable to log back in.
We can verify that this was successful by asking for the active zones again:
output
home
interfaces: eth0
public
interfaces: eth1
Adjusting the default zone
If all of your interfaces can best be handled by a single zone, it’s probably easier to just select the best default zone and then use that for your configuration.
You can change the default zone with the --set-default-zone=
parameter. This will immediately change any interface that had fallen back on the default to the new zone:
output
success
Setting rules for your applications
The basic way of defining firewall exceptions for the services you wish to make available is easy. We’ll run through the basic idea here.
Adding a service to your zones
The easiest method is to add the services or ports you need to the zones you are using. Again, you can get a list of the available services with the --get-services
option:
output
RH-Satellite-6 amanda-client amanda-k5-client bacula bacula-client bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc ceph ceph-mon cfengine condor-collector ctdb dhcp dhcpv6 dhcpv6-client dns docker-registry dropbox-lansync elasticsearch freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master high-availability http https imap imaps ipp ipp-client ipsec iscsi-target kadmin kerberos kibana klogin kpasswd kshell ldap ldaps libvirt libvirt-tls managesieve mdns mosh mountd ms-wbt mssql mysql nfs nrpe ntp openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy proxy-dhcp ptp pulseaudio puppetmaster quassel radius rpc-bind rsh rsyncd samba samba-client sane sip sips smtp smtp-submission smtps snmp snmptrap spideroak-lansync squid ssh synergy syslog syslog-tls telnet tftp tftp-client tinc tor-socks transmission-client vdsm vnc-server wbem-https xmpp-bosh xmpp-client xmpp-local xmpp-server
Note
You can get more details about each of these services by looking at their associated .xml
file within the /usr/lib/firewalld/services
directory. For instance, the SSH service is defined like this:
/usr/lib/firewalld/services/ssh.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>SSH</short>
<description>Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.</description>
<port protocol="tcp" port="22"/>
</service>
You can enable a service for a zone using the --add-service=
parameter. The operation will target the default zone or whatever zone is specified by the --zone=
parameter. By default, this will only adjust the current firewall session. You can adjust the permanent firewall configuration by including the --permanent
flag.
For instance, if we are running a web server serving conventional HTTP traffic, we can allow this traffic for interfaces in our “public” zone for this session by typing:
You can leave out the --zone=
if you wish to modify the default zone. We can verify the operation was successful by using the --list-all
or --list-services
operations:
output
dhcpv6-client http ssh
Once you have tested that everything is working as it should, you will probably want to modify the permanent firewall rules so that your service will still be available after a reboot. We can make our “public” zone change permanent by typing:
output
success
You can verify that this was successful by adding the --permanent
flag to the --list-services
operation. You need to use sudo
for any --permanent
operations:
output
dhcpv6-client http ssh
Your “public” zone will now allow HTTP web traffic on port 80. If your web server is configured to use SSL/TLS, you’ll also want to add the https
service. We can add that to the current session and the permanent rule-set by typing:
What if no appropriate service is available?
The firewall services that are included with the firewalld installation represent many of the most common requirements for applications that you may wish to allow access to. However, there will likely be scenarios where these services do not fit your requirements.
In this situation, you have two options.
Opening a port for your zones
The easiest way to add support for your specific application is to open up the ports that it uses in the appropriate zone(s). This is as easy as specifying the port or port range, and the associated protocol for the ports you need to open.
For instance, if our application runs on port 5000 and uses TCP, we could add this to the “public” zone for this session using the --add-port=
parameter. Protocols can be either tcp
or udp
:
output
success
We can verify that this was successful using the --list-ports
operation:
output
5000/tcp
It is also possible to specify a sequential range of ports by separating the beginning and ending port in the range with a dash. For instance, if our application uses UDP ports 4990 to 4999, we could open these up on “public” by typing:
After testing, we would likely want to add these to the permanent firewall. You can do that by typing:
output
success
success
5000/tcp 4990-4999/udp
Defining a service
Opening ports for your zones is easy, but it can be difficult to keep track of what each one is for. If you ever decommission a service on your server, you may have a hard time remembering which ports that have been opened are still required. To avoid this situation, it is possible to define a service.
Services are simply collections of ports with an associated name and description. Using services is easier to administer than ports, but requires a bit of upfront work. The easiest way to start is to copy an existing script (found in /usr/lib/firewalld/services
) to the /etc/firewalld/services
directory where the firewall looks for non-standard definitions.
For instance, we could copy the SSH service definition to use for our “example” service definition like this. The filename minus the .xml
suffix will dictate the name of the service within the firewall services list:
Now, you can adjust the definition found in the file you copied:
sudo vi /etc/firewalld/services/example.xml
To start, the file will contain the SSH definition that you copied:
/etc/firewalld/services/example.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>SSH</short>
<description>Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.</description>
<port protocol="tcp" port="22"/>
</service>
The majority of this definition is actually metadata. You will want to change the short name for the service within the <short>
tags. This is a human-readable name for your service. You should also add a description so that you have more information if you ever need to audit the service. The only configuration you need to make that actually affects the functionality of the service will likely be the port definition where you identify the port number and protocol you wish to open. This can be specified multiple times.
For our “example” service, imagine that we need to open up port 7777 for TCP and 8888 for UDP. By entering INSERT mode by pressing i
, we can modify the existing definition with something like this:
/etc/firewalld/services/example.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>Example Service</short>
<description>This is just an example service. It probably shouldn't be used on a real system.</description>
<port protocol="tcp" port="7777"/>
<port protocol="udp" port="8888"/>
</service>
Press ESC
, then enter :x
to save and close the file.
Reload your firewall to get access to your new service:
You can see that it is now among the list of available services:
output
RH-Satellite-6 amanda-client amanda-k5-client bacula bacula-client bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc ceph ceph-mon cfengine condor-collector ctdb dhcp dhcpv6 dhcpv6-client dns docker-registry dropbox-lansync elasticsearch example freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master high-availability http https imap imaps ipp ipp-client ipsec iscsi-target kadmin kerberos kibana klogin kpasswd kshell ldap ldaps libvirt libvirt-tls managesieve mdns mosh mountd ms-wbt mssql mysql nfs nrpe ntp openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy proxy-dhcp ptp pulseaudio puppetmaster quassel radius rpc-bind rsh rsyncd samba samba-client sane sip sips smtp smtp-submission smtps snmp snmptrap spideroak-lansync squid ssh synergy syslog syslog-tls telnet tftp tftp-client tinc tor-socks transmission-client vdsm vnc-server wbem-https xmpp-bosh xmpp-client xmpp-local xmpp-server
You can now use this service in your zones as you normally would.
Creating your own zones
While the predefined zones will probably be more than enough for most users, it can be helpful to define your own zones that are more descriptive of their function.
For instance, you might want to create a zone for your web server, called “publicweb”. However, you might want to have another zone configured for the DNS service you provide on your private network. You might want a zone called “privateDNS” for that.
When adding a zone, you must add it to the permanent firewall configuration. You can then reload to bring the configuration into your running session. For instance, we could create the two zones we discussed above by typing:
You can verify that these are present in your permanent configuration by typing:
output
block dmz drop external home internal privateDNS public publicweb trusted work
As stated before, these won’t be available in the current instance of the firewall yet:
output
block dmz drop external home internal public trusted work
Reload the firewall to bring these new zones into the active configuration:
output
block dmz drop external home internal privateDNS public publicweb trusted work
Now, you can begin assigning the appropriate services and ports to your zones. It’s usually a good idea to adjust the active instance and then transfer those changes to the permanent configuration after testing. For instance, for the “publicweb” zone, you might want to add the SSH, HTTP, and HTTPS services:
output
publicweb
target: default
icmp-block-inversion: no
interfaces:
sources:
services: ssh http https
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
Likewise, we can add the DNS service to our “privateDNS” zone:
output
privateDNS
interfaces:
sources:
services: dns
ports:
masquerade: no
forward-ports:
icmp-blocks:
rich rules:
We could then change our interfaces over to these new zones to test them out:
At this point, you have the opportunity to test your configuration. If these values work for you, you will want to add the same rules to the permanent configuration. You can do that by re-applying the rules with the --permanent
flag:
After permanently applying these your rules, you can restart your network and reload your firewall service:
Validate that the correct zones were assigned:
output
privateDNS
interfaces: eth1
publicweb
interfaces: eth0
And validate that the appropriate services are available for both of the zones:
output
http https ssh
output
dns
You have successfully set up your own zones! If you want to make one of these zones the default for other interfaces, remember to configure that behavior with the --set-default-zone=
parameter:
sudo firewall-cmd --set-default-zone=publicweb
Conclusion
You should now have a fairly good understanding of how to administer the firewalld service on your CentOS system for day-to-day use.
The firewalld service allows you to configure maintainable rules and rule-sets that take into consideration your network environment. It allows you to seamlessly transition between different firewall policies through the use of zones and gives administrators the ability to abstract the port management into more friendly service definitions. Acquiring a working knowledge of this system will allow you to take advantage of the flexibility and power that this tool provides.
Opening a port for your zones
The easiest way to add support for your specific application is to open up the ports that it uses in the appropriate zone(s). This is as easy as specifying the port or port range, and the associated protocol for the ports you need to open.
For instance, if our application runs on port 5000 and uses TCP, we could add this to the “public” zone for this session using the –add-port= parameter. Protocols can be either tcp or udp:
output
success
We can verify that this was successful using the –list-ports operation:
output
5000/tcp
It is also possible to specify a sequential range of ports by separating the beginning and ending port in the range with a dash. For instance, if our application uses UDP ports 4990 to 4999, we could open these up on “public” by typing:
After testing, we would likely want to add these to the permanent firewall. You can do that by typing:
output
success
success
5000/tcp 4990-4999/udp
Rule permanence
In firewalld, rules can be designated as either permanent or immediate. If a rule is added or modified, by default, the behavior of the currently running firewall is modified. At the next boot, the old rules will be reverted.
Most firewall-cmd operations can take the –permanent flag to indicate that the non-ephemeral firewall should be targeted. This will affect the rule set that is reloaded upon boot. This separation means that you can test rules in your active firewall instance and then reload if there are problems.
Zones
The firewalld daemon manages groups of rules using entities called “zones”. Zones are basically sets of rules dictating what traffic should be allowed depending on the level of trust you have in the networks your computer is connected to. Network interfaces are assigned a zone to dictate the behavior that the firewall should allow.
For computers that might move between networks frequently (like laptops), this kind of flexibility provides a good method of changing your rules depending on your environment. You may have strict rules in place prohibiting most traffic when operating on a public WiFi network, while allowing more relaxed restrictions when connected to your home network. For a server, these zones are not as immediately important because the network environment rarely, if ever, changes.
Regardless of how dynamic your network environment may be, it is still useful to be familiar with the general idea behind each of the predefined zones for firewalld. In order from least trusted to most trusted, the predefined zones within firewalld are:
To use the firewall, we can create rules and alter the properties of our zones and then assign our network interfaces to whichever zones are most appropriate.
Возможности firewalld
Firewalld запускается как демон, новые правила добавляются без перезапуска и без сброса установленного файрвола. Изменения в конфигурации могут быть сделаны в любое время и применяются мгновенно: сохранять или применять изменения не требуется. Поддерживается IPv4, IPv6, автоматическая загрузка модулей ядра и сетевые зоны, определяющие уровень доверия соединений.
Предоставляется простой интерфейс добавления правил для служб и приложений, белый список приложений, имеющих право менять правила. В настоящее время такую возможность поддерживает libvirt, Docker, fail2ban, Puppet, скрипт установки Virtuozzo и многие другие проекты. В репозитории YUM уже есть пакеты fail2ban-firewalld и puppet-firewalld, поэтому подключить их можно одной командой.
Firewalld предоставляет информацию о текущих настройках брандмауэра через D-Bus API, а также принимает изменения через D-Bus с использованием методов аутентификации PolicyKit. В качестве бэкенда используются iptables, ip6tables, ebtables, ipset и планируется nftables.
Управление производится при помощи утилит командной строки firewall-cmd или графической firewall-config, позволяющей настроить все правила в удобной среде. Для помощи в миграции текущих правил iptables на firewalld используется утилита firewall-offline-cmd, по умолчанию считывающая /etc/sysconfig/system-config-firewall.


Смотрим статус:
# systemctl status firewalld
# firewall-cmd --state
running
Разрешить соединение на определенный порт очень просто:
# firewall-cmd --permanent --add-port=22/tcp
Чтобы любые изменения вступили в силу, всегда после правок должна быть запущена команда
# firewall-cmd --reload
Для удаления порта из правил используется параметр –remove-port:
# firewall-cmd --remove-port=22/tcp
Вообще, многие команды –add-* имеют значения для проверки статуса –query-*, –list-* — список, изменения –change-* или удаления –remove соответствующего значения. Для краткости на этом не будем дальше заострять внимание. После релоада правил проверяем:
# firewall-cmd --list-ports
В firewalld предусмотрен режим, позволяющий одной командой заблокировать все соединения:
# firewall-cmd --panic-on
Для проверки, в каком режиме находится файрвол, есть специальный ключ:
# firewall-cmd --query-panic
Отключается panic mode:
# firewall-cmd --panic-off
В firewalld необязательно знать, какой порт привязан к сервису, достаточно указать название сервиса. Все остальное утилита возьмет на себя.
После установки firewalld знает настройки более 50 сервисов, получаем их список.
# firewall-cmd --get-services
Если нужный сервис не доступен
Брандмауэр FirewallD включает в себя многие наиболее распространённые сервисы. Однако, возможны сценарии, при которых эти сервисы не будут отвечать требованиям. В таком случае есть два варианта решения.
Открытие порта для зоны. Самый простой способ добавить поддержку для конкретного приложения — открыть порты, которые оно использует в соответствующей зоне/зонах. Для этого достаточно указать порт или диапазон портов и соответствующий протокол для них.
Например, если наше приложение использует порт 5000 и протокол TCP, можно добавить их в зону public для этой сессии, используя параметр –add-port=. Протоколы могут быть tcp или udp:
sudo firewall-cmd --zone=public --add-port=5000/tcp
Ответ:
success
С помощью –list-ports проверим, что операция прошла успешно:
sudo firewall-cmd --zone=public --list-ports
Ответ:
5000/tcp
Также можно указать диапазон портов, разделив начальный и конечный порт в диапазоне с помощью тире. Например, если наше приложение использует UDP-порты с 4990 по 4999, мы можем открыть их в зоне public, набрав:
sudo firewall-cmd --zone=public --add-port=4990-4999/udp
После тестирования можно добавить их к постоянным правилам брандмауэра:
sudo firewall-cmd --zone=public --permanent --add-port=5000/tcp sudo firewall-cmd --zone=public --permanent --add-port=4990-4999/udp sudo firewall-cmd --zone=public --permanent --list-ports
Ответ:
success success 5000/tcp 4990-4999/udp
Определение нового сервиса. Открыть порты для зон легко, но может быть трудно отследить, для чего предназначен каждый из них. Если вы когда-либо выводили службу из эксплуатации на своем сервере, то могли столкнуться с проблемой вспомнить, какие из открытых портов еще необходимы. Чтобы избежать этой ситуации, можно определить сервис.
Сервисы представляют собой наборы портов со связанным именем и описанием. Использование сервисов проще в администрировании, чем использование портов, но это требует некоторой предварительной подготовки. Для начала необходимо скопировать существующий скрипт из каталога /usr/lib/firewalld/services в каталог /etc/firewalld/services, который является местоположением для созданных пользователем сервисов, и заменить в нем параметры.
Например, можно скопировать определение сервиса SSH, чтобы использовать его для определения сервиса example следующим образом. Имя файла должно совпадать с именем сервиса и иметь суффикс .xml:
sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/example.xml
Теперь можно настроить определение для сервиса example:
sudo vi /etc/firewalld/services/example.xml
Файл /etc/firewalld/services/example.xml содержит определение SSH:
Большую часть определения составляют метаданные. Короткое имя сервиса в тегах можно изменить на более читаемое имя. Также нужно добавить описание, чтобы понимать, что это за сервис. Единственная конфигурация, которую нужно задать и которая повлияет на работу сервиса, — это определение порта, где следует указать порты и протоколы, которые необходимо открыть.
Например, в нашем случае нужно открыть порт 7777 для TCP и 8888 для UDP. Внесем изменения в определение:
Сохраним изменения и закроем файл.
Перезагрузим брандмауэр, чтобы получить доступ к новому сервису:
sudo firewall-cmd --reload
Теперь сервис в списке доступных сервисов:
firewall-cmd --get-services
Ответ:
Избавляемся от firewalld
Если, являясь сторонником старой школы, мы решили избавиться от FirewallD и вернуться, к iptables, то это вполне возможно даже на CentOS 7:
# systemctl disable firewalld
# systemctl stop firewalld
# yum install iptables-services
# touch /etc/sysconfig/iptables
# touch /etc/sysconfig/ip6tables
# systemctl start iptables
# systemctl start ip6tables
# systemctl enable iptables
# systemctl enable ip6tables
Если же мы переходим на FirewallD, то разбираемся дальше.
Проверяем, установлены ли нужные пакеты, ставим если нужно
yum -y install firewalld firewall-config
Поехали!
Изменение зоны по умолчанию
Если для вашей задачи возможно расположить все интерфейсы в одной зоне, лучше всего выбрать наиболее подходящую зону и задать ее как зону по умолчанию.
Для этого используется параметр –set-default-zone=. Тогда все интерфейсы зоны по умолчанию будут привязаны к новой зоне:
sudo firewall-cmd --set-default-zone=home
Ответ:
success
Как добавить новую службу
Как говорилось выше, полное описание служб внутри серверной ОС расположено по следующему пути: /usr/lib/firewalld/services/, далее идет xml-файл с именем службы.
Чтобы создать новый сервис, просто скопируем один из готовых вариантов в папку services, которая расположена внутри директории firewalld. В качестве примера взяли описание сервиса SSH и скопировали его с именем test:
sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/test.xml
Важно! Операция копирования выполняется только с правами администратора.
Откроем его при помощи текстового редактора nano:
sudo nano /etc/firewalld/services/test.xml
На экране появится подробное описание сервиса SSH:

В первом пункте меняем название службы на произвольное. По полю short она активируется через команды в дальнейшем. Второй пункт дает полное описание сервиса: прописываем детально.
Третий шаг – указываем порты и протокол по которым она будет работать. В дальнейшем firewalld будет активировать значения после указания соответствующего ключа.
Отредактировав файл, сохраняем изменения и перезапускаем службу.
Конфигурация
FirewallD может быть настроен через инструмент конфигурации firewall-config с графическим интерфейсом, через командную строку firewall-cmd или интерфейс D-BUS.
Доступ к инструмент конфигурации firewall-config с графическим интерфейсом осуществляется командой firewall-config или же запуском через меню.
После запуска будет виден список зон, о которых говорилось выше, можно выбрать любую из них и выполнить настройки в соответствии с вариантами:
На мой взгляд, наиболее удобным инструментом настройки остаётся командная строка и, соответственно, команда firewall-cmd. Рассмотрим наиболее употребимые команды:
Конец.
Конфигурирование firewalld
Определим текущую настройку утилиты:
firewall-cmd --get-default-zone

Сейчас установлен шаблон public, т.е. все разрешено. Если необходимо получить подробный отчет, то используем —list-all в качестве ключа. Результат приведен ниже.
Важно! Команда запускается только с правами sudo.

Курсы cisco и linux с трудоустройством!
Спешите подать заявку! Осталось пару мест. Группы стартуют 22 июля, а следующая 19 августа, 23 сентября, 21 октября, 25 ноября, 16 декабря, 20 января, 24 февраля.
Что Вы получите?
- Поможем стать экспертом в сетевом администрировании и получить международные сертификаты Cisco CCNA Routing & Switching или Linux LPI.
- Предлагаем проверенную программу и учебник экспертов из Cisco Networking Academy и Linux Professional Institute, сертифицированных инструкторов и личного куратора.
- Поможем с трудоустройством и сделать карьеру. 100% наших выпускников трудоустраиваются.
Как проходит обучение?
- Проводим вечерние онлайн-лекции на нашей платформе или обучайтесь очно на базе Киевского офиса.
- Спросим у вас об удобном времени для практик и подстроимся: понимаем, что времени учиться мало.
- Если хотите индивидуальный график — обсудим и осуществим.
- Выставим четкие дедлайны для самоорганизации. Личный куратор будет на связи, чтобы ответить на вопросы, проконсультировать и мотивировать придерживаться сроков сдачи экзаменов.
А еще поможем Вам:
Открываем порт (сервис)
Firewalld также предоставляет сервисам доступ к портам используя ключ —add-service=<имя службы>. Для начала проверим список сервисов на сервере, запустив утилиту с опцией —get-services.

Получить подробную информацию о любом сервисе, обратившись через команду cat к внутреннему списку firewalld. Например, просмотрим описание службы audit:
cat /usr/lib/firewalld/services/audit.xml

Для активации порта любого сервиса из перечня прописываем в терминале:
sudo firewall-cmd --zone=work --add-service=audit
Данная конфигурация будет активна только до перезагрузки серверной платформы. Чтобы сделать ее постоянной, прописываем ключ —permanent:
sudo firewall-cmd --permanent --zone=work --add-service=audit
Если сервис audit больше не нужен, удалим его, используя опцию –remove-service=<имя службы>:
sudo firewall-cmd --zone=work --remove-service=audit --permanent
Альтернативный вариант открытия порта – указываем номер и имя протокола с указанием флага —add-port:
sudo firewall-cmd --zone=work --add-port=443/tcp
Важно! Любое изменение в списке сервисов можно отследить используя опцию —list-ports.
Удаление порта происходит при замене ключа —add-port на —remove-port с сохранением дальнейшего синтаксиса.
Правила брандмауэра по умолчанию
Чтобы узнать, какая зона выбрана по умолчанию, используйте:
firewall-cmd --get-default-zone
Ответ:
public
Так как на данный момент FirewallD не получал никаких инструкций относительно других зон, кроме того, к другим зонам не привязан ни один интерфейс, то сейчас зона public является зоной по умолчанию, а также единственной «активной» зоной (той зоной, которая контролирует трафик интерфейсов). Проверим это:
firewall-cmd --get-active-zones
Ответ:
public interfaces: eth0 eth1
Мы видим, что наш сервер имеет два сетевых интерфейса: eth0 и eth1. Они оба управляются в соответствии с правилами, заданными для зоны public.
Чтобы узнать правила этой зоны, введите:
sudo firewall-cmd --list-all
Ответ:
Сложные правила
Для отдельного ПК или небольших сетей базовых возможностей вполне хватает, для настройки сложных правил в firewalld изначально предлагался так называемый direct-синтаксис, чуть позже появился собственный язык Rich Language. В первом варианте достаточно знать синтаксис iptables, рекомендуется использовать в крайнем случае, так как правила не сохраняются после перезагрузки.
Синтаксис direct правила такой:
# firewall-cmd [--permanent] --direct --add-rule { ipv4 | ipv6 | eb } <table> <chain> <priority> <args>
Позиция полностью совпадает с синтаксисом iptables. Получаем текущие установки:
# firewall-cmd --direct --get-chains ipv4 filter
# firewall-cmd --direct --get-rules ipv4 filter input
Добавляем правило, разрешающее соединение по 25-му порту:
# firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -m tcp -p tcp --dport 25 -j ACCEPT
Пробросим соединение по 22-му на другой сервер:
# firewall-cmd --permanent --direct --add-rule ipv4 filter FORWARD 0 -i eno1 -o eno2 -p tcp --dport 22 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
Проверяем:
# firewall-cmd --direct --get-all-rules
Смена политики и интерфейса
Для смены шаблона, используем ключ —zone совместно с опцией смены сетевого интерфейса —change-interface. Например, заменить политику public на work с ее активацией на eth0:
sudo firewall-cmd --zone=work --change-interface=eth0
В случае успешной операции на мониторе появится соответствующее сообщение. Наберем следующую команду, чтобы убедиться в правильности выполненных действий:
sudo firewall-cmd --get-active-zones

Как видно на изображении выше, сетевой интерфейс использует политику work, а другие по-прежнему работают с public.
Если требуется сменить политику, которая наследуется по умолчанию для всех интерфейсов, используем другой синтаксис:
sudo firewall-cmd --set-default-zone=home
После выполнения команды всем сетевым интерфейсам пропишется шаблон home. Для показа текущего уровня вводим уже известный ключ —get-default-zone.
Создание пользовательских зон
Часто предопределенных зон вполне достаточно для работы, но иногда возникает необходимость определить пользовательские зоны.
Например, создадим зону publicweb для веб-сервера. Для нее потребуется настроить дополнительную зону для DNS-сервиса, которая предоставляется в частной сети, назовем ее privateDNS.
Создавая зону, ее нужно добавить к постоянным правилам брандмауэра, а затем перезагрузить FirewallD, чтобы перенести конфигурацию в рабочую сессию. Создадим две зоны, указанные выше, с помощью команд:
sudo firewall-cmd --permanent --new-zone=publicweb sudo firewall-cmd --permanent --new-zone=privateDNS
Проверим, что они присутствуют в постоянных правилах:
firewall-cmd --get-zones
Ответ:
Сохранение правил
FirewallD использует два набора правил — постоянные и временные. Временные правила представляет собой фактическую рабочую конфигурацию и при перезагрузке не сохраняются. Если правило добавляется или изменяется, поведение запущенного брандмауэра сразу изменяется. Но при перезагрузке все изменения утрачиваются, если они не были сохранены.
По умолчанию при внесении изменений в конфигурацию FirewallD с использованием утилиты firewall-cmd изменения применяются к временному набору правил. Большинство команд firewall-cmd может использовать флаг –permanent, он позволяет cоздать постоянный набор правил, которые будут применяться сразу после выполнения команды перезагрузки.
Управление зонами
Для определения уровня доверия сетевому соединению в firewalld используются зоны. Зона может содержать несколько сетевых подключений, но сетевое соединение может входить только в одну зону. Список всех зон получаем командой firewall-cmd –get-zones.

После установки создается девять зон, в зависимости от назначения может быть использована одна или несколько зон:
Установка и подключение брандмауэра для запуска при загрузке
На некоторых дистрибутивах Linux, включая многие образы CentOS 7, FirewallD установлен по умолчанию. Однако, если необходимо установить FirewallD, выполните следующую команду:
sudo yum install -y firewalld
После установки FirewallD необходимо включить сервис и перезагрузить сервер. Помните, что если FirewallD включен, то при загрузке он сразу запустится. Поэтому необходимо создавать правила брандмауэра и тестировать их до конфигурирования автоматического запуска брандмауэра во избежание возможных проблем.
sudo systemctl enable firewalld sudo reboot
При перезапуске сервера брандмауэр будет запущен и поместит сетевые интерфейсы в сконфигурированные зонаы (или переключится на зону по умолчанию), любые правила, связанные с зоной/зонами, будут применены к соответствующим интерфейсам.
Проверить, что сервис запущен и доступен можно с помощью:
sudo firewall-cmd --state
Ответ:
running
Теперь брандмауэр запущен и работает согласно конфигурации по умолчанию.