Allow overriding jail base permissions

This commit is contained in:
Alex David 2025-08-07 15:29:16 -07:00
commit f18f1cf701
8 changed files with 154 additions and 74 deletions

26
base-permissions.nix Normal file
View file

@ -0,0 +1,26 @@
pkgs: let helpers = import ./helpers.nix pkgs; in combinators: with combinators; [
(unsafe-add-raw-args "--proc /proc")
(unsafe-add-raw-args "--dev /dev")
(unsafe-add-raw-args "--tmpfs /tmp")
(unsafe-add-raw-args "--tmpfs ~")
(unsafe-add-raw-args "--clearenv")
(unsafe-add-raw-args "--die-with-parent")
(readonly "/nix/store")
(readonly "/bin/sh")
(fwd-env "LANG")
(fwd-env "HOME")
(fwd-env "TERM")
(add-runtime ''
if [ ! -e ${helpers.dataDirSubPath "passwd"} ] || [ ! -e ${helpers.dataDirSubPath "group"} ]; then
NOLOGIN=${pkgs.shadow}/bin/nologin
mkdir -p ${helpers.dataDir}
echo "root:x:0:0:System administrator:/root:$NOLOGIN" > ${helpers.dataDirSubPath "passwd"}
echo "$(id -un):x:$(id -u):$(id -g)::$HOME:$NOLOGIN" >> ${helpers.dataDirSubPath "passwd"}
echo "root:x:0:" > ${helpers.dataDirSubPath "group"}
echo "$(id -gn):x:$(id -g):" >> ${helpers.dataDirSubPath "group"}
fi
'')
(ro-bind (noescape (helpers.dataDirSubPath "passwd")) "/etc/passwd")
(ro-bind (noescape (helpers.dataDirSubPath "group")) "/etc/group")
]

View file

@ -1,4 +1,7 @@
{ pkgs, lib, helpers }: rec { pkgs: let
inherit (pkgs) lib;
helpers = import ./helpers.nix pkgs;
in rec {
noescape = { noescape = {
sig = "String -> NoEscapedString"; sig = "String -> NoEscapedString";
doc = '' doc = ''
@ -25,9 +28,7 @@
(readonly (noescape "\"$FOO\"")) (readonly (noescape "\"$FOO\""))
``` ```
''; '';
__functor = _: __functor = _: helpers.noescape;
value: { _noescape = value; }
;
}; };
escape = { escape = {
@ -52,12 +53,7 @@
} }
``` ```
''; '';
__functor = _: __functor = _: helpers.escape;
rawOrStr:
if builtins.typeOf rawOrStr == "set" && rawOrStr ? _noescape
then rawOrStr._noescape
else lib.strings.escapeShellArg rawOrStr
;
}; };
compose = { compose = {

12
helpers.nix Normal file
View file

@ -0,0 +1,12 @@
pkgs: rec {
dataDir = "~/.local/share/jail.nix";
dataDirSubPath = subPath: "${dataDir}/${escape subPath}";
noescape = value: { _noescape = value; };
escape = rawOrStr:
if builtins.typeOf rawOrStr == "set" && rawOrStr ? _noescape
then rawOrStr._noescape
else pkgs.lib.strings.escapeShellArg rawOrStr;
}

62
lib.nix
View file

@ -1,21 +1,24 @@
{ pkgs { pkgs
, additionalCombinators ? _: {} , additionalCombinators ? _: {}
, basePermissions ? import ./base-permissions.nix pkgs
}: let }: let
inherit (pkgs) lib; inherit (pkgs) lib;
helpers = rec { builtinCombinators = import ./combinators.nix pkgs;
dataDir = "~/.local/share/jail.nix";
dataDirSubPath = subPath: "${dataDir}/${builtinCombinators.escape subPath}";
};
builtinCombinators = import ./combinators.nix { inherit pkgs lib helpers; };
allCombinators = builtinCombinators // additionalCombinators builtinCombinators; allCombinators = builtinCombinators // additionalCombinators builtinCombinators;
normalizePermissionsToList = combinators:
let t = builtins.typeOf combinators; in
if t == "lambda" then combinators allCombinators else
if t == "list" then combinators else
if t == "null" then []
else throw "Unknown combinator type ${t}. Must be a function, list, or null";
in { in {
combinators = allCombinators; combinators = allCombinators;
__functor = _: name: exe: combinatorsToApply: let __functor = _: name: exe: permissions: let
initialState = { initialState = {
name = name; name = name;
cmd = "${lib.getExe pkgs.bubblewrap}"; cmd = "${lib.getExe pkgs.bubblewrap}";
@ -30,47 +33,14 @@ in {
included-once = []; # See include-once combinator included-once = []; # See include-once combinator
cleanup = []; # See cleanup combinator cleanup = []; # See cleanup combinator
}; };
userCombinators =
let t = builtins.typeOf combinatorsToApply; in
if t == "lambda" then combinatorsToApply allCombinators else
if t == "list" then combinatorsToApply else
if t == "null" then []
else throw "Unknown combinator type ${t}. Must be a function, list, or null";
in lib.pipe initialState ( in lib.pipe initialState (
# apply pre-user combinators # Permissions shared by all invocations of jail
(with builtinCombinators; [ (normalizePermissionsToList basePermissions)
(unsafe-add-raw-args "--proc /proc")
(unsafe-add-raw-args "--dev /dev")
(unsafe-add-raw-args "--tmpfs /tmp")
(unsafe-add-raw-args "--tmpfs ~")
(unsafe-add-raw-args "--clearenv")
(unsafe-add-raw-args "--die-with-parent")
(readonly "/nix/store")
(readonly "/bin/sh")
(fwd-env "LANG")
(fwd-env "HOME")
(fwd-env "TERM")
(add-runtime '' # Permissions for this specific jail
if [ ! -e ${helpers.dataDirSubPath "passwd"} ] || [ ! -e ${helpers.dataDirSubPath "group"} ]; then ++ (normalizePermissionsToList permissions)
NOLOGIN=${pkgs.shadow}/bin/nologin
mkdir -p ${helpers.dataDir}
echo "root:x:0:0:System administrator:/root:$NOLOGIN" > ${helpers.dataDirSubPath "passwd"}
echo "$(id -un):x:$(id -u):$(id -g)::$HOME:$NOLOGIN" >> ${helpers.dataDirSubPath "passwd"}
echo "root:x:0:" > ${helpers.dataDirSubPath "group"}
echo "$(id -gn):x:$(id -g):" >> ${helpers.dataDirSubPath "group"}
fi
'')
(ro-bind (noescape (helpers.dataDirSubPath "passwd")) "/etc/passwd")
(ro-bind (noescape (helpers.dataDirSubPath "group")) "/etc/group")
])
# apply user combinators # Finalize everything remaining in state into bwrap args
++ userCombinators
# apply post-user combinators
++ (with builtinCombinators; [ ++ (with builtinCombinators; [
(s: (s:
# See `--unshare-*` in BWRAP(1) # See `--unshare-*` in BWRAP(1)
@ -89,7 +59,7 @@ in {
) s (builtins.attrNames s.env)) ) s (builtins.attrNames s.env))
]) ])
# build jailed app from state # Build jailed app from state
++ [ ++ [
(state: '' (state: ''
RUNTIME_ARGS=() RUNTIME_ARGS=()

View file

@ -5,7 +5,7 @@
outputs = { nixpkgs, ... }: let outputs = { nixpkgs, ... }: let
pkgs = import nixpkgs { system = "x86_64-linux"; }; pkgs = import nixpkgs { system = "x86_64-linux"; };
lib = pkgs.lib; lib = pkgs.lib;
jail = import ../lib.nix { inherit pkgs; }; jail-nix.lib.extend = import ../lib.nix;
ansi = clrCode: "[${toString clrCode}m"; ansi = clrCode: "[${toString clrCode}m";
green = ansi 32; green = ansi 32;
@ -36,7 +36,7 @@
if lib.isDerivation testBody then lib.getExe testBody else if lib.isDerivation testBody then lib.getExe testBody else
throw "Unknown test body type ${type}"; throw "Unknown test body type ${type}";
testCases = import ./test-cases.nix { inherit pkgs lib test jail; }; testCases = import ./test-cases.nix { inherit pkgs lib test jail-nix; };
in { in {
apps.x86_64-linux.runChecks = { apps.x86_64-linux.runChecks = {
type = "app"; type = "app";

View file

@ -1,11 +1,25 @@
{ pkgs, lib, test, jail }: with test; let { pkgs, lib, test, jail-nix }: with test; let
sh = script: (pkgs.writeShellApplication { name = "test-script"; text = script; }); sh = script: (pkgs.writeShellApplication { name = "test-script"; text = script; });
defaultPath = "${pkgs.coreutils}/bin"; defaultPath = "${pkgs.coreutils}/bin";
jail = jail-nix.lib.extend { inherit pkgs; };
in { in {
"simple jail works" = assertStdout "simple jail works" = assertStdout
(jail "hello" pkgs.hello []) (jail "hello" pkgs.hello [])
"Hello, world!"; "Hello, world!";
"it allows overriding base permissions shared across all jails" = let
jail' = jail-nix.lib.extend {
inherit pkgs;
basePermissions = c: [
(c.readonly "/build/secret")
(c.readonly "/nix/store")
];
};
in [
"echo hunter2 > /build/secret"
(assertStdout (jail' "hello" (sh "cat /build/secret") []) "hunter2")
];
"it sets a sane default path" = assertStdout "it sets a sane default path" = assertStdout
(jail "test" (sh ''echo "$PATH"'') []) (jail "test" (sh ''echo "$PATH"'') [])
defaultPath; defaultPath;

View file

@ -0,0 +1,64 @@
# Advanced Configuration
All configuration options on this page can be passed into `jail-nix.lib.extend`.
## additionalCombinators
`additionalCombinators` takes in a list of custom combinators to expose under
`jail.combinators` and in jail definitions. If passed a funciton, jail.nix will
inject the builtin combinators.
For example, this creates a `jail` function that exposes a `my-combinator`
combinator:
```nix
jail = jail-nix.lib.extend {
inherit pkgs;
additionalCombinators = builtinCombinators: with builtinCombinators; [
my-combinator = compose [
(readonly "/foo")
(readonly "/bar")
];
];
};
# Now my-combinator is exposed in all the places the builtin combinators are exposed:
jailed-hello = jail "jailed-hello" pkgs.hello (c: with c; [
my-combinator
]);
# Alternatively, using jail.combinators:
jailed-hello = jail "jailed-hello" pkgs.hello [
jail.combinators.my-combinator
];
```
## basePermissions
By default, jail.nix comes with a base set of permissions that all jails
inherit by default. This configuration option allows you to override these.
The goal of the base permissions are to provide a reasonably secure default
with enough permissions to have most software behave correctly.
Example:
```nix
jail = jail-nix.lib.extend {
inherit pkgs;
basePermissions = builtinCombinators: with builtinCombinators; [
(unsafe-add-raw-args "--proc /proc")
(unsafe-add-raw-args "--dev /dev")
(unsafe-add-raw-args "--tmpfs /tmp")
(unsafe-add-raw-args "--tmpfs ~")
(unsafe-add-raw-args "--clearenv")
(unsafe-add-raw-args "--die-with-parent")
(readonly "/nix/store")
(readonly "/bin/sh")
(fwd-env "LANG")
(fwd-env "HOME")
(fwd-env "TERM")
];
};
```

View file

@ -16,6 +16,8 @@ configuration:
} }
``` ```
---
## Initializing ## Initializing
The core functionality of jail.nix is a `jail` function that wraps derivations The core functionality of jail.nix is a `jail` function that wraps derivations
@ -37,29 +39,23 @@ jail = jail-nix.lib.init pkgs;
You can set more options in the initialization with `jail-nix.lib.extend`. You can set more options in the initialization with `jail-nix.lib.extend`.
You must pass in an instantiated nixpkgs attribute `pkgs`. This takes in a single attribute set as an argument. The only required key is
`pkgs` which must be an instantiated nixpkgs.
For example, the below snippet creates a `jail` function where `my-combinator`
is passed to jail definitions.
Example:
```nix ```nix
pkgs = import nixpkgs { system = "x86_64-linux"; }; pkgs = import nixpkgs { system = "x86_64-linux"; };
jail = jail-nix.lib.extend { jail = jail-nix.lib.extend {
inherit pkgs; inherit pkgs;
additionalCombinators = baseCombinators: with baseCombinators; [
my-combinator = compose [
(readonly "/foo")
(readonly "/bar")
];
];
};
jailed-hello = jail "jailed-hello" pkgs.hello (c: with c; [ # Other configuration options here...
my-combinator };
]);
``` ```
For a full list of options see [Advanced Configuration](advanced-configuration).
---
## Usage ## Usage
Once you have an [initialized](#initializing) `jail` function, it takes the Once you have an [initialized](#initializing) `jail` function, it takes the
@ -77,6 +73,8 @@ following positional arguments:
a function, jail.combinators will be passed in, and the return value will be a function, jail.combinators will be passed in, and the return value will be
used. used.
---
## Examples ## Examples
### Provide jail.nix as a module arg in a Nixos configuration: ### Provide jail.nix as a module arg in a Nixos configuration: