Difference between pages "Install/ru/Partitioning" and "Package:Nftables"

From Funtoo
< Install‎ | ru(Difference between pages)
Jump to navigation Jump to search
 
 
Line 1: Line 1:
<noinclude>
{{Ebuild
{{InstallPart|процесс разбиения диска и создания файловых систем}}
|Summary=Linux kernel (3.13+) firewall, NAT and packet mangling tools
</noinclude>
|CatPkg=net-firewall/nftables
=== Подготовка жесткого диска ===
|Repository=Gentoo Portage Tree
}}
=== What is nftables? ===
'''nftables''' is the successor to [[iptables]]. It replaces the existing iptables, ip6tables, arptables and ebtables framework. It uses the Linux kernel and a new userspace utility called nft. nftables provides a compatibility layer for the ip(6)tables and framework.


В этой части  мы научимся различным способам установки Funtoo Linux -- и загрузки с -- жесткого диска.
==Introduction==
As with the iptables framework, nftables is build upon rules which specify the actions. These rules are attached to chains. A chain can contain a collection of rules and is registered into the netfilter hooks. Chains are stored inside tables. A table is specific for one of the layer 3 protocols. One of the main differences with iptables is that there are no predefined tables and chains anymore.


==== Введение ====
===Tables===
A table is nothing more than a container for your chains. With nftables there are no predefined tables (filter, raw, mangle...) anymore. You are free to recreate the iptables-like structure, but anything might do.
Currently there are 5 different families of tables:
* '''ip''': Used for IPv4 related chains;
* '''ip6''': Used for IPv6 related chains;
* '''arp''': Used for ARP related chains;
* '''bridge''': Used for bridging related chains;
* '''inet''': Mixed ipv4/ipv6 chains (kernel 3.14 and up).


В прежние времена существовал лишь один способ загрузить PC-совместимый компьютер. Все наши дектопы и сервера имели стандартный PC BIOS, все наши харды использовали MBR и были разбиты используя схему разбивки MBR. Вот как это все было и нам это нравилось!
It is not hard to recognize the old tables framework in these tables. The only new one is the inet table which is used for both IPv4 and IPv6 traffic. It should make firewalling for dual-stack hosts easier by combining the rules for IPv4 and IPv6.


Затем появились EFI и UEFIвстроенные программы нового образца наряду со схемой разбивки GPT, поддерживающая диски размером более 2.2TБ. Неожиданно, нам стали доступны различные способы установки и загрузки Линукс систем . То, что было единым методом, стало чем-то более сложным.
===Chains===
Chains are used to group together rules. As with the tables, nftables does not have any predefined chains. Chains are grouped in base and non-base types. Base chains are registered in one of the netfilter hooks. A base chain has a hook its registered with, a type and a priority. Non-base chains are not attached to a hook and they don't see any traffic by default. They can be used to arrange a rule-set in a tree of chains.
There are currently three types of chains:
* '''filter''': for filtering packets
* '''route''': for rerouting packets
* '''nat''': for performing Network Address Translation. Only the first packet of a flow hits this chain, making it impossible to use it for filtering.
The hooks that can be used are:
* '''prerouting''': This is before the routing decision, all packets entering the machine hits this chain
* '''input''': All packets for the local system hits this hook
* '''forward''': Packets not for the local system, those that need to be forwarded hits this hook
* '''output''': Packets that originate from the local system pass this hook
* '''postrouting''': This hook is after the routing decision, all packets leaving the machine hits this chain
{{Note|The ARP address family only supports the input and output hook}}
{{Note|The bridge address family only seems to supports the input, forward and output hook}}


Воспользуемся моментом и рассмотрим доступные способы конфигурации жесткого диска для загрузки Funtoo Linux. Данное Руководство рекомендует способ "по-старинке" , загрузка BIOS и использование MBR.  Данный способ работает (за исключением редких случаев) и всесторонне поддерживается. И в этом нет ничего плохого. Если Ваш жесткий диск 2TБ или меньшего размера это не является препятствием для использования всего дискового пространства.
====Priorities====
{{Note| Priorities do not currently appear to have any effect on which chain sees packets first.}}
{{Note| Since the priority seems to be an unsigned integer, negative priorities will be converted into very high priorities.}}


Но, бывают ситуации когда метод "по-старинке"  не является оптимальным. Если Ваш жесткий диск размером более 2TБ , MBR разбивка не сможет обеспечить доступ ко всему дисковому пространству. Это одна из причин. Вторая причина: существуют  "PC" системы, которые более не поддерживают  BIOS загрузку  и  форсируют UEFI загрузку. Из чувства сострадания к тем, кто попал в затруднение перед выбором, это Руководство также описывает установку и загрузку UEFI систем.
===Rules===
Rules specify which action has to be taken for which packets. Rules are attached to chains. Each rule can has an expression to match packets with and one or multiple actions when matching. Main differences with iptables is that it is possible to specify multiple actions and that by default counters are off. It must be specified explicitly in rules if you want packet- and byte-counters for a rule.
Each rule has a unique handle number by which it can be distinguished.
The following matches are available:
* '''ip''': IP protocol
* '''ip6''': IPv6 protocol
* '''tcp''': TCP protocol
* '''udp''': UDP protocol
* '''udplite''': UDP-lite protocol
* '''sctp''': SCTP protocol
* '''dccp''': DCCP protocol
* '''ah''': Authentication headers
* '''esp''': Encrypted security payload headers
* '''ipcomp''': IPcomp headers
* '''icmp''': icmp protocol
* '''icmpv6''': icmpv6 protocol
* '''ct''': Connection tracking
* '''meta''': meta properties such as interfaces


Мы всё же рекомендуем разбивку "по-старинке". Загрузчик, который мы используем для загрузки Линукс в этом руководстве называется GRUB, таки образом мы называем метод  как '''BIOS + GRUB (MBR)''' . Это традиционный способ установки на PC-совместимые компьютеры.
====Matches====
{|class=wikitable
| Match
| Arguments
| Description/Example
|-
| rowspan="11" | '''ip'''
| version
| Ip Header version
|-
| hdrlength
| IP header length
|-
| tos
|Type of Service
|-
| length
| Total packet length
|-
| id
| IP ID
|-
| frag-off
| Fragmentation offset
|-
| ttl
| Time to live
|-
| protocol
| Upper layer protocol
|-
| checksum
| IP header checksum
|-
| saddr
| Source address
|-
| daddr
| Destination address
|-
| rowspan="8" | '''ip6'''
| version
| IP header version
|-
| priority
|
|-
| flowlabel
| Flow label
|-
| length
| Payload length
|-
| nexthdr
| Next header type (Upper layer protocol number)
|-
| hoplimit
| Hop limit
|-
|saddr
| Source Address
|-
|daddr
| Destination Address
|-
| rowspan="9" | '''tcp'''
| sport
| Source port
|-
| dport
| Destination port
|-
| sequence
| Sequence number
|-
| ackseq
| Acknowledgement number
|-
| doff
| Data offset
|-
| flags
| TCP flags
|-
| window
| Window
|-
| checksum
| Checksum
|-
| urgptr
| Urgent pointer
|-
| rowspan="4" | '''udp'''
| sport
| Source port
|-
| dport
| destination port
|-
| length
| Total packet length
|-
| checksum
| Checksum
|-
| rowspan="4" | '''udplite'''
| sport
| Source port
|-
| dport
| destination port
|-
| cscov
| Checksum coverage
|-
| checksum
| Checksum
|-
| rowspan="4" |'''sctp'''
| sport
| Source port
|-
| dport
| destination port
|-
|vtag
|Verification tag
|-
| checksum
| Checksum
|-
| rowspan="2" |'''dccp'''
| sport
| Source port
|-
| dport
| destination port
|-
| rowspan="4" |'''ah'''
| nexthdr
| Next header protocol (Upper layer protocol)
|-
| hdrlength
| AH header length
|-
| spi
| Security Parameter Index
|-
| sequence
| Sequence Number
|-
| rowspan="2" | '''esp'''
| spi
| Security Parameter Index
|-
| sequence
| Sequence Number
|-
| rowspan="3" | '''ipcomp'''
| nexthdr
| Next header protocol (Upper layer protocol)
|-
| flags
| Flags
|-
| cfi
| Compression Parameter Index
|-
| '''icmp'''
| type
| icmp packet type
|-
| '''icmpv6'''
| type
| icmpv6 packet type
|-
|rowspan="12"|'''ct'''
|state
|State of the connection
|-
|direction
|Direction of the packet relative to the connection
|-
|status
|Status of the connection
|-
|mark
|Connection mark
|-
|expiration
|Connection expiration time
|-
|helper
|Helper associated with the connection
|-
|l3proto
|Layer 3 protocol of the connection
|-
|saddr
|Source address of the connection for the given direction
|-
|daddr
|Destination address of the connection for the given direction
|-
|protocol
|Layer 4 protocol of the connection for the given direction
|-
|proto-src
|Layer 4 protocol source for the given direction
|-
|proto-dst
|Layer 4 protocol destination for the given direction
|-
| rowspan="13" | '''meta'''
| length
| Length of the packet in bytes: ''meta length > 1000''
|-
| protocol
| ethertype protocol: ''meta protocol vlan''
|-
| priority
| TC packet priority
|-
| mark
| Packet mark
|-
| iif
| Input interface index
|-
| iifname
| Input interface name
|-
| iiftype
| Input interface type
|-
| oif
| Output interface index
|-
| oifname
| Output interface name
|-
| oiftype
| Output interface hardware type
|-
| skuid
| UID associated with originating socket
|-
| skgid
| GID associated with originating socket
|-
| rtclassid
| Routing realm
|-
|}
====Statements====
Statements represent the action to be performed when the rule matches. They exist in two kinds: Terminal statements, unconditionally terminate the evaluation of the current rules and non-terminal statements that either conditionally or never terminate the current rules. There can be an arbitrary amount of non-terminal statements, but there must be only a single terminal statement.
The terminal statements can be:
* '''accept''': Accept the packet and stop the ruleset evaluation.
* '''drop''': Drop the packet and stop the ruleset evaluation.
* '''reject''': Reject the packet with an icmp message
* '''queue''': Queue the packet to userspace and stop the ruleset evaluation.
* '''continue''':
* '''return''': Return from the current chain and continue at the next rule of the last chain. In a base chain it is equivalent to accept
* '''jump <chain>''': Continue at the first rule of <chain>. It will continue at the next rule after a return statement is issued
* '''goto <chain>''': Similar to jump, but after the new chain the evaluation will continue at the last chain instead of the one containing the goto statement


Если Вам необходимо использование UEFI для загрузки, мы советуем не использовать MBR вообще, ввиду того, что некоторые системы поддерживают MBR,  а некоторые нет. Вместо, мы советуем использование UEFI  для загрузки GRUB, который, затем в свою очередь загрузит Линукс. Мы называем этот  метод как '''UEFI + GRUB (GPT)'''.
== Installing nftables ==
=== Kernel ===
These kernel options must be set:


И да, есть еще несколько способов, некоторые из них задокументированы в [[Boot Methods]] . Обычно мы рекомендуем  '''BIOS + GRUB (GPT)''' метод, но он ограничивается не столь широкой поддержкой со стороны комплектующих.
[*] Networking support  --->
    Networking options  --->
        [*] Network packet filtering framework (Netfilter) --->
            Core Netfilter Configuration  --->
                <M> Netfilter nf_tables support
                <M>  Netfilter nf_tables IPv6 exthdr module
                <M>  Netfilter nf_tables meta module
                <M>  Netfilter nf_tables conntrack module
                <M>  Netfilter nf_tables rbtree set module
                <M>  Netfilter nf_tables hash set module
                <M>  Netfilter nf_tables counter module
                <M>  Netfilter nf_tables log module
                <M>  Netfilter nf_tables limit module
                <M>  Netfilter nf_tables nat module
                <M>  Netfilter x_tables over nf_tables module
            IP: Netfilter Configuration  --->
                <M> IPv4 nf_tables support
                <M>  nf_tables IPv4 reject support
                <M>  IPv4 nf_tables route chain support
                <M>  IPv4 nf_tables nat chain support
            IPv6: Netfilter Configuration  --->
                <M> IPv6 nf_tables support
                <M>  IPv6 nf_tables route chain support
                <M>  IPv6 nf_tables nat chain support
            <M>  Ethernet Bridge nf_tables support


'''Вопрос --  какой из методов использовать?'''  Вот какой.
=== Emerging ===
To install nftables, run the following command:
<console>
###i## emerge net-firewall/nftables
</console>


;Принцип 1 - "По-старинке":  Если Вы можете успешно загрузить System Rescue CD и видите синее меню, то Вы используете BIOS,  и скорее всего Вы можете загрузить Funtoo Linux используя BIOS. Итак,  следуйте этому способу и используйте BIOS загрузку,  кроме случаев Вам по-какой либо причине необходим UEFI, например если размер жесткого диска >2.2TБ.  В этом случае следуйте Принцип  2.


;Принцип 2 - "Модерн": Если Вы можете успешно загрузить System Rescue CD и видите черно-белое меню -- поздравления,  Ваша система поддерживает UEFI загрузку. Это значит, что Вы готовы установить Funtoo Linux к загрузке с помощью UEFI.  Ваша система также может поддерживать загрузку BIOS,  но попрбуйте UEFI для начала. Вы можете "покопаться" в настройках BIOS.
== OpenRC configuration ==
Don't forget to add nftables service to startup:
<console>
###i## rc-update add nftables default
</console>


;Какая разница между "По-старинке" и "Модерн"?:  Если Вы следуете  MBR разбивке, Ваш <code>/boot</code> раздел будет отформатирован файловой системой ext2 , и Вы будете использовать <code>fdisk</code> для создания MBR разделов. Если Вы следуете "модерн", GPT разделам и UEFI загрузке,  Ваш <code>/boot</code> раздел будет отформатирован  в файловую систему vfat,  поскольку это единственная файловая система поддерживаемая UEFI, и Вы будете использовать <code>gdisk</code> для создания GPT разделов. И Вы установите GRUB несколько иначе.  Вот к чему сводится различие между методами.
You cannot use iptables and nft to perform NAT at the same time. So make sure that the iptable_nat module is unloaded. Remove iptables_nat module:
 
<console>
;Имейте в виду: Для установки Funtoo Linux используя метод "модерн", Вы должны загрузить System Rescue CD в UEFI режиме -- и увидеть начальное черно-белое меню. В противном случае, UEFI не активно и Вы не сможете продолжить!
###i## rmmod iptable_nat
 
</console>
{{Note|'''Некоторые материнские платы якобы поддерживают UEFI, но на самом деле нет.''' Исследуйте . К примеру,  Award BIOS в моей Gigabyte GA-990FXA-UD7 rev 1.1 имеет возможность включить UEFI загрузку для CD/DVD. '''Этого не достаточно для обеспечения UEFI загрузки для жестких дисков и установки Funtoo Linux.''' UEFI должно поддерживать и сьемные носители (таким образом Вы сможете загрузить System Rescue CD используя  UEFI) и жесткие диски (Вы можете загрузить Funtoo Linux.) Оказывается, что более поздние ревизии этой платы (rev 3.0) имеют новую версию BIOS который полностью поддерживает UEFI.  Это приводит к третьему принципу -- знайте Ваши комплектующие.}}
 
==== Метод (BIOS/MBR) "По-старинке" ====
 
{{Note|Используйте данный метод при загрузке с помощью BIOS,  и если System Rescue CD имеет начальное меню загрузки светло-голубое.  Если Вы собираетесь использовать "модерн", [[#Метод (UEFI/GPT) "Модерн"|кликните здесь в меню UEFI/GPT.]]}}
 
===== Подготовка =====
 
Прежде чем начать , неплохо бы удостовериться, что Вы используете нужный диск для разбивки.  Попробуйте эту комманду и проверьте, что <code>/dev/sda</code> тот самый диск, который Вы желаете разбить:


Start nftables:
<console>
<console>
# ##i##fdisk -l /dev/sda
###i## /etc/init.d/nftables start
 
Disk /dev/sda: 640.1 GB, 640135028736 bytes, 1250263728 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt
 
 
#        Start          End    Size  Type            Name
1        2048  1250263694  596.2G  Linux filesyste Linux filesystem
</console>
</console>


Теперь, рекомендуем стереть  существующие таблицы разделов  MBR или GPT,  которые могут помешать BIOS во время загрузки. Мы используем комманду <code>sgdisk</code>:
{{fancywarning|Это необратимый процесс, который уничтожит все разделы!  Вы предупреждены! Советуем сохранить критические данние перед этим.}}


== Using nftables ==
All nftable commands are done with the nft ultility from {{Package|net-firewall/nftables}}.
===Tables===
====Creating tables====
The following command adds a table called filter for the ip(v4) layer
<console>
<console>
# ##i##sgdisk --zap-all /dev/sda
###i## nft add table ip filter
 
Creating new GPT entries.
GPT data structures destroyed! You may now partition the disk using fdisk or
other utilities.
</console>
</console>
 
Likewise a table for arp can be created with
Не стоит беспокоится об этом сообщении, так как комманда успешно выполнена:
 
<console>
<console>
***************************************************************
###i## nft add table arp filter
Found invalid GPT and valid MBR; converting MBR to GPT format
in memory.
***************************************************************
</console>
</console>
 
{{Note|The name "filter" used here is completly arbitrary. It could have any name}}
===== Разбивка диска =====
====Listing tables====
 
The following command lists all tables for the ip(v4) layer
Теперь мы используем <code>fdisk</code> для создания таблицы разделов MBR и самих разделов:
 
<console>
<console>
# ##i##fdisk /dev/sda
###i## nft list tables ip
</console>
</console>
 
<pre>
В консоли <code>fdisk</code>, следуйте следующим шагам:
table filter
 
</pre>
'''Очистить таблицу разделов''':
The contents of the table filter can be listed with:
 
<console>
<console>
Command (m for help): ##i##o ↵
###i## nft list table ip filter
</console>
</console>
 
<pre>
'''Создать раздел 1''' (boot):
table ip filter {
 
        chain input {
                type filter hook input priority 0;
                ct state established,related accept
                iifname "lo" accept
                ip protocol icmp accept
                drop
        }
}
</pre>
using -a with the nft command, it shows the handle of each rule. Handles are used for various operations on specific rules:
<console>
<console>
Command (m for help): ##i##n ↵
###i## nft -a list table ip filter
Partition type (default p): ##i##
Partition number (1-4, default 1): ##i##↵
First sector: ##i##↵
Last sector: ##i##+128M ↵
</console>
</console>
<pre>
table ip filter {
        chain input {
                type filter hook input priority 0;
                ct state established,related accept # handle 2
                iifname "lo" accept # handle 3
                ip protocol icmp accept # handle 4
                drop # handle 5
        }
}
</pre>


'''Создать раздел 2''' (своп):
====Deleting tables====
 
The following command deletes the table called filter for the ip(v4) layer:
<console>
<console>
Command (m for help): ##i##n ↵
###i## nft delete table ip filter
Partition type (default p): ##i##↵
Partition number (2-4, default 2): ##i##↵
First sector: ##i##↵
Last sector: ##i##+2G ↵
Command (m for help): ##i##t ↵
Partition number (1,2, default 2): ##i## ↵
Hex code (type L to list all codes): ##i##82 ↵
</console>
</console>
 
===chains===
'''Создать корневой раздел:'''
====Adding chains====
 
The following command adds a chain called input to the ip filter table and registered to the input hook with priority 0. It is of the type filter.
<console>
<console>
Command (m for help): ##i##n ↵
###i## nft add chain ip filter input { type filter hook input priority 0 \; }
Partition type (default p): ##i##↵
Partition number (3,4, default 3): ##i##↵
First sector: ##i##↵
Last sector: ##i##↵
</console>
</console>
{{Note|If You're running this command from Bash you need to escape the semicolon}}
A non-base chain can be added by not specifying the chain configurations between the curly braces.


'''Проверить таблицу разделов:'''
====Removing chains====
 
The following command deletes the chain called input
<console>
<console>
Command (m for help): ##i##p
###i## nft delete chain ip filter input
 
Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x82abc9a6
 
Device    Boot    Start      End    Blocks  Id System
/dev/sda1          2048    264191    131072  83 Linux
/dev/sda2        264192  4458495  2097152  82 Linux swap / Solaris
/dev/sda3        4458496 625142447 310341976  83 Linux
</console>
</console>
 
{{Note|Chains can only be deleted if there are no rules in them.}}
'''Записать таблицу разделов на диск:'''
===rules===
 
====Adding rules====
The following command adds a rule to the chain called input, on the ip filter table, dropping all traffic to port 80:
<console>
<console>
Command (m for help): ##i##w
###i## nft add rule ip filter input tcp dport 80 drop
</console>
</console>
 
====Deleting Rules====
Ваша новая таблица разделов будет записана на диск.
To delete a rule, you first need to get the handle number of the rule. This can be done by using the -a flag on nft:
 
{{Note|Вы завершили создание разделов! Теперь, перейдите к  [[#Создание файловых систем|Создание файловых систем]].}}
 
==== Метод (UEFI/GPT) "Модерн" ====
 
{{Note|Используйте данный метод при загрузке с помощью UEFI, и если System Rescue CD имеет начальное меню загрузки черно-белого цвета. Если оно было светло-голубого цвета, этот метод не будет работать.}}
 
Комманда <tt>gdisk</tt> используется для создания таблицы разделов GPT .  Измените размеры в соответсвии Вашим требованиям, хотя приведенные ниже размеры будут работать для большинства пользователей. Запустите <code>gdisk</code>:
 
<console>
<console>
# ##i##gdisk
###i## nft  rule ip filter input tcp dport 80 drop
</console>
</console>
 
<pre>
В консоли <tt>gdisk</tt>,  следуйте следующим шагам:
table ip filter {
 
        chain input {
'''Создайте новую пустую таблицу разделов''' (Это уничтожит данные при сохранении на диск):
                type filter hook input priority 0;
 
                tcp dport http drop # handle 2
        }
}
</pre>
It is then possible to delete the rule with:
<console>
<console>
Command: ##i##o ↵
###i## nft delete rule ip filter input handle 2
This option deletes all partitions and creates a new protective MBR.
Proceed? (Y/N): ##i##y ↵
</console>
</console>
 
== Management ==
'''Создайте раздел 1''' (загрузочный):
=== Backup ===
 
You can also backup your rules:
<console>
<console>
Command: ##i##n ↵
###i## echo "nft flush ruleset" > backup.nft
Partition Number: ##i##1 ↵
First sector: ##i##↵
Last sector: ##i##+500M ↵
Hex Code: ##i##
</console>
</console>
'''Создайте раздел 2''' (своп):


<console>
<console>
Command: ##i##n ↵
###i## nft list ruleset >> backup.nft
Partition Number: ##i##2 ↵
First sector: ##i##↵
Last sector: ##i##+4G ↵
Hex Code: ##i##8200 ↵
</console>
</console>


'''Создайте раздел 3''' (корневой):
=== Restoration ===
 
And load it atomically:
<console>
<console>
Command: ##i##n ↵
###i## nft -f backup.nft
Partition Number: ##i##3 ↵
First sector: ##i##↵
Last sector: ##i##↵##!i## (for rest of disk)
Hex Code: ##i##
</console>
</console>


По пути Вы можете набрать "<tt>p</tt>" и нажать Enter для просмотра текущей таблицы разделов. Если Вы допустили ошибку,  наберите "<tt>d</tt>" для удаления созданного раздела. Если Вы удовлетворены Вашей схемой разделов, наберите "<tt>w</tt>" для записи таблицы на диск:
== OpenRC configuration ==
 
'''Записать таблицу разделов на диск''':


Don't forget to add nftables service to startup:
<console>
<console>
Command: ##i##w ↵
###i## rc-update add nftables default
Do you want to proceed? (Y/N): ##i##Y ↵
</console>
</console>
== Init script - firewall nftables like a firewall iptables ==
<pre>
#!/sbin/runscript
#      Raphael Bastos aka coffnix        #
#      Init Script for Funtoo Linux      #
##########################################


Таблица разделов будет записана на диск и <tt>gdisk</tt> завершит работу.
depend() {
 
        need net
Теперь  GPT/GUID разделы созданы, и будут показаны как ''блочные утройства'' в Linux:
        need nftables
 
        }
* <tt>/dev/sda1</tt>, будет использоваться  для <tt>/boot</tt>, загрузочный раздел
* <tt>/dev/sda2</tt>, будет использоваться как своп , и
* <tt>/dev/sda3</tt>, корневой раздел.


==== Создание файловых систем ====
start(){
##################### PARTE 1 #####################
ebegin "Starting Firewall NFTables"


{{Note|Данная часть рассматривает как BIOS ''так и'' UEFI установки. Не пропускайте раздел!}}
#######################################################################
### Incompatibilities ###
# You cannot use iptables and nft to perform NAT at the same time.
# So make sure that the iptable_nat module is unloaded
rmmod iptable_nat


Before your newly-created partitions can be used, the block devices need to be initialized with filesystem ''metadata''. This process is known as ''creating a filesystem'' on the block devices. After filesystems are created on the block devices, they can be mounted and used to store files.
#######################################################################


Let's keep this simple. Are you using old-school MBR partitions? If so, let's create an ext2 filesystem on /dev/sda1:
echo 1 > /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/ipv4/ip_dynaddr
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done


<console>
#######################################################################
# ##i##mkfs.ext2 /dev/sda1
</console>


If you're using new-school GPT partitions for UEFI, you'll want to create a vfat filesystem on /dev/sda1, because this is what UEFI is able to read:
iptables -t nat -F


<console>
#######################################################################
# ##i##mkfs.vfat -F 32 /dev/sda1
</console>


Now, let's create a swap partition. This partition will be used as disk-based virtual memory for your Funtoo Linux system.
# ipv4
nft -f /etc/nftables/ipv4-filter


You will not create a filesystem on your swap partition, since it is not used to store files. But it is necessary to initialize it using the <code>mkswap</code> command. Then we'll run the <code>swapon</code> command to make your newly-initialized swap space immediately active within the live CD environment, in case it is needed during the rest of the install process:
# ipv4 nat
nft -f /etc/nftables/ipv4-nat


<console>
# ipv6
# ##i##mkswap /dev/sda2
nft -f /etc/nftables/ipv6-filter
# ##i##swapon /dev/sda2
</console>


Now, we need to create a root filesystem. This is where Funtoo Linux will live. We generally recommend ext4 or XFS root filesystems. If you're not sure, choose ext4. Here's how to create a root ext4 filesystem:
# Rules firewall NTFtables
nft -f /etc/nftables/firewall.rules


<console>
#######################################################################
# ##i##mkfs.ext4 /dev/sda3
</console>


...and here's how to create an XFS root filesystem, if you choose to use XFS:
}


<console>
stop(){
# ##i##mkfs.xfs /dev/sda3
ebegin "Stoping Firewall NFTables"
</console>


Your filesystems (and swap) have all now been initialized, so that that can be mounted (attached to your existing directory heirarchy) and used to store files. We are ready to begin installing Funtoo Linux on these brand-new filesystems.
#######################################################################


{{fancywarning|1=
#iptables -t nat -F
When deploying an OpenVZ host, please use ext4 exclusively. The Parallels development team tests extensively with ext4, and modern versions of <code>openvz-rhel6-stable</code> are '''not''' compatible with XFS, and you may experience kernel bugs.
NFT=nft
}}
FAMILIES="ip ip6 arp bridge"


==== Mounting filesystems ====
for FAMILY in $FAMILIES; do
  TABLES=$($NFT list tables $FAMILY | grep "^table\s" | cut -d' ' -f2)


Mount the newly-created filesystems as follows, creating <code>/mnt/funtoo</code> as the installation mount point:
  for TABLE in $TABLES; do
    CHAINS=$($NFT list table $FAMILY $TABLE | grep "^\schain\s" | cut -d' ' -f2)


<console>
    for CHAIN in $CHAINS; do
# ##i##mkdir /mnt/funtoo
      echo "Flushing chain: $FAMILY->$TABLE->$CHAIN"
# ##i##mount /dev/sda3 /mnt/funtoo
      $NFT flush chain $FAMILY $TABLE $CHAIN
# ##i##mkdir /mnt/funtoo/boot
      $NFT delete chain $FAMILY $TABLE $CHAIN
# ##i##mount /dev/sda1 /mnt/funtoo/boot
    done
</console>


Optionally, if you have a separate filesystem for <code>/home</code> or anything else:
    echo "Flushing table: $FAMILY->$TABLE"
    $NFT flush table $FAMILY $TABLE
    $NFT delete table $FAMILY $TABLE
  done
done
}


<console>
status(){
# ##i##mkdir /mnt/funtoo/home
nft list ruleset
# ##i##mount /dev/sda4 /mnt/funtoo/home
}
</console>


If you have <code>/tmp</code> or <code>/var/tmp</code> on a separate filesystem, be sure to change the permissions of the mount point to be globally-writeable after mounting, as follows:
# End
</pre>


<console>
[[Category:System]]
# ##i##chmod 1777 /mnt/funtoo/tmp
[[Category:First Steps]]
</console>
{{EbuildFooter}}

Revision as of 14:22, February 22, 2015

Nftables

   Tip

We welcome improvements to this page. To edit this page, Create a Funtoo account. Then log in and then click here to edit this page. See our editing guidelines to becoming a wiki-editing pro.

What is nftables?

nftables is the successor to iptables. It replaces the existing iptables, ip6tables, arptables and ebtables framework. It uses the Linux kernel and a new userspace utility called nft. nftables provides a compatibility layer for the ip(6)tables and framework.

Introduction

As with the iptables framework, nftables is build upon rules which specify the actions. These rules are attached to chains. A chain can contain a collection of rules and is registered into the netfilter hooks. Chains are stored inside tables. A table is specific for one of the layer 3 protocols. One of the main differences with iptables is that there are no predefined tables and chains anymore.

Tables

A table is nothing more than a container for your chains. With nftables there are no predefined tables (filter, raw, mangle...) anymore. You are free to recreate the iptables-like structure, but anything might do. Currently there are 5 different families of tables:

  • ip: Used for IPv4 related chains;
  • ip6: Used for IPv6 related chains;
  • arp: Used for ARP related chains;
  • bridge: Used for bridging related chains;
  • inet: Mixed ipv4/ipv6 chains (kernel 3.14 and up).

It is not hard to recognize the old tables framework in these tables. The only new one is the inet table which is used for both IPv4 and IPv6 traffic. It should make firewalling for dual-stack hosts easier by combining the rules for IPv4 and IPv6.

Chains

Chains are used to group together rules. As with the tables, nftables does not have any predefined chains. Chains are grouped in base and non-base types. Base chains are registered in one of the netfilter hooks. A base chain has a hook its registered with, a type and a priority. Non-base chains are not attached to a hook and they don't see any traffic by default. They can be used to arrange a rule-set in a tree of chains. There are currently three types of chains:

  • filter: for filtering packets
  • route: for rerouting packets
  • nat: for performing Network Address Translation. Only the first packet of a flow hits this chain, making it impossible to use it for filtering.

The hooks that can be used are:

  • prerouting: This is before the routing decision, all packets entering the machine hits this chain
  • input: All packets for the local system hits this hook
  • forward: Packets not for the local system, those that need to be forwarded hits this hook
  • output: Packets that originate from the local system pass this hook
  • postrouting: This hook is after the routing decision, all packets leaving the machine hits this chain
   Note

The ARP address family only supports the input and output hook

   Note

The bridge address family only seems to supports the input, forward and output hook

Priorities

   Note
Priorities do not currently appear to have any effect on which chain sees packets first.
   Note
Since the priority seems to be an unsigned integer, negative priorities will be converted into very high priorities.

Rules

Rules specify which action has to be taken for which packets. Rules are attached to chains. Each rule can has an expression to match packets with and one or multiple actions when matching. Main differences with iptables is that it is possible to specify multiple actions and that by default counters are off. It must be specified explicitly in rules if you want packet- and byte-counters for a rule. Each rule has a unique handle number by which it can be distinguished. The following matches are available:

  • ip: IP protocol
  • ip6: IPv6 protocol
  • tcp: TCP protocol
  • udp: UDP protocol
  • udplite: UDP-lite protocol
  • sctp: SCTP protocol
  • dccp: DCCP protocol
  • ah: Authentication headers
  • esp: Encrypted security payload headers
  • ipcomp: IPcomp headers
  • icmp: icmp protocol
  • icmpv6: icmpv6 protocol
  • ct: Connection tracking
  • meta: meta properties such as interfaces

Matches

Match Arguments Description/Example
ip version Ip Header version
hdrlength IP header length
tos Type of Service
length Total packet length
id IP ID
frag-off Fragmentation offset
ttl Time to live
protocol Upper layer protocol
checksum IP header checksum
saddr Source address
daddr Destination address
ip6 version IP header version
priority
flowlabel Flow label
length Payload length
nexthdr Next header type (Upper layer protocol number)
hoplimit Hop limit
saddr Source Address
daddr Destination Address
tcp sport Source port
dport Destination port
sequence Sequence number
ackseq Acknowledgement number
doff Data offset
flags TCP flags
window Window
checksum Checksum
urgptr Urgent pointer
udp sport Source port
dport destination port
length Total packet length
checksum Checksum
udplite sport Source port
dport destination port
cscov Checksum coverage
checksum Checksum
sctp sport Source port
dport destination port
vtag Verification tag
checksum Checksum
dccp sport Source port
dport destination port
ah nexthdr Next header protocol (Upper layer protocol)
hdrlength AH header length
spi Security Parameter Index
sequence Sequence Number
esp spi Security Parameter Index
sequence Sequence Number
ipcomp nexthdr Next header protocol (Upper layer protocol)
flags Flags
cfi Compression Parameter Index
icmp type icmp packet type
icmpv6 type icmpv6 packet type
ct state State of the connection
direction Direction of the packet relative to the connection
status Status of the connection
mark Connection mark
expiration Connection expiration time
helper Helper associated with the connection
l3proto Layer 3 protocol of the connection
saddr Source address of the connection for the given direction
daddr Destination address of the connection for the given direction
protocol Layer 4 protocol of the connection for the given direction
proto-src Layer 4 protocol source for the given direction
proto-dst Layer 4 protocol destination for the given direction
meta length Length of the packet in bytes: meta length > 1000
protocol ethertype protocol: meta protocol vlan
priority TC packet priority
mark Packet mark
iif Input interface index
iifname Input interface name
iiftype Input interface type
oif Output interface index
oifname Output interface name
oiftype Output interface hardware type
skuid UID associated with originating socket
skgid GID associated with originating socket
rtclassid Routing realm

Statements

Statements represent the action to be performed when the rule matches. They exist in two kinds: Terminal statements, unconditionally terminate the evaluation of the current rules and non-terminal statements that either conditionally or never terminate the current rules. There can be an arbitrary amount of non-terminal statements, but there must be only a single terminal statement. The terminal statements can be:

  • accept: Accept the packet and stop the ruleset evaluation.
  • drop: Drop the packet and stop the ruleset evaluation.
  • reject: Reject the packet with an icmp message
  • queue: Queue the packet to userspace and stop the ruleset evaluation.
  • continue:
  • return: Return from the current chain and continue at the next rule of the last chain. In a base chain it is equivalent to accept
  • jump <chain>: Continue at the first rule of <chain>. It will continue at the next rule after a return statement is issued
  • goto <chain>: Similar to jump, but after the new chain the evaluation will continue at the last chain instead of the one containing the goto statement

Installing nftables

Kernel

These kernel options must be set:

[*] Networking support  --->
   Networking options  --->
       [*] Network packet filtering framework (Netfilter)  --->
           Core Netfilter Configuration  --->
               <M> Netfilter nf_tables support
               <M>   Netfilter nf_tables IPv6 exthdr module
               <M>   Netfilter nf_tables meta module
               <M>   Netfilter nf_tables conntrack module
               <M>   Netfilter nf_tables rbtree set module
               <M>   Netfilter nf_tables hash set module
               <M>   Netfilter nf_tables counter module
               <M>   Netfilter nf_tables log module
               <M>   Netfilter nf_tables limit module
               <M>   Netfilter nf_tables nat module
               <M>   Netfilter x_tables over nf_tables module
           IP: Netfilter Configuration  --->
               <M> IPv4 nf_tables support
               <M>   nf_tables IPv4 reject support
               <M>   IPv4 nf_tables route chain support
               <M>   IPv4 nf_tables nat chain support
           IPv6: Netfilter Configuration  --->
               <M> IPv6 nf_tables support
               <M>   IPv6 nf_tables route chain support
               <M>   IPv6 nf_tables nat chain support
           <M>   Ethernet Bridge nf_tables support

Emerging

To install nftables, run the following command:

root # emerge net-firewall/nftables


OpenRC configuration

Don't forget to add nftables service to startup:

root # rc-update add nftables default

You cannot use iptables and nft to perform NAT at the same time. So make sure that the iptable_nat module is unloaded. Remove iptables_nat module:

root # rmmod iptable_nat

Start nftables:

root # /etc/init.d/nftables start


Using nftables

All nftable commands are done with the nft ultility from net-firewall/nftables.

Tables

Creating tables

The following command adds a table called filter for the ip(v4) layer

root # nft add table ip filter

Likewise a table for arp can be created with

root # nft add table arp filter
   Note

The name "filter" used here is completly arbitrary. It could have any name

Listing tables

The following command lists all tables for the ip(v4) layer

root # nft list tables ip
table filter

The contents of the table filter can be listed with:

root # nft list table ip filter
table ip filter {
        chain input {
                 type filter hook input priority 0;
                 ct state established,related accept
                 iifname "lo" accept
                 ip protocol icmp accept
                 drop
        }
}

using -a with the nft command, it shows the handle of each rule. Handles are used for various operations on specific rules:

root # nft -a list table ip filter
table ip filter {
        chain input {
                 type filter hook input priority 0;
                 ct state established,related accept # handle 2
                 iifname "lo" accept # handle 3
                 ip protocol icmp accept # handle 4
                 drop # handle 5
        }
}

Deleting tables

The following command deletes the table called filter for the ip(v4) layer:

root # nft delete table ip filter

chains

Adding chains

The following command adds a chain called input to the ip filter table and registered to the input hook with priority 0. It is of the type filter.

root # nft add chain ip filter input { type filter hook input priority 0 \; }
   Note

If You're running this command from Bash you need to escape the semicolon

A non-base chain can be added by not specifying the chain configurations between the curly braces.

Removing chains

The following command deletes the chain called input

root # nft delete chain ip filter input
   Note

Chains can only be deleted if there are no rules in them.

rules

Adding rules

The following command adds a rule to the chain called input, on the ip filter table, dropping all traffic to port 80:

root # nft add rule ip filter input tcp dport 80 drop

Deleting Rules

To delete a rule, you first need to get the handle number of the rule. This can be done by using the -a flag on nft:

root # nft  rule ip filter input tcp dport 80 drop
table ip filter {
        chain input {
                 type filter hook input priority 0;
                 tcp dport http drop # handle 2
        }
}

It is then possible to delete the rule with:

root # nft delete rule ip filter input handle 2

Management

Backup

You can also backup your rules:

root # echo "nft flush ruleset" > backup.nft
root # nft list ruleset >> backup.nft

Restoration

And load it atomically:

root # nft -f backup.nft

OpenRC configuration

Don't forget to add nftables service to startup:

root # rc-update add nftables default

Init script - firewall nftables like a firewall iptables

#!/sbin/runscript
#      Raphael Bastos aka coffnix        #
#      Init Script for Funtoo Linux      #
##########################################

depend() {
        need net
        need nftables
        }

start(){
##################### PARTE 1 #####################
ebegin "Starting Firewall NFTables"

#######################################################################
### Incompatibilities ###
# You cannot use iptables and nft to perform NAT at the same time.
# So make sure that the iptable_nat module is unloaded
rmmod iptable_nat

#######################################################################

echo 1 > /proc/sys/net/ipv4/ip_forward
echo 1 > /proc/sys/net/ipv4/ip_dynaddr
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
for f in /proc/sys/net/ipv4/conf/*/rp_filter ; do echo 1 > $f ; done

#######################################################################

iptables -t nat -F

#######################################################################

# ipv4
nft -f /etc/nftables/ipv4-filter

# ipv4 nat
nft -f /etc/nftables/ipv4-nat

# ipv6
nft -f /etc/nftables/ipv6-filter

# Rules firewall NTFtables
nft -f /etc/nftables/firewall.rules

#######################################################################

}

stop(){
ebegin "Stoping Firewall NFTables"

#######################################################################

#iptables -t nat -F
NFT=nft
FAMILIES="ip ip6 arp bridge"

for FAMILY in $FAMILIES; do
  TABLES=$($NFT list tables $FAMILY | grep "^table\s" | cut -d' ' -f2)

  for TABLE in $TABLES; do
    CHAINS=$($NFT list table $FAMILY $TABLE | grep "^\schain\s" | cut -d' ' -f2)

    for CHAIN in $CHAINS; do
      echo "Flushing chain: $FAMILY->$TABLE->$CHAIN"
      $NFT flush chain $FAMILY $TABLE $CHAIN
      $NFT delete chain $FAMILY $TABLE $CHAIN
    done

    echo "Flushing table: $FAMILY->$TABLE"
    $NFT flush table $FAMILY $TABLE
    $NFT delete table $FAMILY $TABLE
  done
done
}

status(){
nft list ruleset
}

# End