Skip to content
Permalink
Browse files

firewall: allow fall-back to fail-safe

  • Loading branch information
peterhoeg committed Nov 7, 2018
1 parent 179b814 commit 5a09aaa1860d19c6623fcd8c3b691093d419ee43
Showing with 54 additions and 2 deletions.
  1. +54 −2 nixos/modules/services/networking/firewall.nix
@@ -58,6 +58,32 @@ let
${text}
''; in "${dir}/bin/${name}";

failsafeScript = writeShScript "firewall-failsafe" (let
chains = [ "INPUT" "FORWARD" "OUTPUT" ];
policy = if cfg.failsafe == "open" then "ACCEPT" else "DROP";
sshPorts = lib.concatStringsSep "," (map (e: toString e) (builtins.unique config.services.openssh.ports));
in ''
${lib.optionalString (cfg.failsafe == "noop") ''
# failsafe not configured, exiting
exit 0
''}
${helpers}
# flush built-in chains and set policy to ${policy}
${lib.concatStringsSep "\n" (map (chain: ''
ip46tables -F ${chain}
ip46tables -P ${chain} ${policy}
'') chains)}
# allow outbound traffic
ip46tables -P OUTPUT ACCEPT
${lib.optionalString (cfg.failsafe == "ssh-only") ''
# allow SSH
ip46tables -A INPUT -p tcp --dports ${sshPorts} -j ACCEPT
''}
'');

startScript = writeShScript "firewall-start" ''
${helpers}
@@ -264,7 +290,7 @@ let
default = [ ];
example = [ 22 80 ];
description =
''
''
List of TCP ports on which incoming connections are
accepted.
'';
@@ -275,7 +301,7 @@ let
default = [ ];
example = [ { from = 8999; to = 9003; } ];
description =
''
''
A range of TCP ports on which incoming connections are
accepted.
'';
@@ -343,6 +369,22 @@ in
'';
};

failsafe = mkOption {
type = types.enum [ "open" "closed" "ssh-only" "noop" ];
default = "noop";
description = ''
In case of errors when starting/stopping/reloading the main firewall
script, reset the firewall state to a known good configuration.
</para>
<para>
The options are:
- open: do not block connections
- closed: block all connections
- ssh-only: allow only SSH
- noop: do not do anything (the default)
'';
};

logRefusedUnicastsOnly = mkOption {
type = types.bool;
default = true;
@@ -558,6 +600,7 @@ in
# better have all necessary modules already loaded.
unitConfig.ConditionCapability = "CAP_NET_ADMIN";
unitConfig.DefaultDependencies = false;
unitConfig.OnFailure = "firewall-failsafe.service";

reloadIfChanged = true;

@@ -570,6 +613,15 @@ in
};
};

systemd.services.firewall-failsafe = {
description = "Fail-safe firewall";
path = with pkgs; [ iptables ];
unitConfig.ConditionCapability = "CAP_NET_ADMIN";
serviceConfig = {
Type = "oneshot";
ExecStart = failsafeScript;
};
};
};

}

0 comments on commit 5a09aaa

Please sign in to comment.
You can’t perform that action at this time.