Difference between pages "Package:Portage (Funtoo)" and "Package:Nftables"

(Difference between pages)
(h3 > h2)
 
 
Line 1: Line 1:
 
{{Ebuild
 
{{Ebuild
|Summary=This is the official package manager/ports system for Funtoo Linux.
+
|Summary=Linux kernel (3.13+) firewall, NAT and packet mangling tools
|CatPkg=sys-apps/portage
+
|CatPkg=net-firewall/nftables
|Maintainer=Drobbins, Oleg
+
|Repository=Gentoo Portage Tree
|Repository=Funtoo Overlay
+
 
}}
 
}}
=== Introduction ===
+
=== 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.
  
Portage is the official package manager of Funtoo Linux. Daniel Robbins maintains a slightly different version from upstream Gentoo Linux, with support for mini-manifests and other features.
+
==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.
  
=== Portage Commands ===
+
===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).
  
; [[emerge]]
+
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.
: high-level dependency-based package merge/unmerge tool
+
; [[ebuild]]
+
: lower-level package build tool
+
  
;{{c|etc-update}}
+
===Chains===
;{{c|dispatch-conf}}
+
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.
:tools to manage /etc/configurations
+
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}}
  
=== Portage Specifications ===
+
====Priorities====
  
The latest progress and changes related to EAPI/PMS and Portage can often be found in the Gentoo Council meeting logs, which are listed on the [http://www.gentoo.org/proj/en/council/ Gentoo Council page].
+
{{Note|Priorities do not currently appear to have any effect on which chain sees packets first.}}
  
The latest PMS specification to be approved by the Gentoo Council is available: [http://distfiles.gentoo.org/distfiles/pms-3.pdf eapi-3-approved-2010-01-18]. The PMS specification is an attempt to codify the inner workings of Portage, and is authored by Ciaran McCreesh and Stephen Bennett as a Gentoo-hosted project.
+
{{Note|Since the priority seems to be an unsigned integer, negative priorities will be converted into very high priorities.}}
  
=== Portage Profiles ===
+
===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
  
Portage uses [[Portage Profiles|profiles]] to define settings for various architectures and types of Funtoo/Gentoo systems. See the [[Portage Profiles]] page for detailed information on how Portage handles profiles. Look at [[Creating_Profiles]] to learn how to create them and at [[Funtoo_1.0_Profile]] to learn about the Funtoo 1.0 profile.
+
====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
  
===Portage Variables ===
+
== Installing nftables ==
 +
=== Kernel ===
 +
These kernel options must be set {{kernelop|title=Network support|desc= 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
 +
}}
  
Portage's behavior can be controlled by a number of configuration settings other variables that can be defined within the ebuild itself. In addition, a number of these variables are defined for the ebuild automatically by Portage. These variables are now documented on their own page: [[Portage Variables]].
+
=== Emerging ===
=== Multiple ABI Support ===
+
To install nftables, run the following command:
 +
<console>
 +
###i## emerge net-firewall/nftables
 +
</console>
  
Portage contains support for multiple ABIs (Application Binary Interfaces) co-existing on the same system. This functionality has been extensively documented and has been moved to its own page: [[Multiple ABI Support]].
 
  
=== Ebuild Functions ===
+
== OpenRC configuration ==  
 +
Don't forget to add nftables service to startup:
 +
<console>
 +
###i## rc-update add nftables default
 +
</console>
  
An ebuild developer has the ability to define [[Ebuild Functions]] that define steps to perform during a particular part of the ebuild lifecycle. These steps are now documented on their own page: [[Ebuild Functions]].
+
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>
 +
###i## rmmod iptable_nat
 +
</console>
  
=== Funtoo Portage Development ===
+
Start nftables:
 +
<console>
 +
###i## /etc/init.d/nftables start
 +
</console>
  
The Funtoo Core Team is currently working on a general-purpose plug-in system so that the GNU info file regeneration, news update display, and scanning of files that need updating in /etc can be pulled out of the official Portage emerge code. In addition, this plug-in system will allow other types of things to be hooked into various phases of emerge. This will allow various new plug-ins to be developed and used on systems, such as periodic security checks, etc.
 
  
=== Portage Logs ===
+
== Using nftables ==
Logs of portage actions can be found at <code>/var/log/emerge.log</code> & <code>/var/log/portage/elog/summary.log-(date the log is generated)</code>
+
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>
 +
###i## nft add table ip filter
 +
</console>
 +
Likewise a table for arp can be created with
 +
<console>
 +
###i## nft add table arp filter
 +
</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
 +
<console>
 +
###i## nft list tables ip
 +
</console>
 +
<pre>
 +
table filter
 +
</pre>
 +
The contents of the table filter can be listed with:
 +
<console>
 +
###i## nft list table ip filter
 +
</console>
 +
<pre>
 +
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>
 +
###i## nft -a list table ip filter
 +
</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>
  
=== TODO ===
+
====Deleting tables====
 +
The following command deletes the table called filter for the ip(v4) layer:
 +
<console>
 +
###i## nft delete table ip filter
 +
</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>
 +
###i## nft add chain ip filter input { type filter hook input priority 0 \; }
 +
</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.
  
Add support to portage, so that when an ebuild is merged, the /var/db/pkg entry contains a list of all currently-installed versions of all ebuilds upon which that ebuild RDEPENDs. This, combined with a comprehensive set of past USE settings (may need to implement this too,) can be used to detect when an ebuild needs to be rebuilt. This could help to address issues like those in [http://bugs.gentoo.org/167662 Gentoo Bug 167662] and allow easier implementation of support for things like perl-cleaner. Currently, perl-cleaner doesn't detect that vim uses perl and moving from -ithreads to ithreads causes vim to die, so it needs to be manually rebuilt.
+
====Removing chains====
 +
The following command deletes the chain called input
 +
<console>
 +
###i## nft delete chain ip filter input
 +
</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>
 +
###i## nft add rule ip filter input tcp dport 80 drop
 +
</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:
 +
<console>
 +
###i## nft  rule ip filter input tcp dport 80 drop
 +
</console>
 +
<pre>
 +
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>
 +
###i## nft delete rule ip filter input handle 2
 +
</console>
 +
== Management ==
 +
=== Backup ===
 +
You can also backup your rules:
 +
<console>
 +
###i## echo "nft flush ruleset" > backup.nft
 +
</console>
  
Add support for portage to understand which version of a particular app is the "active" version that it was built against, and record this information in /var/db/pkg. This can help to implement perl-cleaner-like support in Portage.
+
<console>
 +
###i## nft list ruleset >> backup.nft
 +
</console>
  
=== Funtoo Features/Changes ===
+
=== Restoration ===
 +
And load it atomically:
 +
<console>
 +
###i## nft -f backup.nft
 +
</console>
  
==== Summary ====
+
== OpenRC configuration ==  
 
+
In [https://github.com/funtoo/portage-funtoo/tree/thin-manifest the thin-manifest branch], Funtoo changes have been isolated into the following commits:
+
  
 +
Don't forget to add nftables service to startup:
 +
<console>
 +
###i## rc-update add nftables default
 +
</console>
 +
== Init script (firewall nftables like a iptables) ==
 
<pre>
 
<pre>
e5a6649e094eb7230aa8f56d97fe303f77b158e9 preserve bindist through use expansion
+
#!/sbin/runscript
5a092fdae8afbff679350dc5d8818e10ab35fd80 safetydance feature
+
#      Raphael Bastos aka coffnix        #
16887ddce712da8b61887f9bce70e19b95e75c25 core funtoo git-sync implementation
+
#      Init Script for Funtoo Linux      #
2c6e2b427a2aa179b61667caf89497818ec34ae2 run pwconv and grpconv after emerge completes to ensure /etc/shadow and /etc/gshadow are valid.
+
##########################################
ea565da9ab5f54580f66814a17aca39d8e568732 funtoo-specific man page changes
+
 
c8f130fa4b332d87f2202ddaf0222b89018914d0 Funtoo config file changes. This includes stuff related to rsync as well as /lib/firmware
+
depend() {
dba5a350e16043a6ff6281ea80fc02c8f56efd4f remove emerge-webrsync -- not supported in funtoo
+
        need net
0d9dda7b2b3165b268545e3e8eb44aa8d3c20a57 small ebuild.sh fix to not source any stray directories
+
        need nftables
8500043b3075d26c77a7ec1b8c2745373ca0c3b5 disable warning for use of *, -* in KEYWORDS
+
        }
86ed81605e73b8b6d6b06fc60a9a0bc0c13ee429 protect firmware as well as modules
+
 
e7b6512e582fbcd9af0eb82c617549b101c8ae97 slashbeast's localpatch feature
+
start(){
5af34ad9334310c0926e52d9e1801ee170e12184 simplify path setting in ebuild.sh by using getpath() function
+
##################### PARTE 1 #####################
42789a70184343008c4cb1fe20bc4398e881d285 remove bin/ebuild-helpers/sed
+
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
 
</pre>
 
</pre>
  
These commits do not yet include the unified-path/funtoo-profile 1.0 patches.
+
=== Personal Rules ===
 +
And configure your personal rules:
 +
<pre>
 +
# A simple firewall
 +
#
  
==== In Funtoo stable/current Portage ====
+
table ip filter {
 +
        chain input {
 +
                type filter hook input priority 0;
 +
                ct state established,related accept
  
;emerge --sync from git
+
                # invalid connections
:If a git-based Portage tree is already in place, <tt>emerge --sync</tt> will run "git pull" to update the underlying Portage tree. If one is not in place, the contents of the SYNC variable will be used as the remote URI from which to clone a git tree (2.2). In addition, SYNC_USER and SYNC_UMASK (defaulting to root and 022) can be used to define the user account to use for cloning/syncing, as well as the umask to use. (2.2).
+
                ct state invalid drop
  
;Sed Wrapper Symlink and PATH fix
+
                # loopback interface
: The Funtoo version of Portage has replaced the BSD-only sed wrapper with a symlink. This will eventually be deprecated. The sed wrapper was a way to provide BSD systems with a "sed" command that could be used inside ebuilds that worked similarly to GNU sed. A PATH fix has been applied so that /bin/sed will be detected first anyway.
+
                iifname "lo" accept
  
;mini-manifest
+
                # icmp
:Funtoo's Portage supports a special mode of operation where Manifests only contain digests for distfiles and not for files in the Portage tree. This is to eliminate redundant digests since git already provides SHA1 digests. This feature is currently enabled by adding "mini-manifest" to FEATURES in /etc/make.conf but the intention is to eventually move it to a repo-specific option (note: this has now been done, as "thin-manifest" functionality has been integrated into recent versions of Portage, and is being beta tested in Funtoo.) Funtoo provides a special "mini-manifest" tree that is smaller than the full-size Portage tree, and is intended to be used with the mini-manifest feature.
+
                ip protocol icmp accept
  
;preserve bindist through USE filtering
+
                # open ports
: Normally, anything not in an ebuild's IUSE is stripped from the USE passed to ebuild.sh. This patch allows "bindist" to not be stripped, so it can be used as a means to disable pre-merge sanity checks that may exist in pkg_setup() and pkg_pretend() but will not otherwise affect the resultant build. If "bindist" will affect some functionality in the package, then it should be added to an ebuild's IUSE. This patch allows pkg_setup() and pkg_pretend() to look for "bindist", which indicates that the ebuild is being built for release, typically in an automated fashion, and thus runtime sanity checks that might otherwise run can be optionally skipped. This check is used by the udev-160-r1.ebuild to see if we should fail if we are merging udev on a system where the kernel will not support it. In Metro, this is not a big deal, but on a ''real'' production system, merging the udev on an incompatible system will render the kernel inoperable.
+
                #tcp dport {ssh, http} accept
 +
                #udp dport {5060} accept
 +
                #udp dport {4000-20000} accept
  
;safetydance FEATURE
+
                # Bind DNS Server
:A new FEATURE setting is used by Funtoo's udev ebuild called "safetydance" which can be used to manually bypass sanity checks. This is an alternative to the "bindist" approach above. udev-160 in Funtoo Linux supports both approaches and Metro sets "safetydance" by default.
+
                udp sport domain accept
 +
                tcp sport domain accept
  
;GLEP 55 removal
 
:Some code to support GLEP 55 has been removed.
 
  
;new metadata format (experimental)
+
                # LAN
:Some tweaks to ebuild.sh have been made so that it is easier to support new metadata formats in the future.
+
                #ip saddr 192.168.100.0/24 ct state new counter accept
  
;xz-utils auto-dependency
+
                # everything else
:There are several ebuilds in the Gentoo Portage repository that use .xz files but do not explicitly depend on xz-utils. A workaround has been added to ebuild.sh to add this dependency to metadata automatically if a .xz file exists in SRC_URI. This change is not yet in the official Portage sources but is being used on the Funtoo side when generating our git-based Portage trees.
+
                drop
 +
        }
 +
        chain forward {
 +
                #ip daddr 192.168.100.0/24 accept
 +
        }
 +
}
 +
 
 +
 
 +
table ip6 filter {
 +
        chain input {
 +
                type filter hook input priority 0;
 +
 
 +
                # established/related connections
 +
                ct state established,related accept
 +
 
 +
                # invalid connections
 +
                ct state invalid drop
 +
 
 +
                # loopback interface
 +
                iifname lo accept
 +
 
 +
                # icmp
 +
                ip6 nexthdr icmpv6 accept
 +
 
 +
                # open tcp ports: sshd (22), httpd (80)
 +
                #tcp dport {ssh, http} accept
 +
                #udp dport {5060} accept
 +
                #udp dport {4000-20000} accept
 +
 
 +
                # everything else
 +
                drop
 +
        }
 +
}
 +
 
 +
 
 +
table ip nat {
 +
        chain prerouting {
 +
                #tcp dport 8081 ip protocol tcp counter dnat 192.168.100.24
 +
        }
 +
        chain postrouting {
 +
                #masquerade random,persistent
 +
                #ip saddr 192.168.100.0/24 oif eth0 snat 192.168.25.3
 +
        }
 +
 
 +
}
 +
</pre>
  
[[Category:Projects]]
+
[[Category:System]]
[[Category:Portage]]
+
[[Category:First Steps]]
 
{{EbuildFooter}}
 
{{EbuildFooter}}

Revision as of 19:44, February 22, 2015

net-firewall/nftables


Source Repository:Gentoo Portage Tree

Summary: Linux kernel (3.13+) firewall, NAT and packet mangling tools


News

Drobbins

RSS/Atom Support

You can now follow this news feed at http://www.funtoo.org/news/atom.xml .
10 February 2015 by Drobbins
Drobbins

Creating a Friendly Funtoo Culture

This news item details some recent steps that have been taken to help ensure that Funtoo is a friendly and welcoming place for our users.
2 February 2015 by Drobbins
Mgorny

CPU FLAGS X86

CPU_FLAGS_X86 are being introduced to group together USE flags managing CPU instruction sets.
31 January 2015 by Mgorny
View More News...

Nftables

Tip

This is a wiki page. To edit it, 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 Under Network 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:

# emerge net-firewall/nftables


OpenRC configuration

Don't forget to add nftables service to startup:

# 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:

# rmmod iptable_nat

Start nftables:

# /etc/init.d/nftables start


Using nftables

All nftable commands are done with the nft ultility from Nftables.

Tables

Creating tables

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

# nft add table ip filter

Likewise a table for arp can be created with

# 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

# nft list tables ip
table filter

The contents of the table filter can be listed with:

# 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:

# 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:

# 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.

# 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

# 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:

# 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:

# 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:

# nft delete rule ip filter input handle 2

Management

Backup

You can also backup your rules:

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

Restoration

And load it atomically:

# nft -f backup.nft

OpenRC configuration

Don't forget to add nftables service to startup:

# rc-update add nftables default

Init script (firewall nftables like a 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

Personal Rules

And configure your personal rules:

# A simple firewall
#

table ip filter {
        chain input {
                type filter hook input priority 0;
                ct state established,related accept

                # invalid connections
                ct state invalid drop

                # loopback interface
                iifname "lo" accept

                # icmp
                ip protocol icmp accept

                # open ports
                #tcp dport {ssh, http} accept
                #udp dport {5060} accept
                #udp dport {4000-20000} accept

                # Bind DNS Server
                udp sport domain accept
                tcp sport domain accept


                # LAN
                #ip saddr 192.168.100.0/24 ct state new counter accept

                # everything else
                drop
        }
        chain forward {
                #ip daddr 192.168.100.0/24 accept
        }
}


table ip6 filter {
        chain input {
                type filter hook input priority 0;

                # established/related connections
                ct state established,related accept

                # invalid connections
                ct state invalid drop

                # loopback interface
                iifname lo accept

                # icmp
                ip6 nexthdr icmpv6 accept

                # open tcp ports: sshd (22), httpd (80)
                #tcp dport {ssh, http} accept
                #udp dport {5060} accept
                #udp dport {4000-20000} accept

                # everything else
                drop
        }
}


table ip nat {
        chain prerouting {
                #tcp dport 8081 ip protocol tcp counter dnat 192.168.100.24
        }
        chain postrouting {
                #masquerade random,persistent
                #ip saddr 192.168.100.0/24 oif eth0 snat 192.168.25.3
        }

}