2 This module enables a simple firewall.
4 The firewall can be customised in arbitrary ways by setting
5 ‘networking.firewall.extraCommands’. For modularity, the firewall
8 - ‘nixos-fw’ is the main chain for input packet processing.
10 - ‘nixos-fw-accept’ is called for accepted packets. If you want
11 additional logging, or want to reject certain packets anyway, you
12 can insert rules at the start of this chain.
14 - ‘nixos-fw-log-refuse’ and ‘nixos-fw-refuse’ are called for
15 refused packets. (The former jumps to the latter after logging
16 the packet.) If you want additional logging, or want to accept
17 certain packets anyway, you can insert rules at the start of
20 - ‘nixos-fw-rpfilter’ is used as the main chain in the mangle table,
21 called from the built-in ‘PREROUTING’ chain. If the kernel
22 supports it and `cfg.checkReversePath` is set this chain will
23 perform a reverse path filter test.
25 - ‘nixos-drop’ is used while reloading the firewall in order to drop
26 all traffic. Since reloading isn't implemented in an atomic way
27 this'll prevent any traffic from leaking through while reloading
28 the firewall. However, if the reloading fails, the ‘firewall-stop’
29 script will be called which in return will effectively disable the
30 complete firewall (in the default configuration).
40 cfg = config.networking.firewall;
42 inherit (config.boot.kernelPackages) kernel;
45 ((kernel.config.isEnabled or (x: false)) "IP_NF_MATCH_RPFILTER")
46 || (kernel.features.netfilterRPFilter or false);
48 helpers = import ./helpers.nix { inherit config lib; };
53 dir = pkgs.writeScriptBin name ''
54 #! ${pkgs.runtimeShell} -e
60 startScript = writeShScript "firewall-start" ''
63 # Flush the old firewall rules. !!! Ideally, updating the
64 # firewall would be atomic. Apparently that's possible
65 # with iptables-restore.
66 ip46tables -D INPUT -j nixos-fw 2> /dev/null || true
67 for chain in nixos-fw nixos-fw-accept nixos-fw-log-refuse nixos-fw-refuse; do
68 ip46tables -F "$chain" 2> /dev/null || true
69 ip46tables -X "$chain" 2> /dev/null || true
73 # The "nixos-fw-accept" chain just accepts packets.
74 ip46tables -N nixos-fw-accept
75 ip46tables -A nixos-fw-accept -j ACCEPT
78 # The "nixos-fw-refuse" chain rejects or drops packets.
79 ip46tables -N nixos-fw-refuse
82 if cfg.rejectPackets then
84 # Send a reset for existing TCP connections that we've
85 # somehow forgotten about. Send ICMP "port unreachable"
86 # for everything else.
87 ip46tables -A nixos-fw-refuse -p tcp ! --syn -j REJECT --reject-with tcp-reset
88 ip46tables -A nixos-fw-refuse -j REJECT
92 ip46tables -A nixos-fw-refuse -j DROP
97 # The "nixos-fw-log-refuse" chain performs logging, then
98 # jumps to the "nixos-fw-refuse" chain.
99 ip46tables -N nixos-fw-log-refuse
101 ${lib.optionalString cfg.logRefusedConnections ''
102 ip46tables -A nixos-fw-log-refuse -p tcp --syn -j LOG --log-level info --log-prefix "refused connection: "
104 ${lib.optionalString (cfg.logRefusedPackets && !cfg.logRefusedUnicastsOnly) ''
105 ip46tables -A nixos-fw-log-refuse -m pkttype --pkt-type broadcast \
106 -j LOG --log-level info --log-prefix "refused broadcast: "
107 ip46tables -A nixos-fw-log-refuse -m pkttype --pkt-type multicast \
108 -j LOG --log-level info --log-prefix "refused multicast: "
110 ip46tables -A nixos-fw-log-refuse -m pkttype ! --pkt-type unicast -j nixos-fw-refuse
111 ${lib.optionalString cfg.logRefusedPackets ''
112 ip46tables -A nixos-fw-log-refuse \
113 -j LOG --log-level info --log-prefix "refused packet: "
115 ip46tables -A nixos-fw-log-refuse -j nixos-fw-refuse
118 # The "nixos-fw" chain does the actual work.
119 ip46tables -N nixos-fw
121 # Clean up rpfilter rules
122 ip46tables -t mangle -D PREROUTING -j nixos-fw-rpfilter 2> /dev/null || true
123 ip46tables -t mangle -F nixos-fw-rpfilter 2> /dev/null || true
124 ip46tables -t mangle -X nixos-fw-rpfilter 2> /dev/null || true
126 ${lib.optionalString (kernelHasRPFilter && (cfg.checkReversePath != false)) ''
127 # Perform a reverse-path test to refuse spoofers
128 # For now, we just drop, as the mangle table doesn't have a log-refuse yet
129 ip46tables -t mangle -N nixos-fw-rpfilter 2> /dev/null || true
130 ip46tables -t mangle -A nixos-fw-rpfilter -m rpfilter --validmark ${
131 lib.optionalString (cfg.checkReversePath == "loose") "--loose"
134 # Allows this host to act as a DHCP4 client without first having to use APIPA
135 iptables -t mangle -A nixos-fw-rpfilter -p udp --sport 67 --dport 68 -j RETURN
137 # Allows this host to act as a DHCPv4 server
138 iptables -t mangle -A nixos-fw-rpfilter -s 0.0.0.0 -d 255.255.255.255 -p udp --sport 68 --dport 67 -j RETURN
140 ${lib.optionalString cfg.logReversePathDrops ''
141 ip46tables -t mangle -A nixos-fw-rpfilter -j LOG --log-level info --log-prefix "rpfilter drop: "
143 ip46tables -t mangle -A nixos-fw-rpfilter -j DROP
145 ip46tables -t mangle -A PREROUTING -j nixos-fw-rpfilter
148 # Accept all traffic on the trusted interfaces.
149 ${lib.flip lib.concatMapStrings cfg.trustedInterfaces (iface: ''
150 ip46tables -A nixos-fw -i ${iface} -j nixos-fw-accept
153 # Accept packets from established or related connections.
154 ip46tables -A nixos-fw -m conntrack --ctstate ESTABLISHED,RELATED -j nixos-fw-accept
156 # Accept connections to the allowed TCP ports.
157 ${lib.concatStrings (
160 lib.concatMapStrings (port: ''
161 ip46tables -A nixos-fw -p tcp --dport ${toString port} -j nixos-fw-accept ${
162 lib.optionalString (iface != "default") "-i ${iface}"
164 '') cfg.allowedTCPPorts
168 # Accept connections to the allowed TCP port ranges.
169 ${lib.concatStrings (
172 lib.concatMapStrings (
175 range = toString rangeAttr.from + ":" + toString rangeAttr.to;
178 ip46tables -A nixos-fw -p tcp --dport ${range} -j nixos-fw-accept ${
179 lib.optionalString (iface != "default") "-i ${iface}"
182 ) cfg.allowedTCPPortRanges
186 # Accept packets on the allowed UDP ports.
187 ${lib.concatStrings (
190 lib.concatMapStrings (port: ''
191 ip46tables -A nixos-fw -p udp --dport ${toString port} -j nixos-fw-accept ${
192 lib.optionalString (iface != "default") "-i ${iface}"
194 '') cfg.allowedUDPPorts
198 # Accept packets on the allowed UDP port ranges.
199 ${lib.concatStrings (
202 lib.concatMapStrings (
205 range = toString rangeAttr.from + ":" + toString rangeAttr.to;
208 ip46tables -A nixos-fw -p udp --dport ${range} -j nixos-fw-accept ${
209 lib.optionalString (iface != "default") "-i ${iface}"
212 ) cfg.allowedUDPPortRanges
216 # Optionally respond to ICMPv4 pings.
217 ${lib.optionalString cfg.allowPing ''
218 iptables -w -A nixos-fw -p icmp --icmp-type echo-request ${
219 lib.optionalString (cfg.pingLimit != null) "-m limit ${cfg.pingLimit} "
223 ${lib.optionalString config.networking.enableIPv6 ''
224 # Accept all ICMPv6 messages except redirects and node
225 # information queries (type 139). See RFC 4890, section
227 ip6tables -A nixos-fw -p icmpv6 --icmpv6-type redirect -j DROP
228 ip6tables -A nixos-fw -p icmpv6 --icmpv6-type 139 -j DROP
229 ip6tables -A nixos-fw -p icmpv6 -j nixos-fw-accept
231 # Allow this host to act as a DHCPv6 client
232 ip6tables -A nixos-fw -d fe80::/64 -p udp --dport 546 -j nixos-fw-accept
237 # Reject/drop everything else.
238 ip46tables -A nixos-fw -j nixos-fw-log-refuse
241 # Enable the firewall.
242 ip46tables -A INPUT -j nixos-fw
245 stopScript = writeShScript "firewall-stop" ''
248 # Clean up in case reload fails
249 ip46tables -D INPUT -j nixos-drop 2>/dev/null || true
251 # Clean up after added ruleset
252 ip46tables -D INPUT -j nixos-fw 2>/dev/null || true
254 ${lib.optionalString (kernelHasRPFilter && (cfg.checkReversePath != false)) ''
255 ip46tables -t mangle -D PREROUTING -j nixos-fw-rpfilter 2>/dev/null || true
258 ${cfg.extraStopCommands}
261 reloadScript = writeShScript "firewall-reload" ''
264 # Create a unique drop rule
265 ip46tables -D INPUT -j nixos-drop 2>/dev/null || true
266 ip46tables -F nixos-drop 2>/dev/null || true
267 ip46tables -X nixos-drop 2>/dev/null || true
268 ip46tables -N nixos-drop
269 ip46tables -A nixos-drop -j DROP
271 # Don't allow traffic to leak out until the script has completed
272 ip46tables -A INPUT -j nixos-drop
274 ${cfg.extraStopCommands}
276 if ${startScript}; then
277 ip46tables -D INPUT -j nixos-drop 2>/dev/null || true
279 echo "Failed to reload firewall... Stopping"
291 networking.firewall = {
292 extraCommands = lib.mkOption {
293 type = lib.types.lines;
295 example = "iptables -A INPUT -p icmp -j ACCEPT";
297 Additional shell commands executed as part of the firewall
298 initialisation script. These are executed just before the
299 final "reject" firewall rule is added, so they can be used
300 to allow packets that would otherwise be refused.
302 This option only works with the iptables based firewall.
306 extraStopCommands = lib.mkOption {
307 type = lib.types.lines;
309 example = "iptables -P INPUT ACCEPT";
311 Additional shell commands executed as part of the firewall
312 shutdown script. These are executed just after the removal
313 of the NixOS input rule, or if the service enters a failed
316 This option only works with the iptables based firewall.
323 # FIXME: Maybe if `enable' is false, the firewall should still be
324 # built but not started by default?
325 config = lib.mkIf (cfg.enable && config.networking.nftables.enable == false) {
328 # This is approximately "checkReversePath -> kernelHasRPFilter",
329 # but the checkReversePath option can include non-boolean
332 assertion = cfg.checkReversePath == false || kernelHasRPFilter;
333 message = "This kernel does not support rpfilter";
337 networking.firewall.checkReversePath = lib.mkIf (!kernelHasRPFilter) (lib.mkDefault false);
339 systemd.services.firewall = {
340 description = "Firewall";
341 wantedBy = [ "sysinit.target" ];
342 wants = [ "network-pre.target" ];
343 after = [ "systemd-modules-load.service" ];
348 conflicts = [ "shutdown.target" ];
350 path = [ cfg.package ] ++ cfg.extraPackages;
352 # FIXME: this module may also try to load kernel modules, but
353 # containers don't have CAP_SYS_MODULE. So the host system had
354 # better have all necessary modules already loaded.
355 unitConfig.ConditionCapability = "CAP_NET_ADMIN";
356 unitConfig.DefaultDependencies = false;
358 reloadIfChanged = true;
362 RemainAfterExit = true;
363 ExecStart = "@${startScript} firewall-start";
364 ExecReload = "@${reloadScript} firewall-reload";
365 ExecStop = "@${stopScript} firewall-stop";