Would NixOS options to easily control core dumps be of general interest?

Enabling or disabling core dumps system-wide is a little finicky. You have to set both systemd extra options and PAM limits, and you may also want to mess with the kernel.core_pattern sysctl option. I wrote a local module to make it as simple as possible, so that I can have them usually be off but easily enabled for troubleshooting:

core dump control module
{ lib, pkgs, config, ... }:
with lib;
{
  imports = [];
  options.coredumps = {
    enable = mkEnableOption "capturing core dumps";
    limit = mkOption {
      type = types.ints.positive;
      default = 2097152;  # 1G worth of 512-byte abstract disk blocks
      description = "Maximum size for core dumps, when enabled.";
    };
  };
  config = mkMerge [
    # No matter what, we don't want systemd messing with core dumps.
    {
      systemd.coredump.enable = false;
    }

    # Settings when core dumps are on.
    (mkIf config.coredumps.enable {
      systemd.extraConfig = ''
        DefaultLimitCORE=${toString config.coredumps.limit
                          }:${toString config.coredumps.limit}
      '';
      security.pam.loginLimits = [
        {
          domain = "*";
          item = "core";
          type = "-";
          value = "${toString config.coredumps.limit}";
        }
      ];

      boot.kernel.sysctl."kernel.core_pattern" = "/var/crash/%e.%p.core";
      systemd.tmpfiles.rules = [
        "d /var/crash 0700 root root  14d -"
      ];
    })

    # Settings when core dumps are off.
    # For some reason, there isn't any such thing as mkIfElse.
    (mkIf (!config.coredumps.enable) {
      systemd.extraConfig = ''
        DefaultLimitCORE=0:0
      '';
      security.pam.loginLimits = [
        {
          domain = "*";
          item = "core";
          type = "-";
          value = "0";
        }
      ];

      # To prevent the kernel from ever generating core dumps, make it
      # try to write to a nonexistent directory.  It doesn't work to specify
      # /dev/null; that will cause the kernel to *replace* /dev/null with the
      # core dump if a process running as root dumps core.
      boot.kernel.sysctl."kernel.core_pattern" = "/nonexistent/core";
    })
  ];
}

I’m tempted to propose this for inclusion in NixOS proper. Obviously it would need to be made quite a bit more configurable, but before I do all that work I thought I would ask here whether anyone besides me would find such a thing useful.

3 Likes

I don’t need it myself, with coredumpctl fitting me well, but it makes sense as an abstraction to have in NixOS config.