Advanced Pagina 7: Diferență între versiuni

De la Wiki Linux Advanced
Sari la navigare Sari la căutare
Fără descriere a modificării
Fără descriere a modificării
 
(Nu s-au afișat 3 versiuni intermediare efectuate de același utilizator)
Linia 17: Linia 17:
   The bridge family handles ethernet packets traversing bridge devices.
   The bridge family handles ethernet packets traversing bridge devices.
   The hooks for netdev are: ingress, egress.
   The hooks for netdev are: ingress, egress.
policy este verdictul pentru a controla cursul acelui pachet in lant si tabel. Posibile valori: accept (default) si drop.


<pre>
<pre>
  % nft (add | create) chain [<family>] <table> <name> [ \{ type <type> hook <hook> [device <device>] priority <priority> \; [policy <policy> \;] \} ]
  % nft (add | create) chain [<family>] <table> <name> [ \{ type <type> hook <hook> [device <device>] priority <priority> \; [policy (accept | drop) \;] \} ]
  % nft (delete | list | flush) chain [<family>] <table> <name>
  % nft (delete | list | flush) chain [<family>] <table> <name>
  % nft rename chain [<family>] <table> <name> <newname>
  % nft rename chain [<family>] <table> <name> <newname>
Linia 92: Linia 90:
</pre>
</pre>


====Exemplu 3====
====Exemplu 3, log====
<pre>
<pre>
table inet firewall {
table inet firewall {
Linia 117: Linia 115:
====Operatii la nivel de ruleset====
====Operatii la nivel de ruleset====


listing
'''Listarea'''


Listing the complete ruleset:
Listing the complete ruleset:
Linia 134: Linia 132:
These commands will print all tables/chains/sets/rules of the given family.
These commands will print all tables/chains/sets/rules of the given family.


flushing
'''Curatarea'''


In addition, you can also flush (erase, delete, wipe) the complete ruleset:
In addition, you can also flush (erase, delete, wipe) the complete ruleset:
Linia 148: Linia 146:
  % nft flush ruleset inet
  % nft flush ruleset inet


backup/restore
'''Backup/restaurare'''


You can combine these two commands above to backup your ruleset:
You can combine these two commands above to backup your ruleset, then load it atomically:


  % echo "flush ruleset" > backup.nft
  % echo "flush ruleset" > backup.nft
  % nft list ruleset >> backup.nft
  % nft list ruleset >> backup.nft
And load it [[Atomic_rule_replacement|atomically]]:
  % nft -f backup.nft
  % nft -f backup.nft


Listing in JSON format
'''Listarea in format JSON'''


You can also export your ruleset in JSON format, just pass the
You can also export your ruleset in JSON format, just pass the
Linia 166: Linia 161:
  % nft --json list ruleset > ruleset.json
  % nft --json list ruleset > ruleset.json


====Creare regula blocare ip-uri de sine statoare====
====Creare regula blocare ip-uri (nativa)====
 
-''functia ipv(4|6)_validate este un grep pe clase de ip-uri, nu este necesar pentru o lista simpla.''
 
-''Numarul de reguli verificabil cu " nft list table inet utilities_filter | grep -oc ',' "''


<pre>
<pre>
if ! nft list chain inet filter INPUT >$quiet 2>&1; then
echo '
echo '
add table inet filter
add table inet filter
Linia 181: Linia 171:
insert rule inet filter INPUT ip saddr @ipmaster counter drop
insert rule inet filter INPUT ip saddr @ipmaster counter drop
insert rule inet filter INPUT ip6 saddr @ipmaster6 counter drop
insert rule inet filter INPUT ip6 saddr @ipmaster6 counter drop
' | nft -f -; fi
' | nft -f -
ipv4_validate </tmp/ip_lists | awk '{print "add element inet filter ipmaster { "$1" }"}' | nft -f - # import ipv4
ipv4_validate <lista_ip | awk '{print "add element inet filter ipmaster { "$1" }"}' | nft -f - # import ipv4
ipv6_validate </tmp/ip_lists | awk '{print "add element inet filter ipmaster6 { "$1" }"}' | nft -f - # import ipv6
ipv6_validate <lista_ip | awk '{print "add element inet filter ipmaster6 { "$1" }"}' | nft -f - # import ipv6
</pre>
 
'''Note:'''
 
-''functia ipv(4|6)_validate este un grep pe clase de ip-uri, nu este necesar pentru o lista simpla.''
 
-''Numarul de reguli verificabil cu " nft list table inet filter | grep -oc ',' " ''
 
-''Verificarea numarului de "hits" catre adresele blocate se poate face cu " ip(6)tables -vL " sau insumat cu:''
 
perl -E '/packets (\d+)/ and $s += $1 for `nft list ruleset | grep ipmaster`; say $s'
 
 
====Creare regula conectare vpn wireguard (nativa)====
 
<pre>
[[ -n $wg_file ]] && file=$wg_file || file=$opt_file; ! [[ -s $file ]] && return 1; iname=$(basename -s .conf $file) address=$(grep '^Address' $file | ipv4_validate) address6=$(grep '^Address' $file | ipv6_validate)
ip link add $iname type wireguard || return 1; wg setconf $iname <(grep -E '^\[Interface|^\[Peer|^PrivateKey|^PublicKey|^Endpoint|^AllowedIPs|^$' $file) || return 1
ip -4 address add $address dev $iname; ip -6 address add $address6 dev $iname
grep '^DNS' $file | sed 's/DNS =/nameserver/' | resolvconf -a tun."$iname" -m 0 -x
wg set $iname fwmark 51820
ip link set mtu 1420 up dev $iname
sysctl -q net.ipv4.conf.all.src_valid_mark=1
ip -4 route add 0.0.0.0/0 dev $iname table 51820; ip -6 route add ::/0 dev $iname table 51820
for cmd in 'ip -4' 'ip -6'; do $cmd rule add not fwmark 51820 table 51820; $cmd rule add table main suppress_prefixlength 0; done
echo '
add table inet fw
add chain inet fw INPUT { type filter hook input priority 0 ; }
add chain inet fw preraw { type filter hook prerouting priority -300; }
add rule inet fw preraw iifname != '$iname' ip daddr '$(cut -d/ -f1 <<<$address)' fib saddr type != local drop
add rule inet fw preraw iifname != '$iname' ip6 daddr '$(cut -d/ -f1 <<<$address6)' fib saddr type != local drop
add chain inet fw premangle { type filter hook prerouting priority -150; }
add rule inet fw premangle meta l4proto udp meta mark set ct mark
add chain inet fw postmangle { type filter hook postrouting priority -150; }
add rule inet fw postmangle meta l4proto udp mark 51820 ct mark set mark
' | nft -f - && echo $iname connected
</pre>
</pre>


===iptables===
===iptables===
Regulile se pot incarca cu comanda iptables-restore sau se pot salva in /etc/sysconfig/iptables
====Exemplu 1====
<pre>
# iptables-save > /dev/stdout
# Warning: iptables-legacy tables present, use iptables-legacy-save to see them
# iptables-legacy-save > /dev/stdout
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*mangle
:PREROUTING ACCEPT [192:15752]
:INPUT ACCEPT [192:15752]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [192:15752]
:POSTROUTING ACCEPT [192:15752]
COMMIT
# Completed on Mon Nov 11 14:43:17 2024
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [50:3402]
:POSTROUTING ACCEPT [50:3402]
COMMIT
# Completed on Mon Nov 11 14:43:17 2024
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:bad_packets - [0:0]
:bad_tcp_packets - [0:0]
:icmp_packets - [0:0]
:tcp_inbound - [0:0]
:tcp_outbound - [0:0]
:udp_inbound - [0:0]
:udp_outbound - [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -j bad_packets
-A INPUT -d 224.0.0.1/32 -j DROP
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -j tcp_inbound
-A INPUT -p udp -j udp_inbound
-A INPUT -p icmp -j icmp_packets
-A INPUT -m pkttype --pkt-type broadcast -j DROP
-A INPUT -m limit --limit 3/min --limit-burst 3 -j LOG --log-prefix "INPUT packet died: "
-A OUTPUT -p icmp -m conntrack --ctstate INVALID -j DROP
-A OUTPUT -s 127.0.0.1/32 -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -j ACCEPT
-A OUTPUT -m limit --limit 3/min --limit-burst 3 -j LOG --log-prefix "OUTPUT packet died: "
-A bad_packets -m conntrack --ctstate INVALID -j LOG --log-prefix "Invalid packet: "
-A bad_packets -m conntrack --ctstate INVALID -j DROP
-A bad_packets -p tcp -j bad_tcp_packets
-A bad_packets -j RETURN
-A bad_tcp_packets -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j LOG --log-prefix "New not syn: "
-A bad_tcp_packets -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j DROP
-A bad_tcp_packets -p tcp -j RETURN
-A icmp_packets -p icmp -f -j LOG --log-prefix "ICMP Fragment: "
-A icmp_packets -p icmp -f -j DROP
-A icmp_packets -p icmp -m icmp --icmp-type 8 -j DROP
-A icmp_packets -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A icmp_packets -p icmp -j RETURN
-A tcp_inbound -p tcp -m tcp --dport 21 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --sport 20 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --dport 22 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --dport 631 -j ACCEPT
-A tcp_inbound -p tcp -j RETURN
-A tcp_outbound -p tcp -j ACCEPT
-A udp_inbound -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 631 -j ACCEPT
-A udp_inbound -p udp -m udp --sport 68 --dport 67 -j ACCEPT
-A udp_inbound -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 111 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9400 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 2049 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9401 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9402 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9403 -j ACCEPT
-A udp_inbound -p udp -j RETURN
-A udp_outbound -p udp -j ACCEPT
COMMIT
# Completed on Mon Nov 11 14:43:17 2024
</pre>
Ceea ce se traduce in:
<pre>
iptables -L
Chain INPUT (policy DROP)
target    prot opt source              destination       
ACCEPT    all  --  anywhere            anywhere           
bad_packets  all  --  anywhere            anywhere           
DROP      all  --  anywhere            224.0.0.1         
ACCEPT    all  --  anywhere            anywhere            ctstate RELATED,ESTABLISHED
tcp_inbound  tcp  --  anywhere            anywhere           
udp_inbound  udp  --  anywhere            anywhere           
icmp_packets  icmp --  anywhere            anywhere           
DROP      all  --  anywhere            anywhere            PKTTYPE = broadcast
LOG        all  --  anywhere            anywhere            limit: avg 3/min burst 3 LOG level warn prefix "INPUT packet died: "
Chain FORWARD (policy DROP)
target    prot opt source              destination       
Chain OUTPUT (policy DROP)
target    prot opt source              destination       
DROP      icmp --  anywhere            anywhere            ctstate INVALID
ACCEPT    all  --  localhost            anywhere           
ACCEPT    all  --  anywhere            anywhere           
ACCEPT    all  --  anywhere            anywhere           
LOG        all  --  anywhere            anywhere            limit: avg 3/min burst 3 LOG level warn prefix "OUTPUT packet died: "
Chain bad_packets (1 references)
target    prot opt source              destination       
LOG        all  --  anywhere            anywhere            ctstate INVALID LOG level warn prefix "Invalid packet: "
DROP      all  --  anywhere            anywhere            ctstate INVALID
bad_tcp_packets  tcp  --  anywhere            anywhere           
RETURN    all  --  anywhere            anywhere           
Chain bad_tcp_packets (1 references)
target    prot opt source              destination       
LOG        tcp  --  anywhere            anywhere            tcp flags:!FIN,SYN,RST,ACK/SYN ctstate NEW LOG level warn prefix "New not syn: "
DROP      tcp  --  anywhere            anywhere            tcp flags:!FIN,SYN,RST,ACK/SYN ctstate NEW
LOG        tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE
LOG        tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG
LOG        tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,PSH,URG LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,PSH,URG
LOG        tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,ACK,URG LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,ACK,URG
LOG        tcp  --  anywhere            anywhere            tcp flags:SYN,RST/SYN,RST LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:SYN,RST/SYN,RST
LOG        tcp  --  anywhere            anywhere            tcp flags:FIN,SYN/FIN,SYN LOG level warn prefix "Stealth scan: "
DROP      tcp  --  anywhere            anywhere            tcp flags:FIN,SYN/FIN,SYN
RETURN    tcp  --  anywhere            anywhere           
Chain icmp_packets (1 references)
target    prot opt source              destination       
LOG        icmp -f  anywhere            anywhere            LOG level warn prefix "ICMP Fragment: "
DROP      icmp -f  anywhere            anywhere           
DROP      icmp --  anywhere            anywhere            icmp echo-request
ACCEPT    icmp --  anywhere            anywhere            icmp time-exceeded
RETURN    icmp --  anywhere            anywhere           
Chain tcp_inbound (1 references)
target    prot opt source              destination       
ACCEPT    tcp  --  anywhere            anywhere            tcp dpt:ftp
ACCEPT    tcp  --  anywhere            anywhere            tcp spt:ftp-data
ACCEPT    tcp  --  anywhere            anywhere            tcp dpt:ssh
ACCEPT    tcp  --  anywhere            anywhere            tcp dpt:ipp
RETURN    tcp  --  anywhere            anywhere           
Chain tcp_outbound (0 references)
target    prot opt source              destination       
ACCEPT    tcp  --  anywhere            anywhere           
Chain udp_inbound (1 references)
target    prot opt source              destination       
ACCEPT    udp  --  anywhere            anywhere            udp spt:bootps dpt:bootpc
ACCEPT    udp  --  anywhere            anywhere            udp dpt:ipp
ACCEPT    udp  --  anywhere            anywhere            udp spt:bootpc dpt:bootps
ACCEPT    udp  --  anywhere            anywhere            udp spt:bootps dpt:bootpc
ACCEPT    udp  --  anywhere            anywhere            udp dpt:sunrpc
ACCEPT    udp  --  anywhere            anywhere            udp dpt:9400
ACCEPT    udp  --  anywhere            anywhere            udp dpt:nfs
ACCEPT    udp  --  anywhere            anywhere            udp dpt:9401
ACCEPT    udp  --  anywhere            anywhere            udp dpt:9402
ACCEPT    udp  --  anywhere            anywhere            udp dpt:9403
RETURN    udp  --  anywhere            anywhere           
Chain udp_outbound (0 references)
target    prot opt source              destination       
ACCEPT    udp  --  anywhere            anywhere 
</pre>
====Exemplu 2====
<pre>
*filter
# Allow all outgoing, but drop incoming and forwarding packets by default
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
# Custom per-protocol chains
:UDP - [0:0]
:TCP - [0:0]
:ICMP - [0:0]
# Acceptable UDP traffic
# Acceptable TCP traffic
-A TCP -p tcp --dport 22 -j ACCEPT
# Acceptable ICMP traffic
# Boilerplate acceptance policy
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -i lo -j ACCEPT
# Drop invalid packets
-A INPUT -m conntrack --ctstate INVALID -j DROP
# Pass traffic to protocol-specific chains
## Only allow new connections (established and related should already be handled)
## For TCP, additionally only allow new SYN packets since that is the only valid
## method for establishing a new TCP connection
-A INPUT -p udp -m conntrack --ctstate NEW -j UDP
-A INPUT -p tcp --syn -m conntrack --ctstate NEW -j TCP
-A INPUT -p icmp -m conntrack --ctstate NEW -j ICMP
# Reject anything that's fallen through to this point
## Try to be protocol-specific w/ rejection message
-A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
-A INPUT -p tcp -j REJECT --reject-with tcp-reset
-A INPUT -j REJECT --reject-with icmp-proto-unreachable
# Commit the changes
COMMIT
*raw
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*security
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
</pre>
====Creare regula blocare ip-uri (folosind ipset)====
<pre>
ipv4_validate <lista_ip | awk 'NR==1{print "create ipmaster hash:net family inet hashsize 100000 maxelem 100000"}''{print "add ipmaster "$1}' | ipset restore -!
iptables -I INPUT -m set --match-set ipmaster src -j DROP # import ipv4
ipv6_validate <lista_ip | awk 'NR==1{print "create ipmaster6 hash:net family inet6 hashsize 500000 maxelem 500000"}''{print "add ipmaster6 "$1}' | ipset restore -!
ip6tables -I INPUT -m set --match-set ipmaster6 src -j DROP # import ipv6
</pre>
'''Note:'''
-''functia ipv(4|6)_validate este un grep pe clase de ip-uri, nu este necesar pentru o lista simpla.''
-''Numarul de reguli verificabil cu " ipset list -t " sau insumat cu:''
perl -E '/Number of entries: (\d+)/ and $s += $1 for `ipset list -t`; say $s'
-''Verificarea numarului de "hits" catre adresele blocate se poate face cu " ip(6)tables -vL " sau insumat cu:''
perl -E "say $(iptables -vL | awk 'NR==3{print $1}') + $(ip6tables -vL | awk 'NR==3{print $1}')"


[[Advanced_Pagina_6|Pagina anterioară]] | [[Advanced_Pagina_8|Următoarea pagină]]
[[Advanced_Pagina_6|Pagina anterioară]] | [[Advanced_Pagina_8|Următoarea pagină]]

Versiunea curentă din 13 noiembrie 2024 09:24

Firewall avansat

nftables

Tabele: ip (implicit), arp, ip6, bridge, inet, netdev.

Lanturi:

 filter: Supported by arp, bridge, ip, ip6 and inet table families.
 route: Mark packets (like mangle for the output hook, for other hooks use the type filter instead), supported by ip and ip6.
 nat: In order to perform Network Address Translation, supported by ip and ip6.

Hook: Se refera la stadiul acelui pachet in timp ce este procesat de kernel in Netfilter.

 The hooks for ip, ip6 and inet families are: prerouting, input, forward, output, postrouting.
 The hooks for arp family are: input, output.
 The bridge family handles ethernet packets traversing bridge devices.
 The hooks for netdev are: ingress, egress.
 % nft (add | create) chain [<family>] <table> <name> [ \{ type <type> hook <hook> [device <device>] priority <priority> \; [policy (accept | drop) \;] \} ]
 % nft (delete | list | flush) chain [<family>] <table> <name>
 % nft rename chain [<family>] <table> <name> <newname>

Reguli: nft (add | insert | replace | displace) rule

Exemplu 1, imitare iptables

Exemplu de reguli nftables, de importat cu comanda nft -f. O parte din chain-uri imita iptables. Nota: unele distributii acum implementeaza propriile reguli, de recomandat folosita comanda "flush ruleset" inainte.

table inet filter {
        chain input {
                type filter hook input priority filter;

                # Allow loopback (local connections)
                iifname lo accept

                # Allow established/related
                ct state established,related accept

                # Allow incoming pings
                ip protocol icmp limit rate 1/second accept

                # Allow SSH and HTTP
                tcp dport {ssh,http} accept

                # Drop everything else
                drop
        }
        chain forward {
                type filter hook forward priority filter;

                # Disallow forwarding
                drop
        }
        chain output {
                type filter hook output priority filter;

                # Allow all outgoing traffic
                accept
        }
}

Exemplu 2, prioritati

table ip filter {
        # This chain is evaluated first due to priority
        chain services {
                type filter hook input priority 0; policy accept;

                # If matched, this rule will prevent any further evaluation
                tcp dport http drop

                # If matched, and despite the accept verdict, the packet proceeds to enter the chain below
                tcp dport ssh accept

                # Likewise for any packets that get this far and hit the default policy
        }

        # This chain is evaluated last due to priority
        chain input {
                type filter hook input priority 1; policy drop;
                # All ingress packets end up being dropped here!
        }
}

Exemplu 3, log

table inet firewall {
    chain inbound {                                                              

        # By default, drop all traffic unless it meets a filter
        # criteria specified by the rules that follow below.
        type filter hook input priority 0; policy drop;

        # Allow traffic from established and related packets, drop invalid
        ct state vmap { established : accept, related : accept, invalid : drop } 

        # Allow loopback traffic.
        iifname lo accept

        tcp dport { 22, 80, 443, 55291, 5900 } accept
                                                                                                                                                                                                                                                                                          
        # Uncomment to enable logging of denied inbound traffic                                                                                                                                                                                                                           
        log prefix "[nftables] Inbound Denied: " counter drop                                                                                                                                                                                                                             
    }                                                                                                                                                                                                                                                                                     
}

Operatii la nivel de ruleset

Listarea

Listing the complete ruleset:

% nft list ruleset


Listing the ruleset per family:

% nft list ruleset arp
% nft list ruleset ip
% nft list ruleset ip6
% nft list ruleset bridge
% nft list ruleset inet

These commands will print all tables/chains/sets/rules of the given family.

Curatarea

In addition, you can also flush (erase, delete, wipe) the complete ruleset:

% nft flush ruleset

Also per family:

% nft flush ruleset arp
% nft flush ruleset ip
% nft flush ruleset ip6
% nft flush ruleset bridge
% nft flush ruleset inet

Backup/restaurare

You can combine these two commands above to backup your ruleset, then load it atomically:

% echo "flush ruleset" > backup.nft
% nft list ruleset >> backup.nft
% nft -f backup.nft

Listarea in format JSON

You can also export your ruleset in JSON format, just pass the '--json' option:

% nft --json list ruleset > ruleset.json

Creare regula blocare ip-uri (nativa)

echo '
add table inet filter
add chain inet filter INPUT { type filter hook input priority 1 ; }
add set inet filter ipmaster { flags interval; type ipv4_addr; auto-merge; }
add set inet filter ipmaster6 { flags interval; type ipv6_addr; auto-merge; }
insert rule inet filter INPUT ip saddr @ipmaster counter drop
insert rule inet filter INPUT ip6 saddr @ipmaster6 counter drop
' | nft -f -
ipv4_validate <lista_ip | awk '{print "add element inet filter ipmaster { "$1" }"}' | nft -f - # import ipv4
ipv6_validate <lista_ip | awk '{print "add element inet filter ipmaster6 { "$1" }"}' | nft -f - # import ipv6

Note:

-functia ipv(4|6)_validate este un grep pe clase de ip-uri, nu este necesar pentru o lista simpla.

-Numarul de reguli verificabil cu " nft list table inet filter | grep -oc ',' "

-Verificarea numarului de "hits" catre adresele blocate se poate face cu " ip(6)tables -vL " sau insumat cu:

perl -E '/packets (\d+)/ and $s += $1 for `nft list ruleset | grep ipmaster`; say $s'


Creare regula conectare vpn wireguard (nativa)

[[ -n $wg_file ]] && file=$wg_file || file=$opt_file; ! [[ -s $file ]] && return 1; iname=$(basename -s .conf $file) address=$(grep '^Address' $file | ipv4_validate) address6=$(grep '^Address' $file | ipv6_validate)
ip link add $iname type wireguard || return 1; wg setconf $iname <(grep -E '^\[Interface|^\[Peer|^PrivateKey|^PublicKey|^Endpoint|^AllowedIPs|^$' $file) || return 1
ip -4 address add $address dev $iname; ip -6 address add $address6 dev $iname
grep '^DNS' $file | sed 's/DNS =/nameserver/' | resolvconf -a tun."$iname" -m 0 -x
wg set $iname fwmark 51820
ip link set mtu 1420 up dev $iname
sysctl -q net.ipv4.conf.all.src_valid_mark=1
ip -4 route add 0.0.0.0/0 dev $iname table 51820; ip -6 route add ::/0 dev $iname table 51820
for cmd in 'ip -4' 'ip -6'; do $cmd rule add not fwmark 51820 table 51820; $cmd rule add table main suppress_prefixlength 0; done
echo '
add table inet fw
add chain inet fw INPUT { type filter hook input priority 0 ; }
add chain inet fw preraw { type filter hook prerouting priority -300; }
add rule inet fw preraw iifname != '$iname' ip daddr '$(cut -d/ -f1 <<<$address)' fib saddr type != local drop
add rule inet fw preraw iifname != '$iname' ip6 daddr '$(cut -d/ -f1 <<<$address6)' fib saddr type != local drop
add chain inet fw premangle { type filter hook prerouting priority -150; }
add rule inet fw premangle meta l4proto udp meta mark set ct mark
add chain inet fw postmangle { type filter hook postrouting priority -150; }
add rule inet fw postmangle meta l4proto udp mark 51820 ct mark set mark
' | nft -f - && echo $iname connected

iptables

Regulile se pot incarca cu comanda iptables-restore sau se pot salva in /etc/sysconfig/iptables

Exemplu 1

# iptables-save > /dev/stdout
# Warning: iptables-legacy tables present, use iptables-legacy-save to see them
# iptables-legacy-save > /dev/stdout
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*mangle
:PREROUTING ACCEPT [192:15752]
:INPUT ACCEPT [192:15752]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [192:15752]
:POSTROUTING ACCEPT [192:15752]
COMMIT
# Completed on Mon Nov 11 14:43:17 2024
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [50:3402]
:POSTROUTING ACCEPT [50:3402]
COMMIT
# Completed on Mon Nov 11 14:43:17 2024
# Generated by iptables-save v1.8.9 on Mon Nov 11 14:43:17 2024
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:bad_packets - [0:0]
:bad_tcp_packets - [0:0]
:icmp_packets - [0:0]
:tcp_inbound - [0:0]
:tcp_outbound - [0:0]
:udp_inbound - [0:0]
:udp_outbound - [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -j bad_packets
-A INPUT -d 224.0.0.1/32 -j DROP
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -j tcp_inbound
-A INPUT -p udp -j udp_inbound
-A INPUT -p icmp -j icmp_packets
-A INPUT -m pkttype --pkt-type broadcast -j DROP
-A INPUT -m limit --limit 3/min --limit-burst 3 -j LOG --log-prefix "INPUT packet died: "
-A OUTPUT -p icmp -m conntrack --ctstate INVALID -j DROP
-A OUTPUT -s 127.0.0.1/32 -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -j ACCEPT
-A OUTPUT -m limit --limit 3/min --limit-burst 3 -j LOG --log-prefix "OUTPUT packet died: "
-A bad_packets -m conntrack --ctstate INVALID -j LOG --log-prefix "Invalid packet: "
-A bad_packets -m conntrack --ctstate INVALID -j DROP
-A bad_packets -p tcp -j bad_tcp_packets
-A bad_packets -j RETURN
-A bad_tcp_packets -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j LOG --log-prefix "New not syn: "
-A bad_tcp_packets -p tcp -m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,PSH,ACK,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,PSH,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG FIN,SYN,RST,ACK,URG -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags SYN,RST SYN,RST -j DROP
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j LOG --log-prefix "Stealth scan: "
-A bad_tcp_packets -p tcp -m tcp --tcp-flags FIN,SYN FIN,SYN -j DROP
-A bad_tcp_packets -p tcp -j RETURN
-A icmp_packets -p icmp -f -j LOG --log-prefix "ICMP Fragment: "
-A icmp_packets -p icmp -f -j DROP
-A icmp_packets -p icmp -m icmp --icmp-type 8 -j DROP
-A icmp_packets -p icmp -m icmp --icmp-type 11 -j ACCEPT
-A icmp_packets -p icmp -j RETURN
-A tcp_inbound -p tcp -m tcp --dport 21 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --sport 20 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --dport 22 -j ACCEPT
-A tcp_inbound -p tcp -m tcp --dport 631 -j ACCEPT
-A tcp_inbound -p tcp -j RETURN
-A tcp_outbound -p tcp -j ACCEPT
-A udp_inbound -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 631 -j ACCEPT
-A udp_inbound -p udp -m udp --sport 68 --dport 67 -j ACCEPT
-A udp_inbound -p udp -m udp --sport 67 --dport 68 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 111 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9400 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 2049 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9401 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9402 -j ACCEPT
-A udp_inbound -p udp -m udp --dport 9403 -j ACCEPT
-A udp_inbound -p udp -j RETURN
-A udp_outbound -p udp -j ACCEPT
COMMIT
# Completed on Mon Nov 11 14:43:17 2024

Ceea ce se traduce in:

iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             anywhere            
bad_packets  all  --  anywhere             anywhere            
DROP       all  --  anywhere             224.0.0.1           
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
tcp_inbound  tcp  --  anywhere             anywhere            
udp_inbound  udp  --  anywhere             anywhere            
icmp_packets  icmp --  anywhere             anywhere            
DROP       all  --  anywhere             anywhere             PKTTYPE = broadcast
LOG        all  --  anywhere             anywhere             limit: avg 3/min burst 3 LOG level warn prefix "INPUT packet died: "

Chain FORWARD (policy DROP)
target     prot opt source               destination         

Chain OUTPUT (policy DROP)
target     prot opt source               destination         
DROP       icmp --  anywhere             anywhere             ctstate INVALID
ACCEPT     all  --  localhost            anywhere            
ACCEPT     all  --  anywhere             anywhere            
ACCEPT     all  --  anywhere             anywhere            
LOG        all  --  anywhere             anywhere             limit: avg 3/min burst 3 LOG level warn prefix "OUTPUT packet died: "

Chain bad_packets (1 references)
target     prot opt source               destination         
LOG        all  --  anywhere             anywhere             ctstate INVALID LOG level warn prefix "Invalid packet: "
DROP       all  --  anywhere             anywhere             ctstate INVALID
bad_tcp_packets  tcp  --  anywhere             anywhere            
RETURN     all  --  anywhere             anywhere            

Chain bad_tcp_packets (1 references)
target     prot opt source               destination         
LOG        tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN ctstate NEW LOG level warn prefix "New not syn: "
DROP       tcp  --  anywhere             anywhere             tcp flags:!FIN,SYN,RST,ACK/SYN ctstate NEW
LOG        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE
LOG        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG
LOG        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,PSH,URG LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,PSH,URG
LOG        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,ACK,URG LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,ACK,URG
LOG        tcp  --  anywhere             anywhere             tcp flags:SYN,RST/SYN,RST LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:SYN,RST/SYN,RST
LOG        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN/FIN,SYN LOG level warn prefix "Stealth scan: "
DROP       tcp  --  anywhere             anywhere             tcp flags:FIN,SYN/FIN,SYN
RETURN     tcp  --  anywhere             anywhere            

Chain icmp_packets (1 references)
target     prot opt source               destination         
LOG        icmp -f  anywhere             anywhere             LOG level warn prefix "ICMP Fragment: "
DROP       icmp -f  anywhere             anywhere            
DROP       icmp --  anywhere             anywhere             icmp echo-request
ACCEPT     icmp --  anywhere             anywhere             icmp time-exceeded
RETURN     icmp --  anywhere             anywhere            

Chain tcp_inbound (1 references)
target     prot opt source               destination         
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ftp
ACCEPT     tcp  --  anywhere             anywhere             tcp spt:ftp-data
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ipp
RETURN     tcp  --  anywhere             anywhere            

Chain tcp_outbound (0 references)
target     prot opt source               destination         
ACCEPT     tcp  --  anywhere             anywhere            

Chain udp_inbound (1 references)
target     prot opt source               destination         
ACCEPT     udp  --  anywhere             anywhere             udp spt:bootps dpt:bootpc
ACCEPT     udp  --  anywhere             anywhere             udp dpt:ipp
ACCEPT     udp  --  anywhere             anywhere             udp spt:bootpc dpt:bootps
ACCEPT     udp  --  anywhere             anywhere             udp spt:bootps dpt:bootpc
ACCEPT     udp  --  anywhere             anywhere             udp dpt:sunrpc
ACCEPT     udp  --  anywhere             anywhere             udp dpt:9400
ACCEPT     udp  --  anywhere             anywhere             udp dpt:nfs
ACCEPT     udp  --  anywhere             anywhere             udp dpt:9401
ACCEPT     udp  --  anywhere             anywhere             udp dpt:9402
ACCEPT     udp  --  anywhere             anywhere             udp dpt:9403
RETURN     udp  --  anywhere             anywhere            

Chain udp_outbound (0 references)
target     prot opt source               destination         
ACCEPT     udp  --  anywhere             anywhere  

Exemplu 2

*filter
# Allow all outgoing, but drop incoming and forwarding packets by default
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]

# Custom per-protocol chains
:UDP - [0:0]
:TCP - [0:0]
:ICMP - [0:0]

# Acceptable UDP traffic

# Acceptable TCP traffic
-A TCP -p tcp --dport 22 -j ACCEPT

# Acceptable ICMP traffic

# Boilerplate acceptance policy
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -i lo -j ACCEPT

# Drop invalid packets
-A INPUT -m conntrack --ctstate INVALID -j DROP

# Pass traffic to protocol-specific chains
## Only allow new connections (established and related should already be handled)
## For TCP, additionally only allow new SYN packets since that is the only valid
## method for establishing a new TCP connection
-A INPUT -p udp -m conntrack --ctstate NEW -j UDP
-A INPUT -p tcp --syn -m conntrack --ctstate NEW -j TCP
-A INPUT -p icmp -m conntrack --ctstate NEW -j ICMP

# Reject anything that's fallen through to this point
## Try to be protocol-specific w/ rejection message
-A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
-A INPUT -p tcp -j REJECT --reject-with tcp-reset
-A INPUT -j REJECT --reject-with icmp-proto-unreachable

# Commit the changes
COMMIT

*raw
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT

*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT

*security
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT

*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT

Creare regula blocare ip-uri (folosind ipset)

ipv4_validate <lista_ip | awk 'NR==1{print "create ipmaster hash:net family inet hashsize 100000 maxelem 100000"}''{print "add ipmaster "$1}' | ipset restore -!
iptables -I INPUT -m set --match-set ipmaster src -j DROP # import ipv4
ipv6_validate <lista_ip | awk 'NR==1{print "create ipmaster6 hash:net family inet6 hashsize 500000 maxelem 500000"}''{print "add ipmaster6 "$1}' | ipset restore -!
ip6tables -I INPUT -m set --match-set ipmaster6 src -j DROP # import ipv6

Note:

-functia ipv(4|6)_validate este un grep pe clase de ip-uri, nu este necesar pentru o lista simpla.

-Numarul de reguli verificabil cu " ipset list -t " sau insumat cu:

perl -E '/Number of entries: (\d+)/ and $s += $1 for `ipset list -t`; say $s'

-Verificarea numarului de "hits" catre adresele blocate se poate face cu " ip(6)tables -vL " sau insumat cu:

perl -E "say $(iptables -vL | awk 'NR==3{print $1}') + $(ip6tables -vL | awk 'NR==3{print $1}')"

Pagina anterioară | Următoarea pagină