summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/security/reaction.nix
blob: dd0642aa04f36ffb90a3d15591a0be77c1b26f78 (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
{
  lib,
  pkgs,
  config,
  ...
}:
let
  settingsFormat = pkgs.formats.yaml { };

  cfg = config.services.reaction;

  inherit (lib)
    concatMapStringsSep
    filterAttrs
    getExe
    mkDefault
    mkEnableOption
    mkIf
    mkOption
    mkPackageOption
    mapAttrs
    optional
    optionals
    optionalString
    types
    ;
in
{
  options.services.reaction = {
    enable = mkEnableOption "enable reaction";
    package = mkPackageOption pkgs "reaction" { };

    settings = mkOption {
      description = ''
        Configuration for reaction. See the [wiki](https://framagit.org/ppom/reaction-wiki).

        The settings are written as a YAML file.

        Can be used in combination with `settingsFiles` option, both will be present in the configuration directory.
      '';
      default = { };
      type = types.submodule {
        freeformType = settingsFormat.type;
        options = {
          plugins = mkOption {
            description = ''
              Nixpkgs provides a `reaction-plugins` package set which includes both offical and community plugins for reaction.

              To use the plugins in your module configuration, in `settings.plugins` you can use for e.g. `''${lib.getExe reaction-plugins.reaction-plugin-ipset}`
              See https://reaction.ppom.me/plugins/ to configure plugins.
            '';
            default = { };
            type = types.attrsOf (
              types.submodule (
                { name, ... }:
                {
                  options = {
                    enable = mkOption {
                      description = "enable reaction-plugin-${name}";
                      type = types.bool;
                      default = true;
                    };
                    path = mkOption {
                      description = "path to the plugin binary";
                      type = types.str;
                      default = "${cfg.package.plugins."reaction-plugin-${name}"}/bin/reaction-plugin-${name}";
                      defaultText = lib.literalExpression ''''${cfg.package.plugins."reaction-plugin-${name}"}/bin/reaction-plugin-${name}'';
                    };
                    check_root = mkOption {
                      description = "Whether reaction must check that the executable is owned by root";
                      type = types.bool;
                      default = true;
                    };
                    systemd = mkOption {
                      description = "Whether reaction must isolate the plugin using systemd's run0";
                      type = types.bool;
                      default = cfg.runAsRoot;
                      defaultText = "config.services.reaction.runAsRoot";
                    };
                    systemd_options = mkOption {
                      description = ''
                        A key-value map of systemd options.
                        Keys must be strings and values must be string arrays.

                        See `man systemd.directives` for all supported options, and particularly options in `man systemd.exec`
                      '';
                      type = types.attrsOf (types.listOf types.str);
                      default = { };
                    };
                  };
                }
              )
            );
            # Filter plugins which are disabled
            apply =
              self:
              lib.pipe self [
                (filterAttrs (name: p: p.enable))
                (mapAttrs (name: p: removeAttrs p [ "enable" ]))
              ];
          };
        };
      };
    };

    settingsFiles = mkOption {
      description = ''
        Configuration for reaction, see the [wiki](https://framagit.org/ppom/reaction-wiki).

        reaction supports JSON, YAML and JSONnet. For those who prefer to take advantage of JSONnet rather than Nix.

        Can be used in combination with `settings` option, both will be present in the configuration directory.
      '';
      default = [ ];
      type = types.listOf types.path;
    };

    loglevel = mkOption {
      description = ''
        reaction's loglevel. One of DEBUG, INFO, WARN, ERROR.
      '';
      default = null;
      type = types.nullOr (
        types.enum [
          "DEBUG"
          "INFO"
          "WARN"
          "ERROR"
        ]
      );
    };

    stopForFirewall = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to stop reaction when reloading the firewall.

        The presence of a reaction chain in the INPUT table may cause the firewall
        reload to fail.
        One can alternatively cherry-pick the right iptables commands to execute before and after the firewall
        ```nix
        {
          systemd.services.firewall.serviceConfig = {
            ExecStopPre = [ "''${pkgs.iptables}/bin/iptables -w -D INPUT -p all -j reaction" ];
            ExecStartPost = [ "''${pkgs.iptables}/bin/iptables -w -I INPUT -p all -j reaction" ];
          };
        }
        ```
      '';
    };

    checkConfig = mkOption {
      type = types.bool;
      default = true;
      description = "Check the syntax of the configuration files at build time";
    };

    runAsRoot = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to run reaction as root.
        Defaults to false, where an unprivileged reaction user is created.

        Be sure to give it sufficient permissions.
        Example config permitting `iptables` and `journalctl` use

        ```nix
        {
          # allows reading journal logs of processess
          users.users.reaction.extraGroups = [ "systemd-journal" ];

          # allows modifying ip firewall rules
          systemd.services.reaction.unitConfig.ConditionCapability = "CAP_NET_ADMIN";
          systemd.services.reaction.serviceConfig = {
            CapabilityBoundingSet = [ "CAP_NET_ADMIN" ];
            AmbientCapabilities = [ "CAP_NET_ADMIN" ];
          };

          # optional, if more control over ssh logs is needed
          services.openssh.settings.LogLevel = lib.mkDefault "VERBOSE";
        }
        ```

        ```nix
        # core ipset plugin requires these if running as non-root
        systemd.services.reaction.serviceConfig = {
          CapabilityBoundingSet = [
            "CAP_NET_ADMIN"
            "CAP_NET_RAW"
            "CAP_DAC_READ_SEARCH" # for journalctl
          ];
          AmbientCapabilities = [
            "CAP_NET_ADMIN"
            "CAP_NET_RAW"
            "CAP_DAC_READ_SEARCH"
          ];
        };
        ```
      '';
    };
  };

  config =
    let
      generatedSettings = settingsFormat.generate "reaction.yml" cfg.settings;
      settingsDir = pkgs.runCommand "reaction-settings-dir" { } ''
        mkdir -p $out
        ${concatMapStringsSep "\n" (file: ''
          filename=$(basename "${file}")
          ln -s "${file}" "$out/$filename"
        '') cfg.settingsFiles}
        ln -s ${generatedSettings} $out/reaction.yml
      '';
    in
    mkIf cfg.enable {
      assertions = [
        {
          assertion = cfg.settings != { } || (builtins.length cfg.settingsFiles) != 0;
          message = "You must specify settings and/or settingsFile options";
        }
      ];

      users = mkIf (!cfg.runAsRoot) {
        users.reaction = {
          isSystemUser = true;
          group = "reaction";
        };
        groups.reaction = { };
      };

      system.checks =
        optional (cfg.checkConfig && pkgs.stdenv.hostPlatform == pkgs.stdenv.buildPlatform)
          (
            pkgs.runCommand "reaction-config-validation" { } ''
              ${getExe cfg.package} test-config -c ${settingsDir} >/dev/null
              echo "reaction config ${settingsDir} is valid"
              touch $out
            ''
          );

      systemd.slices.system-reaction = {
        description = "Reaction system slice";
      };

      systemd.services.reaction = {
        description = "A daemon that scans program outputs for repeated patterns, and takes action.";
        documentation = [ "https://reaction.ppom.me" ];
        after = [ "network.target" ];
        wantedBy = [ "multi-user.target" ];
        partOf = optionals cfg.stopForFirewall [ "firewall.service" ];
        path = [ pkgs.iptables ];
        serviceConfig = {
          Type = "simple";
          KillMode = "mixed"; # for plugins
          Slice = "system-reaction.slice";
          User = if (!cfg.runAsRoot) then "reaction" else "root";
          ExecStart = ''
            ${getExe cfg.package} start -c ${settingsDir}${
              optionalString (cfg.loglevel != null) " -l ${cfg.loglevel}"
            }
          '';

          NoNewPrivileges = true;

          RuntimeDirectory = "reaction";
          RuntimeDirectoryMode = "0750";
          WorkingDirectory = "%S/reaction";
          StateDirectory = "reaction";
          StateDirectoryMode = "0750";
          LogsDirectory = "reaction";
          LogsDirectoryMode = "0750";
          UMask = 0077;

          RemoveIPC = true;
          PrivateTmp = true;
          ProtectHome = true;
          ProtectClock = true;
          PrivateDevices = true;
          ProtectHostname = true;
          ProtectSystem = "strict";
          ProtectKernelTunables = true;
          ProtectKernelModules = true;
          ProtectControlGroups = true;
          ProtectKernelLogs = true;
        };
      };

      # pre-configure official plugins
      services.reaction.settings.plugins = {
        ipset = {
          enable = mkDefault true;
          systemd_options = {
            CapabilityBoundingSet = [
              "~CAP_NET_ADMIN"
              "~CAP_PERFMON"
            ];
          };
        };
        virtual.enable = mkDefault true;
      };

      environment.systemPackages = [ cfg.package ];
    };

  meta.teams = [ lib.teams.ngi ];
  meta.maintainers = with lib.maintainers; [
    ppom
  ];
}