Skip to content

iptables-restore/nftables-restore service is getting executed before bridge creation during system startup #21899

Open

Description

@tglaeser

systemd version the issue has been seen with

249.6

Used distribution

Gentoo

Linux kernel version used (uname -a)

5.10.76-gentoo-r1 #26 SMP Fri Dec 24 15:18:05 EST 2021 x86_64 Intel(R) Core(TM) i7-10510U CPU @ 1.80GHz GenuineIntel GNU/Linux

CPU architecture issue was seen on

x86_64

Expected behavior you didn't see

Successful run of nftables-restore.service during startup

Unexpected behaviour you saw

nftables.sh[3268]: In file included from /dev/stdin:2:1-39:
nftables.sh[3268]: /var/lib/nftables/rules-save:32:7-11: Error: Interface does not exist
nftables.sh[3268]:                 iif "br0" oif "eno0" accept
nftables.sh[3268]:                     ^^^^^
systemd[1]: nftables-restore.service: Main process exited, code=exited, status=1/FAILURE
systemd[1]: nftables-restore.service: Failed with result 'exit-code'.
systemd[1]: Failed to start Store and restore nftables firewall rules.
systemd[1]: Reached target Preparation for Network.

Steps to reproduce the problem
Defining a network bridge under /etc/systemd/network

# cat ./br0.netdev
[NetDev]
Name=br0
Kind=bridge
# cat 50-br0.network
[Match]
Name=br0

[Network]
Address=192.168.139.126/25

as well as NFT rules like

#!/sbin/nft -f
...
table inet filter {
        ...
        chain forward {
                type filter hook forward priority filter; policy accept;
                iif "br0" oif "eno0" accept
                iif "eno0" oif "br0" accept
        }
        ...
}

and restarting the system.

Additional program output to the terminal or log subsystem illustrating the issue

This configuration is similar to a working OpenRC configuration. I purposely did not yet have a NIC assigned to br0 as I expect this will be done later by LXC.
I noticed that files

/lib/systemd/system/ip6tables-restore.service
/lib/systemd/system/iptables-restore.service
/lib/systemd/system/nftables-restore.service

all contain section

[Unit]
Before=network-pre.target
Wants=network-pre.target

and therefor seem to get executed before the network daemon actually creates br0 according to the above mentioned configuration.

Am I missing something?

Activity

  1. topimiettinen commented on Dec 26, 2021

    @topimiettinen
    Contributor

    I don't think this is a bug with systemd, but your NFT rules need to handle the fact that the network interfaces may become available later when its kernel module is loaded. I'd suggest either:

    1. Change iif and oif to iifname and oifname, they don't expect the network interface to be available at the time of loading the rules.

    2. Split the rules into multiple files, one for common rules (not specific to an interface) and one file per interface, named /etc/nftables-eth0.conf etc. Then add a service [email protected] containing ExecStart=/usr/sbin/nft -f /etc/nftables-%i.conf and udev rule containing ENV{SYSTEMD_WANTS}+="nftables-dev@$name.service" to start the service when the interface is added. Common rules can be loaded by your nftables-restore.service.

    Method 2. is more complex, but also works with netdev ingress and egress filters where the interface name must be used in base chain rules to specify the device and it needs to be valid when loading rules. Splitting the rules is also useful if you have SELinux packet labeling rules which aren't allowed when SELinux is disabled, then the rules can be loaded with a service which has the condition ConditionSecurity=selinux.

  2. tglaeser commented on Dec 26, 2021

    @tglaeser
    Author

    Option (1) works fine, but please note that the issue happens only with br0 not the physical network interfaces, therefore I think udev and option (2) doesn't come into play. E.g. the following config also works.

    #!/sbin/nft -f
    ...
    table inet filter {
            ...
            chain forward {
                    type filter hook forward priority filter; policy accept;
                    iifname "br0" oif "eno0" accept
                    iif "eno0" oifname "br0" accept
            }
            ...
    }
    

    Given that network-pre.target ensures that the physical network interfaces are know, one would think the same should also apply to virtual interfaces and an ordinary bridge interface; don't you agree?

  3. topimiettinen commented on Dec 26, 2021

    @topimiettinen
    Contributor

    Given that network-pre.target ensures that the physical network interfaces are know, one would think the same should also apply to virtual interfaces and an ordinary bridge interface; don't you agree?

    Sorry, I missed that part. But the manual page entry for network-pre.target and related part of https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/ aren't clear about the interface availability at network-pre.target even if "for the purpose of setting up a firewall." is mentioned. Instead, the entry for network.target says that "any configured synthetic network devices (i.e. not physical ones that require hardware to show up and be probed, but virtual ones like bridge devices and similar which are created programmatically) that do not depend on any underlying hardware should be allocated by the time this target is reached." I'm not familiar with these targets though, so there could be a bug in the implementation too. @yuwata WDYT?

  4. tomty89 commented on Dec 27, 2021

    @tomty89
    Contributor

    @tglaeser I assume you use networkd to create the interface(s)? Regardless, as mentioned in systemd.special(7)

    All network management software orders itself after this target

    And I doubt that

    Given that network-pre.target ensures that the physical network interfaces are know

    is a correct understanding. Rather it (is suppose to) ensure (or provide a "boundary" / indication) that the host is still in an "isolated" state (i.e. no network interface has been configured yet), which is why

    This passive target unit may be pulled in by services that want to run before any network is set up, for example for the purpose of setting up a firewall.

    (I think it also meant to imply ordered after by pulled in by.)

    And given that there's the iifname approach that is working, I'm not seeing a real issue here.

  5. topimiettinen commented on Dec 27, 2021

    @topimiettinen
    Contributor

    @tglaeser I assume you use networkd to create the interface(s)? Regardless, as mentioned in systemd.special(7)

    All network management software orders itself after this target

    And I doubt that

    Given that network-pre.target ensures that the physical network interfaces are know

    is a correct understanding. Rather it (is suppose to) ensure (or provide a "boundary" / indication) that the host is still in an "isolated" state (i.e. no network interface has been configured yet), which is why

    This passive target unit may be pulled in by services that want to run before any network is set up, for example for the purpose of setting up a firewall.

    (I think it also meant to imply ordered after by pulled in by.)

    Do you mean that the manual page should tell to load firewall rules after network.target? Then there could be a window of time where the interface is up but firewall rules haven't been loaded yet.

    And given that there's the iifname approach that is working, I'm not seeing a real issue here.

    String matching approach like iifname isn't always possible. For example:

    table netdev filter {
            chain lan_ingress {
                    type filter hook ingress device lan priority filter; policy drop;
                    ...
                    }
            }
    }
    

    Here device name lan is also renamed from eth0 by networkd. Approach 2 (loading interface specific NFT rules as the interfaces become available) works.

  6. tomty89 commented on Dec 27, 2021

    @tomty89
    Contributor

    No, what I mean is, network-pre.target is an indicator of before any network is set up, and ideally speaking, your firewall rules should be up before the system get past that state/stage. So everything is proper and fine (including the gentoo-provided downstream service files) here, except nftables itself (but well, apparently there's a way for deal with it in every case, perhaps inconvenient).

    (Over) ideally speaking, you can say it would be great if the network managers (e.g. networkd) could be used to bring up the firewall, and by that I don't mean by unit deps or ordering, but like by itself after it's done handling all .netdev but before any .network. But on the other hand, that also seems kinda insane. (And I'm not even sure if networkd actually processes all .netdev first.)

    Also, isn't it obvious this is just some nftables caveat / pitfall? (I've no idea how OpenRC handles things, but I'm not seeing any reason "it works" other than that it does not guarantee network configuration is being done after the firewall is up.)

    (Perhaps you can propose to split networkd into netdevd and networkd, heh...)

    P.S. IIRC, networkd would declare itself "started" and hence make network.target reached after it processes all the .netdev files, but as you said, if nftables is ordered after the target, there would be a security-concerning race.

  7. topimiettinen commented on Dec 27, 2021

    @topimiettinen
    Contributor

    No, what I mean is, network-pre.target is an indicator of before any network is set up, and ideally speaking, your firewall rules should be up before the system get past that state/stage. So everything is proper and fine (including the gentoo-provided downstream service files) here, except nftables itself (but well, apparently there's a way for deal with it in every case, perhaps inconvenient).

    The problem is that firewalls and network configuration can be very tightly coupled. For example, it would be nice if addresses learned from DHCP or when VPN is started (i.e. arbitrary late stage) would be available for firewall and also SELinux netlabelctl rules.

    (Over) ideally speaking, you can say it would be great if the network managers (e.g. networkd) could be used to bring up the firewall, and by that I don't mean by unit deps or ordering, but like by itself after it's done handling all .netdev but before any .network. But on the other hand, that also seems kinda insane. (And I'm not even sure if networkd actually processes all .netdev first.)

    This isn't very different from udev approach 2. above.

    Also, isn't it obvious this is just some nftables caveat / pitfall? (I've no idea how OpenRC handles things, but I'm not seeing any reason "it works" other than that it does not guarantee network configuration is being done after the firewall is up.)

    I suppose that with non-parallelizing sysvinit with /etc/rc.d there could be strict guarantees.

    (Perhaps you can propose to split networkd into netdevd and networkd, heh...)

    Perhaps instead networkd could bring up a new .target when all network devices (including bridge devices) are available, but no network configuration has been performed. To prevent any gaps, it could also wait until firewall etc. setup has been completed before starting network configuration. After the addresses have been found there could be another lock step phase where the firewall is again updated before the interfaces may start using the addresses.

    There's also networkd-dispatcher and firewalld. I don't know if there is an ideal solution (yet?).

  8. tglaeser commented on Dec 27, 2021

    @tglaeser
    Author

    Yes, networkd is used to create/configure the interfaces.

    Given that there are 3 network targets, network.target, network-online.target, and network-pre.target, I simply found it counterintuitive that the firewall rules declare

    Before=network-pre.target
    Wants=network-pre.target
    

    I would have rather expected that the firewall gets configured After=network-pre.target but Before=network-online.target; and from the documentation I'm unclear how the third target fits in here.

    Anyway, I'm only saying that it is somehow unexpected that at the time of firewall activation some network interfaces are defined while others are not.

  9. tomty89 commented on Dec 28, 2021

    @tomty89
    Contributor

    Before=network-online.target won't do what you think it will / should, because that doesn't / can't "hold" networkd itself from "going on" to configure the created interfaces (until the firewall is up). It doesn't work like that and it's not for such purpose. (It can only be used to hold units ordered after it from starting until then.)

    It's a simple logic here: if you want to "inject" the bringing up of the firewall between interface creation and interface configuration, you'll need to "decouple" those two tasks by some means. When they are "atomic" (as one) "the problem" has essentially nothing to do with unit ordering / parallelization.

    it is somehow unexpected that at the time of firewall activation some network interfaces

    You are probably too obsessed with the idea of physical interfaces and virtual interfaces are all interfaces. There's an obvious difference between them with respect to your concern -- the latter are created with what you configure them with while the former are not. If you for example avoid using .netdev at all but resort to e.g. manually-written ip link services, then it would be a different story.

    @topimiettinen For the record, the udev approach does not guarantee the before any .network part, i.e. logically speaking at least, it's "racy".

  10. topimiettinen commented on Dec 28, 2021

    @topimiettinen
    Contributor

    Before=network-online.target won't do what you think it will / should, because that doesn't / can't "hold" networkd itself from "going on" to configure the created interfaces (until the firewall is up). It doesn't work like that and it's not for such purpose. (It can only be used to hold units ordered after it from starting until then.)

    It's a simple logic here: if you want to "inject" the bringing up of the firewall between interface creation and interface configuration, you'll need to "decouple" those two tasks by some means. When they are "atomic" (as one) "the problem" has essentially nothing to do with unit ordering / parallelization.

    Right, the question is how this can be implemented.

    it is somehow unexpected that at the time of firewall activation some network interfaces

    You are probably too obsessed with the idea of physical interfaces and virtual interfaces are all interfaces. There's an obvious difference between them with respect to your concern -- the latter are created with what you configure them with while the former are not. If you for example avoid using .netdev at all but resort to e.g. manually-written ip link services, then it would be a different story.

    Unfortunately the firewall rules don't care if an interface is physical or virtual.

    @topimiettinen For the record, the udev approach does not guarantee the before any .network part, i.e. logically speaking at least, it's "racy".

    I know, but it's the earliest moment when firewall netdev rules which reference interfaces can be loaded. In my case, the netdev rules simply forbid using localhost addresses if the interface is not 'lo' and vice versa. This wouldn't be possible in the general case with several interfaces connected to different networks, configured with DHCP.

  11. tomty89 commented on Dec 28, 2021

    @tomty89
    Contributor

    the question is how this can be implemented

    It can't be, unless you actually want to propose to e.g. split networkd into networkd / netdevd, or something even more insane like to make networkd to wait for something to notify it "the network-pre.target has been reached, you are free to configure the interfaces now".

    And I've given a possible workaround: ip link service(s) instead of .netdev file(s).

    Unfortunately the firewall rules don't care if an interface is physical or virtual.

    Not that I think it should. There's no logical relationship between "they have difference in nature" and "nftables should be interface-type aware". Really it just need to handle the case better when it cannot find a matching interface for its rules. (It's not like physical interfaces couldn't be "gone" in a specific boot. Actually I think it's even technically impossible to guarantee that no connected physical interfaces will show up after any target. It's just in reality, *rarely there'll be devices being that slow.)

    P.S. Just in case: all the netdev I ever typed so far refers to the interface creation with networkd. netdev in nftables is not exactly relevant to the discussion anyway (except for the fact the it's a "problematic" example.)

    *UseDefaultInterface=false in iwd is an example that can cause "headache" of similar nature btw.

  12. topimiettinen commented on Dec 28, 2021

    @topimiettinen
    Contributor

    I think this option should be race-free and the shields should be also up all the time:

    1. Load a small set of preliminary firewall rules before any interfaces are up. These rules allowlist only DHCP packets (even that only if needed), all other traffic is blocked. Then, after all physical and virtual interfaces are up and configured (perhaps after network.target or even network-online.target), full set of firewall rules are loaded by a service. The service could be arbitrarily complex and also full knowledge of the network configuration and topology is available to it, so the rules could be generated just for the current configuration. It may be even possible to configure individual firewall rules for each systemd service by generating cgroup BPF filters and then restarting services, or by populating IPsets. For the VPN scenario, the rules could only allow traffic from known non-VPN interfaces and only DHCP for the VPN interface (perhaps also authentication protocols). Again, after VPN has been configured, rules are recalculated to allow other traffic, perhaps also denying traffic masquerading as coming from VPN for the other interfaces. For extra paranoia, also DHCP could be blocked (no network access at all) while the service is pondering the new rules (unless it's so slow that DHCP timeouts or something). Loading new rules when interfaces appear isn't necessary (but can be done).

    This option doesn't require any changes to networkd, netfilter or kernel. The netlabelctl case may need some more thought but it should be analogous to firewall rules.

    There could be also an additional stage before loading full rules, where DNS is also allowed or a an external configuration server is queried for up to date information using rsync, SSH, SCEP, ACME etc. A machine booting in an internal network of an organization could in this stage update all software from a local repository, before allowing any Internet access.

  13. added
    RFE 🎁
    on Jan 28, 2022
  14. poettering commented on Jan 31, 2022

    @poettering
    Member

    Do I understand correctly: you want firewall rules to be in effect before networkd does its thing, so that they are guaranted to take effect for any traffic generated on the system while a network iface exists? But you also want firewall rules to be create after network interfaces appeared, because you want to reference the interfaces from the rules?

    These two requirements are contradictory. You cannot have that: you cannot both run the fw before and after the network appears.

    YOu could split up your fw rules (so that some are run before any iface shows up, and others on each interface popping up), but this won't fix your problem, since the kernel can create network interfaces any time it wants as effect of network devices being plugged in or so, hence you'd always create those rules after the ifaces already exist, and never before.

    So you have two options:

    1. ensure you only reference ifaces by their symbolic names, to be resolved when the rules are run instead of when the rules are created. Not sure this is possible for all rule types. In systemd we try hard to assign stable names to hw interfaces, so that you can reference them from firewall rules reasonably.
    2. run stuff after interfaces have shown up already, and accept the short window of time where the iface exists but the rules are not in effect. You can implement this via a udev rule that sets SYSTEMD_WANTS udev property and pulls in an instance of a script service that establishes the rules.

    ideally, networkd could be told to install firwall rules for you as part of setting up a device. i.e. if the "nft" tool had a library interface that we could call after seeing the device, before upping it, then we could solve your issue fully. But not sure nft has that.

  15. topimiettinen commented on Jan 31, 2022

    @topimiettinen
    Contributor

    Do I understand correctly: you want firewall rules to be in effect before networkd does its thing, so that they are guaranted to take effect for any traffic generated on the system while a network iface exists? But you also want firewall rules to be create after network interfaces appeared, because you want to reference the interfaces from the rules?

    These two requirements are contradictory. You cannot have that: you cannot both run the fw before and after the network appears.

    YOu could split up your fw rules (so that some are run before any iface shows up, and others on each interface popping up), but this won't fix your problem, since the kernel can create network interfaces any time it wants as effect of network devices being plugged in or so, hence you'd always create those rules after the ifaces already exist, and never before.

    So you have two options:

    1. ensure you only reference ifaces by their symbolic names, to be resolved when the rules are run instead of when the rules are created. Not sure this is possible for all rule types. In systemd we try hard to assign stable names to hw interfaces, so that you can reference them from firewall rules reasonably.
    

    Indeed, this isn't possible for all rule types (specifically ingress filters).

    2. run stuff after interfaces have shown up already, and accept the short window of time where the iface exists but the rules are not in effect. You can implement this via a udev rule that sets SYSTEMD_WANTS udev property and pulls in an instance of a script service that establishes the rules.
    

    I presented option 3. above (minimal initial filter blocking all traffic except DHCP, then open up with full filter later) which doesn't have the vulnerable window.

    ideally, networkd could be told to install firwall rules for you as part of setting up a device. i.e. if the "nft" tool had a library interface that we could call after seeing the device, before upping it, then we could solve your issue fully. But not sure nft has that.

    There's libnftnl and low level Netlink library libmnl. Example program which adds a rule: nft-rule-add.c.

    After the earlier discussion, I installed NetworkManager and use its dispatcher scripts to push IP addresses of the interface to a named set localnet. The static rules (loaded very early) have rules like this:

    table inet filter {
            set localnet {
                    type ipv4_addr;
                    flags interval;
            }
            chain service_x_input {
                    ip saddr @localnet counter accept
                    counter drop
            }
    }
    

    Initially, the set is empty, so the firewall allows nothing until the set gets populated.

    Maybe networkd could keep the addresses of interfaces automatically up to date in NFT sets with prefix systemd, like systemd-eth0-ipv4. That probably shouldn't conflict with existing firewalls but wouldn't also mandate a certain configuration. For maximum compatibility, the mechanism could be opt-in. I suppose nobody wants to introduce arbitrary script launching capabilities to networkd.

  16. sspphheerraa commented on Feb 20, 2025

    @sspphheerraa

    Hello, I have the Host with Gentoo systemd Linux distribution. It provides internet connection to another pc. The nftables rule is:

    chain postrouting {
                    type nat hook postrouting priority srcnat; policy accept;
                    oifname "enp2s0" ip saddr 192.168.0.0/24 masquerade
    }
    
    

    Also the host has virtual machine (kvm / qemu / libvirt / virt-manager) with some guest OSes. The libvirt adds virbr0(1 2) interface and also adds appropriate rules to nftables:

    table ip libvirt_network {
            chain forward {
                    type filter hook forward priority filter; policy accept;
                    counter packets 0 bytes 0 jump guest_cross
                    counter packets 0 bytes 0 jump guest_input
                    counter packets 0 bytes 0 jump guest_output
            }
    
            chain guest_output {
                    iif "virbr2" counter packets 0 bytes 0 reject
                    ip saddr 10.0.2.0/24 iif "virbr1" counter packets 0 bytes 0 accept
                    iif "virbr1" counter packets 0 bytes 0 reject
                    ip saddr 192.168.122.0/24 iif "virbr0" counter packets 0 bytes 0 accept
                    iif "virbr0" counter packets 0 bytes 0 reject
            }
    
            chain guest_input {
                    oif "virbr2" counter packets 0 bytes 0 reject
                    oif "virbr1" ip daddr 10.0.2.0/24 ct state established,related counter packets 0 bytes 0 accept
                    oif "virbr1" counter packets 0 bytes 0 reject
                    oif "virbr0" ip daddr 192.168.122.0/24 ct state established,related counter packets 0 bytes 0 accept
                    oif "virbr0" counter packets 0 bytes 0 reject
            }
    
            chain guest_cross {
                    iif "virbr2" oif "virbr2" counter packets 0 bytes 0 accept
                    iif "virbr1" oif "virbr1" counter packets 0 bytes 0 accept
                    iif "virbr0" oif "virbr0" counter packets 0 bytes 0 accept
            }
    
            chain guest_nat {
                    type nat hook postrouting priority srcnat; policy accept;
                    ip saddr 10.0.2.0/24 ip daddr 224.0.0.0/24 counter packets 0 bytes 0 return
                    ip saddr 10.0.2.0/24 ip daddr 255.255.255.255 counter packets 0 bytes 0 return
                    meta l4proto tcp ip saddr 10.0.2.0/24 ip daddr != 10.0.2.0/24 counter packets 0 bytes 0 masquerade to :1024-65535
                    meta l4proto udp ip saddr 10.0.2.0/24 ip daddr != 10.0.2.0/24 counter packets 0 bytes 0 masquerade to :1024-65535
                    ip saddr 10.0.2.0/24 ip daddr != 10.0.2.0/24 counter packets 0 bytes 0 masquerade
                    ip saddr 192.168.122.0/24 ip daddr 224.0.0.0/24 counter packets 0 bytes 0 return
                    ip saddr 192.168.122.0/24 ip daddr 255.255.255.255 counter packets 0 bytes 0 return
                    meta l4proto tcp ip saddr 192.168.122.0/24 ip daddr != 192.168.122.0/24 counter packets 0 bytes 0 masquerade to :1024-65535
                    meta l4proto udp ip saddr 192.168.122.0/24 ip daddr != 192.168.122.0/24 counter packets 0 bytes 0 masquerade to :1024-65535
                    ip saddr 192.168.122.0/24 ip daddr != 192.168.122.0/24 counter packets 0 bytes 0 masquerade
            }
    }
    table ip6 libvirt_network {
            chain forward {
                    type filter hook forward priority filter; policy accept;
                    counter packets 0 bytes 0 jump guest_cross
                    counter packets 0 bytes 0 jump guest_input
                    counter packets 0 bytes 0 jump guest_output
            }
    
            chain guest_output {
            }
    
            chain guest_input {
            }
    
            chain guest_cross {
            }
    
            chain guest_nat {
                    type nat hook postrouting priority srcnat; policy accept;
            }
    }
    

    The problem is, that when the Host system is shutting down that ruleset saved. And on the next boot nftable-restore service failed to start because there's no virbr0(1 2) interfaces at that moment. And the routing from Host to pc doesn't work. I can't change the rules libvirt adds at startup. So, it's ruleset doesn't need to be saved at shutdown.
    How to solve the problem? Or any workaround here?

  17. mattst88 commented on Mar 11, 2025

    @mattst88
    Contributor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFE 🎁networkpid1

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions