From Fedora Project Wiki
Line 216: Line 216:
   firewall-cmd --query-panic && echo "On" || echo "Off"
   firewall-cmd --query-panic && echo "On" || echo "Off"


==== Выполнение обработки зон ====
==== Обработка зон в среде выполнения ====


В режиме выполнения изменения в зонах не постоянны. Изменения будут применены после перезагрузки или перезапуска.
В режиме выполнения изменения в зонах не постоянны. Изменения будут применены после перезагрузки или перезапуска.

Revision as of 13:18, 9 March 2013

Динамический брандмауэр с использованием FirewallD (firewall daemon / демон межсетевого экрана)

FirewallD предоставляет функционал динамически управляемого брандмауэра с поддержкой сетевых зон, призванных определить уровень доверия для сетевого соединения или интерфейса. Он имеет поддержку настройки межсетевого экрана IPv4, IPv6 и сетевых мостов, а также разделяет среду выполнения и параметры конфигурации. FirewallD также имеет интерфейс для добавления правил брандмауэра непосредственно из служб и приложений.

Прежняя модель брандмауэра (с применением system-config-firewall/lokkit) была статической и каждое изменение требовало полной перезагрузки межсетевого экрана. Такая модель также подразумевала и выгрузку модулей ядра, обеспечивающих функционирование брандмауэра, а также загрузку модулей, необходимых для работы новой конфигурации. Выгрузка модулей приводила к нарушению состояния межсетевого экрана и установленных соединений.

С другой стороны, FirewallD обеспечивает динамическое управление брандмауэром и применяет изменения конфигурации без перезагрузки всего межсетевого экрана. Следовательно, нет необходимости перезагружать все модули ядра, обеспечивающие функционирование брандмауэра. Но использование FirewallD требует, чтобы все изменения в конфигурации межсетевого экрана выполнялись именно демоном, для обеспечения соответствия в состояниях демона и брандмауэра. FirewallD не может анализировать правила брандмауэра, добавленные консольными утилитами ip*tables и ebtables.

FirewallD предоставляет информацию об активных в текущее времени параметрах межсетевого экрана через шину D-BUS, а также утверждает изменения, полученные посредством D-BUS, использую метод аутентификации PolicyKit.

Демон

Приложения, демоны и пользователь могут сделать запрос через D-BUS для разрешения функции брандмауэра. Это может быть одна из предопределённых функций межсетевого экрана, таких как комбинации служб, порта и протокола, перенаправление порта/пакета, маскарадинг или блокирование ICMP. Функция может быть включена на определённое время или может быть снова отключена.

С помощью так называемого прямого интерфейса другие службы (например, такие как libvirt) могут добавлять собственные правила, используя аргументы и параметры iptables.

Вспомогательные модули межсетевого экрана, которые используются, например, для служб amanda, ftp, samba и tftp, также обрабатываются демоном, пока они являются частью определённой заранее службы. Загрузка дополнительных вспомогательных модулей не является частью текущего интерфейса. Для некоторых вспомогательных модулей выгрузка возможна только после того, как все обрабатываемые соединения завершатся. Поэтому отслеживаемые данные о соединении в данном случае важны и должны обрабатываться.

Статический межсетевой экран (system-config-firewall/lokkit)

Действующая статическая модель брандмауэра (с применением system-config-firewall и lokkit) всё ещё будет доступна и пригодна к использованию, но не одновременно с запущенным FirewallD. Пользователь либо администратор могут принимать решение, какой из вариантов межсетевого экрана следует исползовать, путём запуска соответствующей службы.

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

FirewallD не зависит от system-config-firewall, тем не менее, их не следует использовать одновременно.

Что такое зона?

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

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

Определённые заранее службы

Служба ― это комбинация записей портов и/или протоколов. Опционально могут добавляться вспомогательные модули, а также адрес назначения IPv4 и IPv6.

Порты и протоколы

Определение портов TCP или UDP, где порты могут представлять собой единственный порт либо диапазон поротов.

Блоки ICMP

Отдельные блоки межсетевого протокола управляющих сообщений (Internet Control Message Protocol, ICMP). Эти блоки являются либо информационными запросами, либо сообщениями, созданными в ответ на информационные запросы, либо сообщениями об ошибках.

Маскарадинг

Адреса частной сети спрятаны за доступным извне адресом IP и привязаны к нему. Это разновидность трансляции адресов.

Проброс портов

Порт переназначается на другой порт и/или другой узел.

Какие доступны зоны?

Предоставляемые FirewallD зоны по умолчанию отсортированы в соответствии с уронями доверия ― от ненадёжного до доверенного:

Сброс (drop, неизменяемая зона)

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

Блокирование (block, неизменяемая зона)

Все входящие сетевые соединения отклоняются с сообщениями icmp-host-prohibited (для IPv4) и icmp6-adm-prohibited (для IPv6). Возможны только инициированные в рамках данной системы сетевые соединения.

Общественное место (public)

Предназначено для использования в общественных местах. Остальные компьютеры сети считаются ненадёжными (с точки зрения причинения вреда вашему ПК). Разрешены лишь отдельные входящие соединения.

"Внешняя" сеть (external)

Предназначено для использования во "внешних" сетях с активированным режимом маскарадинга, особенно с применением роутеров. Остальные компьютеры сети считаются ненадёжными (с точки зрения причинения вреда вашему ПК). Разрешены лишь отдельные входящие соединения.

"Безоружная" зона (demilitarized zone, DMZ)

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

Рабочее пространство (work)

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

Домашняя сеть (home)

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

"Внутренняя" сеть (internal)

Предназначено для использования во "внутренних" сетях. Остальные компьютеры сети, по большей части, считаются надёжными (с точки зрения причинения вреда вашему ПК). Разрешены лишь отдельные входящие соединения.

Доверенная сеть (trusted, неизменяемая зона)

Разрешены все сетевые соединения.

Какую зону следует использовать?

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

Как добавить или настроить зоны?

Чтобы создать или настроить зоны, вы можете использовать какой-либо из интерфейсов FirewallD, предназначенных для обработки и изменения конфигурации. Ими являются графическое средство конфигурирования firewall-config, консольная утилита firewall-cmd или интерфейс D-BUS. Также вы можете создать или скопировать файл зоны в одном из каталогов конфигурации. Директория /etc/firewalld/zone используется для хранения настроек по-умолчанию, а также для возврата к ним в случае необходимости; каталог @PREFIX@/lib/firewalld/zones используется для хранения изменённых файлов конфигурации либо созданных пользователем.

Как указать или изменить зону для соединения?

Для соединения тип зоны сохраняется в значении опции ZONE= для ifcfg. Если данная опция отсутствует или ей не присвоено значение, то применяется зона, указанная FirewallD по умолчанию.

Если соединение управляется NetworkManager, то для изменения зоны вы также можете использовать nm-connection-editor.

Сетевые соединения, обрабатываемые NetworkManager

Межсетевой экран не может обрабатывать сетевые соединения, созданные в представлении NetworkManager, он может обрабатывать лишь сетевые интерфейсы. Поэтому NetworkManager указывает FirewallD отнести сетевые интерфейсы, относящиеся к соединениям, к зонам, определённым в конфигурационном файле соединения (ifcfg), до установления соединения. Если зона не задана в файле конфигурации, интерфейсы будут отнесены к зоне, указанной FirewallD по умолчанию. Если соединение имеет более одного интерфейса, то все они будут отнесены к соответствующей зоне. Изменения в названиях интерфейсов также будут обработаны NetworkManager и сообщены FirewallD.

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

Кроме того, NetworkManager указывает FirewallD удалить соединения из зон в том случае, если соединение разорвано.

Если FirewallD запускается или перезапускается посредством systemd или скриптов инициализации (init scripts), FirewallD уведомляет NetworkManager и соединения добавятся в соответствующие зоны.

Сетевые соединения, обрабатываемые сетевыми скриптами (network scripts)

Для соединений, обрабатываемых сетевыми скриптами, существуют ограничения. Не существует демона, который мог бы указать FirewallD отнести соединения к той или иной зоне. Это делается только в случае использования скриптов ifcfg-post. Поэтому изменения в именах, произведённые после, не могут буть сообщены FirewallD. Кроме того, перезапуск FirewallD в случае, если соединения уже активны, приведёт к потере связи соединений с зонами. Но существуют идеи, как это исправить. Самая простая из них — относить все соединения к зоне, указанной FirewallD по умолчанию, если не задано другого.

Зона определяет функции межсетевого экрана, разрешённые в данной зоне:

Работа с FirewallD

Для того чтобы, например, разрешить или запретить функции брандмауэра в зонах, вы можете использовать либо графическое средство конфигурирования firewall-config, либо консольную утилиту firewall-cmd.

Использование firewall-cmd

Консольное приложение firewall-cmd поддерживает все функции межсетевого экрана. В режимах статуса и запроса утилита не выдаёт ответных сообщений, но команда возвращает состояние.

Общие положения об использовании

  • Получение статуса FirewallD:
 firewall-cmd --state

Эта команда возвращает статус FirewallD, но видимого ответного сообщения нет. Чтобы получить состояние в визуально различимом виде, следует поступить так:

 firewall-cmd --state && echo "Running" || echo "Not running"
  • Перезагрузка брандмауэра без потери информации о состоянии:
 firewall-cmd --reload

Если вместо этого вы используете ключ --complete-reload, информация о состоянии будет потеряна. Эту опцию следует использовать только в случае серьёзных проблем с межсетевым экраном, например, если существуют такие неполадки с информацией о состоянии, что не может быть установлено ни одно соединение, но все правила межсетевого экрана верны.

  • Получение списка всех поддерживаемых зон:
 firewall-cmd --get-zones

Данная команда выводит список, разделённый пробелами.

  • Получение списка всех поддерживаемых служб:
 firewall-cmd --get-services

Данная команда выводит список, разделённый пробелами.

  • Получение списка всех поддерживаемых типов ICMP:
 firewall-cmd --get-icmptypes

Данная команда выводит список, разделённый пробелами.

  • Вывод всех зон с включённым функционалом:
 firewall-cmd --list-all-zones

Формат вывода таков:

 <zone>
   interfaces: <interface1> ..
   services: <service1> ..
   ports: <port1> ..
   forward-ports: <forward port1> ..
   icmp-blocks: <icmp type1> ..
   
   ..
  • Отображение зоны <zone> с включённым функционалом (если зона не задана, задействуется зона, указанная по умолчанию):
 firewall-cmd [--zone=<zone>] --list-all
  • Получение зоны, указанной по умолчанию для сетевых соединений:
 firewall-cmd --get-default-zone
  • Задание зоны по умолчанию:
 firewall-cmd --set-default-zone=<zone>

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

  • Получение активных зон:
 firewall-cmd --get-active-zones

Данная команда выводит интерфейсы, указанные в качестве части зоны, в следующей форме:

 <zone1>: <interface1> <interface2> ..
 <zone2>: <interface3> ..
  • Получение зон, относящихся к интерфейсу:
 firewall-cmd --get-zone-of-interface=<interface>

Данная команда выводит имя зоны, если интерфейс является частью зоны.

  • Добавление интерфейса в зону:
 firewall-cmd [--zone=<zone>] --add-interface=<interface>

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

  • Изменение зоны, которой принадлежит интерфейс:
 firewall-cmd [--zone=<zone>] --change-interface=<interface>

Данная команда схожа с опцией --add-interface, но она соотносит интерфейс новой зоне, даже если до этого он принадлежал другой зоне.

  • Удаление интерфейса из зоны:
 firewall-cmd [--zone=<zone>] --remove-interface=<interface>
  • Сделать запрос, относится ли интерфейс к зоне:
 firewall-cmd [--zone=<zone>] --query-interface=<interface>

Осуществляет возврат, если интерфейс в зоне. Видимого ответного сообщения нет.

  • Вывод включённых в зоне служб:
 firewall-cmd [ --zone=<zone> ] --list-services
  • Включить "режим паники", блокирующий весь сетевой трафик в случае крайней необходимости:
 firewall-cmd --enable-panic
  • Отключить "режим паники":
 firewall-cmd --disable-panic
  • Сделать запрос на предмет "режима паники":
 firewall-cmd --query-panic

Эта команда возвращает статус "режима паники", но видимого ответного сообщения нет. Чтобы получить состояние в визуально различимом виде, следует поступить так:

 firewall-cmd --query-panic && echo "On" || echo "Off"

Обработка зон в среде выполнения

В режиме выполнения изменения в зонах не постоянны. Изменения будут применены после перезагрузки или перезапуска.

  • Включить службу в пределах зоны:
 firewall-cmd [--zone=<zone>] --add-service=<service> [--timeout=<seconds>]

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

  • Пример: Включить службу ipp-client в пределах зоны на 60 секунд:
 firewall-cmd --zone=home --add-service=ipp-client --timeout=60
  • Пример: Включить службу http в пределах зоны, указанной по умолчанию:
 firewall-cmd --add-service=http
  • Выключить службу для зоны:
 firewall-cmd [--zone=<zone>] --remove-service=<service>

Данная команда выключает службу для зоны. Если зона не задана, будет использована зона, указанная по умолчанию.

  • Пример: Выключить службу http для зоны home:
 firewall-cmd --zone=home --remove-service=http

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

  • Сделать запрос, включена ли служба в пределах зоны:
 firewall-cmd [--zone=<zone>] --query-service=<service>

Эта команда возвращает единицу, если служба включена для зоны, иначе возвращает нуль. Видимого ответного сообщения нет

  • Включить сочетаниепорта и протокола в пределах зоны:
 firewall-cmd [--zone=<zone>] --add-port=<port>[-<port>]/<protocol> [--timeout=<seconds>]

Данная команда включает сочетание порта и протокола. Порт может представлять собой единственный порт <port> или диапазон портов <port>-<port>. Протоколом может быть как tcp, так и udp.

  • Отключить сочетание порта и протокола в пределах зоны:
 firewall-cmd [--zone=<zone>] --remove-port=<port>[-<port>]/<protocol>
  • Сделать запрос, включено ли сочетание порта и протокола в пределах зоны:
 firewall-cmd [--zone=<zone>] --query-port=<port>[-<port>]/<protocol>

Осуществляет возврат, если сочетание включено, видимого ответного сообщения нет.

  • Включить маскарадинг в пределах зоны:
 firewall-cmd [--zone=<zone>] --add-masquerade

Данная команда включает маскарадинг для зоны. Адреса частной сети спрятаны за доступным извне адресом IP и привязаны к нему. Это разновидность трансляции адресов, обычно используется в роутерах. Маскарадинг доступен только для IPv4 из-за ограничений ядра.

  • Отключить маскарадинг для зоны:
 firewall-cmd [--zone=<zone>] --remove-masquerade
  • Сделать запрос на предмет маскарадинга в пределах зоны:
 firewall-cmd [--zone=<zone>] --query-masquerade

Осуществляет возврат, если маскарадинг включён, видимого ответного сообщения нет.

  • Включить блоки ICMP в пределах зоны:
 firewall-cmd [--zone=<zone>] --add-icmp-block=<icmptype>

Эта команда включает блок выбранного межсетевого протокола управляющих сообщений (ICMP). Сообщения ICMP являются либо информационными запросами, либо сообщениями, созданными в ответ на информационные запросы, либо сообщениями об ошибках.

  • Отключить блоки ICMP для зоны:
 firewall-cmd [--zone=<zone>] --remove-icmp-block=<icmptype>
  • Сделать запрос на предмет блоков ICMP в пределах зоны:
 firewall-cmd [--zone=<zone>] --query-icmp-block=<icmptype>

Осуществляет возврат, если блок включён, видимого ответного сообщения нет.

  • Пример: Block echo-reply messages in the public zone: Включить блок сообщений "эхо-ответ" в зоне public:
 firewall-cmd --zone=public --add-icmp-block=echo-reply
  • Включить перенаправление или переназначение портов в пределах зоны:
 firewall-cmd [--zone=<zone>] --add-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }

Порт переназначается либо на такой же порт на другом узле, либо на другой порт на том же узле, либо на другой порт на другом узле. Порт может представлять собой единственный порт <port> или диапазон портов <port>-<port>. Протоколом может быть как tcp, так и udp. Значение опции toport может быть как портом <port>, так и диапазоном портов <port>-<port>. Значение опции toaddr является адресом IPv4. Перенаправление портов доступно только для IPv4 из-за ограничений ядра.

  • Отключить перенаправление или переназначение портов для зоны:
 firewall-cmd [--zone=<zone>] --remove-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }
  • Сделать запрос на предмет перенаправления или переназначения портов в пределах зоны:
 firewall-cmd [--zone=<zone>] --query-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }

This command returns if it is enabled, there is no output. Осуществляет возврат, если перенаправление либо переназначение включены, видимого ответного сообщения нет.

  • Пример: Перенаправить ssh на узел 127.0.0.2 в пределах зоны home:
 firewall-cmd --zone=home --add-forward-port=port=22:proto=tcp:toaddr=127.0.0.2

Permanent/persistent zone handling

The permanent options are not affecting runtime directly. These options are only available after a reload or restart. To have runtime and permanent setting, you need to supply both. The --permanent option needs to be the first option for all permanent calls.

  • Get a list of supported permanent services
 firewall-cmd --permanent --get-services
  • Get a list of supported permanent icmptypes
 firewall-cmd --permanent --get-icmptypes
  • Get a list of supported permanent zones
 firewall-cmd --permanent --get-zones
  • Enable a service in a zone
 firewall-cmd --permanent [--zone=<zone>] --add-service=<service>

This enables the service in the zone permanently. If the zone option is omitted, the default zone is used.

  • Disable a service in a zone
 firewall-cmd --permanent [--zone=<zone>] --remove-service=<service>
  • Query if a service is enabled in a zone
 firewall-cmd --permanent [--zone=<zone>] --query-service=<service>

This command returns if it is enabled, there is no output.

  • Example: Enable service ipp-client permanently in the home zone
 firewall-cmd --permanent --zone=home --add-service=ipp-client
  • Enable a port and protocol combination permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --add-port=<port>[-<port>]/<protocol>
  • Disable a port and protocol combination permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --remove-port=<port>[-<port>]/<protocol>
  • Query if a port and protocol combination is enabled permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --query-port=<port>[-<port>]/<protocol>

This command returns if it is enabled, there is no output.

  • Example: Enable port 443/tcp for https permanently in the home zone
 firewall-cmd --permanent --zone=home --add-port=443/tcp
  • Enable masquerading permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --add-masquerade

This enables masquerading for the zone. The addresses of a private network are mapped to and hidden behind a public IP address. This is a form of address translation and mostly used in routers. Masquerading is IPv4 only because of kernel limitations.

  • Disable masquerading permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --remove-masquerade
  • Query masquerading permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --query-masquerade

This command returns if it is enabled, there is no output.

  • Enable ICMP blocks permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --add-icmp-block=<icmptype>

This enabled the block of a selected Internet Control Message Protocol (ICMP) message. ICMP messages are either information requests or created as a reply to information requests or in error conditions.

  • Disable ICMP blocks permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --remove-icmp-block=<icmptype>
  • Query ICMP blocks permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --query-icmp-block=<icmptype>

This command returns if it is enabled, there is no output.

  • Example: Block echo-reply messages in the public zone:
 firewall-cmd --permanent --zone=public --add-icmp-block=echo-reply
  • Enable port forwarding or port mapping permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --add-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }

The port is either mapped to the same port on another host or to another port on the same host or to another port on another host. The port can be a singe port <port> or a port range <port>-<port>. The protocol is either tcp or udp. toport is either port <port> or a port range <port>-<port>. toaddr is an IPv4 address. Port forwarding is IPv4 only because of kernel limitations.

  • Disable port forwarding or port mapping permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --remove-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }
  • Query port forwarding or port mapping permanently in a zone
 firewall-cmd --permanent [--zone=<zone>] --query-forward-port=port=<port>[-<port>]:proto=<protocol> { :toport=<port>[-<port>] | :toaddr=<address> | :toport=<port>[-<port>]:toaddr=<address> }

This command returns if it is enabled, there is no output.

  • Example: Forward ssh to host 127.0.0.2 in the home zone
 firewall-cmd --permanent --zone=home --add-forward-port=port=22:proto=tcp:toaddr=127.0.0.2

Direct options

The direct options are mostly for services and applications to be able to add custom rules. The rules are not saved and have to get resubmitted after reload or restart. The arguments <args> of the passthrough option are the same as the corresponding iptables, ip6tables and ebtables arguments.

The --direct option needs to be the first option for all direct options.

  • Pass a command through to the firewall. <args> can be all iptables, ip6tables and ebtables command line arguments
 firewall-cmd --direct --passthrough { ipv4 | ipv6 | eb } <args>
  • Add a new chain <chain> to a table <table>.
 firewall-cmd --direct --add-chain { ipv4 | ipv6 | eb } <table> <chain>
  • Remove a chain with name <chain> from table <table>.
 firewall-cmd --direct --remove-chain { ipv4 | ipv6 | eb } <table> <chain>
  • Query if a chain with name <chain> exists in table <table>. Returns 0 if true, 1 otherwise.
 firewall-cmd --direct --query-chain { ipv4 | ipv6 | eb } <table> <chain>

This command returns if it is enabled, there is no output.

  • Get all chains added to table <table> as a space separated list.
 firewall-cmd --direct --get-chains { ipv4 | ipv6 | eb } <table>
  • Add a rule with the arguments <args> to chain <chain> in table <table> with priority <priority>.
 firewall-cmd --direct --add-rule { ipv4 | ipv6 | eb } <table> <chain> <priority> <args>
  • Remove a rule with the arguments <args> from chain <chain> in table <table>.
 firewall-cmd --direct --remove-rule { ipv4 | ipv6 | eb } <table> <chain> <args>
  • Query if a rule with the arguments <args> exists in chain <chain> in table <table>. Returns 0 if true, 1 otherwise.
 firewall-cmd --direct --query-rule { ipv4 | ipv6 | eb } <table> <chain> <args>

This command returns if it is enabled, there is no output.

  • Get all rules added to chain <chain> in table <table> as a newline separated list of arguments.
 firewall-cmd --direct --get-rules { ipv4 | ipv6 | eb } <table> <chain>

The current firewalld features

D-BUS Interface

The D-BUS interface gives information about the firewall state and makes it possible to enable, disable and query firewall settings.

Zones

A network or firewall zone defines the trust level of the interface used for a connection. There are several pre-defined zones provided by firewalld. Zone configuration options and generic file information are described in the firewalld.zone(5) man page.

Services

A service can be a list of local ports and destinations and additionally also a list of firewall helper modules automatically loaded if a service is enabled. The use of predefined services makes it easier for the user to enable and disable access to a service. Service configuration options and generic file information are described in the firewalld.service(5) man page.

ICMP types

The Internet Control Message Protocol (ICMP) is used to exchange information and also error messages in the Internet Protocol (IP). ICMP types can be used in firewalld to limit the exchange of these messages. ICMP type configuration options and generic file information are described in the firewalld.icmptype(5) man page.

Direct interface

The direct interface is mainly used by services or applications to add specific firewall rules. The rules are not persistent and need to get applied after receiving the start, restart or reload message from firewalld using D-BUS.

Runtime configuration

The runtime configuration is not persistent and will only be restored for a reload. After restart or stop of the service or a system reboot, these options will be gone.

Persistent configuration

The persistent configuration is stored in config files and will be restored with every machine boot or service reload or restart.

Tray Applet

The tray applet firewall-applet visualizes the firewall state and also problems with the firewall for the user. It can also be used to configure settings by calling firewall-config.

Graphical Configuration Tool

The configuration tool firewall-config is the main configuration tool for the firewall daemon. It supports all features of the firewall besides the direct interface, this is handled by the service/application that added the rules.

Command Line client

firewall-cmd provides (most of) the configuration features of the graphical tool for the command line.

Support for ebtables

ebtables support is needed to fulfill all needs of the libvirt daemon and to prevent access problems between ip*tables and ebtables on kernel netfilter level. All these commands are accessing the same structures and therefore they should not be used at the same time.

Default/Fallback configuration in /usr/lib/firewalld

This directory contains the default and fallback configuration provided by firewalld for icmptypes, services and zones. The files provided with the firewalld package should not get changed and the changes are gone with an update of the firewalld package. Additional icmptypes, services and zones can be provided with packages or by creating files.

System configuration settings in /etc/firewalld

The system or user configuration stored here is either created by the system administrator or by customization with the configuration interface of firewalld or by hand. The files will overload the default configuration files.

To manually change settings of pre-defined icmptypes, zones or services, copy the file from the default configuration directory to the corresponding directory in the system configuration directory and change it accordingly.

It is not possible to overload immutable zones, because these may not get changed. If you are loading the defaults for a zone that has a default or fallback file, the file in /etc/firewalld will be renamed to <file>.old and the fallback will be used again.

Planned and Proposed Features

Firewall Abstraction Model

Adding an abstraction layer on top of ip*tables and ebtables firewall rules makes adding rules simple and more intuitive. The abstraction layer needs to be powerful, but also simple, which makes this not an easy task. A firewall language has to gen invented for this. Firewall rules have a fixed position and querying generic information about access state, access policies for ports and other firewall features is possible.

Support for conntrack

Conntrack is needed to be able to terminate established connections for features that get disabled. For some use cases it might not be good to terminate the connection: Enabling of a firewall service for a limited time to establish a persistent external connection.

User interaction mode

This is a special mode of in the firewall the user or admin can enable. All requests of applications to alter the firewall are directed to the user to get notified and granted or denied. It is possible to set a time limit for the acceptance of a connection and to limit it to hosts, networks or connections. It can be saved to behave the same in the future without notification.

An additional feature of this mode is direct external connection attempts on preselected services or ports to the user with the same features as the application initiated requests. The limitation on services and ports will also limit the amount of requests sent to the user.

User policy support

The administrator can define which users are able to use the User Interaction Mode and can also limit the firewall features, that can be used with it.

Port metadata information (proposed by Lennart Poettering)

To have a port independent metadata information would be good to have. The current model with a static assignment of ports and protocols from /etc/services is not a good solution and is not reflecting current use cases. Ports in applications or services are dynamic and therefore the port itself does not describe the use case.

This metadata information could be used to form simple rules for the firewall. Here are some examples:

 allow external access to file sharing applications or services
 allow external access to music sharing applications or services
 allow external access to all sharing applications or services
 allow external access to torrent file sharing applications or services
 allow external access to http web services

The metadata information here could not only be application specific, but also a group of use cases. For example the "all sharing" group or the "file sharing" group could match all sharing or file sharing applications, for example torrent file sharing. These are examples, therefore it might be that they are not useful.

There are two possible solutions to get metadata information in the firewall:

The first is to add it to netfilter (kernel space). This has the advantage, that it can be used by everyone, but also limits the use. To get user or system specific information into account, all these need to be implemented in kernel space also.

The other one would be to add this to a firewall daemon. These abstract rules could be used together with information like the trust level of the network connections, the user decision to share with as specific person/host or the hard rule of the administrator to forbid sharing completely.

The second solution would have the advantage that new metadata groups or changes in incorporation of trust levels, user preferences or administrator rules would not require to push a new kernel. Adding these kind of abstract rules to a firewall daemon would make it much more flexible. Even new security levels would be easy to add without kernel updates.

sysctld

At the moment there are sysctl settings that are not properly applied. This happens if the module providing the setting is not loaded at boot time when rc.sysinit runs or it the module gets reloaded at runtime. Another example is net.ipv4.ip_forward, which is needed for example for specific firewall settings, libvirt and also user/admin changes. If there are two apps or daemons enabling ip_forwarding only if needed, then it could happen that one of them is turning it off again without knowing that there is another one, that still needs it tuned on.

The sysctl daemon could solve this by having an internal use count for settings, that will make it possible to turn it off or go to the previous setting again if the requester reverted the request to change it.

Firewall Rules

Netfilter firewalls are always susceptible to rule ordering issues, because a rule does not have a fixed position in a chain. The position can change if other rules are added or removed in a position before that rule.

In the static firewall model a firewall change is recreating a clean and sane firewall setup limited to the features directly supported by system-config-firewall / lokkit. Firewall rules created by other applications are not integrated and s-c-fw / lokkit does not know about them if the customs rules file feature is not in use. Default chains are used and there is no safe way to add and remove rules without interfering with others.

The dynamic model has additional chains for the firewall features. These specific chains are called in a defined ordering and rules added to a chain could not interfere with reject or drop rules in chains that were called before. This makes it possible to have a more sane firewall configuration.

Here are example rules created by the daemon in the filter table with ssh, ipp-client and mdns enabled in the public zone, all other zones have been removed to simplify and shorten the output:

 *filter
 :INPUT ACCEPT [0:0]
 :FORWARD ACCEPT [0:0]
 :OUTPUT ACCEPT [0:0]
 :FORWARD_ZONES - [0:0]
 :FORWARD_direct - [0:0]
 :INPUT_ZONES - [0:0]
 :INPUT_direct - [0:0]
 :IN_ZONE_public - [0:0]
 :IN_ZONE_public_allow - [0:0]
 :IN_ZONE_public_deny - [0:0]
 :OUTPUT_direct - [0:0]
 -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
 -A INPUT -i lo -j ACCEPT
 -A INPUT -j INPUT_direct
 -A INPUT -j INPUT_ZONES
 -A INPUT -p icmp -j ACCEPT
 -A INPUT -j REJECT --reject-with icmp-host-prohibited
 -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
 -A FORWARD -i lo -j ACCEPT
 -A FORWARD -j FORWARD_direct
 -A FORWARD -j FORWARD_ZONES
 -A FORWARD -p icmp -j ACCEPT
 -A FORWARD -j REJECT --reject-with icmp-host-prohibited
 -A OUTPUT -j OUTPUT_direct
 -A IN_ZONE_public -j IN_ZONE_public_deny
 -A IN_ZONE_public -j IN_ZONE_public_allow
 -A IN_ZONE_public_allow -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
 -A IN_ZONE_public_allow -d 224.0.0.251/32 -p udp -m udp --dport 5353 -m conntrack --ctstate NEW -j ACCEPT
 -A IN_ZONE_public_allow -p udp -m udp --dport 631 -m conntrack --ctstate NEW -j ACCEPT

Used is a deny/allow model to have a clear behaviour and at best no rule interferences. Icmp blocks for example will go to the IN_ZONE_public_deny chain if set for the public zone and will be handled before the rules in the IN_ZONE_public_allow chain.

This model makes it more easy to add or remove rules from a specific block without interfering with accept or drop rules from another block.