Skip to content

Commit

Permalink
firewall: allow fall-back to fail-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
peterhoeg committed Nov 7, 2018
1 parent 179b814 commit 5a09aaa
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions nixos/modules/services/networking/firewall.nix
Expand Up @@ -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}
Expand Down Expand Up @@ -264,7 +290,7 @@ let
default = [ ];
example = [ 22 80 ];
description =
''
''
List of TCP ports on which incoming connections are
accepted.
'';
Expand All @@ -275,7 +301,7 @@ let
default = [ ];
example = [ { from = 8999; to = 9003; } ];
description =
''
''
A range of TCP ports on which incoming connections are
accepted.
'';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand All @@ -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.