2.10. Using nftables to limit the amount of connections
You can use nftables to limit the number of connections or to block IP addresses that attempt to establish a given amount of connections to prevent them from using too many system resources.
2.10.1. Limiting the number of connections by using nftables リンクのコピーリンクがクリップボードにコピーされました!
By using the ct count parameter of the nft utility, you can limit the number of simultaneous connections per IP address. For example, you can use this feature to configure that each source IP address can only establish two parallel SSH connections to a host.
Procedure
Create the
filtertable with theinetaddress family:# nft add table inet filterAdd the
inputchain to theinet filtertable:# nft add chain inet filter input { type filter hook input priority 0 \; }Create a dynamic set for IPv4 addresses:
# nft add set inet filter limit-ssh { type ipv4_addr\; flags dynamic \;}Add a rule to the
inputchain that allows only two simultaneous incoming connections to the SSH port (22) from an IPv4 address and rejects all further connections from the same IP:# nft add rule inet filter input tcp dport ssh ct state new add @limit-ssh { ip saddr ct count over 2 } counter reject
Verification
- Establish more than two new simultaneous SSH connections from the same IP address to the host. Nftables refuses connections to the SSH port if two connections are already established.
Display the
limit-sshdynamic set:# nft list set inet filter limit-ssh table inet filter { set limit-ssh { type ipv4_addr size 65535 flags dynamic elements = { 192.0.2.1 ct count over 2 , 192.0.2.2 ct count over 2 } } }The
elementsentry displays addresses that currently match the rule. In this example,elementslists IP addresses that have active connections to the SSH port. Note that the output does not display the number of active connections or if connections were rejected.
2.10.2. Blocking IP addresses that attempt more than ten new incoming TCP connections within one minute リンクのコピーリンクがクリップボードにコピーされました!
You can temporarily block hosts that are establishing more than ten IPv4 TCP connections within one minute.
Procedure
Create the
filtertable with theipaddress family:# nft add table ip filterAdd the
inputchain to thefiltertable:# nft add chain ip filter input { type filter hook input priority 0 \; }Add a set named
denylistto thefiltertable:# nft add set ip filter denylist { type ipv4_addr \; flags dynamic, timeout \; timeout 5m \; }This command creates a dynamic set for IPv4 addresses. The
timeout 5mparameter defines thatnftablesautomatically removes entries after five minutes to prevent that the set fills up with stale entries.Add a rule that automatically adds the source IP address of hosts that attempt to establish more than ten new TCP connections within one minute to the
denylistset:# nft add rule ip filter input ip protocol tcp ct state new, untracked add @denylist { ip saddr limit rate over 10/minute } drop