Firewall linux red hat

Содержание
  1. Firewall linux red hat
  2. Introduction to Linux firewalld zones and rules
  3. More Linux resources
  4. Create custom zones
  5. Assign an interface
  6. Advanced rule creation
  7. Need more info?
  8. Red Hat Customer Portal
  9. Log in to Your Red Hat Account
  10. Red Hat Account
  11. Customer Portal
  12. Select Your Language
  13. Red Hat Training
  14. Chapter 48. Using and configuring firewalld
  15. 48.1. Getting started with firewalld
  16. 48.1.1. When to use firewalld, nftables, or iptables
  17. 48.1.2. Zones
  18. 48.1.3. Predefined services
  19. 48.1.4. Starting firewalld
  20. 48.1.5. Stopping firewalld
  21. 48.1.6. Verifying the permanent firewalld configuration
  22. 48.2. Viewing the current status and settings of firewalld
  23. 48.2.1. Viewing the current status of firewalld
  24. 48.2.2. Viewing allowed services using GUI
  25. 48.2.3. Viewing firewalld settings using CLI
  26. 48.3. Controlling network traffic using firewalld
  27. 48.3.1. Disabling all traffic in case of emergency using CLI
  28. 48.3.2. Controlling traffic with predefined services using CLI
  29. 48.3.3. Controlling traffic with predefined services using GUI
  30. 48.3.4. Adding new services
  31. 48.3.5. Opening ports using GUI
  32. 48.3.6. Controlling traffic with protocols using GUI
  33. 48.3.7. Opening source ports using GUI
  34. 48.4. Controlling ports using CLI
  35. 48.4.1. Opening a port
  36. 48.4.2. Closing a port
  37. 48.5. Working with firewalld zones
  38. 48.5.1. Listing zones
  39. 48.5.2. Modifying firewalld settings for a certain zone
  40. 48.5.3. Changing the default zone
  41. 48.5.4. Assigning a network interface to a zone
  42. 48.5.5. Assigning a zone to a connection using nmcli
  43. 48.5.6. Manually assigning a zone to a network connection in an ifcfg file
  44. 48.5.7. Creating a new zone
  45. 48.5.8. Zone configuration files
  46. 48.5.9. Using zone targets to set default behavior for incoming traffic
  47. 48.6. Using zones to manage incoming traffic depending on a source
  48. 48.6.1. Adding a source
  49. 48.6.2. Removing a source
  50. 48.6.3. Adding a source port
  51. 48.6.4. Removing a source port
  52. 48.6.5. Using zones and sources to allow a service for only a specific domain
  53. 48.7. Configuring NAT using firewalld
  54. 48.7.1. The different NAT types: masquerading, source NAT, destination NAT, and redirect
  55. 48.7.2. Configuring IP address masquerading
  56. 48.8. Port forwarding
  57. 48.8.1. Adding a port to redirect
  58. 48.8.2. Redirecting TCP port 80 to port 88 on the same machine
  59. 48.8.3. Removing a redirected port
  60. 48.8.4. Removing TCP port 80 forwarded to port 88 on the same machine
  61. 48.9. Managing ICMP requests
  62. 48.9.1. Listing and blocking ICMP requests
  63. 48.9.2. Configuring the ICMP filter using GUI
  64. 48.10. Setting and controlling IP sets using firewalld
  65. 48.10.1. Configuring IP set options using CLI
  66. 48.11. Prioritizing rich rules
  67. 48.11.1. How the priority parameter organizes rules into different chains
  68. 48.11.2. Setting the priority of a rich rule
  69. 48.12. Configuring firewall lockdown
  70. 48.12.1. Configuring lockdown using CLI
  71. 48.12.2. Configuring lockdown allowlist options using CLI
  72. 48.12.3. Configuring lockdown allowlist options using configuration files

Firewall linux red hat

Так же, как настоящий брандмауэр в здании защищает его от распространения огня, компьютерный брандмауэр пытается защитить ваш компьютер от проникновения компьютерных вирусов и вторжения неавторизованных пользователей. Брандмауэр устанавливается между вашим компьютером и сетью. Он определяет, к каким службам вашего компьютера могут обращаться удалённые пользователи. Правильно настроенный брандмауэр может сделать вашу систему более безопасной. Брандмауэр рекомендуется настраивать в любой системе Red Hat Enterprise Linux, подключенной к Интернету.

Во время установки Red Hat Enterprise Linux диалог Настройка брандмауэра (Firewall Configuration) предлагал вам возможность включить основной брандмауэр, а также разрешить доступ к определённым устройствам, службам и портам.

После установки вы можете измените эти параметры с помощью средства Настройка уровня безопасности (Security Level Configuration Tool) .

Чтобы запустить это приложение, выберите в Главном меню (Main Menu) (на панели) => Системные параметры (System Settings) => Уровень безопасности (Security Level) или введите команду system-config-securitylevel в приглашении оболочки (например, в XTerm или терминале среды GNOME ).

Рисунок 19-1. Настройка уровня безопасности

Программа Настройка уровня безопасности настраивает только основные параметры брандмауэра. Если для вашей системы необходимы более сложные правила, обратитесь к Справочному руководству по Red Hat Enterprise Linux , где рассматривается настройка правил iptables .

Выберите одни из следующих вариантов:

Выключить брандмауэр (Disable firewall) — При отключении брандмауэра разрешается полный доступ к вашей системе и проверка безопасности не производится. Проверка безопасности подразумевает отказ в доступе к определённым службам. Этот вариант следует выбирать, только если вы работаете в закрытой сети (не в Интернете) или планируете настроить брандмауэр позже.

Замечание

Если у вас уже был настроен брандмауэр или вы определяли свои правила брандмауэра в файле /etc/sysconfig/iptables , выбор варианта Выключить брандмауэр (Disable firewall) и сохранение изменений нажатием OK приводит к удалению этого файла.

Включить брандмауэр (Enable firewall) — В этом режиме система отклоняет входящие подключения, кроме тех, что отвечают на исходящие запросы, как, например, ответы DNS или DHCP.. Если необходим доступ к службам, запущенным на этом компьютере, вы можете разрешить эти службы в брандмауэре.

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

Список Доверенные службы (Trusted services) позволяет выбрать службы, подключения к которым могут проходить через брандмауэр.

Протокол HTTP используется Apache (и другими веб-серверами) для передачи веб-содержимого. Если вы планируете сделать ваш веб-сервер общедоступным, отметьте этот пункт. Установка этого параметра не требуется для локального просмотра или создания веб-страниц. Чтобы ваш компьютер выполнял роль веб-сервера, у вас должен быть установлен пакет httpd .

Включение WWW (HTTP) не открывает порт HTTPS, SSL-версии HTTP.

Протокол FTP используется для передачи файлов между компьютерами в сети. Если вы планируете сделать ваш FTP-сервер общедоступным, отметьте этот пункт. Чтобы этот выбор имел смысл, должен быть установлен пакет vsftpd .

Безопасная оболочка (Secure SHell, SSH) — это набор средств для подключения и выполнения команд на удалённом компьютере. Чтобы разрешить удалённый доступ к компьютеру через SSH, отметьте этот пункт. Чтобы вы могли удалённо обращаться к своему компьютеру, используя инструменты SSH, на компьютере должен быть установлен пакет openssh-server .

Telnet — это протокол для входа на удалённые компьютеры. Соединения telnet не шифруются и не обеспечивают защиты от перехвата сетевых пакетов. Разрешать входящие telnet-соединения не рекомендуется. Чтобы доступ через Telnet был разрешён, у вас должен быть установлен пакет telnet-server .

Почта (Mail) (SMTP)

Чтобы разрешить доставку входящей почты через брандмауэр (чтобы к вашему компьютеру могли подключаться удалённые узлы, доставляющие почту), отметьте этот пункт. Вам не нужно включать его, если вы получаете почту на сервере вашего Интернет-провайдера, используя протокол POP3 или IMAP или программу fetchmail . Обратите внимание, неправильно настроенный SMTP-сервер может быть использован в качестве источника рассылки спама.

Определив Доверенные устройства (Trusted Devices) вы разрешаете полный доступ к вашей системе с этих устройств; они исключаются из правил брандмауэра. Например, если вы работаете в локальной сети, и подключаетесь к Интернету через модемное PPP-соединение, вы можете отметить eth0 и разрешить весь трафик, приходящий из локальной сети. Пометив eth0 как доверенное устройство, вы разрешаете весь трафик, приходящий через Ethernet, тогда как интерфейс ppp0 остаётся защищённым. Чтобы ограничить трафик интерфейса, оставьте его неотмеченным.

Вы можете заметить устройство sit0 в разделе Доверенные устройства (Trusted devices) . Его название расшифровывается как Simple Internet Transition (простое преобразование Интернета), а его роль состоит во вложении трафика IPv6 в трафик IPv4. В правилах простого брандмауэра это устройство можно игнорировать и оставить недоверенным.

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

В программе Настройка уровня безопасности (Security Level Configuration Tool) есть раздел Другие порты (Other ports) , в котором можно определить свои IP-порты, которые должны считаться доверенными в iptables . Например, чтобы разрешить прохождение через брандмауэр протоколов NFS, IRC и протокола печати через Интернет (Internet Printing Protocol, IPP), в раздел Другие порты (Other ports) нужно добавить:

Нажмите OK , чтобы сохранить изменения и включить или отключить брандмауэр. Если выбран вариант Включить брандмауэр (Enable firewall) , назначенные параметры преобразуются в команды iptables и сохраняются в файле /etc/sysconfig/iptables . Также запускается сама служба iptables , чтобы брандмауэр активизировался сразу после сохранения назначенных параметров. Если выбран вариант Отключить брандмауэр (Disable firewall) , файл /etc/sysconfig/iptables удаляется, а служба iptables сразу останавливается.

Выбранные параметры также сохраняются в файле /etc/sysconfig/system-config-securitylevel , чтобы настройки можно было восстановить при следующем запуске приложения. Не редактируйте этот файл вручную.

И хотя брандмауэр активизируется сразу, служба iptables не настраивается для автоматического запуска при загрузке. Подробнее об этом рассказывается в разделе 19.2 Активизация службы iptables .

Источник

Introduction to Linux firewalld zones and rules

More Linux resources

In my previous article, «Beginner’s guide to firewalld in Linux,» we explored the basics of creating allow and deny lists for both services and ports inside of existing zones. If this doesn’t sound familiar, I recommend that you check out that previous piece. However, if you are up to speed with firewalld , zone-based firewalls, and service/port-based rules, then you are in the right place. In this article, we look at three slightly more advanced features of firewalld and how to configure each. Let’s get into it.

Create custom zones

As discussed previously, zone-based firewalls need zones to operate. The goal is to have different security measures for particular zones of the network. Let us assume that we need to create a new zone called enable_test. To do this, we use the following command:

This command creates a new, permanent zone titled enable_test. There are no services or ports added to enable_test yet. Therefore, no traffic is allowed in or out. If you have a configuration file that you normally use for firewall zone configs, you can use it by using this command:

Note 1: In —new-zone-from-file=file , file = the file path of the config.

Note 2: When creating zones, you must use the —permanent flag. You must also —reload the config for the changes to take place.

Assign an interface

Now that we have our new enable_test zone created, we need to associate a network interface with the zone. If we don’t do this, we won’t be able to use the new zone. I am going to associate it with the interface enp0s8 .

Add the interface to the zone:

Verify the interface association:

If you need to remove the interface:

Advanced rule creation

Now, here is where things get interesting. There is a lot of flexibility in the rules you can create with firewalld . You aren’t limited to just «deny this port,» «allow this service,» and so on. You can create highly complex rules for specific situations. These rules are known as rich rules.

Something to know about firewall rules—in general, they are made up of two parts:

  1. Conditions that must be met before the rule can be enacted.
  2. Actions to be carried out once those conditions are met. These actions are accept, reject, and drop.

Let’s assume that we want to create a rule that states something like this:

Reject all FTP connections from Fedora client 2 (172.25.1.7)

Most of these options are self-explanatory; however, you must start with the keyword rule . The family option states the type of traffic to enact the rule on. If left blank, it will default to both IPv4 and IPv6 packets.

Need more info?

As you might have guessed, there are a huge number of options to create even more complex rules. Be sure to check out the firewalld documentation for further information. Hopefully, this look behind one of our most important curtains has been an enlightening experience. While firewalls and security systems are quite complex, at their most basic levels, they are just a set of rules—rules designed not to be broken.

[ Network getting out of control? Check out Network automation for everyone, a free book from Red Hat. ]

Источник

Red Hat Customer Portal

Log in to Your Red Hat Account

Your Red Hat account gives you access to your profile, preferences, and services, depending on your status.

If you are a new customer, register now for access to product evaluations and purchasing capabilities.

Need access to an account?

If your company has an existing Red Hat account, your organization administrator can grant you access.

Red Hat Account

Customer Portal

For your security, if you’re on a public computer and have finished using your Red Hat services, please be sure to log out.

Select Your Language

Red Hat Training

A Red Hat training course is available for RHEL 8

Chapter 48. Using and configuring firewalld

A firewall is a way to protect machines from any unwanted traffic from outside. It enables users to control incoming network traffic on host machines by defining a set of firewall rules . These rules are used to sort the incoming traffic and either block it or allow through.

firewalld is a firewall service daemon that provides a dynamic customizable host-based firewall with a D-Bus interface. Being dynamic, it enables creating, changing, and deleting the rules without the necessity to restart the firewall daemon each time the rules are changed.

firewalld uses the concepts of zones and services, that simplify the traffic management. Zones are predefined sets of rules. Network interfaces and sources can be assigned to a zone. The traffic allowed depends on the network your computer is connected to and the security level this network is assigned. Firewall services are predefined rules that cover all necessary settings to allow incoming traffic for a specific service and they apply within a zone.

Services use one or more ports or addresses for network communication. Firewalls filter communication based on ports. To allow network traffic for a service, its ports must be open. firewalld blocks all traffic on ports that are not explicitly set as open. Some zones, such as trusted, allow all traffic by default.

Note that firewalld with nftables backend does not support passing custom nftables rules to firewalld , using the —direct option.

48.1. Getting started with firewalld

This section provides information about firewalld .

48.1.1. When to use firewalld, nftables, or iptables

The following is a brief overview in which scenario you should use one of the following utilities:

  • firewalld : Use the firewalld utility for simple firewall use cases. The utility is easy to use and covers the typical use cases for these scenarios.
  • nftables : Use the nftables utility to set up complex and performance critical firewalls, such as for a whole network.
  • iptables : The iptables utility on Red Hat Enterprise Linux uses the nf_tables kernel API instead of the legacy back end. The nf_tables API provides backward compatibility so that scripts that use iptables commands still work on Red Hat Enterprise Linux. For new firewall scripts, Red Hat recommends to use nftables .

To avoid that the different firewall services influence each other, run only one of them on a RHEL host, and disable the other services.

48.1.2. Zones

⁠ firewalld can be used to separate networks into different zones according to the level of trust that the user has decided to place on the interfaces and traffic within that network. A connection can only be part of one zone, but a zone can be used for many network connections.

NetworkManager notifies firewalld of the zone of an interface. You can assign zones to interfaces with:

  • NetworkManager
  • firewall-config tool
  • firewall-cmd command-line tool
  • The RHEL web console

The latter three can only edit the appropriate NetworkManager configuration files. If you change the zone of the interface using the web console, firewall-cmd or firewall-config , the request is forwarded to NetworkManager and is not handled by ⁠ firewalld .

The predefined zones are stored in the /usr/lib/firewalld/zones/ directory and can be instantly applied to any available network interface. These files are copied to the /etc/firewalld/zones/ directory only after they are modified. The default settings of the predefined zones are as follows:

One of these zones is set as the default zone. When interface connections are added to NetworkManager , they are assigned to the default zone. On installation, the default zone in firewalld is set to be the public zone. The default zone can be changed.

The network zone names should be self-explanatory and to allow users to quickly make a reasonable decision. To avoid any security problems, review the default zone configuration and disable any unnecessary services according to your needs and risk assessments.

Additional resources

  • The firewalld.zone(5) man page.

48.1.3. Predefined services

A service can be a list of local ports, protocols, source ports, and destinations, as well as a list of firewall helper modules automatically loaded if a service is enabled. Using services saves users time because they can achieve several tasks, such as opening ports, defining protocols, enabling packet forwarding and more, in a single step, rather than setting up everything one after another.

Service configuration options and generic file information are described in the firewalld.service(5) man page. The services are specified by means of individual XML configuration files, which are named in the following format: service-name .xml . Protocol names are preferred over service or application names in firewalld .

Services can be added and removed using the graphical firewall-config tool, firewall-cmd , and firewall-offline-cmd .

Alternatively, you can edit the XML files in the /etc/firewalld/services/ directory. If a service is not added or changed by the user, then no corresponding XML file is found in /etc/firewalld/services/ . The files in the /usr/lib/firewalld/services/ directory can be used as templates if you want to add or change a service.

Additional resources

  • The firewalld.service(5) man page

48.1.4. Starting firewalld

Procedure

To start firewalld , enter the following command as root :

To ensure firewalld starts automatically at system start, enter the following command as root :

48.1.5. Stopping firewalld

Procedure

To stop firewalld , enter the following command as root :

To prevent firewalld from starting automatically at system start:

To make sure firewalld is not started by accessing the firewalld D-Bus interface and also if other services require firewalld :

48.1.6. Verifying the permanent firewalld configuration

In certain situations, for example after manually editing firewalld configuration files, administrators want to verify that the changes are correct. This section describes how to verify the permanent configuration of the firewalld service.

Prerequisites

  • The firewalld service is running.

Procedure

Verify the permanent configuration of the firewalld service:

If the permanent configuration is valid, the command returns success . In other cases, the command returns an error with further details, such as the following:

48.2. Viewing the current status and settings of firewalld

This section covers information about viewing current status, allowed services, and current settings of firewalld .

48.2.1. Viewing the current status of firewalld

The firewall service, firewalld , is installed on the system by default. Use the firewalld CLI interface to check that the service is running.

Procedure

To see the status of the service:

For more information about the service status, use the systemctl status sub-command:

48.2.2. Viewing allowed services using GUI

To view the list of services using the graphical firewall-config tool, press the Super key to enter the Activities Overview, type firewall , and press Enter . The firewall-config tool appears. You can now view the list of services under the Services tab.

You can start the graphical firewall configuration tool using the command-line.

Prerequisites

  • You installed the firewall-config package.

Procedure

To start the graphical firewall configuration tool using the command-line:

The Firewall Configuration window opens. Note that this command can be run as a normal user, but you are prompted for an administrator password occasionally.

48.2.3. Viewing firewalld settings using CLI

With the CLI client, it is possible to get different views of the current firewall settings. The —list-all option shows a complete overview of the firewalld settings.

firewalld uses zones to manage the traffic. If a zone is not specified by the —zone option, the command is effective in the default zone assigned to the active network interface and connection.

Procedure

To list all the relevant information for the default zone:

To specify the zone for which to display the settings, add the —zone= zone-name argument to the firewall-cmd —list-all command, for example:

To see the settings for particular information, such as services or ports, use a specific option. See the firewalld manual pages or get a list of the options using the command help:

To see which services are allowed in the current zone:

Listing the settings for a certain subpart using the CLI tool can sometimes be difficult to interpret. For example, you allow the SSH service and firewalld opens the necessary port (22) for the service. Later, if you list the allowed services, the list shows the SSH service, but if you list open ports, it does not show any. Therefore, it is recommended to use the —list-all option to make sure you receive a complete information.

48.3. Controlling network traffic using firewalld

This section covers information about controlling network traffic using firewalld .

48.3.1. Disabling all traffic in case of emergency using CLI

In an emergency situation, such as a system attack, it is possible to disable all network traffic and cut off the attacker.

Procedure

To immediately disable networking traffic, switch panic mode on:

Enabling panic mode stops all networking traffic. For this reason, it should be used only when you have the physical access to the machine or if you are logged in using a serial console.

Switching off panic mode reverts the firewall to its permanent settings. To switch panic mode off, enter:

Verification

To see whether panic mode is switched on or off, use:

48.3.2. Controlling traffic with predefined services using CLI

The most straightforward method to control traffic is to add a predefined service to firewalld . This opens all necessary ports and modifies other settings according to the service definition file .

Procedure

Check that the service is not already allowed:

List all predefined services:

Add the service to the allowed services:

Make the new settings persistent:

48.3.3. Controlling traffic with predefined services using GUI

This procedure describes how to control the network traffic with predefined services using graphical user interface.

Prerequisites

  • You installed the firewall-config package

Procedure

To enable or disable a predefined or custom service:

  1. Start the firewall-config tool and select the network zone whose services are to be configured.
  2. Select the Services tab.
  3. Select the check box for each type of service you want to trust or clear the check box to block a service.

To edit a service:

  1. Start the firewall-config tool.
  2. Select Permanent from the menu labeled Configuration . Additional icons and menu buttons appear at the bottom of the Services window.
  3. Select the service you want to configure.

The Ports , Protocols , and Source Port tabs enable adding, changing, and removing of ports, protocols, and source port for the selected service. The modules tab is for configuring Netfilter helper modules. The Destination tab enables limiting traffic to a particular destination address and Internet Protocol ( IPv4 or IPv6 ).

It is not possible to alter service settings in the Runtime mode.

48.3.4. Adding new services

Services can be added and removed using the graphical firewall-config tool, firewall-cmd , and firewall-offline-cmd . Alternatively, you can edit the XML files in /etc/firewalld/services/ . If a service is not added or changed by the user, then no corresponding XML file are found in /etc/firewalld/services/ . The files /usr/lib/firewalld/services/ can be used as templates if you want to add or change a service.

Service names must be alphanumeric and can, additionally, include only _ (underscore) and — (dash) characters.

Procedure

To add a new service in a terminal, use firewall-cmd , or firewall-offline-cmd in case of not active firewalld .

Enter the following command to add a new and empty service:

To add a new service using a local file, use the following command:

You can change the service name with the additional —name= service-name option.

As soon as service settings are changed, an updated copy of the service is placed into /etc/firewalld/services/ .

As root , you can enter the following command to copy a service manually:

firewalld loads files from /usr/lib/firewalld/services in the first place. If files are placed in /etc/firewalld/services and they are valid, then these will override the matching files from /usr/lib/firewalld/services . The overridden files in /usr/lib/firewalld/services are used as soon as the matching files in /etc/firewalld/services have been removed or if firewalld has been asked to load the defaults of the services. This applies to the permanent environment only. A reload is needed to get these fallbacks also in the runtime environment.

48.3.5. Opening ports using GUI

To permit traffic through the firewall to a certain port, you can open the port in the GUI.

Prerequisites

  • You installed the firewall-config package

Procedure

  1. Start the firewall-config tool and select the network zone whose settings you want to change.
  2. Select the Ports tab and click the Add button on the right-hand side. The Port and Protocol window opens.
  3. Enter the port number or range of ports to permit.
  4. Select tcp or udp from the list.

48.3.6. Controlling traffic with protocols using GUI

To permit traffic through the firewall using a certain protocol, you can use the GUI.

Prerequisites

  • You installed the firewall-config package

Procedure

  1. Start the firewall-config tool and select the network zone whose settings you want to change.
  2. Select the Protocols tab and click the Add button on the right-hand side. The Protocol window opens.
  3. Either select a protocol from the list or select the Other Protocol check box and enter the protocol in the field.

48.3.7. Opening source ports using GUI

To permit traffic through the firewall from a certain port, you can use the GUI.

Prerequisites

  • You installed the firewall-config package

Procedure

  1. Start the firewall-config tool and select the network zone whose settings you want to change.
  2. Select the Source Port tab and click the Add button on the right-hand side. The Source Port window opens.
  3. Enter the port number or range of ports to permit. Select tcp or udp from the list.

48.4. Controlling ports using CLI

Ports are logical devices that enable an operating system to receive and distinguish network traffic and forward it accordingly to system services. These are usually represented by a daemon that listens on the port, that is it waits for any traffic coming to this port.

Normally, system services listen on standard ports that are reserved for them. The httpd daemon, for example, listens on port 80. However, system administrators by default configure daemons to listen on different ports to enhance security or for other reasons.

48.4.1. Opening a port

Through open ports, the system is accessible from the outside, which represents a security risk. Generally, keep ports closed and only open them if they are required for certain services.

Procedure

To get a list of open ports in the current zone:

List all allowed ports:

Add a port to the allowed ports to open it for incoming traffic:

The port types are either tcp , udp , sctp , or dccp . The type must match the type of network communication.

Make the new settings persistent:

The port types are either tcp , udp , sctp , or dccp . The type must match the type of network communication.

48.4.2. Closing a port

When an open port is no longer needed, close that port in firewalld . It is highly recommended to close all unnecessary ports as soon as they are not used because leaving a port open represents a security risk.

Procedure

To close a port, remove it from the list of allowed ports:

List all allowed ports:

This command will only give you a list of ports that have been opened as ports. You will not be able to see any open ports that have been opened as a service. Therefore, you should consider using the —list-all option instead of —list-ports .

Remove the port from the allowed ports to close it for the incoming traffic:

Make the new settings persistent:

48.5. Working with firewalld zones

Zones represent a concept to manage incoming traffic more transparently. The zones are connected to networking interfaces or assigned a range of source addresses. You manage firewall rules for each zone independently, which enables you to define complex firewall settings and apply them to the traffic.

48.5.1. Listing zones

This procedure describes how to list zones using the command line.

Procedure

To see which zones are available on your system:

The firewall-cmd —get-zones command displays all zones that are available on the system, but it does not show any details for particular zones.

To see detailed information for all zones:

To see detailed information for a specific zone:

48.5.2. Modifying firewalld settings for a certain zone

The Controlling traffic with predefined services using cli and Controlling ports using cli explain how to add services or modify ports in the scope of the current working zone. Sometimes, it is required to set up rules in a different zone.

Procedure

To work in a different zone, use the —zone= zone-name option. For example, to allow the SSH service in the zone public :

48.5.3. Changing the default zone

System administrators assign a zone to a networking interface in its configuration files. If an interface is not assigned to a specific zone, it is assigned to the default zone. After each restart of the firewalld service, firewalld loads the settings for the default zone and makes it active.

Procedure

To set up the default zone:

Display the current default zone:

Set the new default zone:

Following this procedure, the setting is a permanent setting, even without the —permanent option.

48.5.4. Assigning a network interface to a zone

It is possible to define different sets of rules for different zones and then change the settings quickly by changing the zone for the interface that is being used. With multiple interfaces, a specific zone can be set for each of them to distinguish traffic that is coming through them.

Procedure

To assign the zone to a specific interface:

List the active zones and the interfaces assigned to them:

Assign the interface to a different zone:

48.5.5. Assigning a zone to a connection using nmcli

This procedure describes how to add a firewalld zone to a NetworkManager connection using the nmcli utility.

Procedure

Assign the zone to the NetworkManager connection profile:

Reload the connection:

48.5.6. Manually assigning a zone to a network connection in an ifcfg file

When the connection is managed by NetworkManager , it must be aware of a zone that it uses. For every network connection, a zone can be specified, which provides the flexibility of various firewall settings according to the location of the computer with portable devices. Thus, zones and settings can be specified for different locations, such as company or home.

Procedure

To set a zone for a connection, edit the /etc/sysconfig/network-scripts/ifcfg- connection_name file and add a line that assigns a zone to this connection:

48.5.7. Creating a new zone

To use custom zones, create a new zone and use it just like a predefined zone. New zones require the —permanent option, otherwise the command does not work.

Procedure

Create a new zone:

Check if the new zone is added to your permanent settings:

Make the new settings persistent:

48.5.8. Zone configuration files

Zones can also be created using a zone configuration file . This approach can be helpful when you need to create a new zone, but want to reuse the settings from a different zone and only alter them a little.

A firewalld zone configuration file contains the information for a zone. These are the zone description, services, ports, protocols, icmp-blocks, masquerade, forward-ports and rich language rules in an XML file format. The file name has to be zone-name .xml where the length of zone-name is currently limited to 17 chars. The zone configuration files are located in the /usr/lib/firewalld/zones/ and /etc/firewalld/zones/ directories.

The following example shows a configuration that allows one service ( SSH ) and one port range, for both the TCP and UDP protocols:

To change settings for that zone, add or remove sections to add ports, forward ports, services, and so on.

Additional resources

  • firewalld.zone manual page

48.5.9. Using zone targets to set default behavior for incoming traffic

For every zone, you can set a default behavior that handles incoming traffic that is not further specified. Such behaviour is defined by setting the target of the zone. There are four options — default , ACCEPT , REJECT , and DROP . By setting the target to ACCEPT , you accept all incoming packets except those disabled by a specific rule. If you set the target to REJECT or DROP , you disable all incoming packets except those that you have allowed in specific rules. When packets are rejected, the source machine is informed about the rejection, while there is no information sent when the packets are dropped.

Procedure

To set a target for a zone:

List the information for the specific zone to see the default target:

Set a new target in the zone:

48.6. Using zones to manage incoming traffic depending on a source

You can use zones to manage incoming traffic based on its source. That enables you to sort incoming traffic and route it through different zones to allow or disallow services that can be reached by that traffic.

If you add a source to a zone, the zone becomes active and any incoming traffic from that source will be directed through it. You can specify different settings for each zone, which is applied to the traffic from the given sources accordingly. You can use more zones even if you only have one network interface.

48.6.1. Adding a source

To route incoming traffic into a specific zone, add the source to that zone. The source can be an IP address or an IP mask in the classless inter-domain routing (CIDR) notation.

In case you add multiple zones with an overlapping network range, they are ordered alphanumerically by zone name and only the first one is considered.

To set the source in the current zone:

To set the source IP address for a specific zone:

The following procedure allows all incoming traffic from 192.168.2.15 in the trusted zone:

Procedure

List all available zones:

Add the source IP to the trusted zone in the permanent mode:

Make the new settings persistent:

48.6.2. Removing a source

Removing a source from the zone cuts off the traffic coming from it.

Procedure

List allowed sources for the required zone:

Remove the source from the zone permanently:

Make the new settings persistent:

48.6.3. Adding a source port

To enable sorting the traffic based on a port of origin, specify a source port using the —add-source-port option. You can also combine this with the —add-source option to limit the traffic to a certain IP address or IP range.

Procedure

To add a source port:

48.6.4. Removing a source port

By removing a source port you disable sorting the traffic based on a port of origin.

Procedure

To remove a source port:

48.6.5. Using zones and sources to allow a service for only a specific domain

To allow traffic from a specific network to use a service on a machine, use zones and source. The following procedure allows only HTTP traffic from the 192.0.2.0/24 network while any other traffic is blocked.

When you configure this scenario, use a zone that has the default target. Using a zone that has the target set to ACCEPT is a security risk, because for traffic from 192.0.2.0/24 , all network connections would be accepted.

Procedure

List all available zones:

Add the IP range to the internal zone to route the traffic originating from the source through the zone:

Add the http service to the internal zone:

Make the new settings persistent:

Verification

Check that the internal zone is active and that the service is allowed in it:

Additional resources

48.7. Configuring NAT using firewalld

With firewalld , you can configure the following network address translation (NAT) types:

  • Masquerading
  • Source NAT (SNAT)
  • Destination NAT (DNAT)
  • Redirect

48.7.1. The different NAT types: masquerading, source NAT, destination NAT, and redirect

These are the different network address translation (NAT) types:

Use one of these NAT types to change the source IP address of packets. For example, Internet Service Providers do not route private IP ranges, such as 10.0.0.0/8 . If you use private IP ranges in your network and users should be able to reach servers on the Internet, map the source IP address of packets from these ranges to a public IP address.

Both masquerading and SNAT are very similar. The differences are:

  • Masquerading automatically uses the IP address of the outgoing interface. Therefore, use masquerading if the outgoing interface uses a dynamic IP address.
  • SNAT sets the source IP address of packets to a specified IP and does not dynamically look up the IP of the outgoing interface. Therefore, SNAT is faster than masquerading. Use SNAT if the outgoing interface uses a fixed IP address.

48.7.2. Configuring IP address masquerading

The following procedure describes how to enable IP masquerading on your system. IP masquerading hides individual machines behind a gateway when accessing the Internet.

Procedure

To check if IP masquerading is enabled (for example, for the external zone), enter the following command as root :

The command prints yes with exit status 0 if enabled. It prints no with exit status 1 otherwise. If zone is omitted, the default zone will be used.

To enable IP masquerading, enter the following command as root :

  • To make this setting persistent, repeat the command adding the —permanent option.
  • To disable IP masquerading, enter the following command as root :

    48.8. Port forwarding

    Redirecting ports using this method only works for IPv4-based traffic. For IPv6 redirecting setup, you must use rich rules.

    To redirect to an external system, it is necessary to enable masquerading. For more information, see Configuring IP address masquerading.

    48.8.1. Adding a port to redirect

    Using firewalld , you can set up ports redirection so that any incoming traffic that reaches a certain port on your system is delivered to another internal port of your choice or to an external port on another machine.

    Prerequisites

    • Before you redirect traffic from one port to another port, or another address, you have to know three things: which port the packets arrive at, what protocol is used, and where you want to redirect them.

    Procedure

    To redirect a port to another port:

    To redirect a port to another port at a different IP address:

    Add the port to be forwarded:

    48.8.2. Redirecting TCP port 80 to port 88 on the same machine

    Follow the steps to redirect the TCP port 80 to port 88.

    Procedure

    Redirect the port 80 to port 88 for TCP traffic:

    Make the new settings persistent:

    Check that the port is redirected:

    48.8.3. Removing a redirected port

    This procedure describes how to remove the redirected port.

    Procedure

    To remove a redirected port:

    To remove a forwarded port redirected to a different address:

    Remove the forwarded port:

    48.8.4. Removing TCP port 80 forwarded to port 88 on the same machine

    This procedure describes how to remove the port redirection.

    Procedure

    List redirected ports:

    Remove the redirected port from the firewall::

    Make the new settings persistent:

    48.9. Managing ICMP requests

    The Internet Control Message Protocol ( ICMP ) is a supporting protocol that is used by various network devices to send error messages and operational information indicating a connection problem, for example, that a requested service is not available. ICMP differs from transport protocols such as TCP and UDP because it is not used to exchange data between systems.

    Unfortunately, it is possible to use the ICMP messages, especially echo-request and echo-reply , to reveal information about your network and misuse such information for various kinds of fraudulent activities. Therefore, firewalld enables blocking the ICMP requests to protect your network information.

    48.9.1. Listing and blocking ICMP requests

    Listing ICMP requests

    The ICMP requests are described in individual XML files that are located in the /usr/lib/firewalld/icmptypes/ directory. You can read these files to see a description of the request. The firewall-cmd command controls the ICMP requests manipulation.

    To list all available ICMP types:

    The ICMP request can be used by IPv4, IPv6, or by both protocols. To see for which protocol the ICMP request has used:

    The status of an ICMP request shows yes if the request is currently blocked or no if it is not. To see if an ICMP request is currently blocked:

    Blocking or unblocking ICMP requests

    When your server blocks ICMP requests, it does not provide the information that it normally would. However, that does not mean that no information is given at all. The clients receive information that the particular ICMP request is being blocked (rejected). Blocking the ICMP requests should be considered carefully, because it can cause communication problems, especially with IPv6 traffic.

    To see if an ICMP request is currently blocked:

    To block an ICMP request:

    To remove the block for an ICMP request:

    Blocking ICMP requests without providing any information at all

    Normally, if you block ICMP requests, clients know that you are blocking it. So, a potential attacker who is sniffing for live IP addresses is still able to see that your IP address is online. To hide this information completely, you have to drop all ICMP requests.

      To block and drop all ICMP requests:

    Set the target of your zone to DROP :

    Now, all traffic, including ICMP requests, is dropped, except traffic which you have explicitly allowed.

    To block and drop certain ICMP requests and allow others:

    Set the target of your zone to DROP :

    Add the ICMP block inversion to block all ICMP requests at once:

    Add the ICMP block for those ICMP requests that you want to allow:

    Make the new settings persistent:

    The block inversion inverts the setting of the ICMP requests blocks, so all requests, that were not previously blocked, are blocked because of the target of your zone changes to DROP . The requests that were blocked are not blocked. This means that if you want to unblock a request, you must use the blocking command.

    To revert the block inversion to a fully permissive setting:

    Set the target of your zone to default or ACCEPT :

    Remove all added blocks for ICMP requests:

    Remove the ICMP block inversion:

    Make the new settings persistent:

    48.9.2. Configuring the ICMP filter using GUI

    • To enable or disable an ICMP filter, start the firewall-config tool and select the network zone whose messages are to be filtered. Select the ICMP Filter tab and select the check box for each type of ICMP message you want to filter. Clear the check box to disable a filter. This setting is per direction and the default allows everything.
    • To edit an ICMP type, start the firewall-config tool and select Permanent mode from the menu labeled Configuration . Additional icons appear at the bottom of the Services window. Select Yes in the following dialog to enable masquerading and to make forwarding to another machine working.
    • To enable inverting the ICMP Filter , click the Invert Filter check box on the right. Only marked ICMP types are now accepted, all other are rejected. In a zone using the DROP target, they are dropped.

    48.10. Setting and controlling IP sets using firewalld

    To see the list of IP set types supported by firewalld , enter the following command as root.

    48.10.1. Configuring IP set options using CLI

    IP sets can be used in firewalld zones as sources and also as sources in rich rules. In Red Hat Enterprise Linux, the preferred method is to use the IP sets created with firewalld in a direct rule.

    To list the IP sets known to firewalld in the permanent environment, use the following command as root :

    To add a new IP set, use the following command using the permanent environment as root :

    The previous command creates a new IP set with the name test and the hash:net type for IPv4 . To create an IP set for use with IPv6 , add the —option=family=inet6 option. To make the new setting effective in the runtime environment, reload firewalld .

    List the new IP set with the following command as root :

    To get more information about the IP set, use the following command as root :

    Note that the IP set does not have any entries at the moment.

    To add an entry to the test IP set, use the following command as root :

    The previous command adds the IP address 192.168.0.1 to the IP set.

    To get the list of current entries in the IP set, use the following command as root :

    Generate a file containing a list of IP addresses, for example:

    The file with the list of IP addresses for an IP set should contain an entry per line. Lines starting with a hash, a semi-colon, or empty lines are ignored.

    To add the addresses from the iplist.txt file, use the following command as root :

    To see the extended entries list of the IP set, use the following command as root :

    To remove the addresses from the IP set and to check the updated entries list, use the following commands as root :

    You can add the IP set as a source to a zone to handle all traffic coming in from any of the addresses listed in the IP set with a zone. For example, to add the test IP set as a source to the drop zone to drop all packets coming from all entries listed in the test IP set, use the following command as root :

    The ipset: prefix in the source shows firewalld that the source is an IP set and not an IP address or an address range.

    Only the creation and removal of IP sets is limited to the permanent environment, all other IP set options can be used also in the runtime environment without the —permanent option.

    Red Hat does not recommend using IP sets that are not managed through firewalld . To use such IP sets, a permanent direct rule is required to reference the set, and a custom service must be added to create these IP sets. This service needs to be started before firewalld starts, otherwise firewalld is not able to add the direct rules using these sets. You can add permanent direct rules with the /etc/firewalld/direct.xml file.

    48.11. Prioritizing rich rules

    By default, rich rules are organized based on their rule action. For example, deny rules have precedence over allow rules. The priority parameter in rich rules provides administrators fine-grained control over rich rules and their execution order.

    48.11.1. How the priority parameter organizes rules into different chains

    You can set the priority parameter in a rich rule to any number between -32768 and 32767 , and lower values have higher precedence.

    The firewalld service organizes rules based on their priority value into different chains:

    • Priority lower than 0: the rule is redirected into a chain with the _pre suffix.
    • Priority higher than 0: the rule is redirected into a chain with the _post suffix.
    • Priority equals 0: based on the action, the rule is redirected into a chain with the _log , _deny , or _allow the action.

    Inside these sub-chains, firewalld sorts the rules based on their priority value.

    48.11.2. Setting the priority of a rich rule

    The procedure describes an example of how to create a rich rule that uses the priority parameter to log all traffic that is not allowed or denied by other rules. You can use this rule to flag unexpected traffic.

    Procedure

    Add a rich rule with a very low precedence to log all traffic that has not been matched by other rules:

    The command additionally limits the number of log entries to 5 per minute.

    Optionally, display the nftables rule that the command in the previous step created:

    48.12. Configuring firewall lockdown

    Local applications or services are able to change the firewall configuration if they are running as root (for example, libvirt ). With this feature, the administrator can lock the firewall configuration so that either no applications or only applications that are added to the lockdown allow list are able to request firewall changes. The lockdown settings default to disabled. If enabled, the user can be sure that there are no unwanted configuration changes made to the firewall by local applications or services.

    48.12.1. Configuring lockdown using CLI

    This procedure describes how to enable or disable lockdown using the command line.

    To query whether lockdown is enabled, use the following command as root :

    The command prints yes with exit status 0 if lockdown is enabled. It prints no with exit status 1 otherwise.

    To enable lockdown, enter the following command as root :

    To disable lockdown, use the following command as root :

    48.12.2. Configuring lockdown allowlist options using CLI

    The lockdown allowlist can contain commands, security contexts, users and user IDs. If a command entry on the allowlist ends with an asterisk «*», then all command lines starting with that command will match. If the «*» is not there then the absolute command including arguments must match.

    The context is the security (SELinux) context of a running application or service. To get the context of a running application use the following command:

    That command returns all running applications. Pipe the output through the grep tool to get the application of interest. For example:

    To list all command lines that are in the allowlist, enter the following command as root :

    To add a command command to the allowlist, enter the following command as root :

    To remove a command command from the allowlist, enter the following command as root :

    To query whether the command command is in the allowlist, enter the following command as root :

    The command prints yes with exit status 0 if true. It prints no with exit status 1 otherwise.

    To list all security contexts that are in the allowlist, enter the following command as root :

    To add a context context to the allowlist, enter the following command as root :

    To remove a context context from the allowlist, enter the following command as root :

    To query whether the context context is in the allowlist, enter the following command as root :

    Prints yes with exit status 0 , if true, prints no with exit status 1 otherwise.

    To list all user IDs that are in the allowlist, enter the following command as root :

    To add a user ID uid to the allowlist, enter the following command as root :

    To remove a user ID uid from the allowlist, enter the following command as root :

    To query whether the user ID uid is in the allowlist, enter the following command:

    Prints yes with exit status 0 , if true, prints no with exit status 1 otherwise.

    To list all user names that are in the allowlist, enter the following command as root :

    To add a user name user to the allowlist, enter the following command as root :

    To remove a user name user from the allowlist, enter the following command as root :

    To query whether the user name user is in the allowlist, enter the following command:

    Prints yes with exit status 0 , if true, prints no with exit status 1 otherwise.

    48.12.3. Configuring lockdown allowlist options using configuration files

    The default allowlist configuration file contains the NetworkManager context and the default context of libvirt . The user ID 0 is also on the list.

    Following is an example allowlist configuration file enabling all commands for the firewall-cmd utility, for a user called user whose user ID is 815 :

    This example shows both user id and user name , but only one option is required. Python is the interpreter and is prepended to the command line. You can also use a specific command, for example:

    In that example, only the —lockdown-on command is allowed.

    In Red Hat Enterprise Linux, all utilities are placed in the /usr/bin/ directory and the /bin/ directory is sym-linked to the /usr/bin/ directory. In other words, although the path for firewall-cmd when entered as root might resolve to /bin/firewall-cmd , /usr/bin/firewall-cmd can now be used. All new scripts should use the new location. But be aware that if scripts that run as root are written to use the /bin/firewall-cmd path, then that command path must be added in the allowlist in addition to the /usr/bin/firewall-cmd path traditionally used only for non- root users.

    The * at the end of the name attribute of a command means that all commands that start with this string match. If the * is not there then the absolute command including arguments must match.

    Источник

    Читайте также:  Оперативная система mac os что это
    Оцените статью
    Предупреждение