jail.nix/lib/combinators/jail-to-host-channel.nix
Alex David e45e8a7ccb Only forward valid URLs in open-urls-in-browser
This is unlikely to be exploited since the combinator only allows a
single argument and is not parsed by any shell, but it seems like a good
thing to ensure that only valid non-local URLs will be forwarded to
$BROWSER.
2025-10-10 16:28:45 -07:00

101 lines
3 KiB
Nix

{ combinators, pkgs, ... }:
let
inherit (combinators)
add-cleanup
add-pkg-deps
add-runtime
compose
include-once
noescape
ro-bind
;
in
{
sig = "String -> String -> Combinator";
doc = ''
Allows programs in the jail to execute and pass messages to a
specific handler that runs outside of the jail.
The first parameter specifies a name of a program that is exposed
to the jail that, when called, sends its first argument to the
script passed to the second parameter. The script runs *outside*
of the jail. Any stdout generated by the script is relayed back
as stdout from the program in the jail.
Current limitations:
* Only a single argument is supported. For more arguments you
will need to use an encoding like JSON.
* Only stdout is relayed back to the jail, stderr will be
visible in your terminal but the jail won't be able to read
it.
* The first parameter must be a valid POSIX variable name.
Example:
```nix
jail-to-host-channel "getHostFileSize" ${"''"}
# This runs *outside* of the jail
if [ -f "$1" ]; then
wc -c < "$1"
else
echo "$1 is not a file on the host"
fi
${"''"}
```
This exposes a program inside the jail called `getHostFileSize`
that returns the size of the file passed in without needing to
give the jail read access to any files.
'';
impl =
jailTxName: hostRxHandler:
assert pkgs.lib.isValidPosixName jailTxName;
let
varPrefix = "J2H_CHAN_${pkgs.lib.toUpper jailTxName}";
in
include-once "jail-to-host-channel-${jailTxName}" (compose [
(add-runtime ''
# Set up jail-to-host channel "${jailTxName}"
${varPrefix}_TMP=$(mktemp -d)
mkfifo "''$${varPrefix}_TMP/fifo"
(
while true; do
MSG=$(<"''$${varPrefix}_TMP/fifo")
${
pkgs.lib.getExe (
pkgs.writeShellApplication {
name = "${jailTxName}-host-rx-handler";
text = hostRxHandler;
}
)
} "$MSG" > "''$${varPrefix}_TMP/fifo" || break
done
) &
${varPrefix}_RX_PID=$!
'')
(add-cleanup ''
kill "''$${varPrefix}_RX_PID"
rm -rf "''$${varPrefix}_TMP"
'')
(ro-bind (noescape "\"\$${varPrefix}_TMP/fifo\"") "/run/j2hc-${jailTxName}")
(add-pkg-deps [
(pkgs.writeShellApplication {
name = jailTxName;
runtimeInputs = [ pkgs.util-linux ];
text = ''
flock /run/j2hc.lock ${
pkgs.lib.getExe (
pkgs.writeShellApplication {
name = "${jailTxName}-locked";
text = ''
echo "$1" > /run/j2hc-${jailTxName}
echo "$(< /run/j2hc-${jailTxName})"
'';
}
)
} "''${1-}"
'';
})
])
]);
}