# SOME DESCRIPTIVE TITLE # Copyright (C) YEAR The FreeBSD Project # This file is distributed under the same license as the FreeBSD Documentation package. # Vladlen Popolitov , 2025, 2026. msgid "" msgstr "" "Project-Id-Version: FreeBSD Documentation VERSION\n" "POT-Creation-Date: 2026-02-22 15:58+0000\n" "PO-Revision-Date: 2026-03-05 04:45+0000\n" "Last-Translator: Vladlen Popolitov \n" "Language-Team: Russian \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n" "X-Generator: Weblate 4.17\n" #. type: YAML Front Matter: description #: documentation/content/en/books/handbook/firewalls/_index.adoc:1 #, no-wrap msgid "FreeBSD has three firewalls built into the base system: PF, IPFW, and IPFILTER. This chapter covers how to define packet filtering rules, the differences between the firewalls built into FreeBSD and how to use them" msgstr "В базовой системе FreeBSD встроено три межсетевых экрана: PF, IPFW и IPFILTER. В этой главе рассматривается, как определять правила фильтрации пакетов, различия между встроенными в FreeBSD межсетевыми экранами и способы их использования" #. type: YAML Front Matter: part #: documentation/content/en/books/handbook/firewalls/_index.adoc:1 #, no-wrap msgid "IV. Network Communication" msgstr "IV. Сетевое взаимодействие" #. type: YAML Front Matter: title #: documentation/content/en/books/handbook/firewalls/_index.adoc:1 #, no-wrap msgid "Chapter 33. Firewalls" msgstr "Глава 33. Межсетевые экраны" #. type: Title = #: documentation/content/en/books/handbook/firewalls/_index.adoc:15 #, no-wrap msgid "Firewalls" msgstr "Межсетевые экраны" #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:53 #, no-wrap msgid "Synopsis" msgstr "Обзор" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:58 msgid "" "Firewalls make it possible to filter the incoming and outgoing traffic that " "flows through a system. A firewall can use one or more sets of \"rules\" to " "inspect network packets as they come in or go out of network connections and " "either allows the traffic through or blocks it. The rules of a firewall can " "inspect one or more characteristics of the packets such as the protocol " "type, source or destination host address, and source or destination port." msgstr "" "Межсетевые экраны позволяют фильтровать входящий и исходящий трафик, " "проходящий через систему. Межсетевой экран может использовать один или " "несколько наборов \"правил\" для проверки сетевых пакетов при их поступлении " "или выходе из сетевых соединений и либо пропускает трафик, либо блокирует " "его. Правила межсетевого экрана могут проверять одну или несколько " "характеристик пакетов, таких как тип протокола, адрес исходного или целевого " "хоста, а также исходный или целевой порт." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:61 msgid "" "Firewalls can enhance the security of a host or a network. They can be used " "to do one or more of the following:" msgstr "" "Межсетевые экраны могут повысить безопасность узла или сети. Они могут " "использоваться для выполнения одной или нескольких следующих функций:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:63 msgid "" "Protect and insulate the applications, services, and machines of an internal " "network from unwanted traffic from the public Internet." msgstr "" "Защищать и изолировать приложения, сервисы и машины внутренней сети от " "нежелательного трафика из общедоступного Интернета." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:64 msgid "" "Limit or disable access from hosts of the internal network to services of " "the public Internet." msgstr "" "Ограничивать или отключать доступ с хостов внутренней сети к сервисам " "публичного Интернета." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:65 msgid "" "Support network address translation (NAT), which allows an internal network " "to use private IP addresses and share a single connection to the public " "Internet using either a single IP address or a shared pool of automatically " "assigned public addresses." msgstr "" "Поддерживать преобразования сетевых адресов (NAT), что позволяет внутренней " "сети использовать частные IP-адреса и совместно использовать одно " "подключение к публичному интернету с помощью одного IP-адреса или общего " "пула автоматически назначаемых публичных адресов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:70 msgid "" "FreeBSD has three firewalls built into the base system: PF, IPFW, and " "IPFILTER, also known as IPF. FreeBSD also provides two traffic shapers for " "controlling bandwidth usage: man:altq[4] and man:dummynet[4]. ALTQ has " "traditionally been closely tied with PF and dummynet with IPFW. Each " "firewall uses rules to control the access of packets to and from a FreeBSD " "system, although they go about it in different ways and each has a different " "rule syntax." msgstr "" "В базовой системе FreeBSD встроено три межсетевых экрана: PF, IPFW и " "IPFILTER, также известный как IPF. FreeBSD также предоставляет два " "инструмента для управления использованием пропускной способности: man:" "altq[4] и man:dummynet[4]. ALTQ традиционно тесно связан с PF, а dummynet — " "с IPFW. Каждый межсетевой экран использует правила для контроля доступа " "пакетов к системе FreeBSD и из неё, хотя подходы у них различаются, и каждый " "имеет свой собственный синтаксис правил." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:73 msgid "" "FreeBSD provides multiple firewalls in order to meet the different " "requirements and preferences for a wide variety of users. Each user should " "evaluate which firewall best meets their needs." msgstr "" "FreeBSD предоставляет несколько межсетевых экранов для удовлетворения " "различных требований и предпочтений широкого круга пользователей. Каждый " "пользователь должен оценить, какой межсетевой экран лучше всего " "соответствует его потребностям." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:75 msgid "Read this chapter to learn:" msgstr "Прочтите эту главу, чтобы узнать:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:77 msgid "How to define packet filtering rules." msgstr "Как определить правила фильтрации пакетов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:78 msgid "The differences between the firewalls built into FreeBSD." msgstr "Различия между межсетевыми экранами, встроенными в FreeBSD." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:79 msgid "How to use and configure the PF firewall." msgstr "Как использовать и настроить межсетевой экран PF." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:80 msgid "How to use and configure the IPFW firewall." msgstr "Как использовать и настроить межсетевой экран IPFW." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:81 msgid "How to use and configure the IPFILTER firewall." msgstr "Как использовать и настроить межсетевой экран IPFILTER." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:83 msgid "Before reading this chapter:" msgstr "Прежде чем читать эту главу, необходимо:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:85 msgid "Understand basic FreeBSD and Internet concepts." msgstr "Понимать основы FreeBSD и принципы работы Интернета." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:90 msgid "" "Since all firewalls are based on inspecting the values of selected packet " "control fields, the creator of the firewall ruleset must have an " "understanding of how TCP/IP works, what the different values in the packet " "control fields are, and how these values are used in a normal session " "conversation. For a good introduction, refer to http://www.ipprimer." "com[Daryl's TCP/IP Primer]." msgstr "" "Поскольку все межсетевые экраны основаны на проверке значений выбранных " "управляющих полей пакетов, создатель набора правил межсетевого экрана должен " "понимать, как работает TCP/IP, какие значения содержатся в управляющих полях " "пакетов и как эти значения используются в обычном сеансе связи. Хорошее " "введение можно найти в http://www.ipprimer.com[TCP/IP Primer от Daryl]." #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:93 #, no-wrap msgid "Firewall Concepts" msgstr "Концепции межсетевого экрана" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:101 msgid "" "A ruleset contains a group of rules which pass or block packets based on the " "values contained in the packet. The bi-directional exchange of packets " "between hosts comprises a session conversation. The firewall ruleset " "processes both the packets arriving from the public Internet, as well as the " "packets produced by the system as a response to them. Each TCP/IP service " "is predefined by its protocol and listening port. Packets destined for a " "specific service originate from the source address using an unprivileged " "port and target the specific service port on the destination address. All " "the above parameters can be used as selection criteria to create rules which " "will pass or block services." msgstr "" "Набор правил содержит группу правил, которые пропускают или блокируют пакеты " "на основе значений, содержащихся в пакете. Двунаправленный обмен пакетами " "между хостами составляет сеанс взаимодействия. Межсетевой экран обрабатывает " "как пакеты, поступающие из общедоступного Интернета, так и пакеты, " "генерируемые системой в ответ на них. Каждая служба TCP/IP имеет свой " "протокол и порт прослушивания. Пакеты, предназначенные для конкретной " "службы, идут из исходного адреса с использованием непривилегированного порта " "и направляются на конкретный порт службы на адресе назначения. Все " "вышеуказанные параметры могут быть использованы в качестве критериев выбора " "для создания правил, которые будут пропускать или блокировать службы." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:104 msgid "" "To lookup unknown port numbers, refer to [.filename]#/etc/services#. " "Alternatively, visit https://en.wikipedia.org/wiki/" "List_of_TCP_and_UDP_port_numbers[https://en.wikipedia.org/wiki/" "List_of_TCP_and_UDP_port_numbers] and do a port number lookup to find the " "purpose of a particular port number." msgstr "" "Для поиска неизвестных номеров портов обратитесь к [.filename]#/etc/" "services#. Или посетите https://en.wikipedia.org/wiki/" "List_of_TCP_and_UDP_port_numbers[https://en.wikipedia.org/wiki/" "List_of_TCP_and_UDP_port_numbers] и выполните поиск по номеру порта, чтобы " "узнать его назначение." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:106 msgid "" "Check out this link for http://web.archive.org/web/20150803024617/http://www." "sans.org/security-resources/idfaq/oddports.php[port numbers used by Trojans]." msgstr "" "Ознакомьтесь с этой ссылкой для http://web.archive.org/web/20150803024617/" "http://www.sans.org/security-resources/idfaq/oddports.php[номеров портов, " "используемых троянами]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:111 msgid "" "FTP has two modes: active mode and passive mode. The difference is in how " "the data channel is acquired. Passive mode is more secure as the data " "channel is acquired by the ordinal ftp session requester. For a good " "explanation of FTP and the different modes, see http://www.slacksite.com/" "other/ftp.html[http://www.slacksite.com/other/ftp.html]." msgstr "" "FTP имеет два режима: активный режим и пассивный режим. Разница заключается " "в том, как устанавливается канал передачи данных. Пассивный режим более " "безопасен, так как канал передачи данных устанавливается инициатором сессии " "FTP. Для подробного объяснения работы FTP и различных режимов см. http://www." "slacksite.com/other/ftp.html[http://www.slacksite.com/other/ftp.html]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:115 msgid "" "A firewall ruleset can be either \"exclusive\" or \"inclusive\". An " "exclusive firewall allows all traffic through except for the traffic " "matching the ruleset. An inclusive firewall does the reverse as it only " "allows traffic matching the rules through and blocks everything else." msgstr "" "Набор правил межсетевого экрана может быть \"исключающим\" или \"включающим" "\". Исключающий межсетевой экран пропускает весь трафик, кроме трафика, " "соответствующего набору правил. Включающий межсетевой экран действует " "наоборот, пропуская только трафик, соответствующий правилам, и блокируя всё " "остальное." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:120 msgid "" "An inclusive firewall offers better control of the outgoing traffic, making " "it a better choice for systems that offer services to the public Internet. " "It also controls the type of traffic originating from the public Internet " "that can gain access to a private network. All traffic that does not match " "the rules is blocked and logged. Inclusive firewalls are generally safer " "than exclusive firewalls because they significantly reduce the risk of " "allowing unwanted traffic." msgstr "" "Включающий межсетевой экран обеспечивает лучший контроль исходящего трафика, " "что делает его предпочтительным выбором для систем, предоставляющих услуги в " "публичном Интернете. Он также контролирует тип трафика, исходящего из " "публичного Интернета, который может получить доступ к частной сети. Весь " "трафик, не соответствующий правилам, блокируется и регистрируется. " "Включающие межсетевые экраны, как правило, безопаснее исключающих, поскольку " "они значительно снижают риск пропуска нежелательного трафика." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:124 msgid "" "Unless noted otherwise, all configuration and example rulesets in this " "chapter create inclusive firewall rulesets." msgstr "" "Если не указано иное, все конфигурации и примеры наборов правил в этой главе " "создают включающие наборы правил для межсетевого экрана." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:128 msgid "" "Security can be tightened further using a \"stateful firewall\". This type " "of firewall keeps track of open connections and only allows traffic which " "either matches an existing connection or opens a new, allowed connection." msgstr "" "Безопасность можно дополнительно усилить с помощью \"межсетевого экрана с " "отслеживанием состояния\". Такой тип межсетевого экрана отслеживает активные " "соединения и разрешает только трафик, который соответствует существующему " "соединению или открывает новое, разрешённое соединение." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:133 msgid "" "Stateful filtering treats traffic as a bi-directional exchange of packets " "comprising a session. When state is specified on a matching rule the " "firewall dynamically generates internal rules for each anticipated packet " "being exchanged during the session. It has sufficient matching capabilities " "to determine if a packet is valid for a session. Any packets that do not " "properly fit the session template are automatically rejected." msgstr "" "Фильтрация с отслеживанием состояния рассматривает трафик как двусторонний " "обмен пакетами, составляющими сеанс. Когда для соответствующего правила " "указано состояние, межсетевой экран динамически создает внутренние правила " "для каждого ожидаемого пакета, обмениваемого во время сеанса. Он обладает " "достаточными возможностями сопоставления, чтобы определить, является ли " "пакет допустимым для сеанса. Любые пакеты, которые не соответствуют шаблону " "сеанса, автоматически отклоняются." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:135 msgid "When the session completes, it is removed from the dynamic state table." msgstr "" "Когда сеанс завершается, он удаляется из динамической таблицы состояний." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:140 msgid "" "Stateful filtering allows one to focus on blocking/passing new sessions. If " "the new session is passed, all its subsequent packets are allowed " "automatically and any impostor packets are automatically rejected. If a new " "session is blocked, none of its subsequent packets are allowed. Stateful " "filtering provides advanced matching abilities capable of defending against " "the flood of different attack methods employed by attackers." msgstr "" "Фильтрация с сохранением состояния позволяет сосредоточиться на блокировке/" "пропускании новых сеансов. Если новый сеанс пропущен, все последующие его " "пакеты автоматически разрешаются, а любые поддельные пакеты автоматически " "отвергаются. Если новый сеанс заблокирован, ни один из его последующих " "пакетов не разрешается. Фильтрация с сохранением состояния предоставляет " "расширенные возможности сопоставления, способные защитить от потока " "различных методов атак, используемых злоумышленниками." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:144 msgid "" "NAT stands for _Network Address Translation_. NAT function enables the " "private LAN behind the firewall to share a single ISP-assigned IP address, " "even if that address is dynamically assigned. NAT allows each computer in " "the LAN to have Internet access, without having to pay the ISP for multiple " "Internet accounts or IP addresses." msgstr "" "NAT означает _Network Address Translation_ (Преобразование сетевых адресов). " "Функция NAT позволяет частной локальной сети за межсетевым экраном " "использовать один IP-адрес, назначенный провайдером, даже если этот адрес " "динамический. NAT даёт возможность каждому компьютеру в локальной сети " "выходить в Интернет без необходимости оплачивать провайдеру несколько " "интернет-аккаунтов или IP-адресов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:147 msgid "" "NAT will automatically translate the private LAN IP address for each system " "on the LAN to the single public IP address as packets exit the firewall " "bound for the public Internet. It also performs the reverse translation for " "returning packets." msgstr "" "NAT автоматически преобразует частный IP-адрес LAN для каждой системы в " "локальной сети в единственный публичный IP-адрес, когда пакеты выходят за " "пределы межсетевого экрана, направляясь в публичный Интернет. Он также " "выполняет обратное преобразование для возвращающихся пакетов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:149 msgid "" "According to RFC 1918, the following IP address ranges are reserved for " "private networks which will never be routed directly to the public Internet, " "and therefore are available for use with NAT:" msgstr "" "Согласно RFC 1918, следующие диапазоны IP-адресов зарезервированы для " "частных сетей, которые никогда не маршрутизируются напрямую в публичный " "Интернет и, следовательно, могут использоваться с NAT:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:151 msgid "`10.0.0.0/8`." msgstr "`10.0.0.0/8`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:152 msgid "`172.16.0.0/12`." msgstr "`172.16.0.0/12`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:153 msgid "`192.168.0.0/16`." msgstr "`192.168.0.0/16`." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:159 msgid "" "When working with the firewall rules, be _very careful_. Some " "configurations _can lock the administrator out_ of the server. To be on the " "safe side, consider performing the initial firewall configuration from the " "local console rather than doing it remotely over ssh." msgstr "" "При работе с правилами межсетевого экрана будьте _очень осторожны_. " "Некоторые конфигурации _могут заблокировать администратора_ на сервере. Для " "безопасности рекомендуется выполнять первоначальную настройку межсетевого " "экрана с локальной консоли, а не удалённо через ssh." #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:162 #, no-wrap msgid "PF" msgstr "PF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:166 msgid "" "Since FreeBSD 5.3, a ported version of OpenBSD's PF firewall has been " "included as an integrated part of the base system. PF is a complete, full-" "featured firewall that has optional support for ALTQ (Alternate Queuing), " "which provides Quality of Service (QoS)." msgstr "" "Начиная с FreeBSD 5.3, портированная версия межсетевого экрана PF из OpenBSD " "включена в базовую систему как её неотъемлемая часть. PF — это полноценный и " "многофункциональный межсетевой экран с опциональной поддержкой ALTQ " "(Alternate Queuing), которая обеспечивает качество обслуживания (QoS)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:169 msgid "" "The OpenBSD Project maintains the definitive reference for PF in the http://" "www.openbsd.org/faq/pf/[PF FAQ]. Peter Hansteen maintains a thorough PF " "tutorial at http://home.nuug.no/\\~peter/pf/[http://home.nuug.no/~peter/pf/]." msgstr "" "Проект OpenBSD содержит каноническое справочное издание по PF в http://www." "openbsd.org/faq/pf/[FAQ по PF]. Питер Ханстин ведёт подробный учебник по PF " "на http://home.nuug.no/\\~peter/pf/[http://home.nuug.no/~peter/pf/]." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:174 msgid "" "When reading the http://www.openbsd.org/faq/pf/[PF FAQ], keep in mind that " "FreeBSD's version of PF has diverged substantially from the upstream OpenBSD " "version over the years. Not all features work the same way on FreeBSD as " "they do in OpenBSD and vice versa." msgstr "" "При чтении http://www.openbsd.org/faq/pf/[FAQ по PF] учитывайте, что версия " "PF в FreeBSD значительно отличается от оригинальной версии OpenBSD за " "прошедшие годы. Не все функции работают одинаково в FreeBSD и OpenBSD, и " "наоборот." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:178 msgid "" "The {freebsd-pf} is a good place to ask questions about configuring and " "running the PF firewall. Check the mailing list archives before asking a " "question as it may have already been answered." msgstr "" "`{freebsd-pf}` — хорошее место для вопросов о настройке и работе PF " "межсетевого экрана. Перед тем как задать вопрос, проверьте архивы списка " "рассылки — возможно, ответ уже был дан." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:182 msgid "" "This section of the Handbook focuses on PF as it pertains to FreeBSD. It " "demonstrates how to enable PF and ALTQ. It also provides several examples " "for creating rulesets on a FreeBSD system." msgstr "" "Эта часть Руководства посвящена PF в контексте FreeBSD. В ней показано, как " "включить PF и ALTQ, а также приведены несколько примеров создания наборов " "правил в системе FreeBSD." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:183 #, no-wrap msgid "Enabling PF" msgstr "Включение PF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:187 msgid "" "To use PF, its kernel module must be first loaded. This section describes " "the entries that can be added to [.filename]#/etc/rc.conf# to enable PF." msgstr "" "Для использования PF необходимо сначала загрузить его модуль ядра. В этом " "разделе описаны записи, которые можно добавить в [.filename]#/etc/rc.conf# " "для включения PF." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:189 msgid "Start by adding `pf_enable=yes` to [.filename]#/etc/rc.conf#:" msgstr "Начните с добавления `pf_enable=yes` в [.filename]#/etc/rc.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:193 #, no-wrap msgid "# sysrc pf_enable=yes\n" msgstr "# sysrc pf_enable=yes\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:197 msgid "" "Additional options, described in man:pfctl[8], can be passed to PF when it " "is started. Add or change this entry in [.filename]#/etc/rc.conf# and " "specify any required flags between the two quotes (`\"\"`):" msgstr "" "Дополнительные параметры, описанные в man:pfctl[8], могут быть переданы в PF " "при его запуске. Добавьте или измените эту запись в [.filename]#/etc/rc." "conf# и укажите необходимые флаги между кавычками (`\"\"`):" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:201 #, no-wrap msgid "pf_flags=\"\" # additional flags for pfctl startup\n" msgstr "pf_flags=\"\" # additional flags for pfctl startup\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:207 msgid "" "PF will not start if it cannot find its ruleset configuration file. By " "default, FreeBSD does not ship with a ruleset and there is no [.filename]#/" "etc/pf.conf#. Example rulesets can be found in [.filename]#/usr/share/" "examples/pf/#. If a custom ruleset has been saved somewhere else, add a " "line to [.filename]#/etc/rc.conf# which specifies the full path to the file:" msgstr "" "PF не запустится, если не сможет найти файл конфигурации набора правил. По " "умолчанию FreeBSD не поставляется с готовым набором правил, и файл [." "filename]#/etc/pf.conf# отсутствует. Примеры наборов правил можно найти в [." "filename]#/usr/share/examples/pf/#. Если пользовательский набор правил был " "сохранён в другом месте, добавьте строку в [.filename]#/etc/rc.conf#, " "указывающую полный путь к файлу:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:211 #, no-wrap msgid "pf_rules=\"/path/to/pf.conf\"\n" msgstr "pf_rules=\"/path/to/pf.conf\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:215 msgid "" "Logging support for PF is provided by man:pflog[4]. To enable logging " "support, add `pflog_enable=yes` to [.filename]#/etc/rc.conf#:" msgstr "" "Поддержка журналирования для PF предоставляется man:pflog[4]. Для включения " "поддержки журналирования добавьте `pflog_enable=yes` в [.filename]#/etc/rc." "conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:219 #, no-wrap msgid "# sysrc pflog_enable=yes\n" msgstr "# sysrc pflog_enable=yes\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:222 msgid "" "The following lines can also be added to change the default location of the " "log file or to specify any additional flags to pass to man:pflog[4] when it " "is started:" msgstr "" "Следующие строки также могут быть добавлены для изменения расположения файла " "журнала по умолчанию или для указания дополнительных флагов, передаваемых в " "man:pflog[4] при его запуске:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:227 #, no-wrap msgid "" "pflog_logfile=\"/var/log/pflog\" # where pflogd should store the logfile\n" "pflog_flags=\"\" # additional flags for pflogd startup\n" msgstr "" "pflog_logfile=\"/var/log/pflog\" # where pflogd should store the logfile\n" "pflog_flags=\"\" # additional flags for pflogd startup\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:230 msgid "" "Finally, if there is a LAN behind the firewall and packets need to be " "forwarded for the computers on the LAN, or NAT is required, enable the " "following option:" msgstr "" "Наконец, если за межсетевым экраном есть локальная сеть (LAN) и пакеты " "необходимо перенаправлять для компьютеров в этой сети, или требуется NAT, " "включите следующую опцию:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:234 #, no-wrap msgid "gateway_enable=\"YES\" # Enable as LAN gateway\n" msgstr "gateway_enable=\"YES\" # Enable as LAN gateway\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:237 msgid "" "After saving the needed edits, PF can be started with logging support by " "typing:" msgstr "" "После сохранения необходимых изменений, PF можно запустить с поддержкой " "журналирования, набрав:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:242 #, no-wrap msgid "" "# service pf start\n" "# service pflog start\n" msgstr "" "# service pf start\n" "# service pflog start\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:247 msgid "" "By default, PF reads its configuration rules from [.filename]#/etc/pf.conf# " "and modifies, drops, or passes packets according to the rules or definitions " "specified in this file. The FreeBSD installation includes several sample " "files located in [.filename]#/usr/share/examples/pf/#. Refer to the http://" "www.openbsd.org/faq/pf/[PF FAQ] for complete coverage of PF rulesets." msgstr "" "По умолчанию PF читает свои правила конфигурации из [.filename]#/etc/pf." "conf# и изменяет, отбрасывает или пропускает пакеты в соответствии с " "правилами или определениями, указанными в этом файле. Установка FreeBSD " "включает несколько примеров файлов, расположенных в [.filename]#/usr/share/" "examples/pf/#. Полное описание наборов правил PF можно найти в http://www." "openbsd.org/faq/pf/[PF FAQ]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:251 msgid "" "To control PF, use `pfctl`. crossref:firewalls[pfctl,Useful `pfctl` " "Options] summarizes some useful options to this command. Refer to man:" "pfctl[8] for a description of all available options:" msgstr "" "Для управления PF используйте `pfctl`. crossref:firewalls[pfctl,Полезные " "опции `pfctl`] содержит сводку полезных опций этой команды. За подробным " "описанием всех доступных опций обратитесь к man:pfctl[8]:" #. type: Block title #: documentation/content/en/books/handbook/firewalls/_index.adoc:252 #, no-wrap msgid "Useful `pfctl` Options" msgstr "Полезные параметры `pfctl`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:256 #, no-wrap msgid "Command" msgstr "Команда" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:258 #, no-wrap msgid "Purpose" msgstr "Назначение" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:259 #, no-wrap msgid "`pfctl -e`" msgstr "`pfctl -e`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:261 #, no-wrap msgid "Enable PF." msgstr "Включить PF." #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:262 #, no-wrap msgid "`pfctl -d`" msgstr "`pfctl -d`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:264 #, no-wrap msgid "Disable PF." msgstr "Отключить PF." #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:265 #, no-wrap msgid "`pfctl -F all -f /etc/pf.conf`" msgstr "`pfctl -F all -f /etc/pf.conf`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:267 #, no-wrap msgid "Flush all NAT, filter, state, and table rules and reload [.filename]#/etc/pf.conf#." msgstr "Очистить все правила NAT, фильтрации, состояний и таблиц и перезагрузить [.filename]#/etc/pf.conf#." #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:267 #, no-wrap msgid "`pfctl -s [ rules \\" msgstr "`pfctl -s [ rules \\" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:267 #, no-wrap msgid "nat \\" msgstr "nat \\" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:268 #, no-wrap msgid "states ]`" msgstr "states ]`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:270 #, no-wrap msgid "Report on the filter rules, NAT rules, or state table." msgstr "Отчёт о правилах фильтрации, правилах NAT или таблице состояний." #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:271 #, no-wrap msgid "`pfctl -vnf /etc/pf.conf`" msgstr "`pfctl -vnf /etc/pf.conf`" #. type: Table #: documentation/content/en/books/handbook/firewalls/_index.adoc:272 #, no-wrap msgid "Check [.filename]#/etc/pf.conf# for errors, but do not load ruleset." msgstr "Проверить [.filename]#/etc/pf.conf# на ошибки, но не загружать набор правил." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:278 msgid "" "package:security/sudo[] is useful for running commands like `pfctl` that " "require elevated privileges. It can be installed from the Ports Collection." msgstr "" "Пакет package:security/sudo[] полезен для выполнения команд, таких как " "`pfctl`, которые требуют повышенных привилегий. Он может быть установлен из " "Коллекции портов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:282 msgid "" "To keep an eye on the traffic that passes through the PF firewall, consider " "installing the package:sysutils/pftop[] package or port. Once installed, " "pftop can be run to view a running snapshot of traffic in a format which is " "similar to man:top[1]." msgstr "" "Для наблюдения за трафиком, проходящим через межсетевой экран PF, " "рекомендуется установить пакет package:sysutils/pftop[] или порт. После " "установки можно запустить pftop для просмотра текущего снимка трафика в " "формате, аналогичном man:top[1]." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:284 #, no-wrap msgid "PF Rulesets" msgstr "Наборы правил PF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:288 msgid "" "This section demonstrates how to create a customized ruleset. It starts " "with the simplest of rulesets and builds upon its concepts using several " "examples to demonstrate real-world usage of PF's many features." msgstr "" "Этот раздел демонстрирует, как создать настраиваемый набор правил. Он " "начинается с простейшего набора правил и развивает его концепции, используя " "несколько примеров для демонстрации практического применения множества " "возможностей PF." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:291 msgid "" "The simplest possible ruleset is for a single machine that does not run any " "services and which needs access to one network, which may be the Internet. " "To create this minimal ruleset, edit [.filename]#/etc/pf.conf# so it looks " "like this:" msgstr "" "Самый простой возможный набор правил предназначен для одиночной машины, " "которая не запускает никаких сервисов и которой требуется доступ к одной " "сети, возможно, к Интернету. Чтобы создать этот минимальный набор правил, " "отредактируйте файл [.filename]#/etc/pf.conf#, чтобы он выглядел следующим " "образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:296 #, no-wrap msgid "" "block in all\n" "pass out all keep state\n" msgstr "" "block in all\n" "pass out all keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:302 msgid "" "The first rule denies all incoming traffic by default. The second rule " "allows connections created by this system to pass out, while retaining state " "information on those connections. This state information allows return " "traffic for those connections to pass back and should only be used on " "machines that can be trusted. The ruleset can be loaded with:" msgstr "" "Первое правило по умолчанию запрещает весь входящий трафик. Второе правило " "разрешает исходящие соединения, созданные этой системой, сохраняя информацию " "о состоянии этих соединений. Эта информация о состоянии позволяет " "возвратному трафику для этих соединений проходить обратно и должна " "использоваться только на машинах, которым можно доверять. Набор правил можно " "загрузить с помощью:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:306 #, no-wrap msgid "# pfctl -e ; pfctl -f /etc/pf.conf\n" msgstr "# pfctl -e ; pfctl -f /etc/pf.conf\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:311 msgid "" "In addition to keeping state, PF provides _lists_ and _macros_ which can be " "defined for use when creating rules. Macros can include lists and need to " "be defined before use. As an example, insert these lines at the very top of " "the ruleset:" msgstr "" "В дополнение к отслеживанию состояний, PF предоставляет _списки_ и " "_макросы_, которые можно определить для использования при создании правил. " "Макросы могут включать списки и должны быть определены до их использования. " "В качестве примера вставьте следующие строки в самое начало набора правил:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:316 #, no-wrap msgid "" "tcp_services = \"{ ssh, smtp, domain, www, pop3, auth, pop3s }\"\n" "udp_services = \"{ domain }\"\n" msgstr "" "tcp_services = \"{ ssh, smtp, domain, www, pop3, auth, pop3s }\"\n" "udp_services = \"{ domain }\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:323 msgid "" "PF understands port names as well as port numbers, as long as the names are " "listed in [.filename]#/etc/services#. This example creates two macros. The " "first is a list of seven TCP port names and the second is one UDP port " "name. Once defined, macros can be used in rules. In this example, all " "traffic is blocked except for the connections initiated by this system for " "the seven specified TCP services and the one specified UDP service:" msgstr "" "PF понимает как имена портов, так и их номера, при условии, что имена " "перечислены в [.filename]#/etc/services#. В этом примере создаются два " "макроса. Первый — это список из семи имён TCP-портов, а второй — одно имя " "UDP-порта. После определения макросы можно использовать в правилах. В данном " "примере весь трафик блокируется, за исключением соединений, инициированных " "этой системой для семи указанных TCP-сервисов и одного указанного UDP-" "сервиса:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:331 #, no-wrap msgid "" "tcp_services = \"{ ssh, smtp, domain, www, pop3, auth, pop3s }\"\n" "udp_services = \"{ domain }\"\n" "block all\n" "pass out proto tcp to any port $tcp_services keep state\n" "pass proto udp to any port $udp_services keep state\n" msgstr "" "tcp_services = \"{ ssh, smtp, domain, www, pop3, auth, pop3s }\"\n" "udp_services = \"{ domain }\"\n" "block all\n" "pass out proto tcp to any port $tcp_services keep state\n" "pass proto udp to any port $udp_services keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:335 msgid "" "Even though UDP is considered to be a stateless protocol, PF is able to " "track some state information. For example, when a UDP request is passed " "which asks a name server about a domain name, PF will watch for the response " "to pass it back." msgstr "" "Хотя UDP считается протоколом без сохранения состояния, PF способен " "отслеживать некоторую информацию о состоянии. Например, когда передаётся UDP-" "запрос к серверу имён с вопросом о доменном имени, PF будет ожидать ответ, " "чтобы пропустить его обратно." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:337 msgid "" "Whenever an edit is made to a ruleset, the new rules must be loaded so they " "can be used:" msgstr "" "Всякий раз при внесении изменений в набор правил, новые правила должны быть " "загружены для их использования:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:341 #: documentation/content/en/books/handbook/firewalls/_index.adoc:559 #, no-wrap msgid "# pfctl -f /etc/pf.conf\n" msgstr "# pfctl -f /etc/pf.conf\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:345 msgid "" "If there are no syntax errors, `pfctl` will not output any messages during " "the rule load. Rules can also be tested before attempting to load them:" msgstr "" "Если нет синтаксических ошибок, `pfctl` не выводит сообщений во время " "загрузки правил. Правила также можно проверить перед попыткой их загрузки:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:349 #, no-wrap msgid "# pfctl -nf /etc/pf.conf\n" msgstr "# pfctl -nf /etc/pf.conf\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:354 msgid "" "Including `-n` causes the rules to be interpreted only, but not loaded. " "This provides an opportunity to correct any errors. At all times, the last " "valid ruleset loaded will be enforced until either PF is disabled or a new " "ruleset is loaded." msgstr "" "Включение опции `-n` приводит к тому, что правила только интерпретируются, " "но не загружаются. Это даёт возможность исправить любые ошибки. В любое " "время будет применяться последний загруженный корректный набор правил, пока " "либо PF не будет отключён, либо не будет загружен новый набор правил." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:359 msgid "" "Adding `-v` to a `pfctl` ruleset verify or load will display the fully " "parsed rules exactly the way they will be loaded. This is extremely useful " "when debugging rules." msgstr "" "Добавление `-v` к проверке или загрузке набора правил `pfctl` отобразит " "полностью разобранные правила именно так, как они будут загружены. Это " "крайне полезно при отладке правил межсетевого экрана." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:362 #, no-wrap msgid "A Simple Gateway with NAT" msgstr "Простой шлюз с NAT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:367 msgid "" "This section demonstrates how to configure a FreeBSD system running PF to " "act as a gateway for at least one other machine. The gateway needs at least " "two network interfaces, each connected to a separate network. In this " "example, [.filename]#xl0# is connected to the Internet and [.filename]#xl1# " "is connected to the internal network." msgstr "" "В этом разделе показано, как настроить систему FreeBSD с PF для работы в " "качестве шлюза как минимум для одного другого компьютера. Шлюзу требуется " "как минимум два сетевых интерфейса, каждый из которых подключен к отдельной " "сети. В этом примере [.filename]#xl0# подключен к Интернету, а [." "filename]#xl1# подключен к внутренней сети." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:370 msgid "" "First, enable the gateway to let the machine forward the network traffic it " "receives on one interface to another interface. This sysctl setting will " "forward IPv4 packets:" msgstr "" "Включите шлюз, чтобы позволить машине перенаправлять сетевой трафик, " "полученный на одном интерфейсе, на другой интерфейс. Этот параметр sysctl " "перенаправляет IPv4-пакеты:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:374 #, no-wrap msgid "# sysctl net.inet.ip.forwarding=1\n" msgstr "# sysctl net.inet.ip.forwarding=1\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:377 msgid "To forward IPv6 traffic, use:" msgstr "Для переадресации IPv6-трафика используйте:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:381 #, no-wrap msgid "# sysctl net.inet6.ip6.forwarding=1\n" msgstr "# sysctl net.inet6.ip6.forwarding=1\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:384 msgid "" "To enable these settings at system boot, use man:sysrc[8] to add them to [." "filename]#/etc/rc.conf#:" msgstr "" "Чтобы включить эти настройки при загрузке системы, используйте man:sysrc[8] " "для их добавления в [.filename]#/etc/rc.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:389 #, no-wrap msgid "" "# sysrc gateway_enable=yes\n" "# sysrc ipv6_gateway_enable=yes\n" msgstr "" "# sysrc gateway_enable=yes\n" "# sysrc ipv6_gateway_enable=yes\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:392 msgid "Verify with `ifconfig` that both of the interfaces are up and running." msgstr "Проверьте с помощью `ifconfig`, что оба интерфейса активны и работают." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:395 msgid "" "Next, create the PF rules to allow the gateway to pass traffic. While the " "following rule allows stateful traffic from hosts of the internal network to " "pass to the gateway, the `to` keyword does not guarantee passage all the way " "from source to destination:" msgstr "" "Далее создайте правила PF, чтобы позволить шлюзу передавать трафик. Хотя " "следующее правило разрешает трафик с сохранением статуса от хостов " "внутренней сети проходить к шлюзу, ключевое слово `to` не гарантирует " "прохождение всего пути от источника до назначения:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:399 #, no-wrap msgid "pass in on xl1 from xl1:network to xl0:network port $ports keep state\n" msgstr "pass in on xl1 from xl1:network to xl0:network port $ports keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:403 msgid "" "That rule only lets the traffic pass in to the gateway on the internal " "interface. To let the packets go further, a matching rule is needed:" msgstr "" "Это правило разрешает прохождение трафика только внутрь шлюза на внутреннем " "интерфейсе. Чтобы пакеты могли идти дальше, требуется соответствующее " "правило:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:407 #, no-wrap msgid "pass out on xl0 from xl1:network to xl0:network port $ports keep state\n" msgstr "pass out on xl0 from xl1:network to xl0:network port $ports keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:413 msgid "" "While these two rules will work, rules this specific are rarely needed. For " "a busy network admin, a readable ruleset is a safer ruleset. The remainder " "of this section demonstrates how to keep the rules as simple as possible for " "readability. For example, those two rules could be replaced with one rule:" msgstr "" "Хотя эти два правила будут работать, столь специфичные правила редко " "требуются. Для занятого сетевого администратора читаемый набор правил — это " "более безопасный набор правил. В оставшейся части этого раздела показано, " "как сохранять правила максимально простыми для удобочитаемости. Например, " "эти два правила можно заменить одним:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:417 #, no-wrap msgid "pass from xl1:network to any port $ports keep state\n" msgstr "pass from xl1:network to any port $ports keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:422 msgid "" "The `interface:network` notation can be replaced with a macro to make the " "ruleset even more readable. For example, a `$localnet` macro could be " "defined as the network directly attached to the internal interface (`$xl1:" "network`). Alternatively, the definition of `$localnet` could be changed to " "an _IP address/netmask_ notation to denote a network, such as " "`192.168.100.1/24` for a subnet of private addresses." msgstr "" "Обозначение `interface:network` может быть заменено макросом для повышения " "читаемости набора правил. Например, можно определить макрос `$localnet` как " "сеть, непосредственно подключённую к внутреннему интерфейсу (`$xl1:" "network`). Или определение `$localnet` может быть изменено на _IP-адрес/" "маску сети_ для обозначения сети, например `192.168.100.1/24` для подсети " "частных адресов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:425 msgid "" "If required, `$localnet` could even be defined as a list of networks. " "Whatever the specific needs, a sensible `$localnet` definition could be used " "in a typical pass rule as follows:" msgstr "" "Если требуется, `$localnet` можно определить даже как список сетей. " "Независимо от конкретных потребностей, разумное определение `$localnet` " "может быть использовано в типичном правиле пропуска следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:429 #, no-wrap msgid "pass from $localnet to any port $ports keep state\n" msgstr "pass from $localnet to any port $ports keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:433 msgid "" "The following sample ruleset allows all traffic initiated by machines on the " "internal network. It first defines two macros to represent the external and " "internal 3COM interfaces of the gateway." msgstr "" "Следующий пример набора правил разрешает весь трафик, инициированный " "машинами во внутренней сети. Сначала определяются два макроса для " "представления внешнего и внутреннего интерфейсов 3COM настраиваемого шлюза." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:438 msgid "" "For dialup users, the external interface will use [.filename]#tun0#. For an " "ADSL connection, specifically those using PPP over Ethernet (PPPoE), the " "correct external interface is [.filename]#tun0#, not the physical Ethernet " "interface." msgstr "" "Для пользователей коммутируемого доступа внешний интерфейс будет " "использовать [.filename]#tun0#. Для ADSL-подключения, особенно тех, которые " "используют PPP через Ethernet (PPPoE), правильный внешний интерфейс — это [." "filename]#tun0#, а не физический Ethernet-интерфейс." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:449 #, no-wrap msgid "" "ext_if = \"xl0\"\t# macro for external interface - use tun0 for PPPoE\n" "int_if = \"xl1\"\t# macro for internal interface\n" "localnet = $int_if:network\n" "# ext_if IP address could be dynamic, hence ($ext_if)\n" "nat on $ext_if from $localnet to any -> ($ext_if)\n" "block all\n" "pass from { lo0, $localnet } to any keep state\n" msgstr "" "ext_if = \"xl0\"\t# macro for external interface - use tun0 for PPPoE\n" "int_if = \"xl1\"\t# macro for internal interface\n" "localnet = $int_if:network\n" "# ext_if IP address could be dynamic, hence ($ext_if)\n" "nat on $ext_if from $localnet to any -> ($ext_if)\n" "block all\n" "pass from { lo0, $localnet } to any keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:454 msgid "" "This ruleset introduces the `nat` rule which is used to handle the network " "address translation from the non-routable addresses inside the internal " "network to the IP address assigned to the external interface. The " "parentheses surrounding the last part of the nat rule `($ext_if)` is " "included when the IP address of the external interface is dynamically " "assigned. It ensures that network traffic runs without serious " "interruptions even if the external IP address changes." msgstr "" "Этот набор правил вводит правило `nat`, которое используется для обработки " "преобразования сетевых адресов из не маршрутизируемых адресов внутри " "внутренней сети в IP-адрес, назначенный внешнему интерфейсу. Скобки вокруг " "последней части правила nat `($ext_if)` включаются, когда IP-адрес внешнего " "интерфейса назначается динамически. Это гарантирует, что сетевой трафик " "будет работать без серьёзных перебоев, даже если внешний IP-адрес изменится." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:457 msgid "" "Note that this ruleset probably allows more traffic to pass out of the " "network than is needed. One reasonable setup could create this macro:" msgstr "" "Обратите внимание, что этот набор правил, вероятно, разрешает больше трафика " "для выхода из сети, чем необходимо. Один из разумных вариантов настройки " "может создать этот макрос:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:462 #, no-wrap msgid "" "client_out = \"{ ftp-data, ftp, ssh, domain, pop3, auth, nntp, http, \\\n" " https, cvspserver, 2628, 5999, 8000, 8080 }\"\n" msgstr "" "client_out = \"{ ftp-data, ftp, ssh, domain, pop3, auth, nntp, http, \\\n" " https, cvspserver, 2628, 5999, 8000, 8080 }\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:465 msgid "to use in the main pass rule:" msgstr "для использования в основном правиле пропуска:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:470 #, no-wrap msgid "" "pass inet proto tcp from $localnet to any port $client_out \\\n" " flags S/SA keep state\n" msgstr "" "pass inet proto tcp from $localnet to any port $client_out \\\n" " flags S/SA keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:474 msgid "" "A few other pass rules may be needed. This one enables SSH on the external " "interface:" msgstr "" "Еще могут понадобиться несколько других правил пропуска . Это правило " "включает SSH на внешнем интерфейсе:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:478 #, no-wrap msgid "pass in inet proto tcp to $ext_if port ssh\n" msgstr "pass in inet proto tcp to $ext_if port ssh\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:481 msgid "This macro definition and rule allows DNS and NTP for internal clients:" msgstr "" "Это определение макроса и правило разрешают DNS и NTP для внутренних " "клиентов:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:486 #, no-wrap msgid "" "udp_services = \"{ domain, ntp }\"\n" "pass quick inet proto { tcp, udp } to any port $udp_services keep state\n" msgstr "" "udp_services = \"{ domain, ntp }\"\n" "pass quick inet proto { tcp, udp } to any port $udp_services keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:494 msgid "" "Note the `quick` keyword in this rule. Since the ruleset consists of " "several rules, it is important to understand the relationships between the " "rules in a ruleset. Rules are evaluated from top to bottom, in the sequence " "they are written. For each packet or connection evaluated by PF, _the last " "matching rule_ in the ruleset is the one which is applied. However, when a " "packet matches a rule which contains the `quick` keyword, the rule " "processing stops and the packet is treated according to that rule. This is " "very useful when an exception to the general rules is needed." msgstr "" "Обратите внимание на ключевое слово `quick` в этом правиле. Поскольку набор " "правил состоит из нескольких правил, важно понимать взаимосвязи между ними. " "Правила обрабатываются сверху вниз, в порядке их написания. Для каждого " "пакета или соединения, оцениваемого PF, _последнее совпадающее правило_ в " "наборе является тем, которое применяется. Однако, когда пакет совпадает с " "правилом, содержащим ключевое слово `quick`, обработка правил прекращается, " "и пакет обрабатывается в соответствии с этим правилом. Это очень полезно, " "когда требуется исключение из общих правил." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:496 #, no-wrap msgid "Creating an FTP Proxy" msgstr "Создание FTP-прокси" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:501 msgid "" "Configuring working FTP rules can be problematic due to the nature of the " "FTP protocol. FTP pre-dates firewalls by several decades and is insecure in " "its design. The most common points against using FTP include:" msgstr "" "Настройка рабочих правил FTP может быть проблематичной из-за особенностей " "протокола FTP. Протокол FTP появился на несколько десятилетий раньше " "межсетевых экранов и небезопасен по своей конструкции. Наиболее " "распространённые аргументы против использования FTP включают:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:503 msgid "Passwords are transferred in the clear." msgstr "Пароли передаются в открытом виде." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:504 msgid "" "The protocol demands the use of at least two TCP connections (control and " "data) on separate ports." msgstr "" "Протокол требует использования как минимум двух TCP-соединений (управляющего " "канала и канала данных) на отдельных портах." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:505 msgid "" "When a session is established, data is communicated using randomly selected " "ports." msgstr "" "Когда сеанс установлен, данные передаются с использованием случайно " "выбранных портов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:508 msgid "" "All of these points present security challenges, even before considering any " "potential security weaknesses in client or server software. More secure " "alternatives for file transfer exist, such as man:sftp[1] or man:scp[1], " "which both feature authentication and data transfer over encrypted " "connections." msgstr "" "Все эти моменты представляют собой проблемы безопасности, даже без учёта " "потенциальных уязвимостей в клиентском или серверном программном " "обеспечении. Более безопасные альтернативы для передачи файлов существуют, " "например, man:sftp[1] или man:scp[1], которые обеспечивают аутентификацию и " "передачу данных через зашифрованные соединения." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:511 msgid "" "For those situations when FTP is required, PF provides redirection of FTP " "traffic to a small proxy program called man:ftp-proxy[8], which is included " "in the base system of FreeBSD. The role of the proxy is to dynamically " "insert and delete rules in the ruleset, using a set of anchors, to correctly " "handle FTP traffic." msgstr "" "Для случаев, когда требуется FTP, PF предоставляет возможность " "перенаправления FTP-трафика на небольшую прокси-программу под названием man:" "ftp-proxy[8], которая включена в базовую систему FreeBSD. Роль прокси " "заключается в динамическом добавлении и удалении правил в наборе правил, " "используя набор якорей, для корректной обработки FTP-трафика." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:513 msgid "To enable the FTP proxy, add this line to [.filename]#/etc/rc.conf#:" msgstr "" "Чтобы включить FTP-прокси, добавьте следующую строку в [.filename]#/etc/rc." "conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:517 #, no-wrap msgid "ftpproxy_enable=\"YES\"\n" msgstr "ftpproxy_enable=\"YES\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:520 msgid "Then start the proxy by running:" msgstr "Затем запустите прокси, выполнив:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:524 #, no-wrap msgid "# service ftp-proxy start\n" msgstr "# service ftp-proxy start\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:528 msgid "" "For a basic configuration, three elements need to be added to [.filename]#/" "etc/pf.conf#. First, the anchors which the proxy will use to insert the " "rules it generates for the FTP sessions:" msgstr "" "Для базовой конфигурации необходимо добавить три элемента в [.filename]#/etc/" "pf.conf#. Во-первых, якоря, которые прокси будет использовать для вставки " "правил, генерируемых для FTP-сессий:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:533 #, no-wrap msgid "" "nat-anchor \"ftp-proxy/*\"\n" "rdr-anchor \"ftp-proxy/*\"\n" msgstr "" "nat-anchor \"ftp-proxy/*\"\n" "rdr-anchor \"ftp-proxy/*\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:536 msgid "Second, a pass rule is needed to allow FTP traffic in to the proxy." msgstr "" "Во-вторых, необходимо правило pass, чтобы разрешить FTP-трафик к прокси." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:539 msgid "" "Third, redirection and NAT rules need to be defined before the filtering " "rules. Insert this `rdr` rule immediately after the `nat` rule:" msgstr "" "Третье, правила перенаправления и NAT должны быть определены до правил " "фильтрации. Вставьте это правило `rdr` сразу после правила `nat`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:543 #, no-wrap msgid "rdr pass on $int_if proto tcp from any to any port ftp -> 127.0.0.1 port 8021\n" msgstr "rdr pass on $int_if proto tcp from any to any port ftp -> 127.0.0.1 port 8021\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:546 msgid "Finally, allow the redirected traffic to pass:" msgstr "Наконец, разрешите перенаправленному трафику проходить:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:550 #, no-wrap msgid "pass out proto tcp from $proxy to any port ftp\n" msgstr "pass out proto tcp from $proxy to any port ftp\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:553 msgid "where `$proxy` expands to the address the proxy daemon is bound to." msgstr "где `$proxy` раскрывается в адрес, к которому привязан демон прокси." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:555 msgid "" "Save [.filename]#/etc/pf.conf#, load the new rules, and verify from a client " "that FTP connections are working:" msgstr "" "Сохраните [.filename]#/etc/pf.conf#, загрузите новые правила и проверьте с " "клиента, что FTP-подключения работают:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:565 msgid "" "This example covers a basic setup where the clients in the local network " "need to contact FTP servers elsewhere. This basic configuration should work " "well with most combinations of FTP clients and servers. As shown in man:ftp-" "proxy[8], the proxy's behavior can be changed in various ways by adding " "options to the `ftpproxy_flags=` line. Some clients or servers may have " "specific quirks that must be compensated for in the configuration, or there " "may be a need to integrate the proxy in specific ways such as assigning FTP " "traffic to a specific queue." msgstr "" "Этот пример описывает базовую настройку, когда клиенты в локальной сети " "должны обращаться к FTP-серверам в других местах. Данная базовая " "конфигурация должна хорошо работать с большинством комбинаций FTP-клиентов и " "серверов. Как показано в man:ftp-proxy[8], поведение прокси можно изменить " "различными способами, добавляя параметры в строку `ftpproxy_flags=`. " "Некоторые клиенты или серверы могут иметь специфические особенности, которые " "необходимо учитывать в конфигурации, или может возникнуть необходимость " "интегрировать прокси определённым образом, например, назначить FTP-трафик в " "определённую очередь." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:567 msgid "" "For ways to run an FTP server protected by PF and man:ftp-proxy[8], " "configure a separate `ftp-proxy` in reverse mode, using `-R`, on a separate " "port with its own redirecting pass rule." msgstr "" "Для способов запуска FTP-сервера, защищённого PF и man:ftp-proxy[8], " "настройте отдельный `ftp-proxy` в обратном режиме с использованием `-R` на " "отдельном порту с собственным правилом перенаправления pass." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:569 #, no-wrap msgid "Managing ICMP" msgstr "Управление ICMP" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:572 msgid "" "Many of the tools used for debugging or troubleshooting a TCP/IP network " "rely on the Internet Control Message Protocol (ICMP), which was designed " "specifically with debugging in mind." msgstr "" "Многие инструменты, используемые для отладки или устранения неполадок в сети " "TCP/IP, основаны на протоколе ICMP (Internet Control Message Protocol), " "который был специально разработан для целей отладки." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:575 msgid "" "The ICMP protocol sends and receives _control messages_ between hosts and " "gateways, mainly to provide feedback to a sender about any unusual or " "difficult conditions enroute to the target host. Routers use ICMP to " "negotiate packet sizes and other transmission parameters in a process often " "referred to as _path MTU discovery_." msgstr "" "Протокол ICMP отправляет и получает _управляющие сообщения_ между хостами и " "шлюзами, в основном для предоставления отправителю обратной связи о любых " "необычных или сложных условиях на пути к целевому хосту. Маршрутизаторы " "используют ICMP для согласования размеров пакетов и других параметров " "передачи в процессе, часто называемом _обнаружением MTU пути_." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:579 msgid "" "From a firewall perspective, some ICMP control messages are vulnerable to " "known attack vectors. Also, letting all diagnostic traffic pass " "unconditionally makes debugging easier, but it also makes it easier for " "others to extract information about the network. For these reasons, the " "following rule may not be optimal:" msgstr "" "С точки зрения межсетевого экрана, некоторые управляющие ICMP-сообщения " "уязвимы к известным векторам атак. Кроме того, безусловный пропуск всего " "диагностического трафика упрощает отладку, но также облегчает для других " "получение информации о сети. По этим причинам следующее правило может быть " "неоптимальным:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:583 #, no-wrap msgid "pass inet proto icmp from any to any\n" msgstr "pass inet proto icmp from any to any\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:586 msgid "" "One solution is to let all ICMP traffic from the local network through while " "stopping all probes from outside the network:" msgstr "" "Одно из решений — пропускать весь ICMP-трафик из локальной сети, блокируя " "все запросы извне:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:591 #, no-wrap msgid "" "pass inet proto icmp from $localnet to any keep state\n" "pass inet proto icmp from any to $ext_if keep state\n" msgstr "" "pass inet proto icmp from $localnet to any keep state\n" "pass inet proto icmp from any to $ext_if keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:596 msgid "" "Additional options are available which demonstrate some of PF's " "flexibility. For example, rather than allowing all ICMP messages, one can " "specify the messages used by man:ping[8] and man:traceroute[8]. Start by " "defining a macro for that type of message:" msgstr "" "Дополнительные параметры демонстрируют гибкость PF. Например, вместо " "разрешения всех ICMP-сообщений можно указать сообщения, используемые man:" "ping[8] и man:traceroute[8]. Начните с определения макроса для этого типа " "сообщения:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:600 #, no-wrap msgid "icmp_types = \"echoreq\"\n" msgstr "icmp_types = \"echoreq\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:603 msgid "and a rule which uses the macro:" msgstr "и правила, которое использует макрос:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:607 #: documentation/content/en/books/handbook/firewalls/_index.adoc:647 #, no-wrap msgid "pass inet proto icmp all icmp-type $icmp_types keep state\n" msgstr "pass inet proto icmp all icmp-type $icmp_types keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:612 msgid "" "If other types of ICMP packets are needed, expand `icmp_types` to a list of " "those packet types. Type `more /usr/src/sbin/pfctl/pfctl_parser.c` to see " "the list of ICMP message types supported by PF. Refer to http://www.iana." "org/assignments/icmp-parameters/icmp-parameters.xhtml[http://www.iana.org/" "assignments/icmp-parameters/icmp-parameters.xhtml] for an explanation of " "each message type." msgstr "" "Если требуются другие типы ICMP-пакетов, расширьте `icmp_types` до списка " "этих типов пакетов. Введите `more /usr/src/sbin/pfctl/pfctl_parser.c`, чтобы " "увидеть список типов ICMP-сообщений, поддерживаемых PF. Дополнительные " "сведения о каждом типе сообщения можно найти по ссылке http://www.iana.org/" "assignments/icmp-parameters/icmp-parameters.xhtml[http://www.iana.org/" "assignments/icmp-parameters/icmp-parameters.xhtml]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:614 msgid "" "Since Unix `traceroute` uses UDP by default, another rule is needed to allow " "Unix `traceroute`:" msgstr "" "Поскольку Unix `traceroute` по умолчанию использует UDP, требуется " "дополнительное правило для разрешения Unix `traceroute`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:619 #, no-wrap msgid "" "# allow out the default range for traceroute(8):\n" "pass out on $ext_if inet proto udp from any to any port 33433 >< 33626 keep state\n" msgstr "" "# allow out the default range for traceroute(8):\n" "pass out on $ext_if inet proto udp from any to any port 33433 >< 33626 keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:624 msgid "" "Since `TRACERT.EXE` on Microsoft Windows systems uses ICMP echo request " "messages, only the first rule is needed to allow network traces from those " "systems. Unix `traceroute` can be instructed to use other protocols as " "well, and will use ICMP echo request messages if `-I` is used. Check the " "man:traceroute[8] man page for details." msgstr "" "Поскольку `TRACERT.EXE` в системах Microsoft Windows использует сообщения " "запроса эхо-ответа ICMP, достаточно только первого правила, чтобы разрешить " "трассировку сети с этих систем. В Unix `traceroute` можно настроить на " "использование других протоколов, и он будет использовать сообщения запроса " "эхо-ответа ICMP, если указан параметр `-I`. Подробности смотрите на man:" "traceroute[8]." #. type: Title ===== #: documentation/content/en/books/handbook/firewalls/_index.adoc:626 #, no-wrap msgid "Path MTU Discovery" msgstr "Обнаружение MTU пути" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:631 msgid "" "Internet protocols are designed to be device independent, and one " "consequence of device independence is that the optimal packet size for a " "given connection cannot always be predicted reliably. The main constraint " "on packet size is the _Maximum Transmission Unit_ (MTU) which sets the upper " "limit on the packet size for an interface. Type `ifconfig` to view the MTUs " "for a system's network interfaces." msgstr "" "Протоколы Интернета разработаны так, чтобы быть независимыми от устройств, и " "одним из следствий этой независимости является то, что оптимальный размер " "пакета для данного соединения не всегда может быть надёжно предсказан. " "Основное ограничение на размер пакета — это _Maximum Transmission Unit_ " "(MTU), который устанавливает верхний предел размера пакета для интерфейса. " "Введите `ifconfig`, чтобы просмотреть MTU для сетевых интерфейсов системы." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:636 msgid "" "TCP/IP uses a process known as path MTU discovery to determine the right " "packet size for a connection. This process sends packets of varying sizes " "with the \"Do not fragment\" flag set, expecting an ICMP return packet of " "\"type 3, code 4\" when the upper limit has been reached. Type 3 means " "\"destination unreachable\", and code 4 is short for \"fragmentation needed, " "but the do-not-fragment flag is set\". To allow path MTU discovery in order " "to support connections to other MTUs, add the `destination unreachable` type " "to the `icmp_types` macro:" msgstr "" "TCP/IP использует процесс, известный как обнаружение MTU пути, для " "определения правильного размера пакета для соединения. Этот процесс " "отправляет пакеты различного размера с установленным флагом \"Не " "фрагментировать\", ожидая возврата ICMP-пакета с \"типом 3, кодом 4\", когда " "достигнут верхний предел. Тип 3 означает \"адресат недостижим\", а код 4 " "является сокращением для \"требуется фрагментация, но установлен флаг 'не " "фрагментировать'\". Чтобы разрешить обнаружение MTU пути для поддержки " "соединений с другими MTU, добавьте тип `destination unreachable` в макрос " "`icmp_types`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:640 #, no-wrap msgid "icmp_types = \"{ echoreq, unreach }\"\n" msgstr "icmp_types = \"{ echoreq, unreach }\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:643 msgid "" "Since the pass rule already uses that macro, it does not need to be modified " "to support the new ICMP type:" msgstr "" "Поскольку правило `pass` уже использует этот макрос, его не нужно изменять " "для поддержки нового типа ICMP:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:651 msgid "" "PF allows filtering on all variations of ICMP types and codes. The list of " "possible types and codes are documented in man:icmp[4] and man:icmp6[4]." msgstr "" "PF позволяет фильтрацию по всем вариантам типов и кодов ICMP. Список " "возможных типов и кодов документирован в man:icmp[4] и man:icmp6[4]." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:653 #, no-wrap msgid "Using Tables" msgstr "Использование таблиц" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:658 msgid "" "Some types of data are relevant to filtering and redirection at a given " "time, but their definition is too long to be included in the ruleset file. " "PF supports the use of tables, which are defined lists that can be " "manipulated without needing to reload the entire ruleset, and which can " "provide fast lookups. Table names are always enclosed within `< >`, like " "this:" msgstr "" "Некоторые типы данных важны для фильтрации и перенаправления в определённый " "момент времени, но их определение слишком длинное, чтобы включать его в файл " "набора правил. PF поддерживает использование таблиц — это определённые " "списки, которыми можно управлять без необходимости перезагружать весь набор " "правил, и которые обеспечивают быстрый поиск. Имена таблиц всегда " "заключаются в `< >`, например:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:662 #, no-wrap msgid "table { 192.168.2.0/24, !192.168.2.5 }\n" msgstr "table { 192.168.2.0/24, !192.168.2.5 }\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:666 msgid "" "In this example, the `192.168.2.0/24` network is part of the table, except " "for the address `192.168.2.5`, which is excluded using the `!` operator. It " "is also possible to load tables from files where each item is on a separate " "line, as seen in this example [.filename]#/etc/clients#:" msgstr "" "В этом примере сеть `192.168.2.0/24` является частью таблицы, за исключением " "адреса `192.168.2.5`, который исключен с помощью оператора `!`. Также можно " "загружать таблицы из файлов, где каждый элемент находится на отдельной " "строке, как показано в этом примере [.filename]#/etc/clients#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:671 #, no-wrap msgid "" "192.168.2.0/24\n" "!192.168.2.5\n" msgstr "" "192.168.2.0/24\n" "!192.168.2.5\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:674 msgid "To refer to the file, define the table like this:" msgstr "Для обращения к файлу определите таблицу следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:678 #, no-wrap msgid "table persist file \"/etc/clients\"\n" msgstr "table persist file \"/etc/clients\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:681 msgid "Once the table is defined, it can be referenced by a rule:" msgstr "После определения таблицы на неё можно ссылаться в правиле:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:685 #, no-wrap msgid "pass inet proto tcp from to any port $client_out flags S/SA keep state\n" msgstr "pass inet proto tcp from to any port $client_out flags S/SA keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:689 msgid "" "A table's contents can be manipulated live, using `pfctl`. This example " "adds another network to the table:" msgstr "" "Содержимое таблицы можно изменять в реальном времени с помощью `pfctl`. В " "этом примере добавляется ещё одна сеть в таблицу:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:693 #, no-wrap msgid "# pfctl -t clients -T add 192.168.1.0/16\n" msgstr "# pfctl -t clients -T add 192.168.1.0/16\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:699 msgid "" "Note that any changes made this way will take affect now, making them ideal " "for testing, but will not survive a power failure or reboot. To make the " "changes permanent, modify the definition of the table in the ruleset or edit " "the file that the table refers to. One can maintain the on-disk copy of the " "table using a man:cron[8] job which dumps the table's contents to disk at " "regular intervals, using a command such as `pfctl -t clients -T show >/etc/" "clients`. Alternatively, [.filename]#/etc/clients# can be updated with the " "in-memory table contents:" msgstr "" "Обратите внимание, что любые изменения, внесенные таким образом, вступят в " "силу немедленно, что делает их идеальными для тестирования, но они не " "сохранятся после отключения питания или перезагрузки. Чтобы сделать " "изменения постоянными, необходимо изменить определение таблицы в наборе " "правил или отредактировать файл, на который ссылается таблица. Можно " "поддерживать копию таблицы на диске с помощью задания man:cron[8], которое " "периодически сохраняет содержимое таблицы на диск, используя команду вида " "`pfctl -t clients -T show >/etc/clients`. Или [.filename]#/etc/clients# " "можно обновить содержимым таблицы из памяти:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:703 #, no-wrap msgid "# pfctl -t clients -T replace -f /etc/clients\n" msgstr "# pfctl -t clients -T replace -f /etc/clients\n" #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:706 #, no-wrap msgid "Using Overload Tables to Protect SSH" msgstr "Использование таблиц превышения нагрузки для защиты SSH" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:709 msgid "" "Those who run SSH on an external interface have probably seen something like " "this in the authentication logs:" msgstr "" "Те, кто запускает SSH на внешнем интерфейсе, вероятно, видели что-то " "подобное в журналах аутентификации:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:718 #, no-wrap msgid "" "Sep 26 03:12:34 skapet sshd[25771]: Failed password for root from 200.72.41.31 port 40992 ssh2\n" "Sep 26 03:12:34 skapet sshd[5279]: Failed password for root from 200.72.41.31 port 40992 ssh2\n" "Sep 26 03:12:35 skapet sshd[5279]: Received disconnect from 200.72.41.31: 11: Bye Bye\n" "Sep 26 03:12:44 skapet sshd[29635]: Invalid user admin from 200.72.41.31\n" "Sep 26 03:12:44 skapet sshd[24703]: input_userauth_request: invalid user admin\n" "Sep 26 03:12:44 skapet sshd[24703]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2\n" msgstr "" "Sep 26 03:12:34 skapet sshd[25771]: Failed password for root from 200.72.41.31 port 40992 ssh2\n" "Sep 26 03:12:34 skapet sshd[5279]: Failed password for root from 200.72.41.31 port 40992 ssh2\n" "Sep 26 03:12:35 skapet sshd[5279]: Received disconnect from 200.72.41.31: 11: Bye Bye\n" "Sep 26 03:12:44 skapet sshd[29635]: Invalid user admin from 200.72.41.31\n" "Sep 26 03:12:44 skapet sshd[24703]: input_userauth_request: invalid user admin\n" "Sep 26 03:12:44 skapet sshd[24703]: Failed password for invalid user admin from 200.72.41.31 port 41484 ssh2\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:721 msgid "" "This is indicative of a brute force attack where somebody or some program is " "trying to discover the user name and password which will let them into the " "system." msgstr "" "Это указывает на атаку методом грубой силы, когда кто-то или какая-то " "программа пытается подобрать имя пользователя и пароль, чтобы получить " "доступ к системе." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:726 msgid "" "If external SSH access is needed for legitimate users, changing the default " "port used by SSH can offer some protection. However, PF provides a more " "elegant solution. Pass rules can contain limits on what connecting hosts " "can do and violators can be banished to a table of addresses which are " "denied some or all access. It is even possible to drop all existing " "connections from machines which overreach the limits." msgstr "" "Если необходим внешний доступ по SSH для законных пользователей, изменение " "порта по умолчанию, используемого SSH, может обеспечить некоторую защиту. " "Однако PF предоставляет более элегантное решение. Правила `pass` могут " "содержать ограничения на действия подключающихся хостов, а нарушители могут " "быть заблокированы в таблице адресов, которым запрещён частичный или полный " "доступ. Также возможно разорвать все существующие соединения с машинами, " "которые превышают установленные ограничения." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:728 msgid "" "To configure this, create this table in the tables section of the ruleset:" msgstr "" "Для настройки создайте следующую таблицу в разделе tables набора правил:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:732 #, no-wrap msgid "table persist\n" msgstr "table persist\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:735 msgid "" "Then, somewhere early in the ruleset, add rules to block brute access while " "allowing legitimate access:" msgstr "" "Затем, где-то в начале набора правил добавьте правила для блокировки " "перебора, разрешая при этом законный доступ:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:743 #, no-wrap msgid "" "block quick from \n" "pass inet proto tcp from any to $localnet port $tcp_services \\\n" " flags S/SA keep state \\\n" " (max-src-conn 100, max-src-conn-rate 15/5, \\\n" " overload flush global)\n" msgstr "" "block quick from \n" "pass inet proto tcp from any to $localnet port $tcp_services \\\n" " flags S/SA keep state \\\n" " (max-src-conn 100, max-src-conn-rate 15/5, \\\n" " overload flush global)\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:747 msgid "" "The part in parentheses defines the limits and the numbers should be changed " "to meet local requirements. It can be read as follows:" msgstr "" "Часть в скобках определяет ограничения, и числа должны быть изменены в " "соответствии с местными требованиями. Это можно прочитать следующим образом:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:749 msgid "" "`max-src-conn` is the number of simultaneous connections allowed from one " "host." msgstr "" "`max-src-conn` — это количество одновременных подключений, разрешённых с " "одного хоста." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:751 msgid "" "`max-src-conn-rate` is the rate of new connections allowed from any single " "host (_15_) per number of seconds (_5_)." msgstr "" "`max-src-conn-rate` — это частота новых соединений, разрешённых с любого " "отдельного хоста (_15_) за указанное количество секунд (_5_)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:754 msgid "" "`overload ` means that any host which exceeds these limits gets " "its address added to the `bruteforce` table. The ruleset blocks all traffic " "from addresses in the `bruteforce` table." msgstr "" "`overload ` означает, что любой хост, превышающий эти " "ограничения, добавляет свой адрес в таблицу `bruteforce`. Набор правил " "блокирует весь трафик с адресов, находящихся в таблице `bruteforce`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:756 msgid "" "Finally, `flush global` says that when a host reaches the limit, that all " "(`global`) of that host's connections will be terminated (`flush`)." msgstr "" "Наконец, `flush global` означает, что когда хост достигает лимита, все " "(`global`) соединения этого хоста будут разорваны (`flush`)." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:760 msgid "" "These rules will _not_ block slow bruteforcers, as described in http://home." "nuug.no/\\~peter/hailmary2013/[http://home.nuug.no/~peter/hailmary2013/]." msgstr "" "Эти правила _не_ заблокируют медленные брутфорсеры, как описано в http://" "home.nuug.no/\\~peter/hailmary2013/[http://home.nuug.no/~peter/" "hailmary2013/]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:764 msgid "" "This example ruleset is intended mainly as an illustration. For example, if " "a generous number of connections in general are wanted, but the desire is to " "be more restrictive when it comes to ssh, supplement the rule above with " "something like the one below, early on in the rule set:" msgstr "" "Этот пример набора правил предназначен в основном для иллюстрации. Например, " "если требуется разрешить большое количество соединений в целом, но " "необходимо быть более строгим в отношении ssh, дополните приведённое выше " "правило чем-то вроде следующего, в начале набора правил:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:771 #, no-wrap msgid "" "pass quick proto { tcp, udp } from any to any port ssh \\\n" " flags S/SA keep state \\\n" " (max-src-conn 15, max-src-conn-rate 5/3, \\\n" " overload flush global)\n" msgstr "" "pass quick proto { tcp, udp } from any to any port ssh \\\n" " flags S/SA keep state \\\n" " (max-src-conn 15, max-src-conn-rate 5/3, \\\n" " overload flush global)\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:776 #, no-wrap msgid "*It May Not be Necessary to Block All Overloaders:* +\n" msgstr "*Не всегда необходимо блокировать всех превышающих нагрузки:* +\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:778 msgid "" "It is worth noting that the overload mechanism is a general technique which " "does not apply exclusively to SSH, and it is not always optimal to entirely " "block all traffic from offenders." msgstr "" "Стоит отметить, что механизм превышения нагрузки — это общий метод, который " "применяется не только к SSH, и не всегда оптимально полностью блокировать " "весь трафик от нарушителей." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:780 msgid "" "For example, an overload rule could be used to protect a mail service or a " "web service, and the overload table could be used in a rule to assign " "offenders to a queue with a minimal bandwidth allocation or to redirect to a " "specific web page." msgstr "" "Например, правило превышения нагрузки может использоваться для защиты " "почтовой службы или веб-сервиса, а таблица превышения нагрузки может " "применяться в правиле для назначения нарушителей в очередь с минимальным " "выделением пропускной способности или для перенаправления на определённую " "веб-страницу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:784 msgid "" "Over time, tables will be filled by overload rules and their size will grow " "incrementally, taking up more memory. Sometimes an IP address that is " "blocked is a dynamically assigned one, which has since been assigned to a " "host who has a legitimate reason to communicate with hosts in the local " "network." msgstr "" "Со временем таблицы будут заполняться правилами превышения нагрузки, и их " "размер будет постепенно увеличиваться, занимая больше памяти. Иногда " "заблокированный IP-адрес оказывается динамически назначенным, который с тех " "пор был выделен хосту, имеющему законные основания для взаимодействия с " "хостами в локальной сети." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:787 msgid "" "For situations like these, pfctl provides the ability to expire table " "entries. For example, this command will remove `` table entries " "which have not been referenced for `86400` seconds:" msgstr "" "Для подобных ситуаций `pfctl` предоставляет возможность удалять записи из " "таблиц. Например, следующая команда удалит записи из таблицы ``, " "к которым не было обращений в течение `86400` секунд:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:791 #, no-wrap msgid "# pfctl -t bruteforce -T expire 86400\n" msgstr "# pfctl -t bruteforce -T expire 86400\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:794 msgid "" "Similar functionality is provided by package:security/expiretable[], which " "removes table entries which have not been accessed for a specified period of " "time." msgstr "" "Аналогичную функциональность предоставляет пакет package:security/" "expiretable[], который удаляет записи таблицы, к которым не было обращений в " "течение указанного периода времени." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:797 msgid "" "Once installed, expiretable can be run to remove `` table " "entries older than a specified age. This example removes all entries older " "than 24 hours:" msgstr "" "После установки `expiretable` можно запустить для удаления записей из " "таблицы ``, которые старше указанного времени. В этом примере " "удаляются все записи старше 24 часов:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:801 #, no-wrap msgid "/usr/local/sbin/expiretable -v -d -t 24h bruteforce\n" msgstr "/usr/local/sbin/expiretable -v -d -t 24h bruteforce\n" #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:804 #, no-wrap msgid "Protecting Against SPAM" msgstr "Защита от SPAM" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:808 msgid "" "Not to be confused with the spamd daemon which comes bundled with " "spamassassin, package:mail/spamd[] can be configured with PF to provide an " "outer defense against SPAM. This spamd hooks into the PF configuration " "using a set of redirections." msgstr "" "package:mail/spamd[] можно настроить совместно с PF для обеспечения внешней " "защиты от SPAM (Не путайте его с демоном spamd, который поставляется вместе " "с spamassassin). Этот spamd интегрируется в конфигурацию PF с помощью набора " "перенаправлений." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:810 msgid "" "Spammers tend to send a large number of messages, and SPAM is mainly sent " "from a few spammer friendly networks and a large number of hijacked " "machines, both of which are reported to _blocklists_ fairly quickly." msgstr "" "Спамеры обычно рассылают большое количество сообщений, и СПАМ в основном " "отправляется из нескольких дружественных к спамерам сетей и множества " "взломанных машин, которые быстро попадают в _списки блокировки_." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:814 msgid "" "When an SMTP connection from an address in a blocklist is received, spamd " "presents its banner and immediately switches to a mode where it answers SMTP " "traffic one byte at a time. This technique, which is intended to waste as " "much time as possible on the spammer's end, is called _tarpitting_. The " "specific implementation which uses one byte SMTP replies is often referred " "to as _stuttering_." msgstr "" "Когда SMTP-соединение с адреса из блок-листа получено, spamd отображает свой " "баннер и немедленно переключается в режим, где он отвечает на SMTP-трафик по " "одному байту за раз. Эта техника, предназначенная для максимально возможной " "потери времени на стороне спамера, называется _тарпиттинг_ (tarpitting, " "намеренное замедление). Конкретная реализация, использующая однобайтовые " "SMTP-ответы, часто упоминается как _прерывистые ответы_ (stuttering, метод " "заикания)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:817 msgid "" "This example demonstrates the basic procedure for setting up spamd with " "automatically updated blocklists. Refer to the man pages which are " "installed with package:mail/spamd[] for more information." msgstr "" "В этом примере показана базовая процедура настройки spamd с автоматически " "обновляемыми списками блокировки. Для получения дополнительной информации " "обратитесь к руководствам, которые устанавливаются вместе с пакетом package:" "mail/spamd[]." #. type: Block title #: documentation/content/en/books/handbook/firewalls/_index.adoc:820 #, no-wrap msgid "Procedure: Configuring spamd" msgstr "Процедура: Настройка spamd" #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:822 msgid "" "Install the package:mail/spamd[] package or port. To use spamd's greylisting " "features, man:fdescfs[5] must be mounted at [.filename]#/dev/fd#. Add the " "following line to [.filename]#/etc/fstab#:" msgstr "" "Установите пакет package:mail/spamd[] или порт. Для использования функции " "серого списка (greylisting) в spamd, необходимо подключить man:fdescfs[5] в " "[.filename]#/dev/fd#. Добавьте следующую строку в [.filename]#/etc/fstab#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:826 #, no-wrap msgid " fdescfs /dev/fd fdescfs rw 0 0\n" msgstr " fdescfs /dev/fd fdescfs rw 0 0\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:829 msgid "Then, mount the filesystem:" msgstr "Затем смонтируйте файловую систему:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:833 #, no-wrap msgid "# mount fdescfs\n" msgstr "# mount fdescfs\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:836 msgid "Next, edit the PF ruleset to include:" msgstr "Далее отредактируйте набор правил PF, включив:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:845 #, no-wrap msgid "" "table persist\n" "table persist\n" "rdr pass on $ext_if inet proto tcp from to \\\n" " { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025\n" "rdr pass on $ext_if inet proto tcp from ! to \\\n" " { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025\n" msgstr "" "table persist\n" "table persist\n" "rdr pass on $ext_if inet proto tcp from to \\\n" " { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025\n" "rdr pass on $ext_if inet proto tcp from ! to \\\n" " { $ext_if, $localnet } port smtp -> 127.0.0.1 port 8025\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:849 msgid "" "The two tables `` and `` are essential. SMTP traffic " "from an address listed in `` but not in `` is redirected " "to the spamd daemon listening at port 8025." msgstr "" "Две таблицы `` и `` являются обязательными. SMTP-трафик " "с адреса, указанного в ``, но отсутствующего в ``, " "перенаправляется к демону spamd, ожидающему на порту 8025." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:850 msgid "" "The next step is to configure spamd in [.filename]#/usr/local/etc/spamd." "conf# and to add some [.filename]#rc.conf# parameters." msgstr "" "Следующий шаг — настроить spamd в [.filename]#/usr/local/etc/spamd.conf# и " "добавить параметры в [.filename]#rc.conf#." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:853 msgid "" "The installation of package:mail/spamd[] includes a sample configuration " "file ([.filename]#/usr/local/etc/spamd.conf.sample#) and a man page for [." "filename]#spamd.conf#. Refer to these for additional configuration options " "beyond those shown in this example." msgstr "" "Установка пакета package:mail/spamd[] включает образец файла конфигурации ([." "filename]#/usr/local/etc/spamd.conf.sample#) и man-страницу для [." "filename]#spamd.conf#. Обратитесь к ним для получения дополнительных " "параметров конфигурации, помимо показанных в этом примере." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:855 msgid "" "One of the first lines in the configuration file that does not begin with a `" "+#+` comment sign contains the block which defines the `all` list, which " "specifies the lists to use:" msgstr "" "Одна из первых строк в файле конфигурации, которая не начинается с символа " "комментария `+#+`, содержит блок, определяющий список `all`, который " "указывает списки для использования:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:860 #, no-wrap msgid "" "all:\\\n" " :traplist:allowlist:\n" msgstr "" "all:\\\n" " :traplist:allowlist:\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:863 msgid "" "This entry adds the desired blocklists, separated by colons (`:`). To use " "an allowlist to subtract addresses from a blocklist, add the name of the " "allowlist _immediately_ after the name of that blocklist. For example: `:" "blocklist:allowlist:`." msgstr "" "Эта запись добавляет желаемые списки блокировок, разделённые двоеточиями (`:" "`). Чтобы использовать список разрешений для исключения адресов из списка " "блокировок, добавьте имя списка разрешений _непосредственно_ после имени " "этого списка блокировок. Например: `:blocklist:allowlist:`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:865 msgid "This is followed by the specified blocklist's definition:" msgstr "За этим следует определение указанного списка блокировки:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:873 #, no-wrap msgid "" "traplist:\\\n" " :black:\\\n" " :msg=\"SPAM. Your address %A has sent spam within the last 24 hours\":\\\n" " :method=http:\\\n" " :file=www.openbsd.org/spamd/traplist.gz\n" msgstr "" "traplist:\\\n" " :black:\\\n" " :msg=\"SPAM. Your address %A has sent spam within the last 24 hours\":\\\n" " :method=http:\\\n" " :file=www.openbsd.org/spamd/traplist.gz\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:879 msgid "" "where the first line is the name of the blocklist and the second line " "specifies the list type. The `msg` field contains the message to display to " "blocklisted senders during the SMTP dialogue. The `method` field specifies " "how spamd-setup fetches the list data; supported methods are `http`, `ftp`, " "from a `file` in a mounted file system, and via `exec` of an external " "program. Finally, the `file` field specifies the name of the file spamd " "expects to receive." msgstr "" "где первая строка — это имя списка блокировки, а вторая строка определяет " "тип списка. Поле `msg` содержит сообщение, которое будет отображаться " "заблокированным отправителям во время SMTP-диалога. Поле `method` указывает, " "каким образом spamd-setup получает данные списка; поддерживаемые методы — " "`http`, `ftp`, из `file` в смонтированной файловой системе и через `exec` " "внешней программы. Наконец, поле `file` определяет имя файла, который " "ожидает получить spamd." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:881 msgid "" "The definition of the specified allowlist is similar, but omits the `msg` " "field since a message is not needed:" msgstr "" "Определение указанного разрешенного списка аналогично, но опускает поле " "`msg`, так как сообщение не требуется:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:888 #, no-wrap msgid "" "allowlist:\\\n" " :white:\\\n" " :method=file:\\\n" " :file=/var/mail/allowlist.txt\n" msgstr "" "allowlist:\\\n" " :white:\\\n" " :method=file:\\\n" " :file=/var/mail/allowlist.txt\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:893 #, no-wrap msgid "*Choose Data Sources with Care:* +\n" msgstr "*Выбирайте источники данных с осторожностью:* +\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:896 msgid "" "Using all the blocklists in the sample [.filename]#spamd.conf# will block " "large blocks of the Internet. Administrators need to edit the file to " "create an optimal configuration which uses applicable data sources and, when " "necessary, uses custom lists." msgstr "" "Использование всех блокирующих списков в примере [.filename]#spamd.conf# " "приведет к блокировке больших сегментов Интернета. Администраторам " "необходимо отредактировать файл, чтобы создать оптимальную конфигурацию, " "которая использует подходящие источники данных и, при необходимости, " "пользовательские списки." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:900 msgid "" "Next, add this entry to [.filename]#/etc/rc.conf#. Additional flags are " "described in the man page specified by the comment:" msgstr "" "Далее добавьте эту запись в [.filename]#/etc/rc.conf#. Дополнительные флаги " "описаны в man-странице, указанной в комментарии:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:904 #, no-wrap msgid "spamd_flags=\"-v\" # use \"\" and see spamd-setup(8) for flags\n" msgstr "spamd_flags=\"-v\" # use \"\" and see spamd-setup(8) for flags\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:908 msgid "" "When finished, reload the ruleset, start spamd by typing `service obspamd " "start`, and complete the configuration using `spamd-setup`. Finally, create " "a man:cron[8] job which calls `spamd-setup` to update the tables at " "reasonable intervals." msgstr "" "После завершения перезагрузите набор правил, запустите spamd командой " "`service obspamd start` и завершите настройку с помощью `spamd-setup`. " "Наконец, создайте задание в man:cron[8], которое будет вызывать `spamd-" "setup` для обновления таблиц через разумные промежутки времени." #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:911 msgid "" "On a typical gateway in front of a mail server, hosts will soon start " "getting trapped within a few seconds to several minutes." msgstr "" "На типичном шлюзе перед почтовым сервером узлы начнут попадать в ловушку в " "течение от нескольких секунд до нескольких минут." #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:915 msgid "" "PF also supports _greylisting_, which temporarily rejects messages from " "unknown hosts with _45n_ codes. Messages from greylisted hosts which try " "again within a reasonable time are let through. Traffic from senders which " "are set up to behave within the limits set by RFC 1123 and RFC 2821 are " "immediately let through." msgstr "" "PF также поддерживает _greylisting_, который временно отклоняет сообщения от " "неизвестных хостов с кодами _45n_. Сообщения от хостов, находящихся в " "greylisting, которые повторяют попытку в разумные сроки, пропускаются. " "Трафик от отправителей, настроенных на работу в пределах, установленных RFC " "1123 и RFC 2821, пропускается сразу." #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:919 msgid "" "More information about greylisting as a technique can be found at the http://" "www.greylisting.org/[greylisting.org] web site. The most amazing thing " "about greylisting, apart from its simplicity, is that it still works. " "Spammers and malware writers have been very slow to adapt to bypass this " "technique." msgstr "" "Дополнительная информация о методе серых списков (greylisting) доступна на " "сайте http://www.greylisting.org/[greylisting.org]. Самое удивительное в " "серых списках, помимо их простоты, это то, что они до сих пор работают. " "Спамеры и авторы вредоносного ПО очень медленно адаптируются, чтобы обойти " "этот метод." #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:921 msgid "The basic procedure for configuring greylisting is as follows:" msgstr "Основная процедура настройки серого списка выглядит следующим образом:" #. type: Block title #: documentation/content/en/books/handbook/firewalls/_index.adoc:923 #, no-wrap msgid "Procedure: Configuring Greylisting" msgstr "Процедура: Настройка серого списка" #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:925 msgid "" "Make sure that man:fdescfs[5] is mounted as described in Step 1 of the " "previous Procedure." msgstr "" "Убедитесь, что man:fdescfs[5] смонтирован, как описано в Шаге 1 предыдущей " "процедуры." #. type: delimited block * 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:926 msgid "" "To run spamd in greylisting mode, add this line to [.filename]#/etc/rc.conf#:" msgstr "" "Для запуска spamd в режиме серого списка добавьте следующую строку в [." "filename]#/etc/rc.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:930 #, no-wrap msgid "spamd_grey=\"YES\" # use spamd greylisting if YES\n" msgstr "spamd_grey=\"YES\" # use spamd greylisting if YES\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:933 msgid "" "Refer to the spamd man page for descriptions of additional related " "parameters." msgstr "" "Обратитесь к man-странице spamd для описания дополнительных параметров, " "относящихся к серым спискам." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:934 msgid "To complete the greylisting setup:" msgstr "Для завершения настройки серого списка:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:939 #, no-wrap msgid "" "# service obspamd restart\n" "# service obspamlogd start\n" msgstr "" "# service obspamd restart\n" "# service obspamlogd start\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:943 msgid "" "Behind the scenes, the spamdb database tool and the spamlogd whitelist " "updater perform essential functions for the greylisting feature. spamdb is " "the administrator's main interface to managing the block, grey, and allow " "lists via the contents of the [.filename]#/var/db/spamdb# database." msgstr "" "За кулисами инструмент базы данных spamdb и обновляющий белый список " "spamlogd выполняют важные функции для механизма отложенной доставки. spamdb " "— это основной интерфейс администратора для управления списками блокировки, " "серого списка и списка с разрешениями через содержимое базы данных [." "filename]#/var/db/spamdb#." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:945 #, no-wrap msgid "Network Hygiene" msgstr "Сетевая гигиена" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:948 msgid "" "This section describes how `block-policy`, `scrub`, and `antispoof` can be " "used to make the ruleset behave sanely." msgstr "" "В этом разделе описывается, как `block-policy`, `scrub` и `antispoof` могут " "быть использованы для обеспечения разумного поведения набора правил." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:952 msgid "" "The `block-policy` is an option which can be set in the `options` part of " "the ruleset, which precedes the redirection and filtering rules. This " "option determines which feedback, if any, PF sends to hosts that are blocked " "by a rule. The option has two possible values: `drop` drops blocked packets " "with no feedback, and `return` returns a status code such as `Connection " "refused`." msgstr "" "`block-policy` — это опция, которую можно установить в разделе `options` " "набора правил, предшествующем правилам перенаправления и фильтрации. Эта " "опция определяет, какую обратную связь (если таковая имеется) PF отправляет " "хостам, заблокированным правилом. Опция имеет два возможных значения: `drop` " "отбрасывает заблокированные пакеты без ответа, а `return` возвращает код " "состояния, например `Connection refused`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:955 msgid "" "If not set, the default policy is `drop`. To change the `block-policy`, " "specify the desired value:" msgstr "" "Если не задано, политика по умолчанию — `drop`. Чтобы изменить `block-" "policy`, укажите желаемое значение:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:959 #, no-wrap msgid "set block-policy return\n" msgstr "set block-policy return\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:965 msgid "" "In PF, `scrub` is a keyword which enables network packet normalization. " "This process reassembles fragmented packets and drops TCP packets that have " "invalid flag combinations. Enabling `scrub` provides a measure of " "protection against certain kinds of attacks based on incorrect handling of " "packet fragments. A number of options are available, but the simplest form " "is suitable for most configurations:" msgstr "" "В PF `scrub` — это ключевое слово, которое включает нормализацию сетевых " "пакетов. Этот процесс пересобирает фрагментированные пакеты и отбрасывает " "TCP-пакеты с недопустимыми комбинациями флагов. Включение `scrub` " "обеспечивает защиту от определённых видов атак, основанных на некорректной " "обработке фрагментов пакетов. Доступно несколько опций, но простейшая форма " "подходит для большинства конфигураций:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:969 #, no-wrap msgid "scrub in all\n" msgstr "scrub in all\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:973 msgid "" "Some services, such as NFS, require specific fragment handling options. " "Refer to https://home.nuug.no/\\~peter/pf/en/scrub.html[https://home.nuug.no/" "~peter/pf/en/scrub.html] for more information." msgstr "" "Некоторые службы, такие как NFS, требуют специальных параметров обработки " "фрагментов. Дополнительную информацию можно найти по ссылке https://home." "nuug.no/~peter/pf/en/scrub.html[https://home.nuug.no/~peter/pf/en/scrub." "html]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:975 msgid "" "This example reassembles fragments, clears the \"do not fragment\" bit, and " "sets the maximum segment size to 1440 bytes:" msgstr "" "Этот пример собирает фрагменты, сбрасывает бит \"не фрагментировать\" и " "устанавливает максимальный размер сегмента в 1440 байт:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:979 #, no-wrap msgid "scrub in all fragment reassemble no-df max-mss 1440\n" msgstr "scrub in all fragment reassemble no-df max-mss 1440\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:982 msgid "" "The `antispoof` mechanism protects against activity from spoofed or forged " "IP addresses, mainly by blocking packets appearing on interfaces and in " "directions which are logically not possible." msgstr "" "Механизм `antispoof` защищает от активности с подделанных или " "фальсифицированных IP-адресов, в основном блокируя пакеты, появляющиеся на " "интерфейсах и в направлениях, которые логически невозможны." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:984 msgid "" "These rules weed out spoofed traffic coming in from the rest of the world as " "well as any spoofed packets which originate in the local network:" msgstr "" "Эти правила отсеивают поддельный трафик, поступающий из остального мира, а " "также любые поддельные пакеты, исходящие из локальной сети:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:989 #, no-wrap msgid "" "antispoof for $ext_if\n" "antispoof for $int_if\n" msgstr "" "antispoof for $ext_if\n" "antispoof for $int_if\n" #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:992 #, no-wrap msgid "Handling Non-Routable Addresses" msgstr "Обработка немаршрутизируемых адресов" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:997 msgid "" "Even with a properly configured gateway to handle network address " "translation, one may have to compensate for other people's " "misconfigurations. A common misconfiguration is to let traffic with non-" "routable addresses out to the Internet. Since traffic from non-routeable " "addresses can play a part in several DoS attack techniques, consider " "explicitly blocking traffic from non-routeable addresses from entering the " "network through the external interface." msgstr "" "Даже при правильно настроенном шлюзе для обработки преобразования сетевых " "адресов может потребоваться компенсировать ошибки в конфигурации, сделанные " "другими людьми. Распространённой ошибкой является пропуск трафика с не " "маршрутизируемыми адресами в Интернет. Поскольку трафик с не " "маршрутизируемых адресов может использоваться в нескольких методах DoS-атак, " "рекомендуется явно блокировать такой трафик от попадания в сеть через " "внешний интерфейс." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1000 msgid "" "In this example, a macro containing non-routable addresses is defined, then " "used in blocking rules. Traffic to and from these addresses is quietly " "dropped on the gateway's external interface." msgstr "" "В этом примере определяется макрос, содержащий не маршрутизируемые адреса, " "который затем используется в правилах блокировки. Трафик на эти адреса и с " "этих адресов тихо отбрасывается на внешнем интерфейсе шлюза." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1006 #, no-wrap msgid "" "martians = \"{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \\\n" "\t 10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \\\n" "\t 0.0.0.0/8, 240.0.0.0/4 }\"\n" msgstr "" "martians = \"{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \\\n" "\t 10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \\\n" "\t 0.0.0.0/8, 240.0.0.0/4 }\"\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1009 #, no-wrap msgid "" "block drop in quick on $ext_if from $martians to any\n" "block drop out quick on $ext_if from any to $martians\n" msgstr "" "block drop in quick on $ext_if from $martians to any\n" "block drop out quick on $ext_if from any to $martians\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1011 #, no-wrap msgid "Enabling ALTQ" msgstr "Включение ALTQ" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1015 msgid "" "On FreeBSD, ALTQ can be used with PF to provide Quality of Service (QOS). " "Once ALTQ is enabled, queues can be defined in the ruleset which determine " "the processing priority of outbound packets." msgstr "" "На FreeBSD ALTQ можно использовать с PF для обеспечения качества " "обслуживания (QOS — Quality of Service). После включения ALTQ в наборе " "правил можно определить очереди, которые определяют приоритет обработки " "исходящих пакетов." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1017 msgid "" "Before enabling ALTQ, refer to man:altq[4] to determine if the drivers for " "the network cards installed on the system support it." msgstr "" "Прежде чем включить ALTQ, обратитесь к man:altq[4], чтобы определить, " "поддерживают ли его драйверы сетевых карт, установленных в системе." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1023 msgid "" "ALTQ is not available as a loadable kernel module. If the system's " "interfaces support ALTQ, create a custom kernel using the instructions in " "crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. The " "following kernel options are available. The first is needed to enable " "ALTQ. At least one of the other options is necessary to specify the " "queueing scheduler algorithm:" msgstr "" "ALTQ недоступен в виде загружаемого модуля ядра. Если интерфейсы системы " "поддерживают ALTQ, создайте собственное ядро, следуя инструкциям в crossref:" "kernelconfig[kernelconfig,Настройка ядра FreeBSD]. Доступны следующие " "параметры ядра. Первый необходим для включения ALTQ. Хотя бы один из " "остальных параметров требуется для указания алгоритма планирования очередей:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1032 #, no-wrap msgid "" "options ALTQ\n" "options ALTQ_CBQ # Class Based Queuing (CBQ)\n" "options ALTQ_RED # Random Early Detection (RED)\n" "options ALTQ_RIO # RED In/Out\n" "options ALTQ_HFSC # Hierarchical Packet Scheduler (HFSC)\n" "options ALTQ_PRIQ # Priority Queuing (PRIQ)\n" msgstr "" "options ALTQ\n" "options ALTQ_CBQ # Class Based Queuing (CBQ)\n" "options ALTQ_RED # Random Early Detection (RED)\n" "options ALTQ_RIO # RED In/Out\n" "options ALTQ_HFSC # Hierarchical Packet Scheduler (HFSC)\n" "options ALTQ_PRIQ # Priority Queuing (PRIQ)\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1035 msgid "The following scheduler algorithms are available:" msgstr "Доступны следующие алгоритмы планировщика:" #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1036 #, no-wrap msgid "CBQ" msgstr "CBQ" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1038 msgid "" "Class Based Queuing (CBQ) is used to divide a connection's bandwidth into " "different classes or queues to prioritize traffic based on filter rules." msgstr "" "Очереди на основе классов (CBQ — Class Based Queuing) используется для " "разделения пропускной способности соединения на различные классы или очереди " "с целью приоритизации трафика на основе правил фильтрации." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1039 #, no-wrap msgid "RED" msgstr "RED" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1042 msgid "" "Random Early Detection (RED) is used to avoid network congestion by " "measuring the length of the queue and comparing it to the minimum and " "maximum thresholds for the queue. When the queue is over the maximum, all " "new packets are randomly dropped." msgstr "" "Случайное раннее обнаружение (RED — Random Early Detection) используется для " "предотвращения перегрузки сети путем измерения длины очереди и сравнения её " "с минимальным и максимальным порогами для очереди. Когда очередь превышает " "максимальный порог, все новые пакеты случайным образом отбрасываются." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1043 #, no-wrap msgid "RIO" msgstr "RIO" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1045 msgid "" "In Random Early Detection In and Out (RIO) mode, RED maintains multiple " "average queue lengths and multiple threshold values, one for each QOS level." msgstr "" "В режиме Случайного раннего обнаружения для входящего и исходящего трафика " "(RIO) RED поддерживает несколько средних длин очередей и несколько пороговых " "значений, по одному для каждого уровня QOS." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1046 #, no-wrap msgid "HFSC" msgstr "HFSC" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1048 msgid "" "Hierarchical Fair Service Curve Packet Scheduler (HFSC) is described in " "http://www-2.cs.cmu.edu/\\~hzhang/HFSC/main.html[http://www-2.cs.cmu.edu/" "~hzhang/HFSC/main.html]." msgstr "" "Иерархический планировщик пакетов с гарантированной справедливой кривой " "обслуживания (HFSC) описан на http://www-2.cs.cmu.edu/\\~hzhang/HFSC/main." "html[http://www-2.cs.cmu.edu/~hzhang/HFSC/main.html]." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1049 #, no-wrap msgid "PRIQ" msgstr "PRIQ" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1051 msgid "" "Priority Queuing (PRIQ) always passes traffic that is in a higher queue " "first." msgstr "" "Очереди с приоритетом (PRIQ) всегда пропускают трафик из более " "высокоуровневой очереди первым." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1053 msgid "" "More information about the scheduling algorithms and example rulesets are " "available at the https://web.archive.org/web/20151109213426/http://www." "openbsd.org/faq/pf/queueing.html[OpenBSD's web archive]." msgstr "" "Дополнительная информация о алгоритмах планирования и примеры наборов правил " "доступны на https://web.archive.org/web/20151109213426/http://www.openbsd." "org/faq/pf/queueing.html[архивированной странице OpenBSD]." #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:1055 #, no-wrap msgid "IPFW" msgstr "IPFW" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1059 msgid "" "IPFW is a stateful firewall written for FreeBSD which supports both IPv4 and " "IPv6. It is comprised of several components: the kernel firewall filter " "rule processor and its integrated packet accounting facility, the logging " "facility, NAT, the man:dummynet[4] traffic shaper, a forward facility, a " "bridge facility, and an ipstealth facility." msgstr "" "IPFW — это межсетевой экран с отслеживанием состояний, разработанный для " "FreeBSD, который поддерживает как IPv4, так и IPv6. Он состоит из нескольких " "компонентов: процессора правил фильтрации межсетевого экрана в ядре и " "встроенного механизма учёта пакетов, механизма журналирования, NAT, " "механизма управления трафиком man:dummynet[4], механизма переадресации, " "механизма моста и механизма ipstealth." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1062 msgid "" "FreeBSD provides a sample ruleset in [.filename]#/etc/rc.firewall# which " "defines several firewall types for common scenarios to assist novice users " "in generating an appropriate ruleset. IPFW provides a powerful syntax which " "advanced users can use to craft customized rulesets that meet the security " "requirements of a given environment." msgstr "" "FreeBSD предоставляет пример набора правил в [.filename]#/etc/rc.firewall#, " "который определяет несколько типов межсетевых экранов для распространённых " "сценариев, чтобы помочь новичкам в создании подходящего набора правил. IPFW " "предлагает мощный синтаксис, с помощью которого опытные пользователи могут " "создавать настраиваемые наборы правил, соответствующие требованиям " "безопасности заданного окружения." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1064 msgid "" "This section describes how to enable IPFW, provides an overview of its rule " "syntax, and demonstrates several rulesets for common configuration scenarios." msgstr "" "Этот раздел описывает, как включить IPFW, предоставляет обзор синтаксиса его " "правил и демонстрирует несколько наборов правил для распространённых " "сценариев настройки." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1066 #, no-wrap msgid "Enabling IPFW" msgstr "Включение IPFW" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1069 msgid "" "IPFW is included in the basic FreeBSD install as a kernel loadable module, " "meaning that a custom kernel is not needed in order to enable IPFW." msgstr "" "IPFW включён в базовую установку FreeBSD в виде загружаемого модуля ядра, " "что означает, что для его включения не требуется собирать собственное ядро." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1072 msgid "" "For those users who wish to statically compile IPFW support into a custom " "kernel, see crossref:firewalls[firewalls-ipfw-kernelconfig, IPFW Kernel " "Options]." msgstr "" "Для пользователей, которые хотят статически скомпилировать поддержку IPFW в " "собственном ядре, см. crossref:firewalls[firewalls-ipfw-kernelconfig, " "Параметры ядра IPFW]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1074 msgid "" "To configure the system to enable IPFW at boot time, add `firewall_enable=" "\"YES\"` to [.filename]#/etc/rc.conf#:" msgstr "" "Для настройки системы для включения IPFW при загрузке добавьте " "`firewall_enable=\"YES\"` в файл [.filename]#/etc/rc.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1078 #, no-wrap msgid "# sysrc firewall_enable=\"YES\"\n" msgstr "# sysrc firewall_enable=\"YES\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1081 msgid "" "To use one of the default firewall types provided by FreeBSD, add another " "line which specifies the type:" msgstr "" "Чтобы использовать один из типов межсетевых экранов, предоставляемых " "FreeBSD, добавьте строку с указанием типа:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1085 #, no-wrap msgid "# sysrc firewall_type=\"open\"\n" msgstr "# sysrc firewall_type=\"open\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1088 msgid "The available types are:" msgstr "Доступные типы:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1090 msgid "`open`: passes all traffic." msgstr "`open`: пропускает весь трафик." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1091 msgid "`client`: protects only this machine." msgstr "`client`: защищает только эту машину." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1092 msgid "`simple`: protects the whole network." msgstr "`simple`: защищает всю сеть." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1093 msgid "" "`closed`: entirely disables IP traffic except for the loopback interface." msgstr "" "`closed`: полностью отключает IP-трафик, за исключением интерфейса loopback." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1094 msgid "`workstation`: protects only this machine using stateful rules." msgstr "" "`workstation`: защищает только эту машину с использованием правил с " "отслеживанием состояния." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1095 msgid "`UNKNOWN`: disables the loading of firewall rules." msgstr "`UNKNOWN`: отключает загрузку правил межсетевого экрана." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1096 msgid "" "[.filename]#filename#: full path of the file containing the firewall ruleset." msgstr "" "[.filename]#filename#: полный путь к файлу, содержащему набор правил " "межсетевого экрана." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1098 msgid "" "If `firewall_type` is set to either `client` or `simple`, modify the default " "rules found in [.filename]#/etc/rc.firewall# to fit the configuration of the " "system." msgstr "" "Если `firewall_type` установлен в значение `client` или `simple`, измените " "правила по умолчанию, указанные в [.filename]#/etc/rc.firewall#, чтобы они " "соответствовали конфигурации системы." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1100 msgid "Note that the `filename` type is used to load a custom ruleset." msgstr "" "Обратите внимание, что тип `filename` используется для загрузки " "пользовательского набора правил." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1103 msgid "" "An alternate way to load a custom ruleset is to set the `firewall_script` " "variable to the absolute path of an _executable script_ that includes IPFW " "commands. The examples used in this section assume that the " "`firewall_script` is set to [.filename]#/etc/ipfw.rules#:" msgstr "" "Альтернативный способ загрузки пользовательского набора правил — присвойте " "переменной `firewall_script` значение, равное абсолютному пути к " "_исполняемому скрипту_, который включает команды IPFW. Примеры, используемые " "в этом разделе, предполагают, что `firewall_script` установлен в [." "filename]#/etc/ipfw.rules#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1107 #, no-wrap msgid "# sysrc firewall_script=\"/etc/ipfw.rules\"\n" msgstr "# sysrc firewall_script=\"/etc/ipfw.rules\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1110 msgid "To enable logging through man:syslogd[8], include this line:" msgstr "" "Чтобы включить ведение журнала через man:syslogd[8], добавьте следующую " "строку:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1114 #, no-wrap msgid "# sysrc firewall_logging=\"YES\"\n" msgstr "# sysrc firewall_logging=\"YES\"\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1122 msgid "" "Only firewall rules with the `log` option will be logged. The default rules " "do not include this option and it must be manually added. Therefore it is " "advisable that the default ruleset is edited for logging. In addition, log " "rotation may be desired if the logs are stored in a separate file." msgstr "" "В журнал будут записываться только правила межсетевого экрана с опцией " "`log`. Правила по умолчанию не включают эту опцию, и её необходимо добавить " "вручную. Поэтому рекомендуется отредактировать набор правил по умолчанию для " "ведения журнала. Кроме того, может потребоваться ротация журналов, если они " "сохраняются в отдельный файл." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1126 msgid "" "There is no [.filename]#/etc/rc.conf# variable to set logging limits. To " "limit the number of times a rule is logged per connection attempt, specify " "the number using this line in [.filename]#/etc/sysctl.conf#:" msgstr "" "В файле [.filename]#/etc/rc.conf# нет переменной для установки ограничений " "журналирования. Чтобы ограничить количество записей в журнале для каждого " "правила на одну попытку соединения, укажите число с помощью следующей строки " "в [.filename]#/etc/sysctl.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1130 #, no-wrap msgid "# echo \"net.inet.ip.fw.verbose_limit=5\" >> /etc/sysctl.conf\n" msgstr "# echo \"net.inet.ip.fw.verbose_limit=5\" >> /etc/sysctl.conf\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1133 msgid "" "To enable logging through a dedicated interface named `ipfw0`, add this line " "to [.filename]#/etc/rc.conf# instead:" msgstr "" "Для включения журналирования через выделенный интерфейс с именем `ipfw0`, " "добавьте следующую строку в [.filename]#/etc/rc.conf# вместо этого:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1137 #, no-wrap msgid "# sysrc firewall_logif=\"YES\"\n" msgstr "# sysrc firewall_logif=\"YES\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1140 msgid "Then use tcpdump to see what is being logged:" msgstr "Затем используйте tcpdump для просмотра записываемых данных:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1144 #, no-wrap msgid "# tcpdump -t -n -i ipfw0\n" msgstr "# tcpdump -t -n -i ipfw0\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1150 msgid "There is no overhead due to logging unless tcpdump is attached." msgstr "" "Нет накладных расходов из-за ведения журнала, если не подключен tcpdump." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1154 msgid "" "After saving the needed edits, start the firewall. To enable logging limits " "now, also set the `sysctl` value specified above:" msgstr "" "После сохранения необходимых изменений запустите межсетевой экран. Чтобы " "сразу включить ограничения журналирования, также установите указанное выше " "значение `sysctl`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1159 #, no-wrap msgid "" "# service ipfw start\n" "# sysctl net.inet.ip.fw.verbose_limit=5\n" msgstr "" "# service ipfw start\n" "# sysctl net.inet.ip.fw.verbose_limit=5\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1162 #, no-wrap msgid "IPFW Rule Syntax" msgstr "Синтаксис правил IPFW" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1170 msgid "" "When a packet enters the IPFW firewall, it is compared against the first " "rule in the ruleset and progresses one rule at a time, moving from top to " "bottom in sequence. When the packet matches the selection parameters of a " "rule, the rule's action is executed and the search of the ruleset terminates " "for that packet. This is referred to as \"first match wins\". If the " "packet does not match any of the rules, it gets caught by the mandatory IPFW " "default rule number 65535, which denies all packets and silently discards " "them. However, if the packet matches a rule that contains the `count`, " "`skipto`, or `tee` keywords, the search continues. Refer to man:ipfw[8] for " "details on how these keywords affect rule processing." msgstr "" "Когда пакет попадает в межсетевой экран IPFW, он сравнивается с первым " "правилом в наборе правил и последовательно обрабатывается сверху вниз, " "правило за правилом. Если пакет соответствует параметрам выбора правила, " "выполняется действие этого правила, и поиск в наборе правил для данного " "пакета прекращается. Это называется «первое совпадение побеждает». Если " "пакет не соответствует ни одному из правил, он попадает под действие " "обязательного правила IPFW с номером 65535, которое запрещает все пакеты и " "тихо их отбрасывает. Однако, если пакет соответствует правилу, содержащему " "ключевые слова `count`, `skipto` или `tee`, поиск продолжается. Подробнее о " "том, как эти ключевые слова влияют на обработку правил, см. в man:ipfw[8]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1176 msgid "" "When creating an IPFW rule, keywords must be written in the following " "order. Some keywords are mandatory while other keywords are optional. The " "words shown in uppercase represent a variable and the words shown in " "lowercase must precede the variable that follows it. The `+#+` symbol is " "used to mark the start of a comment and may appear at the end of a rule or " "on its own line. Blank lines are ignored." msgstr "" "При создании правила IPFW ключевые слова должны быть записаны в следующем " "порядке. Некоторые ключевые слова являются обязательными, а другие — " "опциональными. Слова, написанные в верхнем регистре, обозначают переменную, " "а слова в нижнем регистре должны предшествовать следующей за ними " "переменной. Символ `+#+` используется для обозначения начала комментария и " "может находиться в конце правила или на отдельной строке. Пустые строки " "игнорируются." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1178 msgid "" "`_CMD RULE_NUMBER set SET_NUMBER ACTION log LOG_AMOUNT PROTO from SRC " "SRC_PORT to DST DST_PORT OPTIONS_`" msgstr "" "`_CMD RULE_NUMBER set SET_NUMBER ACTION log LOG_AMOUNT PROTO from SRC " "SRC_PORT to DST DST_PORT OPTIONS_`" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1182 msgid "" "This section provides an overview of these keywords and their options. It " "is not an exhaustive list of every possible option. Refer to man:ipfw[8] " "for a complete description of the rule syntax that can be used when creating " "IPFW rules." msgstr "" "В этом разделе представлен обзор этих ключевых слов и их параметров. Это не " "исчерпывающий список всех возможных вариантов. Для полного описания " "синтаксиса правил, которые можно использовать при создании правил IPFW, " "обратитесь к man:ipfw[8]." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1183 #, no-wrap msgid "CMD" msgstr "CMD" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1185 msgid "Every rule must start with `ipfw add`." msgstr "Каждое правило должно начинаться с `ipfw add`." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1186 #, no-wrap msgid "RULE_NUMBER" msgstr "RULE_NUMBER" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1190 msgid "" "Each rule is associated with a number from `1` to `65534`. The number is " "used to indicate the order of rule processing. Multiple rules can have the " "same number, in which case they are applied according to the order in which " "they have been added." msgstr "" "Каждое правило связано с числом от `1` до `65534`. Этот номер используется " "для указания порядка обработки правил. Несколько правил могут иметь " "одинаковый номер, в таком случае они применяются в порядке их добавления." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1191 #, no-wrap msgid "SET_NUMBER" msgstr "SET_NUMBER" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1195 msgid "" "Each rule is associated with a set number from `0` to `31`. Sets can be " "individually disabled or enabled, making it possible to quickly add or " "delete a set of rules. If a SET_NUMBER is not specified, the rule will be " "added to set `0`." msgstr "" "Каждое правило связано с номером набора от `0` до `31`. Наборы можно " "отключать или включать по отдельности, что позволяет быстро добавлять или " "удалять набор правил. Если `SET_NUMBER` не указан, правило будет добавлено в " "набор `0`." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1196 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1942 #, no-wrap msgid "ACTION" msgstr "ACTION" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1199 msgid "" "A rule can be associated with one of the following actions. The specified " "action will be executed when the packet matches the selection criterion of " "the rule." msgstr "" "Правило может быть связано с одним из следующих действий. Указанное действие " "будет выполнено, когда пакет соответствует критерию выбора правила." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1201 msgid "" "`allow | accept | pass | permit`: these keywords are equivalent and allow " "packets that match the rule." msgstr "" "`allow | accept | pass | permit`: эти ключевые слова эквивалентны и " "разрешают пакеты, соответствующие правилу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1206 msgid "" "`check-state`: checks the packet against the dynamic state table. If a " "match is found, execute the action associated with the rule which generated " "this dynamic rule, otherwise move to the next rule. A `check-state` rule " "does not have selection criterion. If no `check-state` rule is present in " "the ruleset, the dynamic rules table is checked at the first `keep-state` or " "`limit` rule." msgstr "" "`check-state`: проверяет пакет по таблице динамических состояний. Если " "совпадение найдено, выполняется действие, связанное с правилом, которое " "создало это динамическое правило, в противном случае осуществляется переход " "к следующему правилу. Правило `check-state` не имеет критериев выбора. Если " "правило `check-state` отсутствует в наборе правил, таблица динамических " "правил проверяется при первом правиле `keep-state` или `limit`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1209 msgid "" "`count`: updates counters for all packets that match the rule. The search " "continues with the next rule." msgstr "" "`count`: обновляет счетчики для всех пакетов, соответствующих правилу. Поиск " "продолжается со следующего правила." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1211 msgid "" "`deny | drop`: either word silently discards packets that match this rule." msgstr "" "`deny | drop`: любое из этих слов тихо отбрасывает пакеты, соответствующие " "этому правилу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1214 msgid "Additional actions are available. Refer to man:ipfw[8] for details." msgstr "Доступны дополнительные действия. Подробности смотрите в man:ipfw[8]." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1215 #, no-wrap msgid "LOG_AMOUNT" msgstr "LOG_AMOUNT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1221 msgid "" "When a packet matches a rule with the `log` keyword, a message will be " "logged to man:syslogd[8] with a facility name of `SECURITY`. Logging only " "occurs if the number of packets logged for that particular rule does not " "exceed a specified LOG_AMOUNT. If no LOG_AMOUNT is specified, the limit is " "taken from the value of `net.inet.ip.fw.verbose_limit`. A value of zero " "removes the logging limit. Once the limit is reached, logging can be re-" "enabled by clearing the logging counter or the packet counter for that rule, " "using `ipfw resetlog`." msgstr "" "Когда пакет соответствует правилу с ключевым словом `log`, сообщение будет " "записано в man:syslogd[8] с именем средства `SECURITY`. Запись в журнал " "происходит только в том случае, если количество пакетов, зарегистрированных " "для этого конкретного правила, не превышает указанного LOG_AMOUNT. Если " "LOG_AMOUNT не указан, лимит берется из значения `net.inet.ip.fw." "verbose_limit`. Значение нуля снимает ограничение на запись в журнал. Как " "только лимит достигнут, запись в журнал можно снова включить, сбросив " "счетчик журналирования или счетчик пакетов для этого правила с помощью `ipfw " "resetlog`." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1226 msgid "" "Logging is done after all other packet matching conditions have been met, " "and before performing the final action on the packet. The administrator " "decides which rules to enable logging on." msgstr "" "Журналирование выполняется после того, как все остальные условия " "сопоставления пакета выполнены, и перед выполнением конечного действия с " "пакетом. Администратор решает, для каких правил включить журналирование." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1228 #, no-wrap msgid "PROTO" msgstr "PROTO" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1230 msgid "" "This optional value can be used to specify any protocol name or number found " "in [.filename]#/etc/protocols#." msgstr "" "Это необязательное значение может использоваться для указания любого имени " "протокола или номера, найденного в [.filename]#/etc/protocols#." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1231 #, no-wrap msgid "SRC" msgstr "SRC" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1236 msgid "" "The `from` keyword must be followed by the source address or a keyword that " "represents the source address. An address can be represented by `any`, `me` " "(any address configured on an interface on this system), `me6`, (any IPv6 " "address configured on an interface on this system), or `table` followed by " "the number of a lookup table which contains a list of addresses. When " "specifying an IP address, it can be optionally followed by its CIDR mask or " "subnet mask. For example, `1.2.3.4/25` or `1.2.3.4:255.255.255.128`." msgstr "" "Ключевое слово `from` должно сопровождаться исходным адресом или ключевым " "словом, представляющим исходный адрес. Адрес может быть представлен как " "`any`, `me` (любой адрес, настроенный на интерфейсе этой системы), `me6` " "(любой IPv6-адрес, настроенный на интерфейсе этой системы) или `table`, за " "которым следует номер таблицы поиска, содержащей список адресов. При " "указании IP-адреса, он может быть дополнительно указан с маской CIDR или " "маской подсети. Например, `1.2.3.4/25` или `1.2.3.4:255.255.255.128`." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1237 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2008 #, no-wrap msgid "SRC_PORT" msgstr "SRC_PORT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1239 msgid "" "An optional source port can be specified using the port number or name from " "[.filename]#/etc/services#." msgstr "" "Необязательный порт источника может быть указан с использованием номера " "порта или имени из [.filename]#/etc/services#." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1240 #, no-wrap msgid "DST" msgstr "DST" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1243 msgid "" "The `to` keyword must be followed by the destination address or a keyword " "that represents the destination address. The same keywords and addresses " "described in the SRC section can be used to describe the destination." msgstr "" "Ключевое слово `to` должно сопровождаться адресом назначения или ключевым " "словом, представляющим адрес назначения. Те же ключевые слова и адреса, " "которые описаны в разделе SRC, могут быть использованы для описания " "назначения." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1244 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2021 #, no-wrap msgid "DST_PORT" msgstr "DST_PORT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1246 msgid "" "An optional destination port can be specified using the port number or name " "from [.filename]#/etc/services#." msgstr "" "Необязательный порт назначения может быть указан с использованием номера " "порта или имени из [.filename]#/etc/services#." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1247 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1972 #, no-wrap msgid "OPTIONS" msgstr "OPTIONS" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1251 msgid "" "Several keywords can follow the source and destination. As the name " "suggests, OPTIONS are optional. Commonly used options include `in` or " "`out`, which specify the direction of packet flow, `icmptypes` followed by " "the type of ICMP message, and `keep-state`." msgstr "" "Несколько ключевых слов могут следовать за источником и назначением. Как " "следует из названия, OPTIONS являются необязательными. Часто используемые " "опции включают `in` или `out`, которые указывают направление потока пакетов, " "`icmptypes` с указанием типа ICMP-сообщения и `keep-state`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1253 msgid "" "When a `keep-state` rule is matched, the firewall will create a dynamic rule " "which matches bidirectional traffic between the source and destination " "addresses and ports using the same protocol." msgstr "" "Когда правило `keep-state` совпадает, межсетевой экран создаст динамическое " "правило, которое соответствует двунаправленному трафику между исходным и " "целевым адресами и портами, используя тот же протокол." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1258 msgid "" "The dynamic rules facility is vulnerable to resource depletion from a SYN-" "flood attack which would open a huge number of dynamic rules. To counter " "this type of attack with IPFW, use `limit`. This option limits the number " "of simultaneous sessions by checking the open dynamic rules, counting the " "number of times this rule and IP address combination occurred. If this " "count is greater than the value specified by `limit`, the packet is " "discarded." msgstr "" "Функция динамических правил уязвима к истощению ресурсов из-за SYN-флуда, " "который может создать огромное количество динамических правил. Для защиты от " "такого типа атак в IPFW используйте параметр `limit`. Этот параметр " "ограничивает количество одновременных сессий, проверяя открытые динамические " "правила и подсчитывая, сколько раз встречалось сочетание данного правила и " "IP-адреса. Если это количество превышает значение, указанное в `limit`, " "пакет отбрасывается." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1261 msgid "" "Dozens of OPTIONS are available. Refer to man:ipfw[8] for a description of " "each available option." msgstr "" "Доступны десятки параметров `OPTIONS`. Описание каждого доступного параметра " "можно найти в man:ipfw[8]." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1262 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2049 #, no-wrap msgid "Example Ruleset" msgstr "Пример набора правил" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1267 msgid "" "This section demonstrates how to create an example stateful firewall ruleset " "script named [.filename]#/etc/ipfw.rules#. In this example, all connection " "rules use `in` or `out` to clarify the direction. They also use `via` " "_interface-name_ to specify the interface the packet is traveling over." msgstr "" "В этом разделе показано, как создать пример набора правил для статического " "межсетевого экрана в виде скрипта с именем [.filename]#/etc/ipfw.rules#. В " "данном примере все правила соединений используют `in` или `out` для указания " "направления. Они также используют `via` _имя-интерфейса_ для указания " "интерфейса, через который проходит пакет." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1271 msgid "" "When first creating or testing a firewall ruleset, consider temporarily " "setting this tunable:" msgstr "" "При первоначальном создании или тестировании набора правил межсетевого " "экрана рекомендуется временно установить этот параметр:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1275 #, no-wrap msgid "net.inet.ip.fw.default_to_accept=\"1\"\n" msgstr "net.inet.ip.fw.default_to_accept=\"1\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1278 msgid "" "This sets the default policy of man:ipfw[8] to be more permissive than the " "default `deny ip from any to any`, making it slightly more difficult to get " "locked out of the system right after a reboot." msgstr "" "Это устанавливает политику по умолчанию для man:ipfw[8] более " "разрешительной, чем стандартная `deny ip from any to any`, что немного " "снижает вероятность блокировки системы сразу после перезагрузки." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1283 msgid "" "The firewall script begins by indicating that it is a Bourne shell script " "and flushes any existing rules. It then creates the `cmd` variable so that " "`ipfw add` does not have to be typed at the beginning of every rule. It " "also defines the `pif` variable which represents the name of the interface " "that is attached to the Internet." msgstr "" "Скрипт межсетевого экрана начинается с указания, что это скрипт Bourne " "shell, и очищает все существующие правила. Затем он создает переменную " "`cmd`, чтобы не приходилось вводить `ipfw add` в начале каждого правила. " "Также определяется переменная `pif`, которая представляет имя интерфейса, " "подключенного к Интернету." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1289 #, no-wrap msgid "" "#!/bin/sh\n" "# Flush out the list before we begin.\n" "ipfw -q -f flush\n" msgstr "" "#!/bin/sh\n" "# Flush out the list before we begin.\n" "ipfw -q -f flush\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1293 #, no-wrap msgid "" "# Set rules command prefix\n" "cmd=\"ipfw -q add\"\n" "pif=\"dc0\" # interface name of NIC attached to Internet\n" msgstr "" "# Set rules command prefix\n" "cmd=\"ipfw -q add\"\n" "pif=\"dc0\" # interface name of NIC attached to Internet\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1296 msgid "" "The first two rules allow all traffic on the trusted internal interface and " "on the loopback interface:" msgstr "" "Первые два правила разрешают весь трафик на доверенном внутреннем интерфейсе " "и на loopback-интерфейсе:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1301 #, no-wrap msgid "" "# Change xl0 to LAN NIC interface name\n" "$cmd 00005 allow all from any to any via xl0\n" msgstr "" "# Change xl0 to LAN NIC interface name\n" "$cmd 00005 allow all from any to any via xl0\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1304 #, no-wrap msgid "" "# No restrictions on Loopback Interface\n" "$cmd 00010 allow all from any to any via lo0\n" msgstr "" "# No restrictions on Loopback Interface\n" "$cmd 00010 allow all from any to any via lo0\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1307 msgid "" "The next rule allows the packet through if it matches an existing entry in " "the dynamic rules table:" msgstr "" "Следующее правило пропускает пакет, если он соответствует существующей " "записи в таблице динамических правил:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1311 #, no-wrap msgid "$cmd 00101 check-state\n" msgstr "$cmd 00101 check-state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1314 msgid "" "The next set of rules defines which stateful connections internal systems " "can create to hosts on the Internet:" msgstr "" "Следующий набор правил определяет, какие состояния соединений внутренние " "системы могут устанавливать с узлами в Интернете:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1322 #, no-wrap msgid "" "# Allow access to public DNS\n" "# Replace x.x.x.x with the IP address of a public DNS server\n" "# and repeat for each DNS server in /etc/resolv.conf\n" "$cmd 00110 allow tcp from any to x.x.x.x 53 out via $pif setup keep-state\n" "$cmd 00111 allow udp from any to x.x.x.x 53 out via $pif keep-state\n" msgstr "" "# Allow access to public DNS\n" "# Replace x.x.x.x with the IP address of a public DNS server\n" "# and repeat for each DNS server in /etc/resolv.conf\n" "$cmd 00110 allow tcp from any to x.x.x.x 53 out via $pif setup keep-state\n" "$cmd 00111 allow udp from any to x.x.x.x 53 out via $pif keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1328 #, no-wrap msgid "" "# Allow access to ISP's DHCP server for cable/DSL configurations.\n" "# Use the first rule and check log for IP address.\n" "# Then, uncomment the second rule, input the IP address, and delete the first rule\n" "$cmd 00120 allow log udp from any to any 67 out via $pif keep-state\n" "#$cmd 00120 allow udp from any to x.x.x.x 67 out via $pif keep-state\n" msgstr "" "# Allow access to ISP's DHCP server for cable/DSL configurations.\n" "# Use the first rule and check log for IP address.\n" "# Then, uncomment the second rule, input the IP address, and delete the first rule\n" "$cmd 00120 allow log udp from any to any 67 out via $pif keep-state\n" "#$cmd 00120 allow udp from any to x.x.x.x 67 out via $pif keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1332 #, no-wrap msgid "" "# Allow outbound HTTP and HTTPS connections\n" "$cmd 00200 allow tcp from any to any 80 out via $pif setup keep-state\n" "$cmd 00220 allow tcp from any to any 443 out via $pif setup keep-state\n" msgstr "" "# Allow outbound HTTP and HTTPS connections\n" "$cmd 00200 allow tcp from any to any 80 out via $pif setup keep-state\n" "$cmd 00220 allow tcp from any to any 443 out via $pif setup keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1336 #, no-wrap msgid "" "# Allow outbound email connections\n" "$cmd 00230 allow tcp from any to any 25 out via $pif setup keep-state\n" "$cmd 00231 allow tcp from any to any 110 out via $pif setup keep-state\n" msgstr "" "# Allow outbound email connections\n" "$cmd 00230 allow tcp from any to any 25 out via $pif setup keep-state\n" "$cmd 00231 allow tcp from any to any 110 out via $pif setup keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1339 #, no-wrap msgid "" "# Allow outbound ping\n" "$cmd 00250 allow icmp from any to any out via $pif keep-state\n" msgstr "" "# Allow outbound ping\n" "$cmd 00250 allow icmp from any to any out via $pif keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1342 #, no-wrap msgid "" "# Allow outbound NTP\n" "$cmd 00260 allow udp from any to any 123 out via $pif keep-state\n" msgstr "" "# Allow outbound NTP\n" "$cmd 00260 allow udp from any to any 123 out via $pif keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1345 #, no-wrap msgid "" "# Allow outbound SSH\n" "$cmd 00280 allow tcp from any to any 22 out via $pif setup keep-state\n" msgstr "" "# Allow outbound SSH\n" "$cmd 00280 allow tcp from any to any 22 out via $pif setup keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1348 #, no-wrap msgid "" "# deny and log all other outbound connections\n" "$cmd 00299 deny log all from any to any out via $pif\n" msgstr "" "# deny and log all other outbound connections\n" "$cmd 00299 deny log all from any to any out via $pif\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1353 msgid "" "The next set of rules controls connections from Internet hosts to the " "internal network. It starts by denying packets typically associated with " "attacks and then explicitly allows specific types of connections. All the " "authorized services that originate from the Internet use `limit` to prevent " "flooding." msgstr "" "Следующий набор правил управляет соединениями от хостов Интернета к " "внутренней сети. Он начинается с запрета пакетов, обычно связанных с " "атаками, а затем явно разрешает определённые типы соединений. Все " "авторизованные сервисы, поступающие из Интернета, используют `limit` для " "предотвращения перегрузки." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1366 #, no-wrap msgid "" "# Deny all inbound traffic from non-routable reserved address spaces\n" "$cmd 00300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP\n" "$cmd 00301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP\n" "$cmd 00302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP\n" "$cmd 00303 deny all from 127.0.0.0/8 to any in via $pif #loopback\n" "$cmd 00304 deny all from 0.0.0.0/8 to any in via $pif #loopback\n" "$cmd 00305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config\n" "$cmd 00306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs\n" "$cmd 00307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster interconnect\n" "$cmd 00308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast\n" msgstr "" "# Deny all inbound traffic from non-routable reserved address spaces\n" "$cmd 00300 deny all from 192.168.0.0/16 to any in via $pif #RFC 1918 private IP\n" "$cmd 00301 deny all from 172.16.0.0/12 to any in via $pif #RFC 1918 private IP\n" "$cmd 00302 deny all from 10.0.0.0/8 to any in via $pif #RFC 1918 private IP\n" "$cmd 00303 deny all from 127.0.0.0/8 to any in via $pif #loopback\n" "$cmd 00304 deny all from 0.0.0.0/8 to any in via $pif #loopback\n" "$cmd 00305 deny all from 169.254.0.0/16 to any in via $pif #DHCP auto-config\n" "$cmd 00306 deny all from 192.0.2.0/24 to any in via $pif #reserved for docs\n" "$cmd 00307 deny all from 204.152.64.0/23 to any in via $pif #Sun cluster interconnect\n" "$cmd 00308 deny all from 224.0.0.0/3 to any in via $pif #Class D & E multicast\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1369 #, no-wrap msgid "" "# Deny public pings\n" "$cmd 00310 deny icmp from any to any in via $pif\n" msgstr "" "# Deny public pings\n" "$cmd 00310 deny icmp from any to any in via $pif\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1372 #, no-wrap msgid "" "# Deny ident\n" "$cmd 00315 deny tcp from any to any 113 in via $pif\n" msgstr "" "# Deny ident\n" "$cmd 00315 deny tcp from any to any 113 in via $pif\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1378 #, no-wrap msgid "" "# Deny all Netbios services.\n" "$cmd 00320 deny tcp from any to any 137 in via $pif\n" "$cmd 00321 deny tcp from any to any 138 in via $pif\n" "$cmd 00322 deny tcp from any to any 139 in via $pif\n" "$cmd 00323 deny tcp from any to any 81 in via $pif\n" msgstr "" "# Deny all Netbios services.\n" "$cmd 00320 deny tcp from any to any 137 in via $pif\n" "$cmd 00321 deny tcp from any to any 138 in via $pif\n" "$cmd 00322 deny tcp from any to any 139 in via $pif\n" "$cmd 00323 deny tcp from any to any 81 in via $pif\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1381 #, no-wrap msgid "" "# Deny fragments\n" "$cmd 00330 deny all from any to any frag in via $pif\n" msgstr "" "# Deny fragments\n" "$cmd 00330 deny all from any to any frag in via $pif\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1384 #, no-wrap msgid "" "# Deny ACK packets that did not match the dynamic rule table\n" "$cmd 00332 deny tcp from any to any established in via $pif\n" msgstr "" "# Deny ACK packets that did not match the dynamic rule table\n" "$cmd 00332 deny tcp from any to any established in via $pif\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1388 #, no-wrap msgid "" "# Allow traffic from ISP's DHCP server.\n" "# Replace x.x.x.x with the same IP address used in rule 00120.\n" "#$cmd 00360 allow udp from any to x.x.x.x 67 in via $pif keep-state\n" msgstr "" "# Allow traffic from ISP's DHCP server.\n" "# Replace x.x.x.x with the same IP address used in rule 00120.\n" "#$cmd 00360 allow udp from any to x.x.x.x 67 in via $pif keep-state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1391 #, no-wrap msgid "" "# Allow HTTP connections to internal web server\n" "$cmd 00400 allow tcp from any to me 80 in via $pif setup limit src-addr 2\n" msgstr "" "# Allow HTTP connections to internal web server\n" "$cmd 00400 allow tcp from any to me 80 in via $pif setup limit src-addr 2\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1394 #, no-wrap msgid "" "# Allow inbound SSH connections\n" "$cmd 00410 allow tcp from any to me 22 in via $pif setup limit src-addr 2\n" msgstr "" "# Allow inbound SSH connections\n" "$cmd 00410 allow tcp from any to me 22 in via $pif setup limit src-addr 2\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1397 #, no-wrap msgid "" "# Reject and log all other incoming connections\n" "$cmd 00499 deny log all from any to any in via $pif\n" msgstr "" "# Reject and log all other incoming connections\n" "$cmd 00499 deny log all from any to any in via $pif\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1400 msgid "" "The last rule logs all packets that do not match any of the rules in the " "ruleset:" msgstr "" "Последнее правило записывает в журнал информацию о всех пакетах, которые не " "соответствуют ни одному из правил в наборе правил:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1405 #, no-wrap msgid "" "# Everything else is denied and logged\n" "$cmd 00999 deny log all from any to any\n" msgstr "" "# Everything else is denied and logged\n" "$cmd 00999 deny log all from any to any\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1408 #, no-wrap msgid "In-kernel NAT" msgstr "NAT в ядре системы" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1413 msgid "" "FreeBSD's IPFW firewall has two implementations of NAT: the userland " "implementation man:natd[8], and the more recent in-kernel NAT " "implementation. Both work in conjunction with IPFW to provide network " "address translation. This can be used to provide an Internet Connection " "Sharing solution so that several internal computers can connect to the " "Internet using a single public IP address." msgstr "" "Межсетевой экран IPFW в FreeBSD имеет две реализации NAT: реализацию в " "пользовательском пространстве man:natd[8] и более новую реализацию NAT в " "ядре. Обе работают совместно с IPFW для преобразования сетевых адресов. Это " "можно использовать для организации общего доступа в Интернет, чтобы " "несколько внутренних компьютеров могли подключаться к Интернету, используя " "один публичный IP-адрес." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1417 msgid "" "To do this, the FreeBSD machine connected to the Internet must act as a " "gateway. This system must have two NICs, where one is connected to the " "Internet and the other is connected to the internal LAN. Each machine " "connected to the LAN should be assigned an IP address in the private network " "space, as defined by https://www.ietf.org/rfc/rfc1918.txt[RFC 1918]." msgstr "" "Для этого машина FreeBSD, подключённая к Интернету, должна выступать в роли " "шлюза. Эта система должна иметь две сетевые карты (NIC), где одна подключена " "к Интернету, а другая — к внутренней локальной сети (LAN). Каждой машине в " "LAN должен быть назначен IP-адрес из частного адресного пространства, как " "определено в https://www.ietf.org/rfc/rfc1918.txt[RFC 1918]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1420 msgid "" "Some additional configuration is needed in order to enable the in-kernel NAT " "facility of IPFW. To enable in-kernel NAT support at boot time, the " "following must be set in [.filename]#/etc/rc.conf#:" msgstr "" "Для включения встроенной в ядро функции NAT в IPFW требуется дополнительная " "настройка. Чтобы поддержка NAT на уровне ядра включалась при загрузке, " "необходимо добавить следующие параметры в [.filename]#/etc/rc.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1426 #, no-wrap msgid "" "gateway_enable=\"YES\"\n" "firewall_enable=\"YES\"\n" "firewall_nat_enable=\"YES\"\n" msgstr "" "gateway_enable=\"YES\"\n" "firewall_enable=\"YES\"\n" "firewall_nat_enable=\"YES\"\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1432 msgid "" "When `firewall_nat_enable` is set but `firewall_enable` is not, it will have " "no effect and do nothing. This is because the in-kernel NAT implementation " "is only compatible with IPFW." msgstr "" "Когда `firewall_nat_enable` установлен, но `firewall_enable` нет, это не " "будет иметь эффекта и ничего не сделает. Это связано с тем, что реализация " "NAT в ядре совместима только с IPFW." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1439 msgid "" "When the ruleset contains stateful rules, the positioning of the NAT rule is " "critical and the `skipto` action is used. The `skipto` action requires a " "rule number so that it knows which rule to jump to. The example below " "builds upon the firewall ruleset shown in the previous section. It adds " "some additional entries and modifies some existing rules in order to " "configure the firewall for in-kernel NAT. It starts by adding some " "additional variables which represent the rule number to skip to, the `keep-" "state` option, and a list of TCP ports which will be used to reduce the " "number of rules." msgstr "" "Когда набор правил содержит правила с отслеживанием состояния, " "позиционирование правила NAT критически важно, и используется действие " "`skipto`. Действие `skipto` требует указания номера правила, чтобы знать, к " "какому правилу перейти. В приведённом ниже примере расширяется набор правил " "межсетевого экрана, показанный в предыдущем разделе. В него добавлены " "некоторые новые записи и изменены существующие правила для настройки " "межсетевого экрана с поддержкой NAT, встроенного в ядро. Начинается он с " "добавления дополнительных переменных, представляющих номер правила для " "перехода, опцию `keep-state` и список TCP-портов, который будет " "использоваться для сокращения количества правил." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1449 #, no-wrap msgid "" "#!/bin/sh\n" "ipfw -q -f flush\n" "cmd=\"ipfw -q add\"\n" "skip=\"skipto 1000\"\n" "pif=dc0\n" "ks=\"keep-state\"\n" "good_tcpo=\"22,25,37,53,80,443,110\"\n" msgstr "" "#!/bin/sh\n" "ipfw -q -f flush\n" "cmd=\"ipfw -q add\"\n" "skip=\"skipto 1000\"\n" "pif=dc0\n" "ks=\"keep-state\"\n" "good_tcpo=\"22,25,37,53,80,443,110\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1454 msgid "" "With in-kernel NAT it is necessary to disable TCP segmentation offloading " "(TSO) due to the architecture of man:libalias[3], a library implemented as a " "kernel module to provide the in-kernel NAT facility of IPFW. TSO can be " "disabled on a per network interface basis using man:ifconfig[8] or on a " "system wide basis using man:sysctl[8]. To disable TSO system wide, the " "following must be set it [.filename]#/etc/sysctl.conf#:" msgstr "" "При использовании NAT в ядре необходимо отключить аппаратную сегментацию TCP " "(TSO) из-за архитектуры man:libalias[3] — библиотеки, реализованной в виде " "модуля ядра для обеспечения функциональности NAT в IPFW. TSO можно отключить " "для каждого сетевого интерфейса с помощью man:ifconfig[8] или для всей " "системы с помощью man:sysctl[8]. Чтобы отключить TSO для всей системы, " "необходимо добавить следующие настройки в [.filename]#/etc/sysctl.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1458 #, no-wrap msgid "net.inet.tcp.tso=\"0\"\n" msgstr "net.inet.tcp.tso=\"0\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1467 msgid "" "A NAT instance will also be configured. It is possible to have multiple NAT " "instances each with their own configuration. For this example only one NAT " "instance is needed, NAT instance number 1. The configuration can take a few " "options such as: `if` which indicates the public interface, `same_ports` " "which takes care that aliased ports and local port numbers are mapped the " "same, `unreg_only` will result in only unregistered (private) address spaces " "to be processed by the NAT instance, and `reset` which will help to keep a " "functioning NAT instance even when the public IP address of the IPFW machine " "changes. For all possible options that can be passed to a single NAT " "instance configuration consult man:ipfw[8]. When configuring a stateful " "NATing firewall, it is necessary to allow translated packets to be " "reinjected in the firewall for further processing. This can be achieved by " "disabling `one_pass` behavior at the start of the firewall script." msgstr "" "Будет также настроен экземпляр NAT. Возможно иметь несколько экземпляров " "NAT, каждый со своей конфигурацией. Для этого примера нужен только один " "экземпляр NAT — экземпляр NAT номер 1. Конфигурация может принимать " "несколько опций, таких как: `if`, указывающий публичный интерфейс, " "`same_ports`, обеспечивающий одинаковое отображение алиасов портов и " "локальных номеров портов, `unreg_only`, приводящий к обработке только " "незарегистрированных (частных) адресных пространств экземпляром NAT, и " "`reset`, который помогает поддерживать работоспособность экземпляра NAT даже " "при изменении публичного IP-адреса машины с IPFW. Для всех возможных опций, " "которые могут быть переданы в конфигурацию отдельного экземпляра NAT, " "обратитесь к man:ipfw[8]. При настройке межсетевого экрана с NAT и " "отслеживанием состояний необходимо разрешить повторное внедрение " "преобразованных пакетов в межсетевой экран для дальнейшей обработки. Это " "можно достичь, отключив поведение `one_pass` в начале скрипта межсетевого " "экрана." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1472 #, no-wrap msgid "" "ipfw disable one_pass\n" "ipfw -q nat 1 config if $pif same_ports unreg_only reset\n" msgstr "" "ipfw disable one_pass\n" "ipfw -q nat 1 config if $pif same_ports unreg_only reset\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1478 msgid "" "The inbound NAT rule is inserted _after_ the two rules which allow all " "traffic on the trusted and loopback interfaces and after the reassemble rule " "but _before_ the `check-state` rule. It is important that the rule number " "selected for this NAT rule, in this example `100`, is higher than the first " "three rules and lower than the `check-state` rule. Furthermore, because of " "the behavior of in-kernel NAT it is advised to place a reassemble rule just " "before the first NAT rule and after the rules that allow traffic on trusted " "interface. Normally, IP fragmentation should not happen, but when dealing " "with IPSEC/ESP/GRE tunneling traffic it might and the reassembling of " "fragments is necessary before handing the complete packet over to the in-" "kernel NAT facility." msgstr "" "Правило входящего NAT вставляется _после_ двух правил, которые разрешают " "весь трафик на доверенных интерфейсах и интерфейсе loopback, а также после " "правила пересборки, но _до_ правила `check-state`. Важно, чтобы номер " "правила, выбранный для этого NAT-правила (в данном примере `100`), был " "больше, чем первые три правила, и меньше, чем правило `check-state`. Кроме " "того, из-за особенностей работы встроенного NAT рекомендуется размещать " "правило пересборки непосредственно перед первым NAT-правилом и после правил, " "разрешающих трафик на доверенных интерфейсах. Обычно фрагментация IP-пакетов " "не должна происходить, но при работе с туннелированным трафиком IPSEC/ESP/" "GRE это возможно, и пересборка фрагментов необходима перед передачей полного " "пакета встроенному механизму NAT." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1482 msgid "" "The reassemble rule was not needed with userland man:natd[8] because the " "internal workings of the IPFW `divert` action already takes care of " "reassembling packets before delivery to the socket as also stated in man:" "ipfw[8]." msgstr "" "Правило пересборки не требовалось при использовании пользовательского демона " "man:natd[8], поскольку внутренняя работа действия `divert` в man:ipfw[8] уже " "обеспечивает пересборку пакетов перед их передачей в сокет, как также " "указано в man:ipfw[8]." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1485 msgid "" "The NAT instance and rule number used in this example does not match with " "the default NAT instance and rule number created by [.filename]#rc." "firewall#. [.filename]#rc.firewall# is a script that sets up the default " "firewall rules present in FreeBSD." msgstr "" "Экземпляр NAT и номер правила, используемые в этом примере, не совпадают с " "экземпляром NAT и номером правила, созданными по умолчанию в [.filename]#rc." "firewall#. [.filename]#rc.firewall# — это скрипт, который настраивает " "правила межсетевого экрана по умолчанию в FreeBSD." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1495 #, no-wrap msgid "" "$cmd 005 allow all from any to any via xl0 # exclude LAN traffic\n" "$cmd 010 allow all from any to any via lo0 # exclude loopback traffic\n" "$cmd 099 reass all from any to any in # reassemble inbound packets\n" "$cmd 100 nat 1 ip from any to any in via $pif # NAT any inbound packets\n" "# Allow the packet through if it has an existing entry in the dynamic rules table\n" "$cmd 101 check-state\n" msgstr "" "$cmd 005 allow all from any to any via xl0 # exclude LAN traffic\n" "$cmd 010 allow all from any to any via lo0 # exclude loopback traffic\n" "$cmd 099 reass all from any to any in # reassemble inbound packets\n" "$cmd 100 nat 1 ip from any to any in via $pif # NAT any inbound packets\n" "# Allow the packet through if it has an existing entry in the dynamic rules table\n" "$cmd 101 check-state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1499 msgid "" "The outbound rules are modified to replace the `allow` action with the `" "$skip` variable, indicating that rule processing will continue at rule " "`1000`. The seven `tcp` rules have been replaced by rule `125` as the `" "$good_tcpo` variable contains the seven allowed outbound ports." msgstr "" "Правила для исходящего трафика изменены, чтобы заменить действие `allow` на " "переменную `$skip`, указывая, что обработка правил продолжится с правила " "`1000`. Семь правил для `tcp` заменены правилом `125`, так как переменная `" "$good_tcpo` содержит семь разрешённых исходящих портов." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1503 msgid "" "Remember that IPFW's performance is largely determined by the number of " "rules present in the ruleset." msgstr "" "Помните, что производительность IPFW в значительной степени определяется " "количеством правил в наборе правил межсетевого экрана." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1512 #, no-wrap msgid "" "# Authorized outbound packets\n" "$cmd 120 $skip udp from any to x.x.x.x 53 out via $pif $ks\n" "$cmd 121 $skip udp from any to x.x.x.x 67 out via $pif $ks\n" "$cmd 125 $skip tcp from any to any $good_tcpo out via $pif setup $ks\n" "$cmd 130 $skip icmp from any to any out via $pif $ks\n" msgstr "" "# Authorized outbound packets\n" "$cmd 120 $skip udp from any to x.x.x.x 53 out via $pif $ks\n" "$cmd 121 $skip udp from any to x.x.x.x 67 out via $pif $ks\n" "$cmd 125 $skip tcp from any to any $good_tcpo out via $pif setup $ks\n" "$cmd 130 $skip icmp from any to any out via $pif $ks\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1518 msgid "" "The inbound rules remain the same, except for the very last rule which " "removes the `via $pif` in order to catch both inbound and outbound rules. " "The NAT rule must follow this last outbound rule, must have a higher number " "than that last rule, and the rule number must be referenced by the `skipto` " "action. In this ruleset, rule number `1000` handles passing all packets to " "our configured instance for NAT processing. The next rule allows any packet " "which has undergone NAT processing to pass." msgstr "" "Правила для входящего трафика остаются такими же, за исключением самого " "последнего правила, в котором удаляется `via $pif`, чтобы охватить как " "входящие, так и исходящие правила. Правило NAT должно следовать за этим " "последним исходящим правилом, иметь номер выше, чем у последнего правила, и " "номер правила должен быть указан в действии `skipto`. В этом наборе правил " "правило номер `1000` обрабатывает передачу всех пакетов в настроенный " "экземпляр для обработки NAT. Следующее правило разрешает прохождение любого " "пакета, прошедшего обработку NAT." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1524 #, no-wrap msgid "" "$cmd 999 deny log all from any to any\n" "$cmd 1000 nat 1 ip from any to any out via $pif # skipto location for outbound stateful rules\n" "$cmd 1001 allow ip from any to any\n" msgstr "" "$cmd 999 deny log all from any to any\n" "$cmd 1000 nat 1 ip from any to any out via $pif # skipto location for outbound stateful rules\n" "$cmd 1001 allow ip from any to any\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1527 msgid "" "In this example, rules `100`, `101`, `125`, `1000`, and `1001` control the " "address translation of the outbound and inbound packets so that the entries " "in the dynamic state table always register the private LANIP address." msgstr "" "В этом примере правила `100`, `101`, `125`, `1000` и `1001` управляют " "преобразованием адресов исходящих и входящих пакетов, чтобы записи в таблице " "динамического состояния всегда указывали на частный LANIP-адрес." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1539 msgid "" "Consider an internal web browser which initializes a new outbound HTTP " "session over port 80. When the first outbound packet enters the firewall, " "it does not match rule `100` because it is headed out rather than in. It " "passes rule `101` because this is the first packet and it has not been " "posted to the dynamic state table yet. The packet finally matches rule " "`125` as it is outbound on an allowed port and has a source IP address from " "the internal LAN. On matching this rule, two actions take place. First, " "the `keep-state` action adds an entry to the dynamic state table and the " "specified action, `skipto rule 1000`, is executed. Next, the packet " "undergoes NAT and is sent out to the Internet. This packet makes its way to " "the destination web server, where a response packet is generated and sent " "back. This new packet enters the top of the ruleset. It matches rule `100` " "and has its destination IP address mapped back to the original internal " "address. It then is processed by the `check-state` rule, is found in the " "table as an existing session, and is released to the LAN." msgstr "" "Рассмотрим внутренний веб-браузер, который инициирует новый исходящий HTTP-" "сеанс через порт 80. Когда первый исходящий пакет попадает в межсетевой " "экран, он не соответствует правилу `100`, так как направлен наружу, а не " "внутрь. Он проходит правило `101`, так как это первый пакет и он ещё не был " "добавлен в таблицу динамического состояния. В итоге пакет соответствует " "правилу `125`, так как он исходящий на разрешённом порту и имеет исходный IP-" "адрес из внутренней LAN. При соответствии этому правилу выполняются два " "действия. Во-первых, действие `keep-state` добавляет запись в таблицу " "динамического состояния, и выполняется указанное действие `skipto rule " "1000`. Затем пакет проходит NAT и отправляется в Интернет. Этот пакет " "достигает целевого веб-сервера, где генерируется и отправляется обратно " "ответный пакет. Этот новый пакет попадает в начало набора правил. Он " "соответствует правилу `100`, и его IP-адрес назначения преобразуется обратно " "в исходный внутренний адрес. Затем он обрабатывается правилом `check-state`, " "обнаруживается в таблице как существующий сеанс и передаётся в LAN." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1544 msgid "" "On the inbound side, the ruleset has to deny bad packets and allow only " "authorized services. A packet which matches an inbound rule is posted to " "the dynamic state table and the packet is released to the LAN. The packet " "generated as a response is recognized by the `check-state` rule as belonging " "to an existing session. It is then sent to rule `1000` to undergo NAT " "before being released to the outbound interface." msgstr "" "На входящей стороне набор правил должен блокировать плохие пакеты и " "разрешать только авторизованные сервисы. Пакет, соответствующий входящему " "правилу, помещается в таблицу динамического состояния и выпускается в " "локальную сеть. Пакет, сгенерированный в ответ, распознаётся правилом `check-" "state` как принадлежащий существующему сеансу. Затем он отправляется к " "правилу `1000` для выполнения NAT перед выпуском на исходящий интерфейс." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1552 msgid "" "Transitioning from userland man:natd[8] to in-kernel NAT might appear " "seamless at first but there is small catch. When using the GENERIC kernel, " "IPFW will load the [.filename]#libalias.ko# kernel module, when " "`firewall_nat_enable` is enabled in [.filename]#/etc/rc.conf#. The [." "filename]#libalias.ko# kernel module only provides basic NAT functionality, " "whereas the userland implementation man:natd[8] has all NAT functionality " "available in its userland library without any extra configuration. All " "functionality refers to the following kernel modules that can additionally " "be loaded when needed besides the standard [.filename]#libalias.ko# kernel " "module: [.filename]#alias_ftp.ko#, [.filename]#alias_bbt.ko#, [." "filename]#skinny.ko#, [.filename]#irc.ko#, [.filename]#alias_pptp.ko# and [." "filename]#alias_smedia.ko# using the `kld_list` directive in [.filename]#/" "etc/rc.conf#. If a custom kernel is used, the full functionality of the " "userland library can be compiled in, in the kernel, using the `options " "LIBALIAS`." msgstr "" "Переход от пользовательской реализации man:natd[8] к NAT в ядре может " "сначала показаться простым, но есть небольшой нюанс. При использовании " "GENERIC ядра IPFW загрузит модуль ядра [.filename]#libalias.ko#, когда в [." "filename]#/etc/rc.conf# включена опция `firewall_nat_enable`. Модуль ядра [." "filename]#libalias.ko# предоставляет только базовую функциональность NAT, в " "то время как пользовательская реализация man:natd[8] имеет все функции NAT в " "своей пользовательской библиотеке без дополнительной настройки. Под всей " "функциональностью подразумеваются следующие модули ядра, которые могут быть " "дополнительно загружены при необходимости, помимо стандартного модуля [." "filename]#libalias.ko#: [.filename]#alias_ftp.ko#, [.filename]#alias_bbt." "ko#, [.filename]#skinny.ko#, [.filename]#irc.ko#, [.filename]#alias_pptp.ko# " "и [.filename]#alias_smedia.ko# с использованием директивы `kld_list` в [." "filename]#/etc/rc.conf#. Если используется собственное ядро, полная " "функциональность пользовательской библиотеки может быть встроена в ядро с " "помощью опции `options LIBALIAS`." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:1554 #, no-wrap msgid "Port Redirection" msgstr "Перенаправление портов" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1560 msgid "" "The drawback with NAT in general is that the LAN clients are not accessible " "from the Internet. Clients on the LAN can make outgoing connections to the " "world but cannot receive incoming ones. This presents a problem if trying " "to run Internet services on one of the LAN client machines. A simple way " "around this is to redirect selected Internet ports on the NAT providing " "machine to a LAN client." msgstr "" "Недостаток NAT в целом заключается в том, что клиенты в локальной сети " "недоступны из Интернета. Клиенты в локальной сети могут устанавливать " "исходящие соединения с внешним миром, но не могут принимать входящие. Это " "создаёт проблему, если необходимо запустить интернет-сервисы на одной из " "машин-клиентов локальной сети. Простое решение этой проблемы — " "перенаправление определённых портов из Интернета на машине, предоставляющей " "NAT, к клиенту в локальной сети." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1563 msgid "" "For example, an IRC server runs on client `A` and a web server runs on " "client `B`. For this to work properly, connections received on ports 6667 " "(IRC) and 80 (HTTP) must be redirected to the respective machines." msgstr "" "Например, сервер IRC работает на клиенте `A`, а веб-сервер — на клиенте `B`. " "Для правильной работы соединения, полученные на портах 6667 (IRC) и 80 " "(HTTP), должны быть перенаправлены на соответствующие машины." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1567 msgid "" "With in-kernel NAT all configuration is done in the NAT instance " "configuration. For a full list of options that an in-kernel NAT instance " "can use, consult man:ipfw[8]. The IPFW syntax follows the syntax of natd. " "The syntax for `redirect_port` is as follows:" msgstr "" "С встроенным в ядро NAT вся конфигурация выполняется в настройках экземпляра " "NAT. Полный список параметров, которые может использовать экземпляр " "встроенного в ядро NAT, приведен в man:ipfw[8]. Синтаксис IPFW соответствует " "синтаксису natd. Синтаксис для `redirect_port` выглядит следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1573 #, no-wrap msgid "" "redirect_port proto targetIP:targetPORT[-targetPORT]\n" " [aliasIP:]aliasPORT[-aliasPORT]\n" " [remoteIP[:remotePORT[-remotePORT]]]\n" msgstr "" "redirect_port proto targetIP:targetPORT[-targetPORT]\n" " [aliasIP:]aliasPORT[-aliasPORT]\n" " [remoteIP[:remotePORT[-remotePORT]]]\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1576 msgid "To configure the above example setup, the arguments should be:" msgstr "Для настройки приведённой выше конфигурации аргументы должны быть:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1581 #, no-wrap msgid "" "redirect_port tcp 192.168.0.2:6667 6667\n" "redirect_port tcp 192.168.0.3:80 80\n" msgstr "" "redirect_port tcp 192.168.0.2:6667 6667\n" "redirect_port tcp 192.168.0.3:80 80\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1584 msgid "" "After adding these arguments to the configuration of NAT instance 1 in the " "above ruleset, the TCP ports will be port forwarded to the LAN client " "machines running the IRC and HTTP services." msgstr "" "После добавления этих аргументов в конфигурацию NAT-экземпляра 1 в " "приведённом выше наборе правил, TCP-порты будут проброшены на клиентские " "машины в локальной сети, на которых работают службы IRC и HTTP." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1590 #, no-wrap msgid "" "ipfw -q nat 1 config if $pif same_ports unreg_only reset \\\n" " redirect_port tcp 192.168.0.2:6667 6667 \\\n" " redirect_port tcp 192.168.0.3:80 80\n" msgstr "" "ipfw -q nat 1 config if $pif same_ports unreg_only reset \\\n" " redirect_port tcp 192.168.0.2:6667 6667 \\\n" " redirect_port tcp 192.168.0.3:80 80\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1594 msgid "" "Port ranges over individual ports can be indicated with `redirect_port`. " "For example, _tcp 192.168.0.2:2000-3000 2000-3000_ would redirect all " "connections received on ports 2000 to 3000 to ports 2000 to 3000 on client " "`A`." msgstr "" "Диапазоны портов вместо отдельных портов могут быть указаны с помощью " "`redirect_port`. Например, _tcp 192.168.0.2:2000-3000 2000-3000_ " "перенаправит все соединения, полученные на портах с 2000 по 3000, на порты с " "2000 по 3000 клиента `A`." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:1595 #, no-wrap msgid "Address Redirection" msgstr "Перенаправление адресов" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1601 msgid "" "Address redirection is useful if more than one IP address is available. " "Each LAN client can be assigned its own external IP address by man:ipfw[8], " "which will then rewrite outgoing packets from the LAN clients with the " "proper external IP address and redirects all traffic incoming on that " "particular IP address back to the specific LAN client. This is also known " "as static NAT. For example, if IP addresses `128.1.1.1`, `128.1.1.2`, and " "`128.1.1.3` are available, `128.1.1.1` can be used as the man:ipfw[8] " "machine's external IP address, while `128.1.1.2` and `128.1.1.3` are " "forwarded back to LAN clients `A` and `B`." msgstr "" "Перенаправление адресов полезно, если доступно более одного IP-адреса. " "Каждому клиенту в локальной сети может быть назначен собственный внешний IP-" "адрес с помощью man:ipfw[8], который затем перезаписывает исходящие пакеты " "от клиентов локальной сети с соответствующим внешним IP-адресом и " "перенаправляет весь входящий трафик для этого конкретного IP-адреса обратно " "к определённому клиенту локальной сети. Это также известно как статический " "NAT. Например, если доступны IP-адреса `128.1.1.1`, `128.1.1.2` и " "`128.1.1.3`, то `128.1.1.1` может использоваться как внешний IP-адрес машины " "с man:ipfw[8], а `128.1.1.2` и `128.1.1.3` перенаправляются обратно клиентам " "`A` и `B` локальной сети." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1603 msgid "" "The `redirect_addr` syntax is as below, where `localIP` is the internal IP " "address of the LAN client, and `publicIP` the external IP address " "corresponding to the LAN client." msgstr "" "Синтаксис `redirect_addr` приведён ниже, где `localIP` — это внутренний IP-" "адрес клиента в локальной сети, а `publicIP` — внешний IP-адрес, " "соответствующий клиенту в локальной сети." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1607 #, no-wrap msgid "redirect_addr localIP publicIP\n" msgstr "redirect_addr localIP publicIP\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1610 msgid "In the example, the arguments would read:" msgstr "В этом примере аргументы выглядели бы следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1615 #, no-wrap msgid "" "redirect_addr 192.168.0.2 128.1.1.2\n" "redirect_addr 192.168.0.3 128.1.1.3\n" msgstr "" "redirect_addr 192.168.0.2 128.1.1.2\n" "redirect_addr 192.168.0.3 128.1.1.3\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1619 msgid "" "Like `redirect_port`, these arguments are placed in a NAT instance " "configuration. With address redirection, there is no need for port " "redirection, as all data received on a particular IP address is redirected." msgstr "" "Как и `redirect_port`, эти аргументы размещаются в конфигурации экземпляра " "NAT. При перенаправлении адреса нет необходимости в перенаправлении портов, " "так как перенаправляются все данные, полученные на определённый IP-адрес." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1622 msgid "" "The external IP addresses on the man:ipfw[8] machine must be active and " "aliased to the external interface. Refer to man:rc.conf[5] for details." msgstr "" "Внешние IP-адреса на машине с man:ipfw[8] должны быть активны и назначены " "как псевдонимы внешнему интерфейсу. Подробности см. в man:rc.conf[5]." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:1623 #, no-wrap msgid "Userspace NAT" msgstr "Пользовательский NAT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1627 msgid "" "Let us start with a statement: the userspace NAT implementation: man:" "natd[8], has more overhead than in-kernel NAT. For man:natd[8] to translate " "packets, the packets have to be copied from the kernel to userspace and back " "which brings in extra overhead that is not present with in-kernel NAT." msgstr "" "Начнем с утверждения: реализация NAT в пользовательском пространстве: man:" "natd[8], имеет больше накладных расходов, чем NAT в ядре. Для работы man:" "natd[8] по преобразованию пакетов, пакеты должны копироваться из ядра в " "пользовательское пространство и обратно, что создает дополнительные " "накладные расходы, отсутствующие при использовании NAT в ядре." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1631 msgid "" "To enable the userspace NAT daemon man:natd[8] at boot time, the following " "is a minimum configuration in [.filename]#/etc/rc.conf#. Where " "`natd_interface` is set to the name of the NIC attached to the Internet. " "The man:rc[8] script of man:natd[8] will automatically check if a dynamic IP " "address is used and configure itself to handle that." msgstr "" "Для включения демона NAT в пользовательском пространстве man:natd[8] при " "загрузке, следующая минимальная конфигурация должна быть добавлена в [." "filename]#/etc/rc.conf#. Параметр `natd_interface` должен быть установлен " "равным имени сетевого интерфейса, подключенного к Интернету. Скрипт man:" "rc[8] для man:natd[8] автоматически проверит, используется ли динамический " "IP-адрес, и настроит себя соответствующим образом." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1637 #, no-wrap msgid "" "gateway_enable=\"YES\"\n" "natd_enable=\"YES\"\n" "natd_interface=\"rl0\"\n" msgstr "" "gateway_enable=\"YES\"\n" "natd_enable=\"YES\"\n" "natd_interface=\"rl0\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1642 msgid "" "In general, the above ruleset as explained for in-kernel NAT can also be " "used together with man:natd[8]. The exceptions are the configuration of the " "in-kernel NAT instance `(ipfw -q nat 1 config ...)` which is not needed " "together with reassemble rule 99 because its functionality is included in " "the `divert` action. Rule number 100 and 1000 will have to change slightly " "as shown below." msgstr "" "В общем случае, приведённый выше набор правил, описанный для NAT в ядре, " "также может использоваться совместно с man:natd[8]. Исключениями являются " "настройка экземпляра NAT в ядре `(ipfw -q nat 1 config ...)`, которая не " "требуется вместе с правилом пересборки 99, так как его функциональность " "включена в действие `divert`. Правила 100 и 1000 необходимо немного " "изменить, как показано ниже." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1647 #, no-wrap msgid "" "$cmd 100 divert natd ip from any to any in via $pif\n" "$cmd 1000 divert natd ip from any to any out via $pif\n" msgstr "" "$cmd 100 divert natd ip from any to any in via $pif\n" "$cmd 1000 divert natd ip from any to any out via $pif\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1652 msgid "" "To configure port or address redirection, a similar syntax as with in-kernel " "NAT is used. Although, now, instead of specifying the configuration in our " "ruleset script like with in-kernel NAT, configuration of man:natd[8] is best " "done in a configuration file. To do this, an extra flag must be passed via " "[.filename]#/etc/rc.conf# which specifies the path of the configuration file." msgstr "" "Для настройки перенаправления портов или адресов используется синтаксис, " "аналогичный NAT в ядре. Однако, в отличие от настройки в скрипте набора " "правил, как в случае с NAT в ядре, конфигурацию man:natd[8] лучше выполнять " "в конфигурационном файле. Для этого необходимо передать дополнительный флаг " "через [.filename]#/etc/rc.conf#, который указывает путь к конфигурационному " "файлу." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1656 #, no-wrap msgid "natd_flags=\"-f /etc/natd.conf\"\n" msgstr "natd_flags=\"-f /etc/natd.conf\"\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1663 msgid "" "The specified file must contain a list of configuration options, one per " "line. For more information about the configuration file and possible " "variables, consult man:natd[8]. Below are two example entries, one per line:" msgstr "" "Указанный файл должен содержать список параметров конфигурации, по одному на " "строку. Для получения дополнительной информации о файле конфигурации и " "возможных переменных обратитесь к man:natd[8]. Ниже приведены два примера " "записей, по одному на строку:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1668 #, no-wrap msgid "" "redirect_port tcp 192.168.0.2:6667 6667\n" "redirect_addr 192.168.0.3 128.1.1.3\n" msgstr "" "redirect_port tcp 192.168.0.2:6667 6667\n" "redirect_addr 192.168.0.3 128.1.1.3\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1673 #, no-wrap msgid "The IPFW Command" msgstr "Команда IPFW" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1678 msgid "" "`ipfw` can be used to make manual, single rule additions or deletions to the " "active firewall while it is running. The problem with using this method is " "that all the changes are lost when the system reboots. It is recommended to " "instead write all the rules in a file and to use that file to load the rules " "at boot time and to replace the currently running firewall rules whenever " "that file changes." msgstr "" "`ipfw` можно использовать для ручного добавления или удаления отдельных " "правил в активный межсетевой экран во время его работы. Проблема этого " "метода в том, что все изменения теряются при перезагрузке системы. " "Рекомендуется вместо этого записывать все правила в файл и использовать его " "для загрузки правил при запуске системы, а также для замены текущих правил " "межсетевого экрана при изменении этого файла." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1682 msgid "" "`ipfw` is a useful way to display the running firewall rules to the console " "screen. The IPFW accounting facility dynamically creates a counter for each " "rule that counts each packet that matches the rule. During the process of " "testing a rule, listing the rule with its counter is one way to determine if " "the rule is functioning as expected." msgstr "" "`ipfw` — это полезный способ отображения текущих правил межсетевого экрана " "на экране консоли. Возможность учёта IPFW динамически создаёт счётчик для " "каждого правила, который подсчитывает каждый пакет, соответствующий правилу. " "В процессе тестирования правила, вывод правила с его счётчиком — это один из " "способов определить, работает ли правило так, как ожидается." #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1684 msgid "To list all the running rules in sequence:" msgstr "Чтобы вывести список всех активных правил в порядке их применения:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1688 #, no-wrap msgid "# ipfw list\n" msgstr "# ipfw list\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1691 msgid "" "To list all the running rules with a time stamp of when the last time the " "rule was matched:" msgstr "" "Для вывода всех активных правил с отметкой времени последнего совпадения " "правила:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1695 #, no-wrap msgid "# ipfw -t list\n" msgstr "# ipfw -t list\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1699 msgid "" "The next example lists accounting information and the packet count for " "matched rules along with the rules themselves. The first column is the rule " "number, followed by the number of matched packets and bytes, followed by the " "rule itself." msgstr "" "Следующий пример выводит информацию о сборе статистики и количество пакетов " "для совпавших правил вместе с самими правилами. Первый столбец — это номер " "правила, за которым следует количество совпавших пакетов и байтов, а затем " "само правило." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1703 #, no-wrap msgid "# ipfw -a list\n" msgstr "# ipfw -a list\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1706 msgid "To list dynamic rules in addition to static rules:" msgstr "Для отображения динамических правил вместе со статическими:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1710 #, no-wrap msgid "# ipfw -d list\n" msgstr "# ipfw -d list\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1713 msgid "To also show the expired dynamic rules:" msgstr "Чтобы также показать истекшие динамические правила:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1717 #, no-wrap msgid "# ipfw -d -e list\n" msgstr "# ipfw -d -e list\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1720 msgid "To zero the counters:" msgstr "Для обнуления счетчиков:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1724 #, no-wrap msgid "# ipfw zero\n" msgstr "# ipfw zero\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1727 msgid "To zero the counters for just the rule with number _NUM_:" msgstr "Обнулить счетчики только для правила с номером _NUM_:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1731 #, no-wrap msgid "# ipfw zero NUM\n" msgstr "# ipfw zero NUM\n" #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:1733 #, no-wrap msgid "Logging Firewall Messages" msgstr "Журналирование сообщений межсетевого экрана" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1740 msgid "" "Even with the logging facility enabled, IPFW will not generate any rule " "logging on its own. The firewall administrator decides which rules in the " "ruleset will be logged, and adds the `log` keyword to those rules. Normally " "only deny rules are logged. It is customary to duplicate the \"ipfw default " "deny everything\" rule with the `log` keyword included as the last rule in " "the ruleset. This way, it is possible to see all the packets that did not " "match any of the rules in the ruleset." msgstr "" "Даже при включенной функции журналирования, IPFW не будет самостоятельно " "генерировать записи о правилах. Администратор межсетевого экрана решает, " "какие правила в наборе правил будут записываться в журнал, и добавляет " "ключевое слово `log` к этим правилам. Обычно журналируются только правила с " "действием deny. Принято дублировать правило \"ipfw default deny everything\" " "с включенным ключевым словом `log` в качестве последнего правила в наборе. " "Таким образом, можно увидеть все пакеты, которые не соответствуют ни одному " "из правил в наборе." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1744 msgid "" "Logging is a two edged sword. If one is not careful, an over abundance of " "log data or a DoS attack can fill the disk with log files. Log messages are " "not only written to syslogd, but also are displayed on the root console " "screen and soon become annoying." msgstr "" "Журналирование — это обоюдоострый меч. Если не быть осторожным, переизбыток " "данных журналирования или атака типа DoS могут заполнить диск файлами " "журналов. Сообщения журнала записываются не только в syslogd, но и выводятся " "на корневую консоль, что быстро становится раздражающим." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1749 msgid "" "The `IPFIREWALL_VERBOSE_LIMIT=5` kernel option limits the number of " "consecutive messages sent to man:syslogd[8], concerning the packet matching " "of a given rule. When this option is enabled in the kernel, the number of " "consecutive messages concerning a particular rule is capped at the number " "specified. There is nothing to be gained from 200 identical log messages. " "With this option set to five, five consecutive messages concerning a " "particular rule would be logged to syslogd and the remainder identical " "consecutive messages would be counted and posted to syslogd with a phrase " "like the following:" msgstr "" "Опция ядра `IPFIREWALL_VERBOSE_LIMIT=5` ограничивает количество " "последовательных сообщений, отправляемых в man:syslogd[8], касающихся " "совпадения пакетов с заданным правилом. Когда эта опция включена в ядре, " "количество последовательных сообщений, касающихся определённого правила, " "ограничивается указанным числом. Нет никакой пользы от 200 одинаковых " "сообщений в журнале. При установке этого параметра в пять, пять " "последовательных сообщений, касающихся определённого правила, будут записаны " "в syslogd, а оставшиеся идентичные последовательные сообщения будут " "подсчитаны и отправлены в syslogd с фразой, подобной следующей:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1753 #, no-wrap msgid "last message repeated 45 times\n" msgstr "last message repeated 45 times\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1756 msgid "" "All logged packets messages are written by default to [.filename]#/var/log/" "security#, which is defined in [.filename]#/etc/syslog.conf#." msgstr "" "Все сообщения о зарегистрированных пакетах по умолчанию записываются в [." "filename]#/var/log/security#, что определено в [.filename]#/etc/syslog.conf#." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:1758 #, no-wrap msgid "Building a Rule Script" msgstr "Построение скрипта правил" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1764 msgid "" "Most experienced IPFW users create a file containing the rules and code them " "in a manner compatible with running them as a script. The major benefit of " "doing this is the firewall rules can be refreshed in mass without the need " "of rebooting the system to activate them. This method is convenient in " "testing new rules as the procedure can be executed as many times as needed. " "Being a script, symbolic substitution can be used for frequently used values " "to be substituted into multiple rules." msgstr "" "Большинство опытных пользователей IPFW создают файл, содержащий правила, и " "оформляют их таким образом, чтобы их можно было запускать как скрипт. " "Основное преимущество этого подхода заключается в том, что правила " "межсетевого экрана можно обновлять массово без необходимости перезагрузки " "системы для их активации. Этот метод удобен при тестировании новых правил, " "так как процедуру можно выполнять столько раз, сколько потребуется. Будучи " "скриптом, можно использовать символические подстановки для часто " "используемых значений, которые будут заменяться в нескольких правилах." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1769 msgid "" "This example script is compatible with the syntax used by the man:sh[1], man:" "csh[1], and man:tcsh[1] shells. Symbolic substitution fields are prefixed " "with a dollar sign ($). Symbolic fields do not have the $ prefix. The " "value to populate the symbolic field must be enclosed in double quotes " "(\"\")." msgstr "" "Синтаксис примера, приведённого ниже, совместим с синтаксисом, используемым " "оболочками man:sh[1], man:csh[1] и man:tcsh[1]. Поля символьной подстановки " "(переменные — один из видов полей подстановки, прим. перев.) начинаются со " "знака доллара ($). Символьные поля не имеют префикса $. Значение для " "заполнения символьного поля должно быть заключено в двойные кавычки (\"\")." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1771 msgid "Start the rules file like this:" msgstr "Начните файл правил следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1789 #, no-wrap msgid "" "############### start of example ipfw rules script #############\n" "#\n" "ipfw -q -f flush # Delete all rules\n" "# Set defaults\n" "oif=\"tun0\" # out interface\n" "odns=\"192.0.2.11\" # ISP's DNS server IP address\n" "cmd=\"ipfw -q add \" # build rule prefix\n" "ks=\"keep-state\" # just too lazy to key this each time\n" "$cmd 00500 check-state\n" "$cmd 00502 deny all from any to any frag\n" "$cmd 00501 deny tcp from any to any established\n" "$cmd 00600 allow tcp from any to any 80 out via $oif setup $ks\n" "$cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks\n" "$cmd 00611 allow udp from any to $odns 53 out via $oif $ks\n" "################### End of example ipfw rules script ############\n" msgstr "" "############### start of example ipfw rules script #############\n" "#\n" "ipfw -q -f flush # Delete all rules\n" "# Set defaults\n" "oif=\"tun0\" # out interface\n" "odns=\"192.0.2.11\" # ISP's DNS server IP address\n" "cmd=\"ipfw -q add \" # build rule prefix\n" "ks=\"keep-state\" # just too lazy to key this each time\n" "$cmd 00500 check-state\n" "$cmd 00502 deny all from any to any frag\n" "$cmd 00501 deny tcp from any to any established\n" "$cmd 00600 allow tcp from any to any 80 out via $oif setup $ks\n" "$cmd 00610 allow tcp from any to $odns 53 out via $oif setup $ks\n" "$cmd 00611 allow udp from any to $odns 53 out via $oif $ks\n" "################### End of example ipfw rules script ############\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1792 msgid "" "The rules are not important as the focus of this example is how the symbolic " "substitution fields are populated." msgstr "" "Правила не важны, так как цель этого примера — показать, как заполняются " "поля символьной подстановки." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1794 msgid "" "If the above example was in [.filename]#/etc/ipfw.rules#, the rules could be " "reloaded by the following command:" msgstr "" "Если приведённый выше пример находится в [.filename]#/etc/ipfw.rules#, " "правила можно перезагрузить следующей командой:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1798 #, no-wrap msgid "# sh /etc/ipfw.rules\n" msgstr "# sh /etc/ipfw.rules\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1801 msgid "" "[.filename]#/etc/ipfw.rules# can be located anywhere and the file can have " "any name." msgstr "" "[.filename]#/etc/ipfw.rules# может находиться в любом месте, и файл может " "иметь любое имя." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1803 msgid "The same thing could be accomplished by running these commands by hand:" msgstr "То же самое можно выполнить вручную, запустив следующие команды:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1813 #, no-wrap msgid "" "# ipfw -q -f flush\n" "# ipfw -q add check-state\n" "# ipfw -q add deny all from any to any frag\n" "# ipfw -q add deny tcp from any to any established\n" "# ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state\n" "# ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state\n" "# ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state\n" msgstr "" "# ipfw -q -f flush\n" "# ipfw -q add check-state\n" "# ipfw -q add deny all from any to any frag\n" "# ipfw -q add deny tcp from any to any established\n" "# ipfw -q add allow tcp from any to any 80 out via tun0 setup keep-state\n" "# ipfw -q add allow tcp from any to 192.0.2.11 53 out via tun0 setup keep-state\n" "# ipfw -q add 00611 allow udp from any to 192.0.2.11 53 out via tun0 keep-state\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1816 #, no-wrap msgid "IPFW Kernel Options" msgstr "Опции ядра для IPFW" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1820 msgid "" "In order to statically compile IPFW support into a custom kernel, refer to " "the instructions in crossref:kernelconfig[kernelconfig,Configuring the " "FreeBSD Kernel]. The following options are available for the custom kernel " "configuration file:" msgstr "" "Для статической компиляции поддержки IPFW в собственное ядро обратитесь к " "инструкциям в crossref:kernelconfig[kernelconfig,Настройка ядра FreeBSD]. В " "файле конфигурации собственного ядра доступны следующие параметры:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1833 #, no-wrap msgid "" "options IPFIREWALL\t\t\t# enables IPFW\n" "options IPFIREWALL_VERBOSE\t\t# enables logging for rules with log keyword to syslogd(8)\n" "options IPFIREWALL_VERBOSE_LIMIT=5\t# limits number of logged packets per-entry\n" "options IPFIREWALL_DEFAULT_TO_ACCEPT # sets default policy to pass what is not explicitly denied\n" "options IPFIREWALL_NAT\t\t# enables basic in-kernel NAT support\n" "options LIBALIAS\t\t\t# enables full in-kernel NAT support\n" "options IPFIREWALL_NAT64\t\t# enables in-kernel NAT64 support\n" "options IPFIREWALL_NPTV6\t\t# enables in-kernel IPv6 NPT support\n" "options IPFIREWALL_PMOD\t\t# enables protocols modification module support\n" "options IPDIVERT\t\t\t# enables NAT through natd(8)\n" msgstr "" "options IPFIREWALL\t\t\t# enables IPFW\n" "options IPFIREWALL_VERBOSE\t\t# enables logging for rules with log keyword to syslogd(8)\n" "options IPFIREWALL_VERBOSE_LIMIT=5\t# limits number of logged packets per-entry\n" "options IPFIREWALL_DEFAULT_TO_ACCEPT # sets default policy to pass what is not explicitly denied\n" "options IPFIREWALL_NAT\t\t# enables basic in-kernel NAT support\n" "options LIBALIAS\t\t\t# enables full in-kernel NAT support\n" "options IPFIREWALL_NAT64\t\t# enables in-kernel NAT64 support\n" "options IPFIREWALL_NPTV6\t\t# enables in-kernel IPv6 NPT support\n" "options IPFIREWALL_PMOD\t\t# enables protocols modification module support\n" "options IPDIVERT\t\t\t# enables NAT through natd(8)\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1838 msgid "" "IPFW can be loaded as a kernel module: options above are built by default as " "modules or can be set at runtime using tunables." msgstr "" "IPFW может быть загружен как модуль ядра: указанные выше параметры по " "умолчанию собираются как модули или могут быть установлены во время " "выполнения с помощью tunables." #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:1841 #, no-wrap msgid "IPFILTER (IPF)" msgstr "IPFILTER (IPF)" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1844 msgid "" "IPFILTER, also known as IPF, is a cross-platform, open source firewall which " "has been ported to several operating systems, including FreeBSD, NetBSD, " "OpenBSD, and Solaris(TM)." msgstr "" "IPFILTER, также известный как IPF, представляет собой кроссплатформенный " "межсетевой экран с открытым исходным кодом, который был портирован на " "несколько операционных систем, включая FreeBSD, NetBSD, OpenBSD и " "Solaris(TM)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1847 msgid "" "IPFILTER is a kernel-side firewall and NAT mechanism that can be controlled " "and monitored by userland programs. Firewall rules can be set or deleted " "using ipf, NAT rules can be set or deleted using ipnat, run-time statistics " "for the kernel parts of IPFILTER can be printed using ipfstat, and ipmon can " "be used to log IPFILTER actions to the system log files." msgstr "" "IPFILTER — это механизм межсетевого экрана и NAT на уровне ядра, которым " "можно управлять и отслеживать его работу с помощью пользовательских " "программ. Правила межсетевого экрана можно устанавливать или удалять с " "помощью `ipf`, правила NAT — с помощью `ipnat`, статистику работы ядерной " "части IPFILTER в реальном времени можно выводить с помощью `ipfstat`, а " "`ipmon` позволяет записывать действия IPFILTER в системные журналы." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1850 msgid "" "IPF was originally written using a rule processing logic of \"the last " "matching rule wins\" and only used stateless rules. Since then, IPF has " "been enhanced to include the `quick` and `keep state` options." msgstr "" "IPF изначально был написан с использованием логики обработки правил " "\"последнее совпавшее правило побеждает\" и использовал только правила без " "состояния. С тех пор IPF был улучшен и теперь включает опции `quick` и `keep " "state`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1853 msgid "" "The IPF FAQ is at http://www.phildev.net/ipf/index.html[http://www.phildev." "net/ipf/index.html]. A searchable archive of the IPFilter mailing list is " "available at http://marc.info/?l=ipfilter[http://marc.info/?l=ipfilter]." msgstr "" "Часто задаваемые вопросы по IPF находятся на сайте http://www.phildev.net/" "ipf/index.html[http://www.phildev.net/ipf/index.html]. Доступен поисковый " "архив списка рассылки IPFilter по адресу http://marc.info/?l=ipfilter[http://" "marc.info/?l=ipfilter]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1856 msgid "" "This section of the Handbook focuses on IPF as it pertains to FreeBSD. It " "provides examples of rules that contain the `quick` and `keep state` options." msgstr "" "Этот раздел Руководства посвящен IPF в контексте FreeBSD. В нём приведены " "примеры правил, содержащих опции `quick` и `keep state`." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1857 #, no-wrap msgid "Enabling IPF" msgstr "Включение IPF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1860 msgid "" "IPF is included in the basic FreeBSD install as a kernel loadable module, " "meaning that a custom kernel is not needed in order to enable IPF." msgstr "" "IPF включён в базовую установку FreeBSD в виде загружаемого модуля ядра, что " "означает, что для включения IPF не требуется создавать собственное ядро." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1863 msgid "" "For users who prefer to statically compile IPF support into a custom kernel, " "refer to the instructions in crossref:kernelconfig[kernelconfig,Configuring " "the FreeBSD Kernel]. The following kernel options are available:" msgstr "" "Для пользователей, которые предпочитают статически компилировать поддержку " "IPF в пользовательское ядро, обратитесь к инструкциям в crossref:" "kernelconfig[kernelconfig,Настройка ядра FreeBSD]. Доступны следующие " "параметры ядра:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1870 #, no-wrap msgid "" "options IPFILTER\n" "options IPFILTER_LOG\n" "options IPFILTER_LOOKUP\n" "options IPFILTER_DEFAULT_BLOCK\n" msgstr "" "options IPFILTER\n" "options IPFILTER_LOG\n" "options IPFILTER_LOOKUP\n" "options IPFILTER_DEFAULT_BLOCK\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1873 msgid "" "where `options IPFILTER` enables support for IPFILTER, `options " "IPFILTER_LOG` enables IPF logging using the [.filename]#ipl# packet logging " "pseudo-device for every rule that has the `log` keyword, `IPFILTER_LOOKUP` " "enables IP pools in order to speed up IP lookups, and `options " "IPFILTER_DEFAULT_BLOCK` changes the default behavior so that any packet not " "matching a firewall `pass` rule gets blocked." msgstr "" "где `options IPFILTER` включает поддержку IPFILTER, `options IPFILTER_LOG` " "включает журналирование IPF с использованием псевдоустройства [." "filename]#ipl# для записи пакетов для каждого правила, содержащего ключевое " "слово `log`, `IPFILTER_LOOKUP` включает пулы IP для ускорения поиска IP, а " "`options IPFILTER_DEFAULT_BLOCK` изменяет поведение по умолчанию так, что " "любой пакет, не соответствующий правилу `pass` межсетевого экрана, " "блокируется." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1877 msgid "" "To configure the system to enable IPF at boot time, add the following " "entries to [.filename]#/etc/rc.conf#. These entries will also enable " "logging and `default pass all`. To change the default policy to `block all` " "without compiling a custom kernel, remember to add a `block all` rule at the " "end of the ruleset." msgstr "" "Для настройки системы на включение IPF при загрузке добавьте следующие " "записи в [.filename]#/etc/rc.conf#. Эти записи также включат журналирование " "и политику `default pass all`. Чтобы изменить политику по умолчанию на " "`block all` без компиляции пользовательского ядра, не забудьте добавить " "правило `block all` в конец набора правил." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1888 #, no-wrap msgid "" "ipfilter_enable=\"YES\" # Start ipf firewall\n" "ipfilter_rules=\"/etc/ipf.rules\" # loads rules definition text file\n" "ipv6_ipfilter_rules=\"/etc/ipf6.rules\" # loads rules definition text file for IPv6\n" "ipmon_enable=\"YES\" # Start IP monitor log\n" "ipmon_flags=\"-Ds\" # D = start as daemon\n" " # s = log to syslog\n" " # v = log tcp window, ack, seq\n" " # n = map IP & port to names\n" msgstr "" "ipfilter_enable=\"YES\" # Start ipf firewall\n" "ipfilter_rules=\"/etc/ipf.rules\" # loads rules definition text file\n" "ipv6_ipfilter_rules=\"/etc/ipf6.rules\" # loads rules definition text file for IPv6\n" "ipmon_enable=\"YES\" # Start IP monitor log\n" "ipmon_flags=\"-Ds\" # D = start as daemon\n" " # s = log to syslog\n" " # v = log tcp window, ack, seq\n" " # n = map IP & port to names\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1891 msgid "If NAT functionality is needed, also add these lines:" msgstr "Если требуется функциональность NAT, также добавьте следующие строки:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1897 #, no-wrap msgid "" "gateway_enable=\"YES\" # Enable as LAN gateway\n" "ipnat_enable=\"YES\" # Start ipnat function\n" "ipnat_rules=\"/etc/ipnat.rules\" # rules definition file for ipnat\n" msgstr "" "gateway_enable=\"YES\" # Enable as LAN gateway\n" "ipnat_enable=\"YES\" # Start ipnat function\n" "ipnat_rules=\"/etc/ipnat.rules\" # rules definition file for ipnat\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1900 msgid "Then, to start IPF now:" msgstr "Затем, чтобы запустить IPF сейчас:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1904 #, no-wrap msgid "# service ipfilter start\n" msgstr "# service ipfilter start\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1908 msgid "" "To load the firewall rules, specify the name of the ruleset file using " "`ipf`. The following command can be used to replace the currently running " "firewall rules:" msgstr "" "Для загрузки правил межсетевого экрана укажите имя файла набора правил, " "используя `ipf`. Следующая команда может быть использована для замены " "текущих работающих правил межсетевого экрана:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:1912 #, no-wrap msgid "# ipf -Fa -f /etc/ipf.rules\n" msgstr "# ipf -Fa -f /etc/ipf.rules\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1915 msgid "" "where `-Fa` flushes all the internal rules tables and `-f` specifies the " "file containing the rules to load." msgstr "" "где `-Fa` очищает все внутренние таблицы правил, а `-f` указывает файл, " "содержащий правила для загрузки." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1918 msgid "" "This provides the ability to make changes to a custom ruleset and update the " "running firewall with a fresh copy of the rules without having to reboot the " "system. This method is convenient for testing new rules as the procedure " "can be executed as many times as needed." msgstr "" "Это предоставляет возможность вносить изменения в пользовательский набор " "правил и обновлять работающий межсетевой экран новой копией правил без " "необходимости перезагрузки системы. Этот метод удобен для тестирования новых " "правил, так как процедуру можно выполнять столько раз, сколько потребуется." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1920 msgid "" "Refer to man:ipf[8] for details on the other flags available with this " "command." msgstr "" "Обратитесь к man:ipf[8] для получения подробностей о других флагах, " "доступных с этой командой." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:1921 #, no-wrap msgid "IPF Rule Syntax" msgstr "Синтаксис правил IPF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1927 msgid "" "This section describes the IPF rule syntax used to create stateful rules. " "When creating rules, keep in mind that unless the `quick` keyword appears in " "a rule, every rule is read in order, with the _last matching rule_ being the " "one that is applied. This means that even if the first rule to match a " "packet is a `pass`, if there is a later matching rule that is a `block`, the " "packet will be dropped. Sample rulesets can be found in [.filename]#/usr/" "share/examples/ipfilter#." msgstr "" "В этом разделе описывается синтаксис правил IPF, используемый для создания " "правил с состояниями. При создании правил следует помнить, что если в " "правиле не указано ключевое слово `quick`, каждое правило обрабатывается по " "порядку, и _последнее совпавшее правило_ будет применено. Это означает, что " "даже если первое совпавшее правило разрешает (`pass`), но далее есть " "совпадающее правило, которое запрещает (`block`), пакет будет отброшен. " "Примеры наборов правил можно найти в [.filename]#/usr/share/examples/" "ipfilter#." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1930 msgid "" "When creating rules, a `+#+` character is used to mark the start of a " "comment and may appear at the end of a rule, to explain that rule's " "function, or on its own line. Any blank lines are ignored." msgstr "" "При создании правил символ `+#+` используется для обозначения начала " "комментария и может находиться в конце правила, чтобы пояснить его функцию, " "или на отдельной строке. Пустые строки игнорируются." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1935 msgid "" "The keywords which are used in rules must be written in a specific order, " "from left to right. Some keywords are mandatory while others are optional. " "Some keywords have sub-options which may be keywords themselves and also " "include more sub-options. The keyword order is as follows, where the words " "shown in uppercase represent a variable and the words shown in lowercase " "must precede the variable that follows it:" msgstr "" "Ключевые слова, используемые в правилах, должны быть записаны в определённом " "порядке, слева направо. Некоторые ключевые слова являются обязательными, а " "другие — опциональными. Некоторые ключевые слова имеют подопции, которые " "могут сами быть ключевыми словами и включать дополнительные подопции. " "Порядок ключевых слов следующий, где слова, написанные в ВЕРХНЕМ РЕГИСТРЕ, " "представляют переменную, а слова, написанные в нижнем регистре, должны " "предшествовать следующей за ними переменной:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1937 msgid "" "`_ACTION DIRECTION OPTIONS proto PROTO_TYPE from SRC_ADDR SRC_PORT to " "DST_ADDR DST_PORT TCP_FLAG|ICMP_TYPE keep state STATE_`" msgstr "" "`_ACTION DIRECTION OPTIONS proto PROTO_TYPE from SRC_ADDR SRC_PORT to " "DST_ADDR DST_PORT TCP_FLAG|ICMP_TYPE keep state STATE_`" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1941 msgid "" "This section describes each of these keywords and their options. It is not " "an exhaustive list of every possible option. Refer to man:ipf[5] for a " "complete description of the rule syntax that can be used when creating IPF " "rules and examples for using each keyword." msgstr "" "В этом разделе описываются ключевые слова и их параметры. Это не " "исчерпывающий список всех возможных параметров. Полное описание синтаксиса " "правил, который можно использовать при создании правил IPF, а также примеры " "использования каждого ключевого слова приведены в man:ipf[5]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1946 msgid "" "The action keyword indicates what to do with the packet if it matches that " "rule. Every rule _must_ have an action. The following actions are " "recognized:" msgstr "" "Ключевое слово `action` указывает действие — что делать с пакетом, если он " "соответствует данному правилу. Каждое правило _должно_ иметь действие. " "Поддерживаются следующие действия:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1948 msgid "`block`: drops the packet." msgstr "`block`: отбрасывает пакет." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1950 msgid "`pass`: allows the packet." msgstr "`pass`: разрешает пакет." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1952 msgid "`log`: generates a log record." msgstr "`log`: создает запись в журнале." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1954 msgid "" "`count`: counts the number of packets and bytes which can provide an " "indication of how often a rule is used." msgstr "" "`count`: подсчитывает количество пакетов и байтов, что может дать " "представление о том, как часто используется правило." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1956 msgid "`auth`: queues the packet for further processing by another program." msgstr "" "`auth`: ставит пакет в очередь для дальнейшей обработки другой программой." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1958 msgid "" "`call`: provides access to functions built into IPF that allow more complex " "actions." msgstr "" "`call`: предоставляет доступ к функциям, встроенным в IPF, которые позволяют " "выполнять более сложные действия." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1960 msgid "" "`decapsulate`: removes any headers in order to process the contents of the " "packet." msgstr "" "`decapsulate`: удаляет любые заголовки для обработки содержимого пакета." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1961 #, no-wrap msgid "DIRECTION" msgstr "DIRECTION" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1963 msgid "" "Next, each rule must explicitly state the direction of traffic using one of " "these keywords:" msgstr "" "Далее, каждое правило должно явно указывать `direction ` — направление " "трафика с использованием одного из следующих ключевых слов:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1965 msgid "`in`: the rule is applied against an inbound packet." msgstr "`in`: правило применяется к входящему пакету." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1967 msgid "`out`: the rule is applied against an outbound packet." msgstr "`out`: правило применяется к исходящему пакету." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1969 msgid "`all`: the rule applies to either direction." msgstr "`all`: правило применяется в обоих направлениях." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1971 msgid "" "If the system has multiple interfaces, the interface can be specified along " "with the direction. An example would be `in on fxp0`." msgstr "" "Если в системе несколько интерфейсов, можно указать интерфейс вместе с " "направлением. Примером может быть `in on fxp0`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1975 msgid "" "Options are optional. However, if multiple options are specified, they must " "be used in the order shown here." msgstr "" "`options` — параметры необязательны. Однако, если указано несколько " "параметров, они должны использоваться в порядке, указанном здесь." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1977 msgid "" "`log`: when performing the specified ACTION, the contents of the packet's " "headers will be written to the man:ipl[4] packet log pseudo-device." msgstr "" "`log`: при выполнении указанного ДЕЙСТВИЯ содержимое заголовков пакета будет " "записано в псевдоустройство журнала пакетов man:ipl[4]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1979 msgid "" "`quick`: if a packet matches this rule, the ACTION specified by the rule " "occurs and no further processing of any following rules will occur for this " "packet." msgstr "" "`quick`: если пакет соответствует этому правилу, происходит ДЕЙСТВИЕ, " "указанное в правиле, и дальнейшая обработка последующих правил для этого " "пакета не выполняется." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1982 msgid "" "`on`: must be followed by the interface name as displayed by man:" "ifconfig[8]. The rule will only match if the packet is going through the " "specified interface in the specified direction." msgstr "" "`on`: должен сопровождаться именем интерфейса, как отображается в man:" "ifconfig[8]. Правило будет применяться только в том случае, если пакет " "проходит через указанный интерфейс в указанном направлении." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1984 msgid "" "When using the `log` keyword, the following qualifiers may be used in this " "order:" msgstr "" "При использовании ключевого слова `log` следующие квалификаторы могут быть " "указаны в таком порядке:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1986 msgid "" "`body`: indicates that the first 128 bytes of the packet contents will be " "logged after the headers." msgstr "" "`body`: указывает, что первые 128 байт содержимого пакета будут записаны в " "журнал после заголовков." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1988 msgid "" "`first`: if the `log` keyword is being used in conjunction with a `keep " "state` option, this option is recommended so that only the triggering packet " "is logged and not every packet which matches the stateful connection." msgstr "" "`first`: если ключевое слово `log` используется вместе с опцией `keep " "state`, рекомендуется использовать эту опцию, чтобы регистрировался только " "инициирующий пакет, а не каждый пакет, соответствующий соединению с " "отслеживанием состояний." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1991 msgid "" "Additional options are available to specify error return messages. Refer to " "man:ipf[5] for more details." msgstr "" "Дополнительные параметры доступны для указания сообщений об ошибках. " "Подробности смотрите в man:ipf[5]." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1992 #, no-wrap msgid "PROTO_TYPE" msgstr "PROTO_TYPE" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:1998 msgid "" "The protocol type is optional. However, it is mandatory if the rule needs " "to specify a SRC_PORT or a DST_PORT as it defines the type of protocol. " "When specifying the type of protocol, use the `proto` keyword followed by " "either a protocol number or name from [.filename]#/etc/protocols#. Example " "protocol names include `tcp`, `udp`, or `icmp`. If PROTO_TYPE is specified " "but no SRC_PORT or DST_PORT is specified, all port numbers for that protocol " "will match that rule." msgstr "" "Тип протокола является необязательным. Однако он обязателен, если в правиле " "необходимо указать SRC_PORT или DST_PORT, так как он определяет тип " "протокола. При указании типа протокола используйте ключевое слово `proto`, " "за которым следует номер протокола или его имя из [.filename]#/etc/" "protocols#. Примеры названий протоколов: `tcp`, `udp` или `icmp`. Если " "указан PROTO_TYPE, но не указаны SRC_PORT или DST_PORT, все номера портов " "для этого протокола будут соответствовать этому правилу." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:1999 #, no-wrap msgid "SRC_ADDR" msgstr "SRC_ADDR" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2003 msgid "" "The `from` keyword is mandatory and is followed by a keyword which " "represents the source of the packet. The source can be a hostname, an IP " "address followed by the CIDR mask, an address pool, or the keyword `all`. " "Refer to man:ipf[5] for examples." msgstr "" "Ключевое слово `from` является обязательным и сопровождается ключевым " "словом, обозначающим источник пакета. Источником может быть имя хоста, IP-" "адрес с указанием маски CIDR, пул адресов или ключевое слово `all`. Примеры " "можно найти в man:ipf[5]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2007 msgid "" "There is no way to match ranges of IP addresses which do not express " "themselves easily using the dotted numeric form / mask-length notation. The " "package:net-mgmt/ipcalc[] package or port may be used to ease the " "calculation of the CIDR mask. Additional information is available at the " "utility's web page: http://jodies.de/ipcalc[http://jodies.de/ipcalc]." msgstr "" "Единственный способ задать диапазоны IP-адресов, это представить их в " "нотации — числа, разделенные точками / длина маски. Пакет или порт package:" "net-mgmt/ipcalc[] может быть использован для упрощения расчета маски CIDR. " "Дополнительная информация доступна на веб-странице утилиты: http://jodies.de/" "ipcalc[http://jodies.de/ipcalc]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2012 msgid "" "The port number of the source is optional. However, if it is used, it " "requires PROTO_TYPE to be first defined in the rule. The port number must " "also be preceded by the `proto` keyword." msgstr "" "Номер порта источника является необязательным. Однако, если он используется, " "требуется, чтобы PROTO_TYPE был сначала определён в правиле. Номер порта " "также должен предваряться ключевым словом `proto`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2014 msgid "" "A number of different comparison operators are supported: `=` (equal to), `!" "=` (not equal to), `<` (less than), `>` (greater than), `<=` (less than or " "equal to), and `>=` (greater than or equal to)." msgstr "" "Поддерживается несколько различных операторов сравнения: `=` (равно), `!=` " "(не равно), `<` (меньше), `>` (больше), `<=` (меньше или равно) и `>=` " "(больше или равно)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2016 msgid "" "To specify port ranges, place the two port numbers between `<>` (less than " "and greater than ), `><` (greater than and less than ), or `:` (greater than " "or equal to and less than or equal to)." msgstr "" "Для указания диапазона портов поместите два номера порта между `<>` (меньше " "и больше), `><` (больше и меньше) или `:` (больше или равно и меньше или " "равно)." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:2017 #, no-wrap msgid "DST_ADDR" msgstr "DST_ADDR" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2020 msgid "" "The `to` keyword is mandatory and is followed by a keyword which represents " "the destination of the packet. Similar to SRC_ADDR, it can be a hostname, " "an IP address followed by the CIDR mask, an address pool, or the keyword " "`all`." msgstr "" "Ключевое слово `to` является обязательным и за ним следует ключевое слово, " "обозначающее назначение пакета. Аналогично SRC_ADDR, это может быть имя " "хоста, IP-адрес с маской CIDR, пул адресов или ключевое слово `all`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2025 msgid "" "Similar to SRC_PORT, the port number of the destination is optional. " "However, if it is used, it requires PROTO_TYPE to be first defined in the " "rule. The port number must also be preceded by the `proto` keyword." msgstr "" "Аналогично SRC_PORT, номер порта назначения является необязательным. Однако, " "если он используется, требуется, чтобы PROTO_TYPE был сначала определён в " "правиле. Номер порта также должен предваряться ключевым словом `proto`." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:2026 #, no-wrap msgid "TCP_FLAG|ICMP_TYPE" msgstr "TCP_FLAG|ICMP_TYPE" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2029 msgid "" "If `tcp` is specified as the PROTO_TYPE, flags can be specified as letters, " "where each letter represents one of the possible TCP flags used to determine " "the state of a connection. Possible values are: `S` (SYN), `A` (ACK), `P` " "(PSH), `F` (FIN), `U` (URG), `R` (RST), `C` (CWN), and `E` (ECN)." msgstr "" "Если в качестве `PROTO_TYPE` указан `tcp`, флаги могут быть заданы в виде " "букв, где каждая буква представляет один из возможных флагов TCP, " "используемых для определения состояния соединения. Возможные значения: `S` " "(SYN), `A` (ACK), `P` (PSH), `F` (FIN), `U` (URG), `R` (RST), `C` (CWN) и " "`E` (ECN)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2032 msgid "" "If `icmp` is specified as the PROTO_TYPE, the ICMP type to match can be " "specified. Refer to man:ipf[5] for the allowable types." msgstr "" "Если указан `icmp` в качестве PROTO_TYPE, можно указать тип ICMP для " "сопоставления. Допустимые типы приведены в man:ipf[5]." #. type: Labeled list #: documentation/content/en/books/handbook/firewalls/_index.adoc:2033 #, no-wrap msgid "STATE" msgstr "STATE" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2037 msgid "" "If a `pass` rule contains `keep state`, IPF will add an entry to its dynamic " "state table and allow subsequent packets that match the connection. IPF can " "track state for TCP, UDP, and ICMP sessions. Any packet that IPF can be " "certain is part of an active session, even if it is a different protocol, " "will be allowed." msgstr "" "Если правило `pass` содержит `keep state`, IPF добавит запись в свою таблицу " "динамического состояния и разрешит последующие пакеты, соответствующие " "соединению. IPF может отслеживать состояние сеансов TCP, UDP и ICMP. Любой " "пакет, который IPF может однозначно идентифицировать как часть активного " "сеанса, даже если это другой протокол, будет разрешён." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2044 msgid "" "In IPF, packets destined to go out through the interface connected to the " "public Internet are first checked against the dynamic state table. If the " "packet matches the next expected packet comprising an active session " "conversation, it exits the firewall and the state of the session " "conversation flow is updated in the dynamic state table. Packets that do " "not belong to an already active session are checked against the outbound " "ruleset. Packets coming in from the interface connected to the public " "Internet are first checked against the dynamic state table. If the packet " "matches the next expected packet comprising an active session, it exits the " "firewall and the state of the session conversation flow is updated in the " "dynamic state table. Packets that do not belong to an already active " "session are checked against the inbound ruleset." msgstr "" "В IPF пакеты, предназначенные для выхода через интерфейс, подключенный к " "публичному интернету, сначала проверяются в динамической таблице состояний. " "Если пакет соответствует следующему ожидаемому пакету активного сеанса " "связи, он проходит через межсетевой экран, и состояние потока сеанса " "обновляется в динамической таблице состояний. Пакеты, не принадлежащие к уже " "активному сеансу, проверяются в соответствии с набором правил для исходящего " "трафика. Пакеты, поступающие через интерфейс, подключенный к публичному " "интернету, сначала проверяются в динамической таблице состояний. Если пакет " "соответствует следующему ожидаемому пакету активного сеанса, он проходит " "через межсетевой экран, и состояние потока сеанса обновляется в динамической " "таблице состояний. Пакеты, не принадлежащие к уже активному сеансу, " "проверяются в соответствии с набором правил для входящего трафика." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2048 msgid "" "Several keywords can be added after `keep state`. If used, these keywords " "set various options that control stateful filtering, such as setting " "connection limits or connection age. Refer to man:ipf[5] for the list of " "available options and their descriptions." msgstr "" "Несколько ключевых слов могут быть добавлены после `keep state`. Если они " "используются, эти ключевые слова устанавливают различные параметры, " "управляющие фильтрацией с отслеживанием статуса, такие как установка " "ограничений на соединения или времени жизни соединения. Подробный список " "доступных параметров и их описания можно найти в man:ipf[5]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2052 msgid "" "This section demonstrates how to create an example ruleset which only allows " "services matching `pass` rules and blocks all others." msgstr "" "Этот раздел демонстрирует, как создать пример набора правил, который " "разрешает только сервисы, соответствующие правилам `pass`, и блокирует все " "остальные." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2055 msgid "" "FreeBSD uses the loopback interface ([.filename]#lo0#) and the IP address " "`127.0.0.1` for internal communication. The firewall ruleset must contain " "rules to allow free movement of these internally used packets:" msgstr "" "FreeBSD использует loopback-интерфейс (интерфейс обратной петли) ([." "filename]#lo0#) и IP-адрес `127.0.0.1` для внутреннего взаимодействия. Набор " "правил межсетевого экрана должен включать правила, разрешающие свободное " "перемещение этих внутренних пакетов:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2061 #, no-wrap msgid "" "# no restrictions on loopback interface\n" "pass in quick on lo0 all\n" "pass out quick on lo0 all\n" msgstr "" "# no restrictions on loopback interface\n" "pass in quick on lo0 all\n" "pass out quick on lo0 all\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2066 msgid "" "The public interface connected to the Internet is used to authorize and " "control access of all outbound and inbound connections. If one or more " "interfaces are cabled to private networks, those internal interfaces may " "require rules to allow packets originating from the LAN to flow between the " "internal networks or to the interface attached to the Internet. The ruleset " "should be organized into three major sections: any trusted internal " "interfaces, outbound connections through the public interface, and inbound " "connections through the public interface." msgstr "" "Публичный интерфейс, подключенный к Интернету, используется для авторизации " "и контроля доступа всех исходящих и входящих соединений. Если один или " "несколько интерфейсов подключены к частным сетям, этим внутренним " "интерфейсам могут потребоваться правила, разрешающие передачу пакетов, " "исходящих из локальной сети, между внутренними сетями или к интерфейсу, " "подключенному к Интернету. Набор правил должен быть организован в три " "основных раздела: доверенные внутренние интерфейсы, исходящие соединения " "через публичный интерфейс и входящие соединения через публичный интерфейс." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2068 msgid "" "These two rules allow all traffic to pass through a trusted LAN interface " "named [.filename]#xl0#:" msgstr "" "Эти два правила разрешают весь трафик через доверенный интерфейс LAN с " "именем [.filename]#xl0#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2074 #, no-wrap msgid "" "# no restrictions on inside LAN interface for private network\n" "pass out quick on xl0 all\n" "pass in quick on xl0 all\n" msgstr "" "# no restrictions on inside LAN interface for private network\n" "pass out quick on xl0 all\n" "pass in quick on xl0 all\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2077 msgid "" "The rules for the public interface's outbound and inbound sections should " "have the most frequently matched rules placed before less commonly matched " "rules, with the last rule in the section blocking and logging all packets " "for that interface and direction." msgstr "" "Правила для исходящего и входящего разделов публичного интерфейса должны " "иметь наиболее часто совпадающие правила, расположенные перед менее часто " "совпадающими, а последнее правило в разделе должно блокировать и " "журналировать все пакеты для этого интерфейса и направления." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2081 msgid "" "This set of rules defines the outbound section of the public interface named " "[.filename]#dc0#. These rules keep state and identify the specific services " "that internal systems are authorized for public Internet access. All the " "rules use `quick` and specify the appropriate port numbers and, where " "applicable, destination addresses." msgstr "" "Этот набор правил определяет исходящий раздел общедоступного интерфейса с " "именем [.filename]#dc0#. Эти правила сохраняют состояние и определяют " "конкретные службы, для которых внутренние системы авторизованы для доступа к " "общедоступному Интернету. Все правила используют `quick` и указывают " "соответствующие номера портов и, где применимо, адреса назначения." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2087 #, no-wrap msgid "" "# interface facing Internet (outbound)\n" "# Matches session start requests originating from or behind the\n" "# firewall, destined for the Internet.\n" msgstr "" "# interface facing Internet (outbound)\n" "# Matches session start requests originating from or behind the\n" "# firewall, destined for the Internet.\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2093 #, no-wrap msgid "" "# Allow outbound access to public DNS servers.\n" "# Replace x.x.x.x with address listed in /etc/resolv.conf.\n" "# Repeat for each DNS server.\n" "pass out quick on dc0 proto tcp from any to x.x.x.x port = 53 flags S keep state\n" "pass out quick on dc0 proto udp from any to x.x.x.x port = 53 keep state\n" msgstr "" "# Allow outbound access to public DNS servers.\n" "# Replace x.x.x.x with address listed in /etc/resolv.conf.\n" "# Repeat for each DNS server.\n" "pass out quick on dc0 proto tcp from any to x.x.x.x port = 53 flags S keep state\n" "pass out quick on dc0 proto udp from any to x.x.x.x port = 53 keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2100 #, no-wrap msgid "" "# Allow access to ISP's specified DHCP server for cable or DSL networks.\n" "# Use the first rule, then check log for the IP address of DHCP server.\n" "# Then, uncomment the second rule, replace z.z.z.z with the IP address,\n" "# and comment out the first rule\n" "pass out log quick on dc0 proto udp from any to any port = 67 keep state\n" "#pass out quick on dc0 proto udp from any to z.z.z.z port = 67 keep state\n" msgstr "" "# Allow access to ISP's specified DHCP server for cable or DSL networks.\n" "# Use the first rule, then check log for the IP address of DHCP server.\n" "# Then, uncomment the second rule, replace z.z.z.z with the IP address,\n" "# and comment out the first rule\n" "pass out log quick on dc0 proto udp from any to any port = 67 keep state\n" "#pass out quick on dc0 proto udp from any to z.z.z.z port = 67 keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2104 #, no-wrap msgid "" "# Allow HTTP and HTTPS\n" "pass out quick on dc0 proto tcp from any to any port = 80 flags S keep state\n" "pass out quick on dc0 proto tcp from any to any port = 443 flags S keep state\n" msgstr "" "# Allow HTTP and HTTPS\n" "pass out quick on dc0 proto tcp from any to any port = 80 flags S keep state\n" "pass out quick on dc0 proto tcp from any to any port = 443 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2108 #, no-wrap msgid "" "# Allow email\n" "pass out quick on dc0 proto tcp from any to any port = 110 flags S keep state\n" "pass out quick on dc0 proto tcp from any to any port = 25 flags S keep state\n" msgstr "" "# Allow email\n" "pass out quick on dc0 proto tcp from any to any port = 110 flags S keep state\n" "pass out quick on dc0 proto tcp from any to any port = 25 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2111 #, no-wrap msgid "" "# Allow NTP\n" "pass out quick on dc0 proto tcp from any to any port = 37 flags S keep state\n" msgstr "" "# Allow NTP\n" "pass out quick on dc0 proto tcp from any to any port = 37 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2114 #, no-wrap msgid "" "# Allow FTP\n" "pass out quick on dc0 proto tcp from any to any port = 21 flags S keep state\n" msgstr "" "# Allow FTP\n" "pass out quick on dc0 proto tcp from any to any port = 21 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2117 #, no-wrap msgid "" "# Allow SSH\n" "pass out quick on dc0 proto tcp from any to any port = 22 flags S keep state\n" msgstr "" "# Allow SSH\n" "pass out quick on dc0 proto tcp from any to any port = 22 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2120 #, no-wrap msgid "" "# Allow ping\n" "pass out quick on dc0 proto icmp from any to any icmp-type 8 keep state\n" msgstr "" "# Allow ping\n" "pass out quick on dc0 proto icmp from any to any icmp-type 8 keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2123 #, no-wrap msgid "" "# Block and log everything else\n" "block out log first quick on dc0 all\n" msgstr "" "# Block and log everything else\n" "block out log first quick on dc0 all\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2127 msgid "" "This example of the rules in the inbound section of the public interface " "blocks all undesirable packets first. This reduces the number of packets " "that are logged by the last rule." msgstr "" "Этот пример правил в разделе входящего трафика публичного интерфейса сначала " "блокирует все нежелательные пакеты. Это уменьшает количество пакетов, " "регистрируемых последним правилом." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2141 #, no-wrap msgid "" "# interface facing Internet (inbound)\n" "# Block all inbound traffic from non-routable or reserved address spaces\n" "block in quick on dc0 from 192.168.0.0/16 to any #RFC 1918 private IP\n" "block in quick on dc0 from 172.16.0.0/12 to any #RFC 1918 private IP\n" "block in quick on dc0 from 10.0.0.0/8 to any #RFC 1918 private IP\n" "block in quick on dc0 from 127.0.0.0/8 to any #loopback\n" "block in quick on dc0 from 0.0.0.0/8 to any #loopback\n" "block in quick on dc0 from 169.254.0.0/16 to any #DHCP auto-config\n" "block in quick on dc0 from 192.0.2.0/24 to any #reserved for docs\n" "block in quick on dc0 from 204.152.64.0/23 to any #Sun cluster interconnect\n" "block in quick on dc0 from 224.0.0.0/3 to any #Class D & E multicast\n" msgstr "" "# interface facing Internet (inbound)\n" "# Block all inbound traffic from non-routable or reserved address spaces\n" "block in quick on dc0 from 192.168.0.0/16 to any #RFC 1918 private IP\n" "block in quick on dc0 from 172.16.0.0/12 to any #RFC 1918 private IP\n" "block in quick on dc0 from 10.0.0.0/8 to any #RFC 1918 private IP\n" "block in quick on dc0 from 127.0.0.0/8 to any #loopback\n" "block in quick on dc0 from 0.0.0.0/8 to any #loopback\n" "block in quick on dc0 from 169.254.0.0/16 to any #DHCP auto-config\n" "block in quick on dc0 from 192.0.2.0/24 to any #reserved for docs\n" "block in quick on dc0 from 204.152.64.0/23 to any #Sun cluster interconnect\n" "block in quick on dc0 from 224.0.0.0/3 to any #Class D & E multicast\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2145 #, no-wrap msgid "" "# Block fragments and too short tcp packets\n" "block in quick on dc0 all with frags\n" "block in quick on dc0 proto tcp all with short\n" msgstr "" "# Block fragments and too short tcp packets\n" "block in quick on dc0 all with frags\n" "block in quick on dc0 proto tcp all with short\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2149 #, no-wrap msgid "" "# block source routed packets\n" "block in quick on dc0 all with opt lsrr\n" "block in quick on dc0 all with opt ssrr\n" msgstr "" "# block source routed packets\n" "block in quick on dc0 all with opt lsrr\n" "block in quick on dc0 all with opt ssrr\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2152 #, no-wrap msgid "" "# Block OS fingerprint attempts and log first occurrence\n" "block in log first quick on dc0 proto tcp from any to any flags FUP\n" msgstr "" "# Block OS fingerprint attempts and log first occurrence\n" "block in log first quick on dc0 proto tcp from any to any flags FUP\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2155 #, no-wrap msgid "" "# Block anything with special options\n" "block in quick on dc0 all with ipopts\n" msgstr "" "# Block anything with special options\n" "block in quick on dc0 all with ipopts\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2159 #, no-wrap msgid "" "# Block public pings and ident\n" "block in quick on dc0 proto icmp all icmp-type 8\n" "block in quick on dc0 proto tcp from any to any port = 113\n" msgstr "" "# Block public pings and ident\n" "block in quick on dc0 proto icmp all icmp-type 8\n" "block in quick on dc0 proto tcp from any to any port = 113\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2165 #, no-wrap msgid "" "# Block incoming Netbios services\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 137\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 138\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 139\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 81\n" msgstr "" "# Block incoming Netbios services\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 137\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 138\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 139\n" "block in log first quick on dc0 proto tcp/udp from any to any port = 81\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2169 msgid "" "Any time there are logged messages on a rule with the `log first` option, " "run `ipfstat -hio` to evaluate how many times the rule has been matched. A " "large number of matches may indicate that the system is under attack." msgstr "" "Всякий раз, когда регистрируются сообщения о правиле с опцией `log first`, " "выполните команду `ipfstat -hio`, чтобы оценить, сколько раз правило " "сработало. Большое количество срабатываний может указывать на то, что " "система подвергается атаке." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2172 msgid "" "The rest of the rules in the inbound section define which connections are " "allowed to be initiated from the Internet. The last rule denies all " "connections which were not explicitly allowed by previous rules in this " "section." msgstr "" "Остальные правила в разделе входящего трафика определяют, какие соединения " "могут быть инициированы из Интернета. Последнее правило запрещает все " "соединения, которые не были явно разрешены предыдущими правилами в этом " "разделе." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2178 #, no-wrap msgid "" "# Allow traffic in from ISP's DHCP server. Replace z.z.z.z with\n" "# the same IP address used in the outbound section.\n" "pass in quick on dc0 proto udp from z.z.z.z to any port = 68 keep state\n" msgstr "" "# Allow traffic in from ISP's DHCP server. Replace z.z.z.z with\n" "# the same IP address used in the outbound section.\n" "pass in quick on dc0 proto udp from z.z.z.z to any port = 68 keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2181 #, no-wrap msgid "" "# Allow public connections to specified internal web server\n" "pass in quick on dc0 proto tcp from any to x.x.x.x port = 80 flags S keep state\n" msgstr "" "# Allow public connections to specified internal web server\n" "pass in quick on dc0 proto tcp from any to x.x.x.x port = 80 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2184 #, no-wrap msgid "" "# Block and log only first occurrence of all remaining traffic.\n" "block in log first quick on dc0 all\n" msgstr "" "# Block and log only first occurrence of all remaining traffic.\n" "block in log first quick on dc0 all\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2186 #, no-wrap msgid "Configuring NAT" msgstr "Настройка NAT" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2189 msgid "" "To enable NAT, add these statements to [.filename]#/etc/rc.conf# and specify " "the name of the file containing the NAT rules:" msgstr "" "Чтобы включить NAT, добавьте следующие выражения в [.filename]#/etc/rc.conf# " "и укажите имя файла, содержащего правила NAT:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2195 #, no-wrap msgid "" "gateway_enable=\"YES\"\n" "ipnat_enable=\"YES\"\n" "ipnat_rules=\"/etc/ipnat.rules\"\n" msgstr "" "gateway_enable=\"YES\"\n" "ipnat_enable=\"YES\"\n" "ipnat_rules=\"/etc/ipnat.rules\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2200 msgid "" "NAT rules are flexible and can accomplish many different things to fit the " "needs of both commercial and home users. The rule syntax presented here has " "been simplified to demonstrate common usage. For a complete rule syntax " "description, refer to man:ipnat[5]." msgstr "" "Правила NAT гибки и могут выполнять множество различных задач, подходящих " "как для коммерческих, так и для домашних пользователей. Синтаксис правил, " "представленный здесь, упрощен для демонстрации типичного использования. " "Полное описание синтаксиса правил можно найти в man:ipnat[5]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2202 msgid "" "The basic syntax for a NAT rule is as follows, where `map` starts the rule " "and _IF_ should be replaced with the name of the external interface:" msgstr "" "Базовая синтаксическая структура правила NAT выглядит следующим образом, где " "`map` начинает правило, а _IF_ следует заменить на имя внешнего интерфейса:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2206 #, no-wrap msgid "map IF LAN_IP_RANGE -> PUBLIC_ADDRESS\n" msgstr "map IF LAN_IP_RANGE -> PUBLIC_ADDRESS\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2211 msgid "" "The _LAN_IP_RANGE_ is the range of IP addresses used by internal clients. " "Usually, it is a private address range such as `192.168.1.0/24`. The " "_PUBLIC_ADDRESS_ can either be the static external IP address or the keyword " "`0/32` which represents the IP address assigned to _IF_." msgstr "" "_LAN_IP_RANGE_ — это диапазон IP-адресов, используемых внутренними " "клиентами. Обычно это частный диапазон адресов, например `192.168.1.0/24`. " "_PUBLIC_ADDRESS_ может быть либо статическим внешним IP-адресом, либо " "ключевым словом `0/32`, которое представляет IP-адрес, назначенный _IF_." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2218 msgid "" "In IPF, when a packet arrives at the firewall from the LAN with a public " "destination, it first passes through the outbound rules of the firewall " "ruleset. Then, the packet is passed to the NAT ruleset which is read from " "the top down, where the first matching rule wins. IPF tests each NAT rule " "against the packet's interface name and source IP address. When a packet's " "interface name matches a NAT rule, the packet's source IP address in the " "private LAN is checked to see if it falls within the IP address range " "specified in _LAN_IP_RANGE_. On a match, the packet has its source IP " "address rewritten with the public IP address specified by _PUBLIC_ADDRESS_. " "IPF posts an entry in its internal NAT table so that when the packet returns " "from the Internet, it can be mapped back to its original private IP address " "before being passed to the firewall rules for further processing." msgstr "" "В IPF, когда пакет прибывает на межсетевой экран из локальной сети с " "публичным адресом назначения, он сначала проходит через исходящие правила " "набора правил межсетевого экрана. Затем пакет передаётся в набор правил NAT, " "который читается сверху вниз, и первое совпадающее правило применяется. IPF " "проверяет каждое правило NAT на соответствие имени интерфейса и исходному IP-" "адресу пакета. Когда имя интерфейса пакета совпадает с правилом NAT, " "исходный IP-адрес пакета в частной локальной сети проверяется на вхождение в " "диапазон IP-адресов, указанный в _LAN_IP_RANGE_. При совпадении исходный IP-" "адрес пакета перезаписывается публичным IP-адресом, указанным в " "_PUBLIC_ADDRESS_. IPF добавляет запись в свою внутреннюю таблицу NAT, чтобы " "при возврате пакета из Интернета он мог быть сопоставлен с исходным частным " "IP-адресом перед передачей в набор правил межсетевого экрана для дальнейшей " "обработки." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2221 msgid "" "For networks that have large numbers of internal systems or multiple " "subnets, the process of funneling every private IP address into a single " "public IP address becomes a resource problem. Two methods are available to " "relieve this issue." msgstr "" "Для сетей с большим количеством внутренних систем или несколькими подсетями " "процесс перенаправления каждого частного IP-адреса в один публичный IP-адрес " "становится проблемой с точки зрения ресурсов. Доступны два метода для " "решения этой проблемы." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2224 msgid "" "The first method is to assign a range of ports to use as source ports. By " "adding the `portmap` keyword, NAT can be directed to only use source ports " "in the specified range:" msgstr "" "Первый метод заключается в назначении диапазона портов для использования в " "качестве исходных портов. Добавление ключевого слова `portmap` позволяет " "указать NAT использовать только исходные порты из заданного диапазона:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2228 #, no-wrap msgid "map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp 20000:60000\n" msgstr "map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp 20000:60000\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2231 msgid "" "Alternately, use the `auto` keyword which tells NAT to determine the ports " "that are available for use:" msgstr "" "Или используйте ключевое слово `auto`, которое указывает NAT определить " "порты, доступные для использования:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2235 #, no-wrap msgid "map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp auto\n" msgstr "map dc0 192.168.1.0/24 -> 0/32 portmap tcp/udp auto\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2240 msgid "" "The second method is to use a pool of public addresses. This is useful when " "there are too many LAN addresses to fit into a single public address and a " "block of public IP addresses is available. These public addresses can be " "used as a pool from which NAT selects an IP address as a packet's address is " "mapped on its way out." msgstr "" "Второй метод заключается в использовании пула публичных адресов. Это " "полезно, когда количество локальных адресов слишком велико, чтобы уместиться " "в один публичный адрес, и доступен блок публичных IP-адресов. Эти публичные " "адреса могут использоваться как пул, из которого NAT выбирает IP-адрес для " "отображения адреса пакета при его выходе." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2243 msgid "" "The range of public IP addresses can be specified using a netmask or CIDR " "notation. These two rules are equivalent:" msgstr "" "Диапазон публичных IP-адресов может быть указан с использованием маски сети " "или нотации CIDR. Эти два правила эквивалентны:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2248 #, no-wrap msgid "" "map dc0 192.168.1.0/24 -> 204.134.75.0/255.255.255.0\n" "map dc0 192.168.1.0/24 -> 204.134.75.0/24\n" msgstr "" "map dc0 192.168.1.0/24 -> 204.134.75.0/255.255.255.0\n" "map dc0 192.168.1.0/24 -> 204.134.75.0/24\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2253 msgid "" "A common practice is to have a publicly accessible web server or mail server " "segregated to an internal network segment. The traffic from these servers " "still has to undergo NAT, but port redirection is needed to direct inbound " "traffic to the correct server. For example, to map a web server using the " "internal address `10.0.10.25` to its public IP address of `20.20.20.5`, use " "this rule:" msgstr "" "Распространённой практикой является размещение общедоступного веб-сервера " "или почтового сервера в изолированном сегменте внутренней сети. Трафик с " "этих серверов всё равно проходит через NAT, но требуется перенаправление " "портов для направления входящего трафика на нужный сервер. Например, чтобы " "сопоставить веб-сервер с внутренним адресом `10.0.10.25` с его публичным IP-" "адресом `20.20.20.5`, используйте следующее правило:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2257 #, no-wrap msgid "rdr dc0 20.20.20.5/32 port 80 -> 10.0.10.25 port 80\n" msgstr "rdr dc0 20.20.20.5/32 port 80 -> 10.0.10.25 port 80\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2260 msgid "" "If it is the only web server, this rule would also work as it redirects all " "external HTTP requests to `10.0.10.25`:" msgstr "" "Если это единственный веб-сервер, это правило также будет работать, так как " "оно перенаправляет все внешние HTTP-запросы на `10.0.10.25`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2264 #, no-wrap msgid "rdr dc0 0.0.0.0/0 port 80 -> 10.0.10.25 port 80\n" msgstr "rdr dc0 0.0.0.0/0 port 80 -> 10.0.10.25 port 80\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2269 msgid "" "IPF has a built in FTP proxy which can be used with NAT. It monitors all " "outbound traffic for active or passive FTP connection requests and " "dynamically creates temporary filter rules containing the port number used " "by the FTP data channel. This eliminates the need to open large ranges of " "high order ports for FTP connections." msgstr "" "В IPF встроен FTP-прокси, который можно использовать с NAT. Он отслеживает " "весь исходящий трафик на предмет запросов активных или пассивных FTP-" "соединений и динамически создает временные правила фильтрации, содержащие " "номер порта, используемого FTP-каналом данных. Это устраняет необходимость " "открывать большие диапазоны портов высокого порядка для FTP-соединений." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2272 msgid "" "In this example, the first rule calls the proxy for outbound FTP traffic " "from the internal LAN. The second rule passes the FTP traffic from the " "firewall to the Internet, and the third rule handles all non-FTP traffic " "from the internal LAN:" msgstr "" "В этом примере первое правило вызывает прокси для исходящего FTP-трафика из " "внутренней локальной сети. Второе правило пропускает FTP-трафик из " "межсетевого экрана в Интернет, а третье правило обрабатывает весь не-FTP " "трафик из внутренней локальной сети:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2278 #, no-wrap msgid "" "map dc0 10.0.10.0/29 -> 0/32 proxy port 21 ftp/tcp\n" "map dc0 0.0.0.0/0 -> 0/32 proxy port 21 ftp/tcp\n" "map dc0 10.0.10.0/29 -> 0/32\n" msgstr "" "map dc0 10.0.10.0/29 -> 0/32 proxy port 21 ftp/tcp\n" "map dc0 0.0.0.0/0 -> 0/32 proxy port 21 ftp/tcp\n" "map dc0 10.0.10.0/29 -> 0/32\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2282 msgid "" "The FTP `map` rules go before the NAT rule so that when a packet matches an " "FTP rule, the FTP proxy creates temporary filter rules to let the FTP " "session packets pass and undergo NAT. All LAN packets that are not FTP will " "not match the FTP rules but will undergo NAT if they match the third rule." msgstr "" "Правила FTP `map` размещаются перед правилом NAT, так что при совпадении " "пакета с правилом FTP прокси-сервер FTP создает временные правила " "фильтрации, позволяющие пакетам FTP-сессии проходить и подвергаться NAT. Все " "пакеты из локальной сети, не относящиеся к FTP, не будут соответствовать " "правилам FTP, но подвергнутся NAT, если они соответствуют третьему правилу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2285 msgid "" "Without the FTP proxy, the following firewall rules would instead be " "needed. Note that without the proxy, all ports above `1024` need to be " "allowed:" msgstr "" "Без FTP-прокси потребуются следующие правила межсетевого экрана. Обратите " "внимание, что без прокси необходимо разрешить все порты выше `1024`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2291 #, no-wrap msgid "" "# Allow out LAN PC client FTP to public Internet\n" "# Active and passive modes\n" "pass out quick on rl0 proto tcp from any to any port = 21 flags S keep state\n" msgstr "" "# Allow out LAN PC client FTP to public Internet\n" "# Active and passive modes\n" "pass out quick on rl0 proto tcp from any to any port = 21 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2294 #, no-wrap msgid "" "# Allow out passive mode data channel high order port numbers\n" "pass out quick on rl0 proto tcp from any to any port > 1024 flags S keep state\n" msgstr "" "# Allow out passive mode data channel high order port numbers\n" "pass out quick on rl0 proto tcp from any to any port > 1024 flags S keep state\n" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2297 #, no-wrap msgid "" "# Active mode let data channel in from FTP server\n" "pass in quick on rl0 proto tcp from any to any port = 20 flags S keep state\n" msgstr "" "# Active mode let data channel in from FTP server\n" "pass in quick on rl0 proto tcp from any to any port = 20 flags S keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2301 msgid "" "Whenever the file containing the NAT rules is edited, run `ipnat` with `-CF` " "to delete the current NAT rules and flush the contents of the dynamic " "translation table. Include `-f` and specify the name of the NAT ruleset to " "load:" msgstr "" "Всякий раз, когда редактируется файл, содержащий правила NAT, выполните " "`ipnat` с `-CF`, чтобы удалить текущие правила NAT и очистить содержимое " "таблицы динамической трансляции. Используйте `-f` и укажите имя набора " "правил NAT для загрузки:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2305 #, no-wrap msgid "# ipnat -CF -f /etc/ipnat.rules\n" msgstr "# ipnat -CF -f /etc/ipnat.rules\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2308 msgid "To display the NAT statistics:" msgstr "Для отображения статистики NAT:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2312 #, no-wrap msgid "# ipnat -s\n" msgstr "# ipnat -s\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2315 msgid "To list the NAT table's current mappings:" msgstr "Для отображения текущих сопоставлений таблицы NAT:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2319 #, no-wrap msgid "# ipnat -l\n" msgstr "# ipnat -l\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2322 msgid "" "To turn verbose mode on and display information relating to rule processing " "and active rules and table entries:" msgstr "" "Чтобы включить подробный режим и отображать информацию, связанную с " "обработкой правил, активными правилами и записями таблиц:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2326 #, no-wrap msgid "# ipnat -v\n" msgstr "# ipnat -v\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2328 #, no-wrap msgid "Viewing IPF Statistics" msgstr "Просмотр статистики IPF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2332 msgid "" "IPF includes man:ipfstat[8] which can be used to retrieve and display " "statistics which are gathered as packets match rules as they go through the " "firewall. Statistics are accumulated since the firewall was last started or " "since the last time they were reset to zero using `ipf -Z`." msgstr "" "В пакет IPF входит программа man:ipfstat[8], которую можно использовать для " "получения и отображения статистики, собираемой при совпадении пакетов с " "правилами при прохождении через межсетевой экран. Статистика накапливается с " "момента последнего запуска межсетевого экрана или с момента последнего " "сброса статистики в ноль с помощью команды `ipf -Z`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2334 msgid "The default `ipfstat` output looks like this:" msgstr "Вывод `ipfstat` по умолчанию выглядит следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2354 #, no-wrap msgid "" "input packets: blocked 99286 passed 1255609 nomatch 14686 counted 0\n" " output packets: blocked 4200 passed 1284345 nomatch 14687 counted 0\n" " input packets logged: blocked 99286 passed 0\n" " output packets logged: blocked 0 passed 0\n" " packets logged: input 0 output 0\n" " log failures: input 3898 output 0\n" " fragment state(in): kept 0 lost 0\n" " fragment state(out): kept 0 lost 0\n" " packet state(in): kept 169364 lost 0\n" " packet state(out): kept 431395 lost 0\n" " ICMP replies: 0 TCP RSTs sent: 0\n" " Result cache hits(in): 1215208 (out): 1098963\n" " IN Pullups succeeded: 2 failed: 0\n" " OUT Pullups succeeded: 0 failed: 0\n" " Fastroute successes: 0 failures: 0\n" " TCP cksum fails(in): 0 (out): 0\n" " Packet log flags set: (0)\n" msgstr "" "input packets: blocked 99286 passed 1255609 nomatch 14686 counted 0\n" " output packets: blocked 4200 passed 1284345 nomatch 14687 counted 0\n" " input packets logged: blocked 99286 passed 0\n" " output packets logged: blocked 0 passed 0\n" " packets logged: input 0 output 0\n" " log failures: input 3898 output 0\n" " fragment state(in): kept 0 lost 0\n" " fragment state(out): kept 0 lost 0\n" " packet state(in): kept 169364 lost 0\n" " packet state(out): kept 431395 lost 0\n" " ICMP replies: 0 TCP RSTs sent: 0\n" " Result cache hits(in): 1215208 (out): 1098963\n" " IN Pullups succeeded: 2 failed: 0\n" " OUT Pullups succeeded: 0 failed: 0\n" " Fastroute successes: 0 failures: 0\n" " TCP cksum fails(in): 0 (out): 0\n" " Packet log flags set: (0)\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2360 msgid "" "Several options are available. When supplied with either `-i` for inbound " "or `-o` for outbound, the command will retrieve and display the appropriate " "list of filter rules currently installed and in use by the kernel. To also " "see the rule numbers, include `-n`. For example, `ipfstat -on` displays the " "outbound rules table with rule numbers:" msgstr "" "Доступно несколько вариантов. При указании `-i` для входящего или `-o` для " "исходящего трафика команда получит и отобразит соответствующий список правил " "фильтрации, установленных и используемых ядром. Чтобы также увидеть номера " "правил, добавьте `-n`. Например, `ipfstat -on` выводит таблицу исходящих " "правил с номерами:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2366 #, no-wrap msgid "" "@1 pass out on xl0 from any to any\n" "@2 block out on dc0 from any to any\n" "@3 pass out quick on dc0 proto tcp/udp from any to any keep state\n" msgstr "" "@1 pass out on xl0 from any to any\n" "@2 block out on dc0 from any to any\n" "@3 pass out quick on dc0 proto tcp/udp from any to any keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2370 msgid "" "Include `-h` to prefix each rule with a count of how many times the rule was " "matched. For example, `ipfstat -oh` displays the outbound internal rules " "table, prefixing each rule with its usage count:" msgstr "" "Включите `-h`, чтобы добавить перед каждым правилом количество его " "совпадений. Например, `ipfstat -oh` выводит таблицу внутренних правил для " "исходящего трафика, добавляя перед каждым правилом количество его " "использований:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2376 #, no-wrap msgid "" "2451423 pass out on xl0 from any to any\n" "354727 block out on dc0 from any to any\n" "430918 pass out quick on dc0 proto tcp/udp from any to any keep state\n" msgstr "" "2451423 pass out on xl0 from any to any\n" "354727 block out on dc0 from any to any\n" "430918 pass out quick on dc0 proto tcp/udp from any to any keep state\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2382 msgid "" "To display the state table in a format similar to man:top[1], use `ipfstat -" "t`. When the firewall is under attack, this option provides the ability to " "identify and see the attacking packets. The optional sub-flags give the " "ability to select the destination or source IP, port, or protocol to be " "monitored in real time. Refer to man:ipfstat[8] for details." msgstr "" "Для отображения таблицы состояний в формате, аналогичном man:top[1], " "используйте `ipfstat -t`. Когда межсетевой экран подвергается атаке, эта " "опция позволяет идентифицировать и просматривать атакующие пакеты. " "Дополнительные подфлаги дают возможность выбора IP-адреса назначения или " "источника, порта или протокола для мониторинга в реальном времени. " "Подробности смотрите в man:ipfstat[8]." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2383 #, no-wrap msgid "IPF Logging" msgstr "Журналирование IPF" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2387 msgid "" "IPF provides `ipmon`, which can be used to write the firewall's logging " "information in a human readable format. It requires that `options " "IPFILTER_LOG` be first added to a custom kernel using the instructions in " "crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]." msgstr "" "IPF предоставляет `ipmon`, который может использоваться для записи " "информации журналирования межсетевого экрана в удобочитаемом формате. Для " "этого требуется сначала добавить `options IPFILTER_LOG` в собственное ядро, " "следуя инструкциям в crossref:kernelconfig[kernelconfig,Настройка ядра " "FreeBSD]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2390 msgid "" "This command is typically run in daemon mode in order to provide a " "continuous system log file so that logging of past events may be reviewed. " "Since FreeBSD has a built in man:syslogd[8] facility to automatically rotate " "system logs, the default [.filename]#rc.conf# `ipmon_flags` statement uses `-" "Ds`:" msgstr "" "Эта команда обычно запускается в режиме демона для обеспечения непрерывного " "ведения системного журнала, чтобы можно было просматривать записи о прошлых " "событиях. Поскольку FreeBSD имеет встроенное средство man:syslogd[8] для " "автоматической ротации системных журналов, параметр `ipmon_flags` по " "умолчанию в [.filename]#rc.conf# использует `-Ds`:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2397 #, no-wrap msgid "" "ipmon_flags=\"-Ds\" # D = start as daemon\n" " # s = log to syslog\n" " # v = log tcp window, ack, seq\n" " # n = map IP & port to names\n" msgstr "" "ipmon_flags=\"-Ds\" # D = start as daemon\n" " # s = log to syslog\n" " # v = log tcp window, ack, seq\n" " # n = map IP & port to names\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2401 msgid "" "Logging provides the ability to review, after the fact, information such as " "which packets were dropped, what addresses they came from, and where they " "were going. This information is useful in tracking down attackers." msgstr "" "Ведение журналов предоставляет возможность последующего просмотра " "информации, такой как: какие пакеты были отброшены, с каких адресов они " "пришли и куда направлялись. Эта информация полезна при отслеживании " "злоумышленников." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2406 msgid "" "Once the logging facility is enabled in [.filename]#rc.conf# and started " "with `service ipmon start`, IPF will only log the rules which contain the " "`log` keyword. The firewall administrator decides which rules in the " "ruleset should be logged and normally only deny rules are logged. It is " "customary to include the `log` keyword in the last rule in the ruleset. " "This makes it possible to see all the packets that did not match any of the " "rules in the ruleset." msgstr "" "После включения системы журналирования в [.filename]#rc.conf# и запуска с " "помощью `service ipmon start`, IPF будет записывать в журнал только те " "правила, которые содержат ключевое слово `log`. Администратор межсетевого " "экрана решает, какие правила из набора должны записываться в журнал, и " "обычно регистрируются только правила с deny. Обычно ключевое слово `log` " "включают в последнее правило набора. Это позволяет увидеть все пакеты, " "которые не соответствуют ни одному из правил набора." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2409 msgid "" "By default, `ipmon -Ds` mode uses `local0` as the logging facility. The " "following logging levels can be used to further segregate the logged data:" msgstr "" "По умолчанию режим `ipmon -Ds` использует `local0` как средство ведения " "журнала. Для дальнейшего разделения регистрируемых данных можно использовать " "следующие уровни ведения журнала:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2416 #, no-wrap msgid "" "LOG_INFO - packets logged using the \"log\" keyword as the action rather than pass or block.\n" "LOG_NOTICE - packets logged which are also passed\n" "LOG_WARNING - packets logged which are also blocked\n" "LOG_ERR - packets which have been logged and which can be considered short due to an incomplete header\n" msgstr "" "LOG_INFO - packets logged using the \"log\" keyword as the action rather than pass or block.\n" "LOG_NOTICE - packets logged which are also passed\n" "LOG_WARNING - packets logged which are also blocked\n" "LOG_ERR - packets which have been logged and which can be considered short due to an incomplete header\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2419 msgid "" "In order to setup IPF to log all data to [.filename]#/var/log/ipfilter.log#, " "first create the empty file:" msgstr "" "Чтобы настроить IPF для записи всех данных в [.filename]#/var/log/ipfilter." "log#, сначала создайте пустой файл:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2423 #, no-wrap msgid "# touch /var/log/ipfilter.log\n" msgstr "# touch /var/log/ipfilter.log\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2426 msgid "" "Then, to write all logged messages to the specified file, add the following " "statement to [.filename]#/etc/syslog.conf#:" msgstr "" "Затем, чтобы записывать все журналируемые сообщения в указанный файл, " "добавьте следующую строку в [.filename]#/etc/syslog.conf#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2430 #, no-wrap msgid "local0.* /var/log/ipfilter.log\n" msgstr "local0.* /var/log/ipfilter.log\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2433 msgid "" "To activate the changes and instruct man:syslogd[8] to read the modified [." "filename]#/etc/syslog.conf#, run `service syslogd reload`." msgstr "" "Для активации изменений и указания man:syslogd[8] прочитать изменённый файл " "[.filename]#/etc/syslog.conf#, выполните команду `service syslogd reload`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2435 msgid "" "Do not forget to edit [.filename]#/etc/newsyslog.conf# to rotate the new log " "file." msgstr "" "Не забудьте отредактировать [.filename]#/etc/newsyslog.conf# для ротации " "нового файла журнала." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2438 msgid "" "Messages generated by `ipmon` consist of data fields separated by white " "space. Fields common to all messages are:" msgstr "" "Сообщения, генерируемые `ipmon`, состоят из полей данных, разделённых " "пробелами. Общие для всех сообщений поля:" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2440 msgid "The date of packet receipt." msgstr "The date of packet receipt." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2441 msgid "" "The time of packet receipt. This is in the form HH:MM:SS.F, for hours, " "minutes, seconds, and fractions of a second." msgstr "" "Время получения пакета. Указывается в формате ЧЧ:ММ:СС.Д, где ЧЧ - часы, ММ " "- минуты, СС - секунды, а Д - доли секунды." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2442 msgid "The name of the interface that processed the packet." msgstr "Имя интерфейса, обработавшего пакет." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2443 msgid "The group and rule number of the rule in the format `@0:17`." msgstr "Группа и номер правила в формате `@0:17`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2444 msgid "" "The action: `p` for passed, `b` for blocked, `S` for a short packet, `n` did " "not match any rules, and `L` for a log rule." msgstr "" "Действие: `p` — пропущено, `b` — заблокировано, `S` — короткий пакет, `n` — " "не совпало ни с одним правилом, `L` — правило для журналирования." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2445 msgid "" "The addresses written as three fields: the source address and port separated " "by a comma, the -> symbol, and the destination address and port. For " "example: `209.53.17.22,80 -> 198.73.220.17,1722`." msgstr "" "Адреса записываются в виде трёх полей: исходный адрес и порт, разделённые " "запятой, символ `->` и адрес назначения с портом. Например: `209.53.17.22,80 " "-> 198.73.220.17,1722`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2446 msgid "`PR` followed by the protocol name or number: for example, `PR tcp`." msgstr "`PR` с указанием имени или номера протокола: например, `PR tcp`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2447 msgid "" "`len` followed by the header length and total length of the packet: for " "example, `len 20 40`." msgstr "" "`len`, за которым следует длина заголовка и общая длина пакета: например, " "`len 20 40`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2450 msgid "" "If the packet is a TCP packet, there will be an additional field starting " "with a hyphen followed by letters corresponding to any flags that were set. " "Refer to man:ipf[5] for a list of letters and their flags." msgstr "" "Если пакет является TCP-пакетом, будет дополнительное поле, начинающееся с " "дефиса, за которым следуют буквы, соответствующие установленным флагам. " "Список букв и соответствующих флагов приведен в man:ipf[5]." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2453 msgid "" "If the packet is an ICMP packet, there will be two fields at the end: the " "first always being \"icmp\" and the next being the ICMP message and sub-" "message type, separated by a slash. For example: `icmp 3/3` for a port " "unreachable message." msgstr "" "Если пакет является ICMP-пакетом, в конце будут два поля: первое всегда " "`icmp`, а следующее — тип ICMP-сообщения и подтип, разделённые косой чертой. " "Например: `icmp 3/3` для сообщения о недоступности порта." #. type: Title == #: documentation/content/en/books/handbook/firewalls/_index.adoc:2455 #, no-wrap msgid "Blocklistd" msgstr "Blocklistd" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2462 msgid "" "Blocklistd is a daemon listening to sockets awaiting to receive " "notifications from other daemons about connection attempts that failed or " "were successful. It is most widely used in blocking too many connection " "attempts on open ports. A prime example is SSH running on the internet " "getting a lot of requests from bots or scripts trying to guess passwords and " "gain access. Using blocklistd, the daemon can notify the firewall to create " "a filter rule to block excessive connection attempts from a single source " "after a number of tries. Blocklistd was first developed on NetBSD and " "appeared there in version 7, it was originally called blacklistd. FreeBSD " "11 imported blocklistd from NetBSD." msgstr "" "Blocklistd — это демон, который прослушивает сокеты, ожидая получения " "уведомлений от других демонов о неудачных или успешных попытках подключения. " "Он наиболее широко используется для блокировки чрезмерного количества " "попыток подключения к открытым портам. Типичный пример — SSH, работающий в " "интернете и получающий множество запросов от ботов или скриптов, пытающихся " "угадать пароли и получить доступ. Используя blocklistd, демон может " "уведомить межсетевой экран о необходимости создания правила фильтрации для " "блокировки чрезмерных попыток подключения с одного источника после " "нескольких попыток. Blocklistd был первоначально разработан в NetBSD и " "появился там в версии 7. FreeBSD 11 импортировал blocklistd из NetBSD (ранее " "он назывался blacklist)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2467 msgid "" "This chapter describes how to set up blocklistd, configure it, and provides " "examples on how to use it. Readers should be familiar with basic firewall " "concepts like rules. For details, refer to the firewall chapter. PF is " "used in the examples, but other firewalls available on FreeBSD should be " "able to work with blocklistd, too." msgstr "" "В этой главе описывается, как настроить blocklistd, его конфигурация, а " "также приводятся примеры использования. Читатели должны быть знакомы с " "основными концепциями межсетевого экрана, такими как правила. Подробности " "см. в главе о межсетевом экране. В примерах используется PF, но другие " "межсетевые экраны, доступные в FreeBSD, также должны работать с blocklistd." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2468 #, no-wrap msgid "Enabling Blocklistd" msgstr "Включение blocklistd" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2474 msgid "" "The main configuration for blocklistd is stored in man:blocklistd.conf[5]. " "Various command line options are also available to change blocklistd's run-" "time behavior. Persistent configuration across reboots should be stored in " "[.filename]#/etc/blocklistd.conf#. To enable the daemon during system boot, " "add a `blocklistd_enable` line to [.filename]#/etc/rc.conf# like this:" msgstr "" "Основная конфигурация для blocklistd хранится в man: blocklistd.conf[5]. " "Также доступны различные параметры командной строки для изменения поведения " "blocklistd во время выполнения. Постоянная конфигурация, сохраняемая после " "перезагрузок, должна храниться в [.filename]#/etc/blocklistd.conf#. Чтобы " "включить демон во время загрузки системы, добавьте строку `blocklistd_enable`" " в [.filename]#/etc/rc.conf# следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2478 #, no-wrap msgid "# sysrc blocklistd_enable=yes\n" msgstr "# sysrc blocklistd_enable=yes\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2481 msgid "To start the service manually, run this command:" msgstr "Чтобы запустить службу вручную, выполните следующую команду:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2485 #, no-wrap msgid "# service blocklistd start\n" msgstr "# service blocklistd start\n" #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2487 #, no-wrap msgid "Creating a Blocklistd Ruleset" msgstr "Создание набора правил для blocklistd" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2492 msgid "" "Rules for blocklistd are configured in man:blocklistd.conf[5] with one entry " "per line. Each rule contains a tuple separated by spaces or tabs. Rules " "either belong to a `local` or a `remote`, which applies to the machine where " "blocklistd is running or an outside source, respectively." msgstr "" "Правила для blocklistd настраиваются в man: blocklistd.conf[5], по одному " "правилу на строку. Каждое правило содержит кортеж, разделённый пробелами или " "табуляциями. Правила относятся либо к `local`, либо к `remote`, что " "применяется соответственно к машине, на которой работает blocklistd, или к " "внешнему источнику." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:2493 #, no-wrap msgid "Local Rules" msgstr "Правила local" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2496 msgid "An example blocklistd.conf entry for a local rule looks like this:" msgstr "" "Пример записи в blocklistd.conf для локального правила выглядит следующим " "образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2501 #, no-wrap msgid "" "[local]\n" "ssh stream * * * 3 24h\n" msgstr "" "[local]\n" "ssh stream * * * 3 24h\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2505 msgid "" "All rules that follow the `[local]` section are treated as local rules " "(which is the default), applying to the local machine. When a `[remote]` " "section is encountered, all rules that follow it are handled as remote " "machine rules." msgstr "" "Все правила, следующие за разделом `[local]`, рассматриваются как локальные " "правила (что является значением по умолчанию) и применяются к локальной " "машине. При обнаружении раздела `[remote]` все последующие правила " "обрабатываются как правила для удалённых машин." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2513 msgid "" "Seven fields separated by either tabs or spaces define a rule. The first " "four fields identify the traffic that should be blocklisted. The three " "fields that follow define blocklistd's behavior. Wildcards are denoted as " "asterisks (`*`), matching anything in this field. The first field defines " "the location. In local rules, these are the network ports. The syntax for " "the location field is as follows:" msgstr "" "Семь полей, разделённых табуляцией или пробелами, определяют правило. Первые " "четыре поля идентифицируют трафик, который должен быть внесён в список " "блокировки. Следующие три поля определяют поведение blocklistd. " "Подстановочные символы обозначаются звёздочками (`*`), которые соответствуют " "любому значению в данном поле. Первое поле определяет местоположение. В " "локальных правилах это сетевые порты. Синтаксис для поля местоположения " "следующий:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2517 #, no-wrap msgid "[address|interface][/mask][:port]\n" msgstr "[address|interface][/mask][:port]\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2521 msgid "" "Addresses can be specified as IPv4 in numeric format or IPv6 in square " "brackets. An interface name like `_em0_` can also be used." msgstr "" "Адреса могут быть указаны в виде IPv4 в числовом формате или IPv6 в " "квадратных скобках. Также можно использовать имя интерфейса, например " "`_em0_`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2525 msgid "" "The socket type is defined by the second field. TCP sockets are of type " "`stream`, whereas UDP is denoted as `dgram`. The example above uses TCP, " "since SSH is using that protocol." msgstr "" "Тип сокета определяется вторым полем. TCP-сокеты имеют тип `stream`, тогда " "как UDP обозначается как `dgram`. В приведённом выше примере используется " "TCP, так как SSH работает по этому протоколу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2529 msgid "" "A protocol can be used in the third field of a blocklistd rule. The " "following protocols can be used: `tcp`, `udp`, `tcp6`, `udp6`, or numeric. " "A wildcard, like in the example, is typically used to match all protocols " "unless there is a reason to distinguish traffic by a certain protocol." msgstr "" "Протокол может быть указан в третьем поле правила blocklistd. Доступны " "следующие протоколы: `tcp`, `udp`, `tcp6`, `udp6` или числовое значение. " "Подстановочный символ, как в примере, обычно используется для соответствия " "всем протоколам, если нет необходимости различать трафик по определённому " "протоколу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2532 msgid "" "In the fourth field, the effective user or owner of the daemon process that " "is reporting the event is defined. The username or UID can be used here, as " "well as a wildcard (see example rule above)." msgstr "" "В четвёртом поле определяется эффективный пользователь или владелец процесса " "демона, который сообщает о событии. Здесь можно использовать имя " "пользователя или UID, а также подстановочный знак (см. пример правила выше)." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2535 msgid "" "The packet filter rule name is declared by the fifth field, which starts the " "behavior part of the rule. By default, blocklistd puts all blocks under a " "pf anchor called `blocklistd` in [.filename]#pf.conf# like this:" msgstr "" "Имя правила фильтра пакетов объявляется пятым полем, которое начинает " "поведенческую часть правила. По умолчанию, blocklistd помещает все " "блокировки в якорь pf под названием `blocklistd ` в [.filename]#pf.conf# " "следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2541 #, no-wrap msgid "" "anchor \"blocklistd/*\" in on $ext_if\n" "block in\n" "pass out\n" msgstr "" "anchor \"blocklistd/*\" in on $ext_if\n" "block in\n" "pass out\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2547 msgid "" "For separate blocklists, an anchor name can be used in this field. In other " "cases, the wildcard will suffice. When a name starts with a hyphen (`-`) it " "means that an anchor with the default rule name prepended should be used. A " "modified example from the above using the hyphen would look like this:" msgstr "" "Для отдельных списков блокировки в этом поле можно использовать имя якоря. В " "остальных случаях подойдет подстановочный знак. Если имя начинается с дефиса " "(`-`), это означает, что следует использовать якорь с добавленным именем " "правила по умолчанию. Модифицированный пример из вышеприведённого с " "использованием дефиса будет выглядеть так:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2551 #, no-wrap msgid "ssh stream * * -ssh 3 24h\n" msgstr "ssh stream * * -ssh 3 24h\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2554 msgid "" "With such a rule, any new blocklist rules are added to an anchor called " "`blocklistd-ssh`." msgstr "" "С таким правилом любые новые правила из списка блокировки добавляются к " "якорю с именем `blocklistd-ssh`." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2558 msgid "" "To block whole subnets for a single rule violation, a `/` in the rule name " "can be used. This causes the remaining portion of the name to be " "interpreted as the mask to be applied to the address specified in the rule. " "For example, this rule would block every address adjoining `/24`." msgstr "" "Для блокировки целых подсетей за одно нарушение правила можно использовать " "символ `/` в имени правила. Это приводит к тому, что оставшаяся часть имени " "интерпретируется как маска, применяемая к адресу, указанному в правиле. " "Например, это правило заблокирует все адреса, входящие в подсеть `/24`." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2562 #, no-wrap msgid "22 stream tcp * */24 3 24h\n" msgstr "22 stream tcp * */24 3 24h\n" #. type: delimited block = 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2568 msgid "" "It is important to specify the proper protocol here. IPv4 and IPv6 " "treat /24 differently, that is the reason why `*` cannot be used in the " "third field for this rule." msgstr "" "Здесь важно указать правильный протокол. IPv4 и IPv6 обрабатывают /24 по-" "разному, поэтому `*` нельзя использовать в третьем поле для этого правила." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2571 msgid "" "This rule defines that if any one host in that network is misbehaving, " "everything else on that network will be blocked, too." msgstr "" "Это правило определяет, что если любой хост в этой сети ведёт себя " "неправильно, всё остальное в этой сети также будет заблокировано." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2575 msgid "" "The sixth field, called `nfail`, sets the number of login failures required " "to blocklist the remote IP in question. When a wildcard is used at this " "position, it means that blocks will never happen. In the example rule " "above, a limit of three is defined meaning that after three attempts to log " "into SSH on one connection, the IP is blocked." msgstr "" "Шестое поле, называемое `nfail`, устанавливает количество неудачных попыток " "входа, необходимых для внесения IP-адреса внешнего хоста в чёрный список. " "Если в этой позиции используется подстановочный знак, это означает, что " "блокировки никогда не будут происходить. В приведённом выше примере правила " "установлен лимит в три попытки, что означает, что после трёх попыток входа " "через SSH с одного соединения IP-адрес будет заблокирован." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2578 msgid "" "The last field in a blocklistd rule definition specifies how long a host is " "blocklisted. The default unit is seconds, but suffixes like `m`, `h`, and " "`d` can also be specified for minutes, hours, and days, respectively." msgstr "" "Последнее поле в определении правила blocklistd указывает, как долго хост " "будет находиться в чёрном списке. По умолчанию единицей измерения являются " "секунды, но также можно указать суффиксы `m`, `h` и `d` для минут, часов и " "дней соответственно." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2582 msgid "" "The example rule in its entirety means that after three times authenticating " "to SSH will result in a new PF block rule for that host. Rule matches are " "performed by first checking local rules one after another, from most " "specific to least specific. When a match occurs, the `remote` rules are " "applied and the `name`, `nfail`, and `duration` fields are changed by the " "`remote` rule that matched." msgstr "" "Пример правила в полном объёме означает, что после трёх попыток " "аутентификации по SSH будет создано новое правило блокировки PF для этого " "хоста. Совпадения правил проверяются путем последовательной проверки " "локальных правил от наиболее специфичных к наименее специфичным. Когда " "совпадение найдено, применяются правила `remote`, а поля `name`, `nfail` и " "`duration` изменяются в соответствии с совпавшим правилом `remote`." #. type: Title ==== #: documentation/content/en/books/handbook/firewalls/_index.adoc:2583 #, no-wrap msgid "Remote Rules" msgstr "Правила remote" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2589 msgid "" "Remote rules are used to specify how blocklistd changes its behavior " "depending on the remote host currently being evaluated. Each field in a " "remote rule is the same as in a local rule. The only difference is in the " "way blocklistd is using them. To explain it, this example rule is used:" msgstr "" "Удалённые правила используются для указания того, как blocklistd изменяет " "своё поведение в зависимости от удалённого хоста, который в данный момент " "оценивается. Каждое поле в удалённом правиле совпадает с таковым в локальном " "правиле. Единственное различие заключается в том, как blocklistd их " "использует. Для объяснения используется следующее примерное правило:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2594 #, no-wrap msgid "" "[remote]\n" "203.0.113.128/25 * * * =/25 = 48h\n" msgstr "" "[remote]\n" "203.0.113.128/25 * * * =/25 = 48h\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2599 msgid "" "The address field can be an IP address (either v4 or v6), a port or both. " "This allows setting special rules for a specific remote address range like " "in this example. The fields for socket type, protocol and owner are " "identically interpreted as in the local rule." msgstr "" "Поле `address` может содержать IP-адрес (как v4, так и v6), порт или оба " "варианта. Это позволяет задавать специальные правила для определённого " "диапазона удалённых адресов, как в этом примере. Поля для типа сокета, " "протокола и владельца интерпретируются так же, как в локальном правиле." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2605 msgid "" "The name fields is different though: the equal sign (`=`) in a remote rule " "tells blocklistd to use the value from the matching local rule. It means " "that the firewall rule entry is taken and the `/25` prefix (a netmask of " "`255.255.255.128`) is added. When a connection from that address range is " "blocklisted, the entire subnet is affected. A PF anchor name can also be " "used here, in which case blocklistd will add rules for this address block to " "the anchor of that name. The default table is used when a wildcard is " "specified." msgstr "" "Поле name отличается: знак равенства (`=`) в удаленном правиле указывает " "blocklistd использовать значение из соответствующего локального правила. Это " "означает, что запись правила межсетевого экрана берется, и добавляется " "префикс `/25` (маска сети `255.255.255.128`). Когда соединение из этого " "диапазона адресов попадает в черный список, затрагивается вся подсеть. Здесь " "также можно использовать имя якоря PF, и в этом случае blocklistd добавит " "правила для этого блока адресов в якорь с указанным именем. Если указана " "подстановка, используется таблица по умолчанию." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2609 msgid "" "A custom number of failures in the `nfail` column can be defined for an " "address. This is useful for exceptions to a specific rule, to maybe allow " "someone a less strict application of rules or a bit more leniency in login " "tries. Blocking is disabled when an asterisk is used in this sixth field." msgstr "" "В столбце `nfail` можно задать произвольное количество неудачных попыток для " "адреса. Это полезно для исключений из конкретного правила, например, чтобы " "разрешить кому-то менее строгое применение правил или немного больше попыток " "входа. Блокировка отключается, если в шестом поле указана звёздочка." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2611 msgid "" "Remote rules allow a stricter enforcement of limits on attempts to log in " "compared to attempts coming from a local network like an office." msgstr "" "Удаленные правила позволяют более строго ограничивать попытки входа по " "сравнению с попытками, поступающими из локальной сети, например, из офиса." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2612 #, no-wrap msgid "Blocklistd Client Configuration" msgstr "Конфигурация клиента blocklistd" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2617 msgid "" "There are a few software packages in FreeBSD that can utilize blocklistd's " "functionality. The two most prominent ones are package:ftp/freebsd-ftpd[] " "and man:sshd[8] to block excessive connection attempts. To activate " "blocklistd in the SSH daemon, add the following line to [.filename]#/etc/ssh/" "sshd_config#:" msgstr "" "В FreeBSD есть несколько программных пакетов, которые могут использовать " "функциональность blocklistd. Два наиболее заметных — это package:ftp/freebsd-" "ftpd[] и man:sshd[8], предназначенные для блокировки чрезмерных попыток " "подключения. Чтобы активировать blocklistd в демоне SSH, добавьте следующую " "строку в [.filename]#/etc/ssh/sshd_config#:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2621 #, no-wrap msgid "UseBlocklist yes\n" msgstr "UseBlocklist yes\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2624 msgid "Restart sshd afterwards to make these changes take effect." msgstr "Перезапустите sshd, чтобы изменения вступили в силу." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2626 msgid "" "Blocklisting for package:ftp/freebsd-ftpd[] is enabled using `-B`, either in " "[.filename]#/etc/inetd.conf# or as a flag in [.filename]#/etc/rc.conf# like " "this:" msgstr "" "Cписок блокировки для package:ftp/freebsd-ftpd[] включается с помощью `-B`, " "либо в [.filename]#/etc/inetd.conf#, либо как флаг в [.filename]#/etc/rc." "conf# следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2630 #, no-wrap msgid "ftpd_flags=\"-B\"\n" msgstr "ftpd_flags=\"-B\"\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2633 msgid "That is all that is needed to make these programs talk to blocklistd." msgstr "" "Вот и всё, что требуется для настройки взаимодействия этих программ с " "blocklistd." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2634 #, no-wrap msgid "Blocklistd Management" msgstr "Управление blocklistd" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2639 msgid "" "Blocklistd provides the user with a management utility called man:" "blocklistctl[8]. It displays blocked addresses and networks that are " "blocklisted by the rules defined in man:blocklistd.conf[5]. To see the list " "of currently blocked hosts, use `dump` combined with `-b` like this." msgstr "" "Blocklistd предоставляет пользователю утилиту управления под названием " "man:blocklistctl[8]. Она отображает заблокированные адреса и сети, которые " "внесены в список блокировки согласно правилам, определённым в man:blacklistd." "conf[5]. Чтобы просмотреть список текущих заблокированных хостов, " "используйте команду `dump` с параметром `-b`, например." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2645 #, no-wrap msgid "" "# blocklistctl dump -b\n" "rulename address/ma:port id nfail last access\n" "blocklistd 213.0.123.128/25:22 OK 6/3 2019/06/08 14:30:19\n" msgstr "" "# blocklistctl dump -b\n" "rulename address/ma:port id nfail last access\n" "blocklistd 213.0.123.128/25:22 OK 6/3 2019/06/08 14:30:19\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2651 msgid "" "This example shows that there were 6 out of three permitted attempts on port " "22 coming from the address range `213.0.123.128/25`. There are more " "attempts listed than are allowed because SSH allows a client to try multiple " "logins on a single TCP connection. A connection that is currently going on " "is not stopped by blocklistd. The last connection attempt is listed in the " "`last access` column of the output." msgstr "" "Этот пример показывает, что было 6 попыток из трёх разрешённых на порт 22, " "исходящих из диапазона адресов `213.0.123.128/25`. Количество попыток " "превышает разрешённое, потому что SSH позволяет клиенту выполнять несколько " "попыток входа в рамках одного TCP-соединения. Текущее соединение не " "прерывается blocklistd. Последняя попытка соединения указана в столбце `last " "access` вывода." #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2653 msgid "" "To see the remaining time that this host will be on the blocklist, add `-r` " "to the previous command." msgstr "" "Чтобы увидеть оставшееся время, в течение которого этот хост будет в списке " "блокировки, добавьте `-r` к предыдущей команде." #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2659 #, no-wrap msgid "" "# blocklistctl dump -br\n" "rulename address/ma:port id nfail remaining time\n" "blocklistd 213.0.123.128/25:22 OK 6/3 36s\n" msgstr "" "# blocklistctl dump -br\n" "rulename address/ma:port id nfail remaining time\n" "blocklistd 213.0.123.128/25:22 OK 6/3 36s\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2662 msgid "" "In this example, there are 36s seconds left until this host will not be " "blocked any more." msgstr "" "В этом примере осталось 36 секунд, пока этот хост не будет разблокирован." #. type: Title === #: documentation/content/en/books/handbook/firewalls/_index.adoc:2663 #, no-wrap msgid "Removing Hosts from the Block List" msgstr "Удаление узлов из списка блокировки" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2674 msgid "" "Sometimes it is necessary to remove a host from the block list before the " "remaining time expires. Unfortunately, there is no functionality in " "blocklistd to do that. However, it is possible to remove the address from " "the PF table using pfctl. For each blocked port, there is a child anchor " "inside the blocklistd anchor defined in [.filename]#/etc/pf.conf#. For " "example, if there is a child anchor for blocking port 22 it is called " "`blocklistd/22`. There is a table inside that child anchor that contains " "the blocked addresses. This table is called port followed by the port " "number. In this example, it would be called `port22`. With that " "information at hand, it is now possible to use man:pfctl[8] to display all " "addresses listed like this:" msgstr "" "Иногда необходимо удалить узел из чёрного списка до истечения оставшегося " "времени. К сожалению, в blocklistd нет функциональности для этого. Однако " "можно удалить адрес из таблицы PF с помощью pfctl. Для каждого " "заблокированного порта существует дочерний якорь внутри якоря blocklistd, " "определённого в [.filename]#/etc/pf.conf#. Например, если есть дочерний " "якорь для блокировки порта 22, он называется `blocklistd/22`. Внутри этого " "дочернего якоря находится таблица, содержащая заблокированные адреса. Эта " "таблица называется port с указанием номера порта. В данном примере она будет " "называться `port22`. Имея эту информацию, можно использовать man:pfctl[8] " "для отображения всех перечисленных адресов следующим образом:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2681 #, no-wrap msgid "" "# pfctl -a blocklistd/22 -t port22 -T show\n" "...\n" "213.0.123.128/25\n" "...\n" msgstr "" "# pfctl -a blocklistd/22 -t port22 -T show\n" "...\n" "213.0.123.128/25\n" "...\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2684 msgid "" "After identifying the address to be unblocked from the list, the following " "command removes it from the list:" msgstr "" "После определения адреса, который нужно разблокировать из списка, следующая " "команда удаляет его из списка:" #. type: delimited block . 4 #: documentation/content/en/books/handbook/firewalls/_index.adoc:2688 #, no-wrap msgid "# pfctl -a blocklistd/22 -t port22 -T delete 213.0.123.128/25\n" msgstr "# pfctl -a blocklistd/22 -t port22 -T delete 213.0.123.128/25\n" #. type: Plain text #: documentation/content/en/books/handbook/firewalls/_index.adoc:2692 msgid "" "The address is now removed from PF, but will still show up in the " "blocklistctl list, since it does not know about any changes made in PF. The " "entry in blocklistd's database will eventually expire and be removed from " "its output. The entry will be added again if the host is matching one of " "the block rules in blocklistd again." msgstr "" "Адрес теперь удалён из PF, но всё ещё будет отображаться в списке " "blocklistctl, так как он не знает о внесённых в PF изменениях. Запись в базе " "данных blocklistd со временем истечёт и будет удалена из вывода. Запись " "будет добавлена снова, если хост снова совпадёт с одним из правил блокировки " "в blocklistd."