Skip to content

RFE/RFD: lightweight integration of NFT sets for use in firewalls #22527

Closed

Description

@topimiettinen

Is your feature request related to a problem? Please describe.
Integrating firewall rules with systemd services is difficult or impossible. There are BPF options but they aren't very nice to administrate. Also, kernel's netfilter system for cgroup matching is based on numeric cgroup IDs, which change every time a service is restarted, making them useless in systemd environment. Typically DNS information isn't available for firewalls.

Describe the solution you'd like
PID1, networkd and resolved should optionally put discovered network and cgroup ID information to NFT sets, for use with firewall rules.

  • PID1 should put cgroupv2 IDs to NFT sets named using cgroup path like systemd.user.slice/user-1000.slice/[email protected]/app.slice/, or perhaps to set specified with Service.CGroupNFTSet=systemd-app
  • networkd should put interface IP address ranges and possibly other information (at the extreme, same as NetworkManager-dispatcher) to set named for example systemd-eth0-ipv4 or perhaps instead specified with Network.IPv4NFTSet=systemd-eth0-ipv4
  • resolved should put DNS information from resolved to set named according to requesting service (see also resolved: access control feature #17126) or explicitly configured

Then the firewall rules can make arbitrarily complex use of the sets. Systemd would not need to gain further firewalling abilities besides the rather simple management of specific NFT sets.

Example NFT rules:

table inet filter {
        set systemd-eth0-ipv4 {
                type ipv4_addr;
                flags interval;
        }
        set systemd-app {
                type integer;
        }
        set systemd-timesyncd {
                type ipv4_addr;
        }

        chain service_x_input {
                ip saddr @systemd-eth0-ipv4 counter accept
                counter drop
        }
        chain service_y_input {
                meta cgroup @systemd-app counter accept
                counter drop
        }
        chain systemd_timesyncd_output {
                ip daddr @systemd-timesyncd counter accept
                counter reject with icmpx admin-prohibited
        }
}

Related discussion in #7327 and #21899.

Describe alternatives you've considered
Daemons to manage cgroup IDs:
https://github.com/helsinki-systems/nft_cgroupv2/
https://github.com/mk-fg/systemd-cgroup-nftables-policy-manager

IPSet module for Unbound DNS puts resolved A and AAAA addresses to IPSet (but it can't identify the calling service):
https://github.com/NLnetLabs/unbound/blob/master/ipset/ipset.c

Activity

  1. added
    RFE 🎁
    on Feb 15, 2022
  2. topimiettinen commented on Feb 16, 2022

    @topimiettinen
    ContributorAuthor

    Benefit of using NFT sets compared to external daemons is that modifying the set is synchronous but very lightweight operation. For example, networkd can set the IP address from DHCP to the set before applying it to the interface, so there are no time windows where the set would be updated too late. This could easily happen if there's an external daemon listening to events (unless PID1 or networkd would wait while scripts execute and signal completion).

    @poettering @yuwata @keszybz @bluca WDYT?

  3. yuwata commented on Feb 16, 2022

    @yuwata
    Member

    Sounds nice!

  4. topimiettinen commented on Feb 18, 2022

    @topimiettinen
    ContributorAuthor

    libnftnl is licensed under GPL2+. Would that be a problem?

    Its dependency, libmnl is under LGPLv2.1+.

  5. bluca commented on Feb 18, 2022

    @bluca
    Member

    Yes, GPL2 library would be a problem, as the combined work after linking would be GPL2 as a whole - weird license choice for a library?

  6. topimiettinen commented on Feb 18, 2022

    @topimiettinen
    ContributorAuthor

    Yes, GPL2 library would be a problem, as the combined work after linking would be GPL2 as a whole - weird license choice for a library?

    Yes, not very inviting. Luckily our own sd-netlink already can process some netlink messages.

  7. poettering commented on Feb 18, 2022

    @poettering
    Member

    Conceptually the networkd ip address thing, and the cgroup id thing make sense to me. Not sure I am convinced by the resolved thing, it sucks for access control...

  8. poettering commented on Feb 18, 2022

    @poettering
    Member

    So we recently discussed whether we should add support to .network files to automatically load nft rules files on interface activation. i.e. that if networkd actviates foobar.network we also load the foobar.nft firewall.

    It appears to me that the concept suggested here of maintaining NFT set objects is a more flexible approach, right?

    i.e. what model is preferable: having a static firewall ruleset with dynamic sets – or having a dynamic firewall ruleset? It appears to me the former makes more sense.

    Thoughts?

  9. topimiettinen commented on Feb 18, 2022

    @topimiettinen
    ContributorAuthor

    I think the models are complementary. Loading rules on interface activation is useful for netdev rules, which can't use a set for the interface name. In other cases, set objects may contain information which can be used with static (but also per-interface) rules.

    The per-interface rules can be implemented with no changes. Example:

    # /etc/udev/rules.d/90-netfilter.rules 
    SUBSYSTEM!="net", GOTO="netfilter_end"
    ENV{SYSTEMD_WANTS}+="nftables-dev@$name.service"
    LABEL="netfilter_end"
    
    # /etc/systemd/system/[email protected]
    [Unit]
    Description=nftables for device %i
    Documentation=man:nft(8) http://wiki.nftables.org
    Wants=network-pre.target nftables.service
    Before=network-pre.target shutdown.target
    Conflicts=shutdown.target
    DefaultDependencies=no
    After=nftables.service
    
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    StandardInput=null
    ProtectSystem=full
    ProtectHome=true
    ExecStart=/usr/sbin/nft -f /etc/nftables-%i.conf
    ExecReload=/usr/sbin/nft -f /etc/nftables-%i.conf
    
    [Install]
    WantedBy=sysinit.target
    
    # /etc/nftables-lan.conf 
    #!/usr/sbin/nft -f
    
    table netdev filter {
            chain lan_ingress {
                    type filter hook ingress device lan priority filter; policy drop;
            }
    }
    
    flush chain netdev filter lan_ingress
    
    table netdev filter {
            chain lan_ingress {
                    type filter hook ingress device lan priority filter; policy drop;
    
                    meta protocol vmap {
                         ip : jump validate_ipv4,
                         ip6 : jump validate_ipv6,
                         arp : jump validate_arp
                    }
                    counter log prefix "[netdev-lan-ingress] " flags all drop
            }
    }
    

    This uses static device name 'lan', but I suppose I could use @@DEVICE@@ insted and use sed to replace the interface name with %i and feed its output in a pipe to nft.

    Some rules above (like validate_ipv4) are defined in static part.

  10. added a commit that references this issue on Feb 21, 2022
    758fdb8
  11. sta-c0000 commented on Mar 2, 2022

    @sta-c0000

    re: resolved and DNS query nft sets
    I think just that is a great idea, I'm using dnsmasq v2.87 for this specific use case (easily backported to Debian bullseye).

    As you might know dnsmasq v2.87 added the --nftset domain name option.
    It's great because the nft sets are populated when, and only when, an actual DNS query is performed by the application / service with the ip addresses returned to them by the DNS reply. It's very efficient.

    I had been trying to work out an allowlist firewall using systemd cgroupv2...
    Instead I settled on forcing every service and application to use specific Linux users and or groups (one for every that requires any network resources).
    nftables is indeed easier, more powerful and flexible, and now better for statistics.
    I've detailed how I'm using nftables with dnsmasq nft sets (with some caveats) here: Group Allow-List Application Firewall

  12. topimiettinen commented on Mar 2, 2022

    @topimiettinen
    ContributorAuthor

    re: resolved and DNS query nft sets I think just that is a great idea, I'm using dnsmasq v2.87 for this specific use case (easily backported to Debian bullseye).

    As you might know dnsmasq v2.87 added the --nftset domain name option. It's great because the nft sets are populated when, and only when, an actual DNS query is performed by the application / service with the ip addresses returned to them by the DNS reply. It's very efficient.

    Thanks, I didn't know about this feature. I have a pretty much complete PR for DNS access control for resolved in #17126. My plan is to integrate it with NFT sets. The advantage of using resolved instead of dnsmasq is tighter integration with NSS (nss_resolve). It uses Unix sockets instead of UDP, so much more information on the calling process is available, which could then be used for filtering.

    I had been trying to work out an allowlist firewall using systemd cgroupv2...

    I think the problem is that the kernel interface for accessing cgroups from NFT filters is poor. The cgroupv1 IDs or cgroupv2 paths should not need to be resolvable when the firewall is installed. Perhaps the kernel should perform path checks at cgroup creation time and then automatically resolve cgroup IDs for NFT. Doing this in userspace is a poor choice. It could work for systemd because it's the entity creating the cgroups in most cases, but I don't think this scales to unprivileged systemd --user, containers or delegated cgroups etc.

    Instead I settled on forcing every service and application to use specific Linux users and or groups (one for every that requires any network resources). nftables is indeed easier, more powerful and flexible, and now better for statistics. I've detailed how I'm using nftables with dnsmasq nft sets (with some caveats) here: Group Allow-List Application Firewall

    What a coincidence, I also discovered GALAF a few days ago. Using a different UID/GID for every application is a nice idea. For system services, this is pretty easy since many services already run with either a fixed UID with User= or use DynamicUser= and then meta skuid can be used for access control. Perhaps the remaining UID 0 services could be convinced to use a different GID (and drop CAP_SETGID). For unprivileged user apps there should be a way to switch to UID/GID per app with Firejail or bubblewrap so that it's integrated with other sandboxing features. It would be awesome if also GUI tools like gnome-system-monitor could show network statistics at app level, perhaps even drilling down to each process/thread.

    SELinux can be also integrated with firewall tables, but the design choice is that the access rules are on SELinux side. This makes sense, but the actual implementation is a bit weird. It would be simpler if the SELinux domain label for the process or socket could be also used directly on NFT side for further access control.

  13. 5 remaining items

  14. added 3 commits that reference this issue on Mar 23, 2022
    7ed18a7
    0821e79
    dc006cb
  15. added 2 commits that reference this issue on Apr 2, 2022
    e0d91ac
    c814855
  16. added a commit that references this issue on Apr 9, 2022
    c8b20c3
  17. topimiettinen commented on Apr 23, 2022

    @topimiettinen
    ContributorAuthor

    Another simple integration feature idea for networkd, this time not with firewalls but NetLabel system (SELinux, Smack, perhaps AppArmor and other LSMs too): new directives Network.IPv4NetLabelUnlabel= and Network.IPv6NetLabelUnlabel= (perhaps the names could be improved...). This would improve handling of dynamic network interfaces with NetLabel subsystem.

    Proposed manual page text:

    Network.IPv4NetLabelUnlabel=label... and Network.IPv6NetLabelUnlabel=label...

    • These settings provide a method for integrating dynamic network configuration into Linux NetLabel subsystem rules, used by Linux security modules (LSMs) for network access control. The options expect a whitespace separated list of NetLabel labels. The labels must conform to lexical restrictions of LSM labels. When an interface is configured with IP addresses, the addresses and subnetwork masks will be appended to the NetLabel Fallback Peer Labeling rules. They will be removed when the interface is deconfigured. Failures to manage the labels will be ignored.

    • As an example for IPv4NetLabelUnlabel=system_u:object_r:localnet_peer_t:s0 for interface eth0, when the interface is configured with an IPv4 address 10.0.0.0/8, networkd performs the equivalent of netlabelctl operation unlbl add interface eth0 address:10.0.0.0/8 label:system_u:object_r:localnet_peer_t:s0 and the reverse when the IPv4 address is deconfigured.

    I think this would also help with NetLabel issue #8, for systems with systemd-networkd. @pcmoore WDYT?

  18. pcmoore commented on Apr 25, 2022

    @pcmoore

    The NetLabel integration seems reasonable to me, although there would likely need to be some additional configuration (or very prominent warnings!) as once you start labeling network traffic a lot of access control points go from dormant to active and it is easy for someone not familiar with the LSM per-packet access controls to get into a bad situation.

  19. pcmoore commented on Apr 25, 2022

    @pcmoore

    I should also add, if NetLabel integration is something systemd is serious about, I can make the netlabel_tools static library a shared library (and likely clean it up a bit too) if systemd wanted to take that approach instead of calling netlabelctl directly.

  20. topimiettinen commented on Apr 26, 2022

    @topimiettinen
    ContributorAuthor

    The NetLabel integration seems reasonable to me, although there would likely need to be some additional configuration (or very prominent warnings!) as once you start labeling network traffic a lot of access control points go from dormant to active and it is easy for someone not familiar with the LSM per-packet access controls to get into a bad situation.

    Yes, the static configuration would have to be managed with netlabelctl like before, the new directive should be needed only if dynamic interfaces need extra configuration. There should be a warning and maybe a reference to NetLabel docs.

    There could be a full-blown implementation, where networkd could be used to configure all NetLabel features, but I don't think that makes too much sense. Testing all features (CIPSO etc) with a CI setup would be also interesting exercise.

    I should also add, if NetLabel integration is something systemd is serious about, I can make the netlabel_tools static library a shared library (and likely clean it up a bit too) if systemd wanted to take that approach instead of calling netlabelctl directly.

    That would be great, assuming that the license will be compatible with systemd's LGPL2.1. Systemd also has an internal implementation of netlink message handling which could be used.

  21. bluca commented on Apr 26, 2022

    @bluca
    Member

    I should also add, if NetLabel integration is something systemd is serious about, I can make the netlabel_tools static library a shared library (and likely clean it up a bit too) if systemd wanted to take that approach instead of calling netlabelctl directly.

    That would be great, assuming that the license will be compatible with systemd's LGPL2.1. Systemd also has an internal implementation of netlink message handling which could be used.

    It would also need to be dlopen-safe, which usually is not a problem, but worth mentioning. But it looks like it's GPL-2.0-only https://github.com/netlabel/netlabel_tools/blob/main/LICENSE which is a problem - we'd need LGPL-2.1-or-later to use it here

  22. pcmoore commented on Apr 26, 2022

    @pcmoore

    Testing all features (CIPSO etc) with a CI setup would be also interesting exercise.

    We do basic SELinux/NetLabel testing as part of the kernel-secnext automated testing, via the selinux-testsuite, but I wouldn't consider that exhaustive testing. In some sense, a fully exhaustive test is out-of-scope for the selinux-testsuite.

    That would be great, assuming that the license will be compatible with systemd's LGPL2.1. Systemd also has an internal implementation of netlink message handling which could be used.

    ... and ...

    ... it looks like it's GPL-2.0-only which is a problem ...

    Part of that comes from the original idea that the only consumers of the netlabel_tools static library were going to be tools included in netlabel_tools. I'm not sure I want to go through the hassle of re-licensing the package/library at this point, especially since systemd already knows how to talk to the kernel via netlink/attributes; it's likely easier and quicker to just have systemd issue whatever NetLabel commands it wants direclty via netlink.

  23. topimiettinen commented on Apr 27, 2022

    @topimiettinen
    ContributorAuthor

    Part of that comes from the original idea that the only consumers of the netlabel_tools static library were going to be tools included in netlabel_tools. I'm not sure I want to go through the hassle of re-licensing the package/library at this point, especially since systemd already knows how to talk to the kernel via netlink/attributes; it's likely easier and quicker to just have systemd issue whatever NetLabel commands it wants direclty via netlink.

    Agreed. The unlabeled protocol seems simple (command, iface, secctx, addr+mask), so we can implement it without any new libraries.

  24. topimiettinen commented on May 4, 2022

    @topimiettinen
    ContributorAuthor

    Made a separate PR #23269 for NetLabel, since it doesn't use NFT sets.

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 🎁networkpid1resolve

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions