summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/security/opensnitch.nix
blob: 0631d0a1863b19871126613aae97cb0d94459812 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.services.opensnitch;
  format = pkgs.formats.json { };

  predefinedRules = lib.flip lib.mapAttrs cfg.rules (
    name: cfg: {
      file = pkgs.writeText "rule" (builtins.toJSON cfg);
    }
  );
  stateDir = lib.strings.match "/var/lib/([^/]+)/.+" cfg.settings.Rules.Path;
in
{
  options = {
    services.opensnitch = {
      enable = lib.mkEnableOption "Opensnitch application firewall";
      package = lib.mkPackageOption pkgs "opensnitch" { };

      rules = lib.mkOption {
        default = { };
        example = lib.literalExpression ''
          {
            "tor" = {
              "name" = "tor";
              "enabled" = true;
              "action" = "allow";
              "duration" = "always";
              "operator" = {
                "type" ="simple";
                "sensitive" = false;
                "operand" = "process.path";
                "data" = "''${lib.getBin pkgs.tor}/bin/tor";
              };
            };
          };
        '';

        description = ''
          Declarative configuration of firewall rules.
          All rules will be stored in `/var/lib/opensnitch/rules` by default.
          Rules path can be configured with `settings.Rules.Path`.
          See [upstream documentation](https://github.com/evilsocket/opensnitch/wiki/Rules)
          for available options.
        '';

        type = lib.types.submodule {
          freeformType = format.type;
        };
      };

      upstreamDefaults = lib.mkOption {
        description = ''
          Whether to base the config declared in {option}`services.opensnitch.settings` on the upstream example config (<https://github.com/evilsocket/opensnitch/blob/master/daemon/data/default-config.json>)

          Disable this if you want to declare your opensnitch config from scratch.
        '';
        type = lib.types.bool;
        default = true;
      };

      configFile = lib.mkOption {
        description = ''
          Path to JSON config file. See: <https://github.com/evilsocket/opensnitch/blob/master/daemon/data/default-config.json>
          If this option is set, it will override any configuration done in options.services.opensnitch.settings.
        '';
        example = "/etc/opensnitchd/default-config.json";
        type = lib.types.path;
        default =
          let
            generatedConfig = format.generate "config.json" cfg.settings;
          in
          if cfg.upstreamDefaults then
            pkgs.runCommand "opensnitch-config.json" { } ''
              ${lib.getExe pkgs.jq} -s '.[0] * .[1]' ${cfg.package}/etc/opensnitchd/default-config.json ${format.generate "config.json" cfg.settings} >"$out"
            ''
          else
            generatedConfig;
        defaultText = lib.literalMD "JSON file generated from {option}`services.opensnitch.settings`";
      };

      settings = lib.mkOption {
        type = lib.types.submodule {
          freeformType = format.type;

          options = {
            ProcMonitorMethod = lib.mkOption {
              type = lib.types.enum [
                "ebpf"
                "proc"
                "ftrace"
                "audit"
              ];
              default = "ebpf";
              description = ''
                Which process monitoring method to use.
              '';
            };

            Firewall = lib.mkOption {
              type = lib.types.enum [
                "iptables"
                "nftables"
              ];
              default = "nftables";
              description = ''
                Which firewall backend to use. `nftables` ruleset can be used for `iptables` firewall too, if `iptables` is built with nftables compatibility.
              '';
            };
            Ebpf.ModulesPath = lib.mkOption {
              type = lib.types.nullOr lib.types.path;
              default =
                if cfg.settings.ProcMonitorMethod == "ebpf" then
                  "${config.boot.kernelPackages.opensnitch-ebpf}/etc/opensnitchd"
                else
                  null;
              defaultText = lib.literalExpression ''
                if cfg.settings.ProcMonitorMethod == "ebpf" then
                  "''${config.boot.kernelPackages.opensnitch-ebpf}/etc/opensnitchd"
                else null;
              '';
              description = ''
                Configure eBPF modules path. Used when
                `settings.ProcMonitorMethod` is set to `ebpf`.
              '';
            };

            Audit.AudispSocketPath = lib.mkOption {
              type = lib.types.path;
              default = "/run/audit/audispd_events";
              description = ''
                Configure audit socket path. Used when
                `settings.ProcMonitorMethod` is set to `audit`.
              '';
            };

            Rules.Path = lib.mkOption {
              type = lib.types.pathWith {
                inStore = false;
                absolute = true;
              };
              default = "/var/lib/opensnitch/rules";
              description = ''
                Path to the directory where firewall rules can be found and will
                get stored by the NixOS module.
              '';
            };

          };
        };
        description = ''
          opensnitchd configuration. Refer to [upstream documentation](https://github.com/evilsocket/opensnitch/wiki/Configurations)
          for details on supported values.
        '';
      };
    };
  };

  config = lib.mkIf cfg.enable {
    assertions = [
      {
        assertion = stateDir != null;
        message = "`config.services.opensnitch.settings.Rules.Path` must be a sub-directory of /var/lib/, currently is ${cfg.settings.Rules.Path}";
      }
    ];

    security.auditd = lib.mkIf (cfg.settings.ProcMonitorMethod == "audit") {
      enable = true;
      plugins.af_unix.active = true;
    };

    systemd = {
      packages = [ cfg.package ];
      services.opensnitchd = {
        wantedBy = [ "multi-user.target" ];
        path = lib.optionals (cfg.settings.ProcMonitorMethod == "audit") [ pkgs.audit ];
        serviceConfig = {
          ExecStart = [
            ""
            "${lib.getExe' cfg.package "opensnitchd"} --config-file ${cfg.configFile}"
          ];
          StateDirectory = builtins.head stateDir; # match produces a list. Null case covered by assertion.
        };
        preStart = ''
          # assert rules directory exists before service starts
          # will be in StateDirectory due to assertion
          mkdir -p ${cfg.settings.Rules.Path}
        ''
        + lib.optionalString (cfg.rules != { }) (
          let
            rules = lib.flip lib.mapAttrsToList predefinedRules (
              file: content: {
                inherit (content) file;
                local = "${cfg.settings.Rules.Path}/${file}.json";
              }
            );
          in
          ''
            # Remove all firewall rules from rules path (configured with
            # cfg.settings.Rules.Path) that are symlinks to a store-path, but aren't
            # declared in `cfg.rules` (i.e. all networks that were "removed" from
            # `cfg.rules`).
            find ${cfg.settings.Rules.Path} -type l -lname '${builtins.storeDir}/*' ${
              lib.optionalString (rules != { }) ''
                -not \( ${
                  lib.concatMapStringsSep " -o " ({ local, ... }: "-name '${baseNameOf local}*'") rules
                } \) \
              ''
            } -delete
            ${lib.concatMapStrings (
              { file, local }:
              ''
                ln -sf '${file}' "${local}"
              ''
            ) rules}
          ''
        );
      };
    };

    environment.etc."opensnitchd/network_aliases.json".source =
      "${cfg.package}/etc/opensnitchd/network_aliases.json";
    environment.etc."opensnitchd/system-fw.json".source =
      "${cfg.package}/etc/opensnitchd/system-fw.json";
  };

  meta.maintainers = with lib.maintainers; [
    onny
    grimmauld
  ];
}