Rules take action on network packets (e.g. accepting or dropping them) based on whether they match specified criteria.
Состояние перевода: На этой странице представлен перевод статьи nftables. Дата последней синхронизации: 11 июля 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.
nftables состоит из трёх основных частей: низкоуровневая реализация в ядре, библиотека libnl, которая обеспечивает netlink-взаимодействие, и пользовательский фронтенд nftables. Ядро предоставляет интерфейс настройки netlink, а также занимается runtime-выполнением наборов правил. Библиотека libnl содержит низкоуровневые функции для взаимодействия с ядром. Фронтенд nftables — то, с чем пользователь взаимодействует утилитой nft.
Подробную информацию о nftables можно найти на вики-странице проекта.
As interest in the NFT space continues to grow, this disruptive new technology has begun to spark debate around the way we define and value art. Due to their intrinsic scarcity and provable ownership, NFTs now provide a unique means for facilitating value across a wide range of digital assets, including music, video, collectibles, video-game items, and digital artwork.
In fact, some of the most expensive NFT sales, such as collections from Beeple and Pak, are worth considerably more than bonafide masterpieces in the traditional art world. For example, Pak’s “The Merge” sold for $91.8million, which surpasses the inflation-adjusted valuation for “Nymphéas en fleur” by Monet, “Laboureur dans un champ” by Van Gogh, and “Au Lapin Agile” from Pablo Picasso.
With such high stakes, more people than ever are eager to get involved in the NFT space, either by investing in prominent NFT collections or by becoming an NFT artist themselves.
But, before you jump in, you need to make sure you have a true understanding of what NFT collections are, what gives them value, which ones to avoid, and how you can get the low-down on NFT collections before they drop.
- Removing all the rules in a chain
- How to find NFT collections that are minting soon
- How to make an NFT collection
- Creating your art
- Set up a crypto wallet
- Set the price of each individual item
- Removing rules
- Примеры
- Несколько сетевых интерфейсов с разными правилами
- NAT с пробросом портов
- Установка
- What makes an NFT collection valuable
- Artist reptation
- Ownership history
- Rarity
- Replacing rules
- Adding a rule at a given position
- Настройка
- Просмотр цепочек и правил в таблице
- Полная перезагрузка правил
- Testing your rule
- Beware of scams when investing
- Простой межсетевой экран
- Where do NFT collections sell?
- Listing rules
- Who can make an NFT collection?
- What are NFT collections?
- Советы и рекомендации
- Настройка межсетевого экрана
- Предотвращение атак перебором
- Решение проблем
- Final Word
- Appending new rules
- Prepending new rules
Table of Contents
I encountered strange problem with Nftables which I don’t understand.
This is the sequence of a commands which lead to my state:
Now, at this state it won’t let me add the «combined» nor «partial» range element:
So removing both elements and checking:
I intentionally tried to remove the combined one first, because it was said earlier that «file exists». But it turned out it only exists when adding, but not when removing. The last command shows the set is empty; now let’s add something back:
How to add it back now?
It is possible to reset this by flushing the set. However, it is this test set is empty, but in the real life it will have other data. This behaviour is retained if the set is created without auto-merge. If I remove flags interval, it works as expected, but only with individual IP addresses.
This is OpenVZ system, 3.10.0-1160.42.2.vz7.184.10 #1 SMP Fri Dec 31 04:05:16 MSK 2021 x86_64 GNU/Linux. Could it be connected to that?
nft version is nftables v0.9.8 (E.D.S.), the system is freshly updated Debian Bullseye.
nftables (nft list ruleset -ay)
Removing all the rules in a chain
% nft flush chain filter output
How to find NFT collections that are minting soon
If you are planning to invest in NFT collections and want the best bang for your buck, your best bet would be to find exclusive NFT drops so you can jump on projects early before their prices increase. Back in June 2017, the CryptoPunks collections were offered for free on a first-come-first-served basis. Over the subsequent few years, the CryptoPunks collection became one of the most sought-after projects in the entire NFT space, making those who participated in the drop very wealthy without having to invest a single cent.
While it is going to be next to impossible to replicate that feat, there are still plenty of tactics you can use to keep your ear to the ground and find out about hot NFT drops before the general public catches wind.
How to make an NFT collection
Wondering how NFT collections are made? Well, the good news is that it’s probably much easier than you imagine. With that said, let’s start off with the first and most difficult step – creating the art that will make up your collection.
Creating your art
To begin with, you need to carefully consider the type of content that you want to produce. Whether you are creating music, memes, avatars, video, or digital art, try to find a niche that suits your interests and has some level of market demand. After all, if your goal is to make money with NFTs, you will want to appeal to as wide a demographic as possible.
As for the production itself, it’s up to you what medium you decide is best for your particular type of NFT. If you’re considering going down the digital art route, many artists use software such as Adobe Photoshop and Adobe Illustrator. If you’re new to these programs, there will be a fairly steep learning curve, although there are plenty of free resources out there that will help you develop your skills.
You can even use an NFT maker that will assist you in generating unique digital art within a matter of minutes. In fact, some of these tools require no artistic skill whatsoever. For example, you can use Hotpot.ai to create beautiful digital art by inputting a few keywords into the AI interface. After tweaking a few preference settings, the AI will present you with a piece of digital art that you can mint into an NFT and sell on the marketplace – and the best part is that it’s completely free!
Remember, since you are creating an NFT collection, you will need to produce at least two unique artworks. The number of pieces you include in your collection is entirely up to you. However, try to take a look at similar artists in your field to see what works for them. Both CryptoPunks and the BoredApeYachtClub have 10,000 unique avatars, but that doesn’t mean you need to match that volume.
Set up a crypto wallet
On top of this, many of the leading NFT exchanges offer a lazy minting service, which means that you do not need to pay any fees to mint your artwork as an NFT. In this process, the NFT is made available off-chain and only gets minted once it has been sold to a buyer. In some cases, the NFT gas fee is passed on to the buyer too, which means the artist does not foot any of the cost for minting. Some of the most popular websites that offer this functionality include:
Set the price of each individual item
Now that you have created your NFT collection, you need to decide on the price you will initially offer them on the market. Generally speaking, the more pieces that you have in your collection, the less valuable each individual item should be. However, that is not always the case. To use the BoredApeYachtClub as an example once again, each Bored Ape was offered for a flat price of $190 during launch in April 2021.
If you are struggling to find a suitable launching price, then carry out some research on similar artists and see what they are charging. That way, you can assess the quality of your work compared to theirs (as well as your audience and the marketability of your brand) before setting a realistic price.
Removing rules
You have to obtain the handle to delete a rule via the -a option. The handle is automagically assigned by the kernel and it uniquely identifies the rule.
% nft -a list table filter
table ip filter
chain input
filter hook input priority
chain output
filter hook output priority
ip daddr .168.1.1 counter packets bytes # handle 5
% nft delete rule filter output handle
Note: There are plans to support rule deletion by passing:
% nft delete rule filter output ip saddr .168.1.1 counter
but this is not yet implemented. So you’ll have to use the handle to delete rules until that feature is implemented.
Примеры
Если вы используете переходы (jumps), то целевая цепочка должна быть описана до перехода. Иначе будет получена ошибка Error: Could not process rule: No such file or directory.
Несколько сетевых интерфейсов с разными правилами
Если у вашей системы несколько сетевых интерфейсов и вы хотите использовать для них разные наборы правил, то создайте фильтрующую цепочку-диспетчер, а после неё опишите цепочки для сетевых интерфейсов. Например, пусть ваша машина выступает в качестве домашнего маршрутизатора и вы желаете запустить веб-сервер, доступный по локальной сети (интерфейс enp3s0), но не из публичного интернета (интерфейс enp2s0). Создайте таблицу вроде этой:
Можно поступить иначе — задать только одну строку iifname, например для интерфейса веб-сервера, а правила для остальных интерфейсов вместо диспетчеризации описать в одном месте.
Правила работы маскарадинга:
Пример правил межсетевого экрана для машины с двумя интерфейсами, локальным enp3s0 и публичным enp2s0:
Поскольку таблица выше относится к типу inet, то маскарадингу подвергаются пакеты и IPv4, и IPv6. Чтобы ограничить маскарадинг только IPv4-пакетами (т.к. у IPv6 большое пространство адресов и NAT не требуется) либо добавьте выражение meta nfproto ipv4 перед oifname «enp2s0» masquerade, либо измените тип таблицы на ip.
NAT с пробросом портов
Для вывода заблокированных адресов выполните nft list set inet dev blackhole.
Установка
Установите пакет или git-версию AUR.
What makes an NFT collection valuable
With that said, you may be wondering what makes one NFT collection more valuable than another? Let’s take a look at some of the major factors that influence the floor price of individual collections.
Artist reptation
We see examples of this all the time, with celebrities and well-known artists cashing in on their brand by releasing an NFT collection in their name. Even Sir Tim Berners-Lee got in on the act after he sold an NFT of the original source code to the World Wide Web for $5.4 million in 2021.
Image Source: The Guardian
Ownership history
Utility is one of the more popular buzzwords in the wider crypto sphere. In general, the term refers to the usefulness of a digital asset (usually a cryptocurrency token) and the value that it brings to its ecosystem. In other words, does the asset do anything, or is its value simply dependent on the speculation of other investors?
Image Source: Gods Unchained
In addition, there are plenty of other use cases for NFTs, such as yield farming through providing liquidity, staking, renting, and even royalty payments.
Rarity
Similar to the traditional art world, the rarer a collection is, the more valuable it becomes. Although, rarity can be viewed from two separate angles. First of all, artists can create one-off bespoke artworks for each of the items in their collection. This would be similar to how Beeple created his “The First 5000 Days” collection, where he made a unique picture every single day from May 1st, 2007 – January 7th, 2021.
Replacing rules
You can replace any rule via the replace command by indicating the rule handle, which you have to find by first listing the ruleset with option -a:
To replace the rule with handle 2, specify its handle number and the new rule that you want to replace it:
nft replace rule filter input handle counter
Listing the ruleset after the above replacement:
# nft list ruleset
table ip filter
chain input
filter hook input priority policy accept
counter packets bytes
you can see that the old rule that counted TCP packets has been replaced by the new rule that counts all packets.
Adding a rule at a given position
If you want to add a rule at a given position, you have to use the handle as reference:
% nft -n -a list table filter
table filter
chain output
filter hook output priority
ip protocol tcp counter packets bytes # handle 8
ip saddr .0.0.1 ip daddr .0.0.6 drop # handle 7
If you want to add a rule after the rule with handler number 8, you have to type:
% nft add rule filter output position ip daddr .0.0.8 drop
Now, you can check the effect of that command by listing the rule-set:
% nft -n -a list table filter
table filter
chain output
filter hook output priority
ip protocol tcp counter packets bytes # handle 8
ip daddr .0.0.8 drop # handle 10
ip saddr .0.0.1 ip daddr .0.0.6 drop # handle 7
If you want to insert a rule before the rule with handler number 8, you have to type:
% nft insert rule filter output position ip daddr .0.0.8 drop
Настройка
Утилита nft выполняет большую часть обработки правил перед передачей их ядру. Правила объединяются в цепочки, которые, в свою очередь, входят в состав таблиц. В последующих разделах описано создание и модифицирование этих структур.
Прочитать правила из файла можно с помощью опции -f/—file:
# nft —file имя-файла
Обратите внимание, что уже загруженные на этот момент правила не будут при этом автоматически стёрты.
Полный список команд можно найти в руководстве .
Таблицы содержат #Цепочки. В отличие от iptables, в nftables отсутствуют встроенные таблицы. Количество таблиц и их имена определяется пользователем. Тем не менее, каждая таблица имеет только одно семейство адресации и применяется к пакетам только этого семейства. Таблицы могут относиться к одному из пяти семейств.
ip (т.е. IPv4) — семейство по умолчанию; используется, если семейство не было указано.
Семейство inet объединяет протоколы IPv4 и IPv6, что позволяет унифицировать семейства ip и ip6 и упростить создание правил.
Описание остальных семейств адресации вы найдёте в руководстве nft(8) § ADDRESS FAMILIES.
В командах ниже параметр семейство будет указываться не всегда; если его нет, то подразумевается семейство ip.
Добавить новую таблицу:
# nft add table семейство таблица
Вывести список таблиц:
# nft list tables
Просмотр цепочек и правил в таблице
Вывести цепочки и правила выбранной таблицы:
# nft list table семейство таблица
Например, чтобы вывести на экран правила таблицы my_table семейства inet, выполните команду:
# nft list table inet my_table
Удалить таблицу со всеми цепочками:
# nft delete table семейство таблица
Стереть все правила в таблице:
# nft flush table семейство таблица
Цепочка содержит #Правила. В отличие от iptables, в nftables отсутствуют встроенные цепочки. Соответственно, если опрелённые типы или хуки фреймворка netfilter не задействованы ни в одной цепочке, то проходящие через эти цепочки пакеты обрабатываться не будут (в отличие от iptables).
Есть два типа цепочек. Базовая цепочка является точкой входа для пакетов из сетевого стека; в ней указывается хук. Обычная цепочка может использоваться в качестве цели перехода и используется для лучшей организации правил.
Добавить обычную цепочку цепочка в таблицу таблица:
# nft add chain семейство таблица цепочка
Например, чтобы добавить обычную цепочку my_tcp_chain к таблице my_table семейства адресации inet, выполните:
# nft add chain inet my_table my_tcp_chain
Чтобы добавить базовую цепочку, укажите хук и значение приоритета:
тип может принимать значения filter, route или nat.
Для семейств адресации IPv4/IPv6/Inet хук может принимать значения prerouting, input, forward, output или postrouting. Описание других возможных хуков вы найдёте в руководстве nft(8) § ADDRESS FAMILIES.
Например, добавим базовую цепочку для фильтрации входящих пакетов:
Если заменить команду add на create в любом из правил выше, то цепочка тоже будет создана, но если цепочка с таким названием уже существует, то вы получите сообщение об ошибке.
Следующая команда выводит на экран все правила в цепочке:
# nft list chain семейство таблица цепочка
Например, следующая команда выведет правила цепочки my_output таблицы my_table семейства inet:
# nft list chain inet my_table my_output
Для редактирования цепочки укажите её название и правила, которые нужно изменить:
Например, для изменения политики обработки входящих пакетов цепочки исходной таблицы с accept на drop выполните команду:
# nft delete chain семейство таблица цепочка
Цепочка должна быть пустой (не содержащей правил) и не должна быть целью перехода из другой цепочки.
Стереть все правила в цепочке:
# nft flush chain семейство таблица цепочка
Правила конструируются из выражений (expressions) и операторов (statements) и содержатся внутри цепочек.
Совет: Утилита iptables-translate поможет преобразовать правила iptables в формат nftables.
Добавить правило в цепочку:
# nft add rule семейство таблица цепочка handle маркер оператор
Правило будет прикреплено после маркер, который можно не указывать. Если маркер (handle) не задать, то правило добавится в конец цепочки.
Чтобы добавить правило перед определённой позицией, выполните
# nft insert rule семейство таблица цепочка handle маркер оператор
Если маркер не указан, то правило добавится в начало цепочки.
Обычно оператор включает некоторое выражение для сравнения и вынесения решения. Решениями могут быть accept, drop, queue, continue, return, jump цепочка и goto цепочка. Возможны и другие операторы помимо решений, подробнее смотрите .
В nftables доступен ряд выражений, по большей части совпадающий с аналогичными в iptables. Наиболее важное отличие заключается в том, что здесь нет обобщённых или неявных параметров. Обобщённый параметр (generic match) обычно доступен для всех правил, например, параметры —protocol или —source. Неявные правила (implicit matches) относятся к конкретному протоколу, как параметр —sport для пакетов TCP.
Ниже представлен неполный список возможных параметров:
Ниже приведён неполный список аргументов для параметров (подробнее см. ):
Отдельные правила могут быть удалены только с помощью маркера. Команда nft —handle list выведет список маркеров.
# nft —handle —numeric list chain inet my_table my_input
Стирание всех цепочек таблицы выполняется командой nft flush table. Отдельные цепочки могут быть стёрты командами nft flush chain или nft delete rule.
# nft flush table таблица
# nft flush chain семейство таблица цепочка
# nft delete rule семейство таблица цепочка
Первая команда стирает все цепочки в ip-таблице таблица. Вторая очищает цепочку цепочка в таблице таблица семейства семейство. Третья удаляет все правила в цепочке цепочка в таблице таблица семейства семейство.
Именованное множество можно изменить, а также присвоить ему тип и установить флаги. sshguard использует именованные множества для хранения адресов блокированных хостов.
Команды для добавления и удаления элементов из множества:
Полная перезагрузка правил
Создать файл для новых правил:
Сбросить дамп правил в новый файл:
Теперь можно редактировать файл /tmp/nftables, создавая и изменяя правила. Применить изменения можно командой:
# nft -f /tmp/nftables
Testing your rule
% ping -c .8.8.8
PING .8.8.8 .8.8.8 bytes of data.
bytes from .8.8.8: .31 ms
Then, if we list the rule-set, we obtain:
% nft -nn list table filter
table ip filter
chain input
filter hook input priority
chain output
filter hook output priority
ip daddr .8.8.8 counter packets bytes
tcp dport counter packets bytes
Note that the counters have been updated.
Beware of scams when investing
В nftables не различаются временные правила, добавленные из командной строки, и постоянные, загруженные из файла или сохранённые в файл.
Все правила должны создаваться или загружаться утилитой nft. Подробнее о работе с ней см. раздел #Настройка.
Текущий набор правил можно узнать командой:
Простой межсетевой экран
В пакет входит простая и надёжная конфигурация экрана, сохранённая в файле /etc/nftables.conf.
Служба nftables.service загрузит эти правила при запуске или включении.
Where do NFT collections sell?
While some of the most expensive collections in the world are sold at traditional auction houses, such as Christie’s, the vast majority of NFT collections are bought and sold across NFT exchanges. Not only do these websites offer a great platform to market and display NFTs, but they provide increased security and liquidity, benefiting both the buyer and the seller. Some of the best NFT marketplaces include:
Listing rules
% nft list table filter
table ip filter
chain input
filter hook input priority
chain output
filter hook output priority
ip daddr .8.8.8 counter packets bytes
tcp dport ssh counter packets bytes
You can also list rules by chain, for example:
% nft list chain filter ouput
table ip filter
chain output
filter hook output priority
ip daddr .8.8.8 counter packets bytes
tcp dport ssh counter packets bytes
There are plenty of output text modifiers than can be used when listing your rules, to for example, translate IP addresses to DNS names, TCP protocols, etc.
Who can make an NFT collection?
One of the most attractive aspects of the NFT world is that anybody can become an NFT artist and make their own collection. Unlike the traditional art scene, which generally requires extensive formal training and a significant amount of skill, the barriers to entry are considerably lower when it comes to NFTs.
For starters, since NFTs are created digitally, artists can lean into graphic design and other computer-based skills, which are generally much simpler to master than becoming adept with a paintbrush. Second, many of the most popular NFT collections are rather simplistic in nature, such as the aforementioned Bored Apes Yacht Club, as well as other highly valued collections such as Crypto Punks.
Image Source: Larva Labs
As you can see, Crypto Punks avatars are made up of pixelated characters that would not require a high level of skill to produce or even replicate. However, this illustrates that a large portion of the value in NFT projects is not directly tied to the creative flair of their creators but rather to the artists’ ability to tap into demand, trends, and how they market their collections.
Of course, that is not to say there aren’t any highly skilled artists in the NFT space. Take Beeple, for example, who produces magnificent NFT collections that provide thought-provoking social/political commentary through bizarre abstract images that would certainly not look out of place in a modern art gallery.
What are NFT collections?
An NFT collection is an assortment of digital assets released by an artist (or group of artists) containing a limited number of individual NFTs. Typically, most NFT collections consist of numerous NFTs that all conform to the same artistic style, with slight variations across each individual token.
Image Source: Rolling Stone
With that said, NFT collections come in a variety of different forms, such as virtual real estate (Decentraland and The Sandbox), music albums, and even sports trading cards (NBA Top Shot and Sorare).
Советы и рекомендации
Вывод команды nft list ruleset можно использовать в качестве входных данных для других команд. Текущий набор правил можно сохранить в файл, а позже — загрузить их из него.
Примечание: Команда nft list не выводит определения переменных. Если в файле /etc/nftables.conf есть какие-либо переменные, то в выводе команды вы их не увидите — все переменные будут заменены на значения.
Настройка межсетевого экрана
См. также Настройка межсетевого экрана.
Сотрите текущий набор правил:
# nft flush ruleset
# nft add table inet my_table
Добавьте базовые цепочки input, forward и output. Политика для входящих и пересылаемых пакетов должна быть drop. Политика для исходящих пакетов — accept.
Добавьте две обычные цепочки, которые будут обрабатывать пакеты протоколов TCP и UDP:
# nft add chain inet my_table my_tcp_chain
# nft add chain inet my_table my_udp_chain
Разрешите related и established трафик:
# nft add rule inet my_table my_input ct state related,established accept
Разрешите трафик на петлевой интерфейс:
# nft add rule inet my_table my_input iif lo accept
Заблокируйте invalid трафик:
# nft add rule inet my_table my_input ct state invalid drop
Разрешите пакеты ICMP и IGMP:
Новый UDP-трафик будет передаваться цепочке my_udp_chain:
# nft add rule inet my_table my_input meta l4proto udp ct state new jump my_udp_chain
Новый TCP-трафик будет передаваться цепочке my_tcp_chain:
Заблокировать весь трафик, который не обрабатывается другими правилами:
# nft add rule inet my_table my_input meta l4proto udp reject
# nft add rule inet my_table my_input meta l4proto tcp reject with tcp reset
# nft add rule inet my_table my_input counter reject with icmpx type port-unreachable
В этом месте необходимо выбрать, какие порты будут оставаться открытыми для входящих соединений, обрабатываемых цепочками my_tcp_chain и my_udp_chain. Например, открыть соединения для веб-сервера:
# nft add rule inet my_table my_tcp_chain tcp dport 80 accept
# nft add rule inet my_table my_tcp_chain tcp dport 443 accept
Разрешить SSH-трафик на порт 22:
# nft add rule inet my_table my_tcp_chain tcp dport 22 accept
Разрешить входящие DNS-запросы:
# nft add rule inet my_table my_tcp_chain tcp dport 53 accept
# nft add rule inet my_table my_udp_chain udp dport 53 accept
В конце не забудьте сохранить набор правил, чтобы они стали постоянными.
Предотвращение атак перебором
Действие log позволяет вести журнал пакетов. Простейшее правило для сохранения информации обо всём поступающем трафике:
# nft add rule inet filter input log
Подробнее см. nftables wiki.
Решение проблем
nftables может создавать помехи сетевой работе контейнеров Docker (возможно, и другим средствам виртуализации тоже). В частности, политика drop цепочки forward блокирует пакеты, источником которых является docker. Если вы не хотите удалять эту цепочку, то сделайте следующее:
Теперь сгенерированные контейнером docker пакеты будут маркироваться и пересылаться дальше, поскольку docker уже их отфильтровал (цепочка forward в docker использует политику drop).
Final Word
Whether you are an investor or artist, the NFT industry provides a wealth of opportunities to connect, engage, and trade digital art with people from all over the world. While the technology is undoubtedly in its infancy, its rapid rise to the mainstream signifies a drastic (and arguably) much-needed shake-up of the art world as people finally have an authentic means to monetize digital art.
Hopefully, after reading this article, you now have all of the tools and knowledge you need to capitalize on this exciting market. That said, if you’re new to the space, remember to keep your wits about you and watch out for some of the scams mentioned above. Other than that, there’s not much more to say other than good luck and happy hunting!
Appending new rules
To add new rules, you have to specify the corresponding table and the chain that you want to use, eg.
% nft add rule filter output ip daddr .8.8.8 counter
Where filter is the table and output is the chain. The example above adds a rule to match all packets seen by the output chain whose destination is 8.8.8.8, in case of matching it updates the rule counters. Note that counters are optional in nftables.
For those familiar with iptables, the rule appending is equivalent to -A command in iptables.
Prepending new rules
To prepend new rules through the insert command:
% nft insert rule filter output ip daddr .168.1.1 counter
This prepends a rule that will update per-rule packet and bytes counters for traffic addressed to 192.168.1.1.
The equivalent in iptables is:
Note that iptables always provides per-rule counters.
