summary refs log tree commit diff
path: root/nixos/modules/services/security/opensnitch.nix
blob: 97ac3a72804c2edf7ed6da8e9fe46ba5050ff06d (plain) (blame)
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
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.opensnitch;
  format = pkgs.formats.json {};

  predefinedRules = flip mapAttrs cfg.rules (name: cfg: {
    file = pkgs.writeText "rule" (builtins.toJSON cfg);
  });

in {
  options = {
    services.opensnitch = {
      enable = mkEnableOption (mdDoc "Opensnitch application firewall");

      rules = mkOption {
        default = {};
        example = 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 = mdDoc ''
          Declarative configuration of firewall rules.
          All rules will be stored in `/var/lib/opensnitch/rules`.
          See [upstream documentation](https://github.com/evilsocket/opensnitch/wiki/Rules)
          for available options.
        '';

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

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

          options = {
            Server = {

              Address = mkOption {
                type = types.str;
                description = mdDoc ''
                  Unix socket path (unix:///tmp/osui.sock, the "unix:///" part is
                  mandatory) or TCP socket (192.168.1.100:50051).
                '';
              };

              LogFile = mkOption {
                type = types.path;
                description = mdDoc ''
                  File to write logs to (use /dev/stdout to write logs to standard
                  output).
                '';
              };

            };

            DefaultAction = mkOption {
              type = types.enum [ "allow" "deny" ];
              description = mdDoc ''
                Default action whether to block or allow application internet
                access.
              '';
            };

            DefaultDuration = mkOption {
              type = types.enum [
                "once" "always" "until restart" "30s" "5m" "15m" "30m" "1h"
              ];
              description = mdDoc ''
                Default duration of firewall rule.
              '';
            };

            InterceptUnknown = mkOption {
              type = types.bool;
              description = mdDoc ''
                Whether to intercept spare connections.
              '';
            };

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

            LogLevel = mkOption {
              type = types.enum [ 0 1 2 3 4 ];
              description = mdDoc ''
                Default log level from 0 to 4 (debug, info, important, warning,
                error).
              '';
            };

            Firewall = mkOption {
              type = types.enum [ "iptables" "nftables" ];
              description = mdDoc ''
                Which firewall backend to use.
              '';
            };

            Stats = {

              MaxEvents = mkOption {
                type = types.int;
                description = mdDoc ''
                  Max events to send to the GUI.
                '';
              };

              MaxStats = mkOption {
                type = types.int;
                description = mdDoc ''
                  Max stats per item to keep in backlog.
                '';
              };

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

  config = mkIf cfg.enable {

    # pkg.opensnitch is referred to elsewhere in the module so we don't need to worry about it being garbage collected
    services.opensnitch.settings = mapAttrs (_: v: mkDefault v) (builtins.fromJSON (builtins.unsafeDiscardStringContext (builtins.readFile "${pkgs.opensnitch}/etc/opensnitchd/default-config.json")));

    systemd = {
      packages = [ pkgs.opensnitch ];
      services.opensnitchd.wantedBy = [ "multi-user.target" ];
    };

    systemd.services.opensnitchd.preStart = mkIf (cfg.rules != {}) (let
      rules = flip mapAttrsToList predefinedRules (file: content: {
        inherit (content) file;
        local = "/var/lib/opensnitch/rules/${file}.json";
      });
    in ''
      # Remove all firewall rules from `/var/lib/opensnitch/rules` 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 /var/lib/opensnitch/rules -type l -lname '${builtins.storeDir}/*' ${optionalString (rules != {}) ''
        -not \( ${concatMapStringsSep " -o " ({ local, ... }:
          "-name '${baseNameOf local}*'")
        rules} \) \
      ''} -delete
      ${concatMapStrings ({ file, local }: ''
        ln -sf '${file}' "${local}"
      '') rules}

      if [ ! -f /etc/opensnitchd/system-fw.json ]; then
        cp "${pkgs.opensnitch}/etc/opensnitchd/system-fw.json" "/etc/opensnitchd/system-fw.json"
      fi
    '');

    environment.etc = mkMerge [ ({
      "opensnitchd/default-config.json".source = format.generate "default-config.json" cfg.settings;
    }) (mkIf (cfg.settings.ProcMonitorMethod == "ebpf") {
      "opensnitchd/opensnitch.o".source = "${config.boot.kernelPackages.opensnitch-ebpf}/etc/opensnitchd/opensnitch.o";
      "opensnitchd/opensnitch-dns.o".source = "${config.boot.kernelPackages.opensnitch-ebpf}/etc/opensnitchd/opensnitch-dns.o";
      "opensnitchd/opensnitch-procs.o".source = "${config.boot.kernelPackages.opensnitch-ebpf}/etc/opensnitchd/opensnitch-procs.o";
    })];

  };
}