summary refs log tree commit diff
path: root/nixos/modules/security/permissions-wrappers
diff options
context:
space:
mode:
authorParnell Springmeyer <parnell@awakenetworks.com>2016-07-15 18:05:28 -0500
committerParnell Springmeyer <parnell@awakenetworks.com>2016-09-01 19:15:56 -0500
commit79e81aa31bc7a0fa88507c06f21b41fbbd1cb863 (patch)
treeffdca983b7c2cd98aedbbcd08d479e6be6508f3b /nixos/modules/security/permissions-wrappers
parentc16647ec29ab46b52cd365220288a8222cfcdad3 (diff)
downloadnixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar.gz
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar.bz2
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar.lz
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar.xz
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.tar.zst
nixlib-79e81aa31bc7a0fa88507c06f21b41fbbd1cb863.zip
security: Removing the old wrappers and replacing with 'permissions-wrappers'
Diffstat (limited to 'nixos/modules/security/permissions-wrappers')
-rw-r--r--nixos/modules/security/permissions-wrappers/default.nix201
-rw-r--r--nixos/modules/security/permissions-wrappers/permissions-wrapper.c224
-rw-r--r--nixos/modules/security/permissions-wrappers/setcap-wrapper-drv.nix37
-rw-r--r--nixos/modules/security/permissions-wrappers/setcap-wrappers.nix162
-rw-r--r--nixos/modules/security/permissions-wrappers/setuid-wrapper-drv.nix36
-rw-r--r--nixos/modules/security/permissions-wrappers/setuid-wrappers.nix145
6 files changed, 805 insertions, 0 deletions
diff --git a/nixos/modules/security/permissions-wrappers/default.nix b/nixos/modules/security/permissions-wrappers/default.nix
new file mode 100644
index 000000000000..a4491946df5d
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/default.nix
@@ -0,0 +1,201 @@
+{ config, lib, pkgs, ... }:
+let
+
+  inherit (config.security) permissionsWrapperDir;
+
+  cfg = config.security.permissionsWrappers;
+
+  setcapWrappers = import ./setcap-wrapper-drv.nix { };
+  setuidWrappers = import ./setuid-wrapper-drv.nix { };
+
+  ###### Activation script for the setcap wrappers
+  configureSetcapWrapper =
+    { program
+    , capabilities
+    , source ? null
+    , owner  ? "nobody"
+    , group  ? "nogroup"
+    , setcap ? false
+    }:
+    ''
+      cp ${setcapWrappers}/bin/${program}.wrapper ${permissionsWrapperDir}/${program}
+
+      # Prevent races
+      chmod 0000 ${permissionsWrapperDir}/${program}
+      chown ${owner}.${group} ${permissionsWrapperDir}/${program}
+
+      # Set desired capabilities on the file plus cap_setpcap so
+      # the wrapper program can elevate the capabilities set on
+      # its file into the Ambient set.
+      #
+      # Only set the capabilities though if we're being told to
+      # do so.
+      ${
+      if setcap then
+        ''
+        ${pkgs.libcap.out}/bin/setcap "cap_setpcap,${capabilities}" ${permissionsWrapperDir}/${program}
+        ''
+      else ""
+      }
+
+      # Set the executable bit
+      chmod u+rx,g+x,o+x ${permissionsWrapperDir}/${program}
+    '';
+
+  ###### Activation script for the setuid wrappers
+  setuidPrograms =
+    (map (x: { program = x; owner = "root"; group = "root"; setuid = true; })
+      config.security.setuidPrograms)
+    ++ config.security.setuidOwners;
+
+  makeSetuidWrapper =
+    { program
+    , source ? null
+    , owner  ? "nobody"
+    , group  ? "nogroup"
+    , setuid ? false
+    , setgid ? false
+    , permissions ? "u+rx,g+x,o+x"
+    }:
+
+    ''
+      cp ${setuidWrappers}/bin/${program}.wrapper ${permissionsWrapperDir}/${program}
+
+      # Prevent races
+      chmod 0000 ${permissionsWrapperDir}/${program}
+      chown ${owner}.${group} ${permissionsWrapperDir}/${program}
+
+      chmod "u${if setuid then "+" else "-"}s,g${if setgid then "+" else "-"}s,${permissions}" ${permissionsWrapperDir}/${program}
+    '';
+in
+{
+
+  ###### interface
+
+  options = {
+    security.permissionsWrappers.setcap = mkOption {
+      type    = types.listOf types.attrs;
+      default = [];
+      example =
+        [ { program = "ping";
+            source  = "${pkgs.iputils.out}/bin/ping"
+            owner   = "nobody";
+            group   = "nogroup";
+            setcap  = true;
+            capabilities = "cap_net_raw+ep";
+          }
+        ];
+      description = ''
+        This option sets capabilities on a wrapper program that
+        propagates those capabilities down to the wrapped, real
+        program.
+
+        The `program` attribute is the name of the program to be
+        wrapped. If no `source` attribute is provided, specifying the
+        absolute path to the program, then the program will be
+        searched for in the path environment variable.
+
+        NOTE: cap_setpcap, which is required for the wrapper program
+        to be able to raise caps into the Ambient set is NOT raised to
+        the Ambient set so that the real program cannot modify its own
+        capabilities!! This may be too restrictive for cases in which
+        the real program needs cap_setpcap but it at least leans on
+        the side security paranoid vs. too relaxed.
+
+        The attribute `setcap` defaults to false and it will create a
+        wrapper program but never set the capability set on it. This
+        is done so that you can remove a capability sent entirely from
+        a wrapper program without also needing to go change any
+        absolute paths that may be directly referencing the wrapper
+        program.
+      '';
+    };
+
+    security.permissionsWrappers.setuid = mkOption {
+      type = types.listOf types.attrs;
+      default = [];
+      example =
+        [ { program = "sendmail";
+            source = "${pkgs.sendmail.bin}/bin/sendmail";
+            owner = "nobody";
+            group = "postdrop";
+            setuid = false;
+            setgid = true;
+            permissions = "u+rx,g+x,o+x";
+          }
+        ];
+      description = ''
+        This option allows the ownership and permissions on the setuid
+        wrappers for specific programs to be overridden from the
+        default (setuid root, but not setgid root).
+      '';
+    };
+
+    security.permissionsWrapperDir = mkOption {
+      type        = types.path;
+      default     = "/var/permissions-wrappers";
+      internal    = true;
+      description = ''
+        This option defines the path to the permissions wrappers. It
+        should not be overriden.
+      '';
+    };
+
+  };
+
+
+  ###### implementation
+  
+  config = {
+
+    # Make sure our setcap-wrapper dir exports to the PATH env
+    # variable when initializing the shell
+    environment.extraInit = ''
+    # The permissions wrappers override other bin directories.
+    export PATH="${config.security.permissionsWrapperDir}:$PATH"
+    '';
+
+    ###### setcap activation script
+    system.activationScripts.setcap =
+      stringAfter [ "users" ]
+        ''
+          # Look in the system path and in the default profile for
+          # programs to be wrapped.
+          PERMISSIONS_WRAPPER_PATH=${config.system.path}/bin:${config.system.path}/sbin
+
+          # When a program is removed from the security.permissionsWrappers.setcap
+          # list we have to remove all of the previous program wrappers
+          # and re-build them minus the wrapper for the program removed,
+          # hence the rm here in the activation script.
+
+          rm -f ${permissionsWrapperDir}/*
+
+          # Concatenate the generated shell slices to configure
+          # wrappers for each program needing specialized capabilities.
+
+          ${concatMapStrings configureSetcapWrapper cfg.setcap}
+        '';
+
+    ###### setuid activation script
+    system.activationScripts.setuid =
+      stringAfter [ "users" ]
+        ''
+          # Look in the system path and in the default profile for
+          # programs to be wrapped.
+          PERMISSIONS_WRAPPER_PATH=${config.system.path}/bin:${config.system.path}/sbin
+
+          # When a program is removed from the security.permissionsWrappers.setcap
+          # list we have to remove all of the previous program wrappers
+          # and re-build them minus the wrapper for the program removed,
+          # hence the rm here in the activation script.
+
+          rm -f ${permissionsWrapperDir}/*
+
+          # Concatenate the generated shell slices to configure
+          # wrappers for each program needing specialized capabilities.
+
+          ${concatMapStrings configureSetuidWrapper cfg.setuid}
+        '';
+
+  };
+}
diff --git a/nixos/modules/security/permissions-wrappers/permissions-wrapper.c b/nixos/modules/security/permissions-wrappers/permissions-wrapper.c
new file mode 100644
index 000000000000..effdaa930963
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/permissions-wrapper.c
@@ -0,0 +1,224 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <dirent.h>
+#include <assert.h>
+#include <errno.h>
+
+// Make sure assertions are not compiled out, we use them to codify
+// invariants about this program and we want it to fail fast and
+// loudly if they are violated.
+#undef NDEBUG
+
+extern char **environ;
+
+// The SOURCE_PROG and WRAPPER_DIR macros are supplied at compile time
+// for a security reason: So they cannot be changed at runtime.
+static char * sourceProg = SOURCE_PROG;
+static char * wrapperDir = WRAPPER_DIR;
+
+// Make sure we have the WRAPPER_TYPE macro specified at compile
+// time...
+#ifdef WRAPPER_SETCAP
+static char * wrapperType = "setcap";
+#elif defined WRAPPER_SETUID
+static char * wrapperType = "setuid";
+#else
+fprintf(stderr, "Program must be compiled with either the WRAPPER_SETCAP or WRAPPER_SETUID macros specified!\n");
+exit(1);
+#endif
+
+#ifdef WRAPPER_SETCAP
+#include <linux/capability.h>
+#include <sys/capability.h>
+#include <linux/prctl.h>
+#include <sys/prctl.h>
+#include <cap-ng.h>
+
+// Update the capabilities of the running process to include the given
+// capability in the Ambient set.
+static void set_ambient_cap(cap_value_t cap)
+{
+    capng_get_caps_process();
+
+    if (capng_update(CAPNG_ADD, CAPNG_INHERITABLE, (unsigned long) cap))
+    {
+        printf("cannot raise the capability into the Inheritable set\n");
+        exit(1);
+    }
+
+    capng_apply(CAPNG_SELECT_CAPS);
+    
+    if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, (unsigned long) cap, 0, 0))
+    {
+        perror("cannot raise the capability into the Ambient set\n");
+        exit(1);
+    }
+}
+
+// Given the path to this program, fetch its configured capability set
+// (as set by `setcap ... /path/to/file`) and raise those capabilities
+// into the Ambient set.
+static int make_caps_ambient(const char *selfPath)
+{
+    cap_t caps = cap_get_file(selfPath);
+
+    if(!caps)
+    {
+        fprintf(stderr, "could not retreive the capability set for this file\n");
+        return 1;
+    }
+
+    // We use `cap_to_text` and iteration over the tokenized result
+    // string because, as of libcap's current release, there is no
+    // facility for retrieving an array of `cap_value_t`'s that can be
+    // given to `prctl` in order to lift that capability into the
+    // Ambient set.
+    //
+    // Some discussion was had around shot-gunning all of the
+    // capabilities we know about into the Ambient set but that has a
+    // security smell and I deemed the risk of the current
+    // implementation crashing the program to be lower than the risk
+    // of a privilege escalation security hole being introduced by
+    // raising all capabilities, even ones we didn't intend for the
+    // program, into the Ambient set.
+    //
+    // `cap_t` which is returned by `cap_get_*` is an opaque type and
+    // even if we could retrieve the bitmasks (which, as far as I can
+    // tell we cannot) in order to get the `cap_value_t`
+    // representation for each capability we would have to take the
+    // total number of capabilities supported and iterate over the
+    // sequence of integers up-to that maximum total, testing each one
+    // against the bitmask ((bitmask >> n) & 1) to see if it's set and
+    // aggregating each "capability integer n" that is set in the
+    // bitmask.
+    //
+    // That, combined with the fact that we can't easily get the
+    // bitmask anyway seemed much more brittle than fetching the
+    // `cap_t`, transforming it into a textual representation,
+    // tokenizing the string, and using `cap_from_name` on the token
+    // to get the `cap_value_t` that we need for `prctl`. There is
+    // indeed risk involved if the output string format of
+    // `cap_to_text` ever changes but at this time the combination of
+    // factors involving the below list have led me to the conclusion
+    // that the best implementation at this time is reading then
+    // parsing with *lots of documentation* about why we're doing it
+    // this way.
+    //
+    // 1. No explicit API for fetching an array of `cap_value_t`'s or
+    //    for transforming a `cap_t` into such a representation
+    // 2. The risk of a crash is lower than lifting all capabilities
+    //    into the Ambient set
+    // 3. libcap is depended on heavily in the Linux ecosystem so
+    //    there is a high chance that the output representation of
+    //    `cap_to_text` will not change which reduces our risk that
+    //    this parsing step will cause a crash
+    //
+    // The preferred method, should it ever be available in the
+    // future, would be to use libcap API's to transform the result
+    // from a `cap_get_*` into an array of `cap_value_t`'s that can
+    // then be given to prctl.
+    //
+    // - Parnell
+    ssize_t capLen;
+    char* capstr = cap_to_text(caps, &capLen);
+    cap_free(caps);
+    
+    // TODO: For now, we assume that cap_to_text always starts its
+    // result string with " =" and that the first capability is listed
+    // immediately after that. We should verify this.
+    assert(capLen >= 2);
+    capstr += 2;
+
+    char* saveptr = NULL;
+    for(char* tok = strtok_r(capstr, ",", &saveptr); tok; tok = strtok_r(NULL, ",", &saveptr))
+    {
+      cap_value_t capnum;
+      if (cap_from_name(tok, &capnum))
+      {
+          fprintf(stderr, "cap_from_name failed, skipping: %s\n", tok);
+      }
+      else if (capnum == CAP_SETPCAP)
+      {
+        // Check for the cap_setpcap capability, we set this on the
+        // wrapper so it can elevate the capabilities to the Ambient
+        // set but we do not want to propagate it down into the
+        // wrapped program.
+        //
+        // TODO: what happens if that's the behavior you want
+        // though???? I'm preferring a strict vs. loose policy here.
+        fprintf(stderr, "cap_setpcap in set, skipping it\n");
+      }
+      else
+      {
+        set_ambient_cap(capnum);
+        printf("raised %s into the Ambient capability set\n", tok);
+      }
+    }
+    cap_free(capstr);
+
+    return 0;
+}
+#endif
+
+int main(int argc, char * * argv)
+{
+    // I *think* it's safe to assume that a path from a symbolic link
+    // should safely fit within the PATH_MAX system limit. Though I'm
+    // not positive it's safe...
+    char selfPath[PATH_MAX];
+    int selfPathSize = readlink("/proc/self/exe", selfPath, sizeof(selfPath) - 1);
+
+    assert(selfPathSize > 0);
+
+    selfPath[selfPathSize] = '\0';
+
+    // Make sure that we are being executed from the right location,
+    // i.e., `safeWrapperDir'.  This is to prevent someone from creating
+    // hard link `X' from some other location, along with a false
+    // `X.real' file, to allow arbitrary programs from being executed
+    // with elevated capabilities.
+    int len = strlen(wrapperDir);
+    if (len > 0 && '/' == wrapperDir[len - 1])
+      --len;
+    assert(!strncmp(selfPath, wrapperDir, len));
+    assert('/' == wrapperDir[0]);
+    assert('/' == selfPath[len]);
+
+    // Make *really* *really* sure that we were executed as
+    // `selfPath', and not, say, as some other setuid program. That
+    // is, our effective uid/gid should match the uid/gid of
+    // `selfPath'.
+    struct stat st;
+    assert(lstat(selfPath, &st) != -1);
+
+    assert(!(st.st_mode & S_ISUID) || (st.st_uid == geteuid()));
+    assert(!(st.st_mode & S_ISGID) || (st.st_gid == getegid()));
+
+    // And, of course, we shouldn't be writable.
+    assert(!(st.st_mode & (S_IWGRP | S_IWOTH)));
+
+    struct stat stR;
+    stat(sourceProg, &stR);
+
+    // Make sure the program we're wrapping is non-zero
+    assert(stR.st_size > 0);
+
+    // Read the capabilities set on the file and raise them in to the
+    // Ambient set so the program we're wrapping receives the
+    // capabilities too!
+    assert(!make_caps_ambient(selfPath));
+
+    execve(sourceProg, argv, environ);
+    
+    fprintf(stderr, "%s: cannot run `%s': %s\n",
+        argv[0], sourceProg, strerror(errno));
+
+    exit(1);
+}
+
+
diff --git a/nixos/modules/security/permissions-wrappers/setcap-wrapper-drv.nix b/nixos/modules/security/permissions-wrappers/setcap-wrapper-drv.nix
new file mode 100644
index 000000000000..f64c683f6e84
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/setcap-wrapper-drv.nix
@@ -0,0 +1,37 @@
+{ config, lib, pkgs, ... }:
+
+let  
+     cfg = config.security.permissionsWrappers;
+
+     # Produce a shell-code splice intended to be stitched into one of
+     # the build or install phases within the derivation.
+     mkSetcapWrapper = { program, source ? null, ...}:
+       ''
+         if ! source=${if source != null then source else "$(readlink -f $(PATH=$PERMISSIONS_WRAPPER_PATH type -tP ${program}))"}; then
+             # If we can't find the program, fall back to the
+             # system profile.
+             source=/nix/var/nix/profiles/default/bin/${program}
+         fi
+
+         gcc -Wall -O2 -DWRAPPER_SETCAP=1 -DSOURCE_PROG=\"$source\" -DWRAPPER_DIR=\"${cfg.permissionsWrapperDir}\" \
+             -lcap-ng -lcap ${./permissions-wrapper.c} -o $out/bin/${program}.wrapper
+       '';
+in
+
+# This is only useful for Linux platforms and a kernel version of
+# 4.3 or greater
+assert pkgs.stdenv.isLinux;
+assert lib.versionAtLeast (lib.getVersion config.boot.kernelPackages.kernel) "4.3";
+
+pkgs.stdenv.mkDerivation {
+  name         = "setcap-wrapper";
+  unpackPhase  = "true";
+  buildInputs  = [ pkgs.linuxHeaders pkgs.libcap pkgs.libcap_ng ];
+  installPhase = ''
+    mkdir -p $out/bin
+
+    # Concat together all of our shell splices to compile
+    # binary wrapper programs for all configured setcap programs.
+    ${concatMapStrings mkSetcapWrapper cfg.setcap}
+  '';
+};
diff --git a/nixos/modules/security/permissions-wrappers/setcap-wrappers.nix b/nixos/modules/security/permissions-wrappers/setcap-wrappers.nix
new file mode 100644
index 000000000000..ead3cb219f19
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/setcap-wrappers.nix
@@ -0,0 +1,162 @@
+{ config, lib, pkgs, ... }:
+
+with lib; with pkgs;
+
+let
+
+  inherit (config.security) setcapWrapperDir;
+
+  cfg = config.security.setcapCapabilities;
+
+  # Produce a shell-code splice intended to be stitched into one of
+  # the build or install phases within the `setcapWrapper` derivation.
+  mkSetcapWrapper = { program, source ? null, ...}:
+    ''
+      if ! source=${if source != null then source else "$(readlink -f $(PATH=$SETCAP_PATH type -tP ${program}))"}; then
+          # If we can't find the program, fall back to the
+          # system profile.
+          source=/nix/var/nix/profiles/default/bin/${program}
+      fi
+
+      gcc -Wall -O2 -DSOURCE_PROG=\"$source\" -DWRAPPER_DIR=\"${setcapWrapperDir}\" \
+          -lcap-ng -lcap ${./setcap-wrapper.c} -o $out/bin/${program}.wrapper
+    '';
+
+  setcapWrappers = 
+
+    # This is only useful for Linux platforms and a kernel version of
+    # 4.3 or greater
+    assert pkgs.stdenv.isLinux;
+    assert versionAtLeast (getVersion config.boot.kernelPackages.kernel) "4.3";
+
+    pkgs.stdenv.mkDerivation {
+      name         = "setcap-wrapper";
+      unpackPhase  = "true";
+      buildInputs  = [ linuxHeaders libcap libcap_ng ];
+      installPhase = ''
+        mkdir -p $out/bin
+
+        # Concat together all of our shell splices to compile
+        # binary wrapper programs for all configured setcap programs.
+        ${concatMapStrings mkSetcapWrapper cfg}
+      '';
+    };
+in
+{
+  options = {
+    security.setcapCapabilities = mkOption {
+      type    = types.listOf types.attrs;
+      default = [];
+      example =
+        [ { program = "ping";
+            owner   = "nobody";
+            group   = "nogroup";
+            setcap  = true;
+            capabilities = "cap_net_raw+ep";
+          }
+        ];
+      description = ''
+        This option sets capabilities on a wrapper program that
+        propagates those capabilities down to the wrapped, real
+        program.
+
+        The `program` attribute is the name of the program to be
+        wrapped. If no `source` attribute is provided, specifying the
+        absolute path to the program, then the program will be
+        searched for in the path environment variable.
+
+        NOTE: cap_setpcap, which is required for the wrapper program
+        to be able to raise caps into the Ambient set is NOT raised to
+        the Ambient set so that the real program cannot modify its own
+        capabilities!! This may be too restrictive for cases in which
+        the real program needs cap_setpcap but it at least leans on
+        the side security paranoid vs. too relaxed.
+
+        The attribute `setcap` defaults to false and it will create a
+        wrapper program but never set the capability set on it. This
+        is done so that you can remove a capability sent entirely from
+        a wrapper program without also needing to go change any
+        absolute paths that may be directly referencing the wrapper
+        program.
+      '';
+    };
+
+    security.setcapWrapperDir = mkOption {
+      type        = types.path;
+      default     = "/var/setcap-wrappers";
+      internal    = true;
+      description = ''
+        This option defines the path to the setcap wrappers. It
+        should generally not be overriden.
+      '';
+    };
+
+  };
+
+  config = {
+
+    # Make sure our setcap-wrapper dir exports to the PATH env
+    # variable when initializing the shell
+    environment.extraInit = ''
+    # The setcap wrappers override other bin directories.
+    export PATH="${config.security.setcapWrapperDir}:$PATH"
+    '';
+
+    system.activationScripts.setcap =
+      let
+        setcapPrograms = cfg;
+        configureSetcapWrapper =
+          { program
+          , capabilities
+          , source ? null
+          , owner  ? "nobody"
+          , group  ? "nogroup"
+          , setcap ? false
+          }:
+          ''
+            mkdir -p ${setcapWrapperDir}
+
+            cp ${setcapWrappers}/bin/${program}.wrapper ${setcapWrapperDir}/${program}
+
+            # Prevent races
+            chmod 0000 ${setcapWrapperDir}/${program}
+            chown ${owner}.${group} ${setcapWrapperDir}/${program}
+
+            # Set desired capabilities on the file plus cap_setpcap so
+            # the wrapper program can elevate the capabilities set on
+            # its file into the Ambient set.
+            #
+            # Only set the capabilities though if we're being told to
+            # do so.
+            ${
+            if setcap then
+              ''
+              ${libcap.out}/bin/setcap "cap_setpcap,${capabilities}" ${setcapWrapperDir}/${program}
+              ''
+            else ""
+            }
+
+            # Set the executable bit
+            chmod u+rx,g+x,o+x ${setcapWrapperDir}/${program}
+          '';
+
+      in stringAfter [ "users" ]
+        ''
+          # Look in the system path and in the default profile for
+          # programs to be wrapped.
+          SETCAP_PATH=${config.system.path}/bin:${config.system.path}/sbin
+
+          # When a program is removed from the security.setcapCapabilities
+          # list we have to remove all of the previous program wrappers
+          # and re-build them minus the wrapper for the program removed,
+          # hence the rm here in the activation script.
+
+          rm -f ${setcapWrapperDir}/*
+
+          # Concatenate the generated shell slices to configure
+          # wrappers for each program needing specialized capabilities.
+
+          ${concatMapStrings configureSetcapWrapper setcapPrograms}
+        '';
+  };
+}
diff --git a/nixos/modules/security/permissions-wrappers/setuid-wrapper-drv.nix b/nixos/modules/security/permissions-wrappers/setuid-wrapper-drv.nix
new file mode 100644
index 000000000000..15dc1918b5c5
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/setuid-wrapper-drv.nix
@@ -0,0 +1,36 @@
+{ config, lib, pkgs, ... }:
+
+let  
+     cfg = config.security.permissionsWrappers;
+
+     # Produce a shell-code splice intended to be stitched into one of
+     # the build or install phases within the derivation.
+     mkSetuidWrapper = { program, source ? null, ...}:
+       ''
+         if ! source=${if source != null then source else "$(readlink -f $(PATH=$PERMISSIONS_WRAPPER_PATH type -tP ${program}))"}; then
+             # If we can't find the program, fall back to the
+             # system profile.
+             source=/nix/var/nix/profiles/default/bin/${program}
+         fi
+
+         gcc -Wall -O2 -DWRAPPER_SETUID=1 -DSOURCE_PROG=\"$source\" -DWRAPPER_DIR=\"${cfg.permissionsWrapperDir}\" \
+             -lcap-ng -lcap ${./permissions-wrapper.c} -o $out/bin/${program}.wrapper
+       '';
+in
+
+# This is only useful for Linux platforms and a kernel version of
+# 4.3 or greater
+assert pkgs.stdenv.isLinux;
+assert lib.versionAtLeast (lib.getVersion config.boot.kernelPackages.kernel) "4.3";
+
+pkgs.stdenv.mkDerivation {
+  name         = "setuid-wrapper";
+  unpackPhase  = "true";
+  installPhase = ''
+    mkdir -p $out/bin
+
+    # Concat together all of our shell splices to compile
+    # binary wrapper programs for all configured setcap programs.
+    ${concatMapStrings mkSetuidWrapper cfg.setuid}
+  '';
+};
diff --git a/nixos/modules/security/permissions-wrappers/setuid-wrappers.nix b/nixos/modules/security/permissions-wrappers/setuid-wrappers.nix
new file mode 100644
index 000000000000..e1dca477d70a
--- /dev/null
+++ b/nixos/modules/security/permissions-wrappers/setuid-wrappers.nix
@@ -0,0 +1,145 @@
+{ config, lib, pkgs, ... }:
+
+with lib;
+
+let
+
+  inherit (config.security) wrapperDir;
+
+  setuidWrapper = pkgs.stdenv.mkDerivation {
+    name = "setuid-wrapper";
+    unpackPhase = "true";
+    installPhase = ''
+      mkdir -p $out/bin
+      cp ${./setuid-wrapper.c} setuid-wrapper.c
+      gcc -Wall -O2 -DWRAPPER_DIR=\"/run/setuid-wrapper-dirs\" \
+          setuid-wrapper.c -o $out/bin/setuid-wrapper
+    '';
+  };
+
+in
+
+{
+
+  ###### interface
+
+  options = {
+
+    security.setuidPrograms = mkOption {
+      type = types.listOf types.str;
+      default = [];
+      example = ["passwd"];
+      description = ''
+        The Nix store cannot contain setuid/setgid programs directly.
+        For this reason, NixOS can automatically generate wrapper
+        programs that have the necessary privileges.  This option
+        lists the names of programs in the system environment for
+        which setuid root wrappers should be created.
+      '';
+    };
+
+    security.setuidOwners = mkOption {
+      type = types.listOf types.attrs;
+      default = [];
+      example =
+        [ { program = "sendmail";
+            owner = "nobody";
+            group = "postdrop";
+            setuid = false;
+            setgid = true;
+            permissions = "u+rx,g+x,o+x";
+          }
+        ];
+      description = ''
+        This option allows the ownership and permissions on the setuid
+        wrappers for specific programs to be overridden from the
+        default (setuid root, but not setgid root).
+      '';
+    };
+
+    security.wrapperDir = mkOption {
+      internal = true;
+      type = types.path;
+      default = "/var/setuid-wrappers";
+      description = ''
+        This option defines the path to the setuid wrappers.  It
+        should generally not be overriden. Some packages in Nixpkgs
+        expect that <option>wrapperDir</option> is
+        <filename>/var/setuid-wrappers</filename>.
+      '';
+    };
+
+  };
+
+
+  ###### implementation
+
+  config = {
+
+    security.setuidPrograms = [ "fusermount" ];
+
+    system.activationScripts.setuid =
+      let
+        setuidPrograms =
+          (map (x: { program = x; owner = "root"; group = "root"; setuid = true; })
+            config.security.setuidPrograms)
+          ++ config.security.setuidOwners;
+
+        makeSetuidWrapper =
+          { program
+          , source ? ""
+          , owner ? "nobody"
+          , group ? "nogroup"
+          , setuid ? false
+          , setgid ? false
+          , permissions ? "u+rx,g+x,o+x"
+          }:
+
+          ''
+            if ! source=${if source != "" then source else "$(readlink -f $(PATH=$SETUID_PATH type -tP ${program}))"}; then
+                # If we can't find the program, fall back to the
+                # system profile.
+                source=/nix/var/nix/profiles/default/bin/${program}
+            fi
+
+            cp ${setuidWrapper}/bin/setuid-wrapper $wrapperDir/${program}
+            echo -n "$source" > $wrapperDir/${program}.real
+            chmod 0000 $wrapperDir/${program} # to prevent races
+            chown ${owner}.${group} $wrapperDir/${program}
+            chmod "u${if setuid then "+" else "-"}s,g${if setgid then "+" else "-"}s,${permissions}" $wrapperDir/${program}
+          '';
+
+      in stringAfter [ "users" ]
+        ''
+          # Look in the system path and in the default profile for
+          # programs to be wrapped.
+          SETUID_PATH=${config.system.path}/bin:${config.system.path}/sbin
+
+          mkdir -p /run/setuid-wrapper-dirs
+          wrapperDir=$(mktemp --directory --tmpdir=/run/setuid-wrapper-dirs setuid-wrappers.XXXXXXXXXX)
+
+          ${concatMapStrings makeSetuidWrapper setuidPrograms}
+
+          if [ -L ${wrapperDir} ]; then
+            # Atomically replace the symlink
+            # See https://axialcorps.com/2013/07/03/atomically-replacing-files-and-directories/
+            old=$(readlink ${wrapperDir})
+            ln --symbolic --force --no-dereference $wrapperDir ${wrapperDir}-tmp
+            mv --no-target-directory ${wrapperDir}-tmp ${wrapperDir}
+            rm --force --recursive $old
+          elif [ -d ${wrapperDir} ]; then
+            # Compatibility with old state, just remove the folder and symlink
+            rm -f ${wrapperDir}/*
+            # if it happens to be a tmpfs
+            umount ${wrapperDir} || true
+            rm -d ${wrapperDir}
+            ln -d --symbolic $wrapperDir ${wrapperDir}
+          else
+            # For initial setup
+            ln --symbolic $wrapperDir ${wrapperDir}
+          fi
+        '';
+
+  };
+
+}