use per-derivation sandbox profiles

This commit is contained in:
Jude Taylor 2015-11-12 18:59:17 -08:00
parent 914e9baefe
commit df80090d09
21 changed files with 209 additions and 50 deletions

View File

@ -17,7 +17,9 @@ let
sexp = tokens: "(" + builtins.concatStringsSep " " tokens + ")";
generateFileList = files:
if builtins.isList files
then concatMapStringsSep " " (x: sexp [ "literal" x ]) files
then concatMapStringsSep " " (x: sexp [ "literal" ''"${x}"'' ]) files
else if builtins.isString files
then generateFileList [ files ]
else concatStringsSep " " (
(map (x: sexp [ "literal" ''"${x}"'' ]) (files.literal or [])) ++
(map (x: sexp [ "subpath" ''"${x}"'' ]) (files.subpath or []))
@ -30,11 +32,23 @@ genActions = actionName: let
"${actionName}File" = applyToFiles action "file*";
"${actionName}FileRead" = applyToFiles action "file-read*";
"${actionName}FileReadMetadata" = applyToFiles action "file-read-metadata";
"${actionName}DirectoryList" = self."${actionName}FileReadMetadata";
"${actionName}FileWrite" = applyToFiles action "file-write*";
"${actionName}FileWriteMetadata" = applyToFiles action "file-write-metadata";
"${actionName}Network" = sexp [ actionName "network*" ];
"${actionName}NetworkBind" = sexp [ actionName "network-bind" ];
"${actionName}NetworkInbound" = sexp [ actionName "network-inbound" ];
"${actionName}NetworkOutbound" = sexp [ actionName "network-outbound" ];
"${actionName}NetworkLocal" = sexp [ actionName "network*" (sexp [ "local" "ip" ]) ];
"${actionName}NetworkInboundLocal" = sexp [ actionName "network-inbound" (sexp [ "local" "ip" ]) ];
"${actionName}NetworkOutboundLocal" = sexp [ actionName "network-outbound" (sexp [ "local" "ip" ]) ];
};
in self;
in
genActions "allow" // genActions "deny"
genActions "allow" // genActions "deny" // {
importProfile = derivation: ''
(import "${derivation}")
'';
}

View File

@ -1,7 +1,7 @@
{ stdenv, fetchurl, ncurses, xlibsWrapper, libXaw, libXpm, Xaw3d
, pkgconfig, gettext, libXft, dbus, libpng, libjpeg, libungif
, libtiff, librsvg, texinfo, gconf, libxml2, imagemagick, gnutls
, alsaLib, cairo, acl, gpm, AppKit
, alsaLib, cairo, acl, gpm, AppKit, CoreWLAN, Kerberos, GSS, ImageIO
, withX ? !stdenv.isDarwin
, withGTK3 ? false, gtk3 ? null
, withGTK2 ? true, gtk2
@ -49,7 +49,7 @@ stdenv.mkDerivation rec {
++ stdenv.lib.optional (withX && withGTK3) gtk3
++ stdenv.lib.optional (stdenv.isDarwin && withX) cairo;
propagatedBuildInputs = stdenv.lib.optional stdenv.isDarwin AppKit;
propagatedBuildInputs = stdenv.lib.optionals stdenv.isDarwin [ AppKit GSS ImageIO ];
configureFlags =
if stdenv.isDarwin

View File

@ -43,6 +43,8 @@ stdenv.mkDerivation rec {
];
};
__sandboxProfile = stdenv.lib.sandbox.allowFileRead "/dev/ptmx";
# To fix the trouble in vim73, that it cannot cross-build with this patch
# to bypass a configure script check that cannot be done cross-building.
# http://groups.google.com/group/vim_dev/browse_thread/thread/66c02efd1523554b?pli=1

View File

@ -36,6 +36,9 @@ stdenv.mkDerivation {
# required to support pthread_cancel()
NIX_LDFLAGS = stdenv.lib.optionalString (!stdenv.isDarwin) "-lgcc_s";
# without this, git fails when trying to check for /etc/gitconfig existence
__propagatedSandboxProfile = stdenv.lib.sandbox.allowDirectoryList "/etc";
makeFlags = "prefix=\${out} sysconfdir=/etc/ PERL_PATH=${perl}/bin/perl SHELL_PATH=${stdenv.shell} "
+ (if pythonSupport then "PYTHON_PATH=${python}/bin/python" else "NO_PYTHON=1")
+ (if stdenv.isSunOS then " INSTALL=install NO_INET_NTOP= NO_INET_PTON=" else "")

View File

@ -118,9 +118,7 @@ if (!hasHash) then throw "Specify hash for fetchurl fixed-output derivation: ${s
outputHashMode = if recursiveHash then "recursive" else "flat";
__sandboxProfile = ''
(allow network-outbound)
'';
__sandboxProfile = stdenv.lib.sandbox.allowNetworkOutbound;
inherit curlOpts showURLs mirrorsFile impureEnvVars postFetch downloadToTemp;

View File

@ -924,4 +924,8 @@ self: super: {
librarySystemDepends = (drv.librarySystemDepends or []) ++ [ pkgs.ncurses ];
});
streaming-commons = pkgs.stdenv.lib.overrideDerivation super.streaming-commons (drv: {
__sandboxProfile = drv.__sandboxProfile +
pkgs.stdenv.lib.sandbox.allowNetworkLocal;
});
}

View File

@ -97,7 +97,9 @@ let
] ++ optionals x11Support [ tcl tk xlibsWrapper libX11 ]
)
++ optional zlibSupport zlib
++ optionals stdenv.isDarwin [ CF configd ];
++ optional stdenv.isDarwin CF;
propagatedBuildInputs = optional stdenv.isDarwin configd;
# Build the basic Python interpreter without modules that have
# external dependencies.
@ -105,8 +107,8 @@ let
name = "python-${version}";
pythonVersion = majorVersion;
inherit majorVersion version src patches buildInputs preConfigure
configureFlags;
inherit majorVersion version src patches buildInputs propagatedBuildInputs
preConfigure configureFlags;
LDFLAGS = stdenv.lib.optionalString (!stdenv.isDarwin) "-lgcc_s";
C_INCLUDE_PATH = concatStringsSep ":" (map (p: "${p}/include") buildInputs);

View File

@ -1,6 +1,7 @@
{ stdenv, fetchurl, xar, gzip, cpio, pkgs }:
let
generateFrameworkProfile = pkgs.callPackage ./generate-framework-profile.nix {};
# sadly needs to be exported because security_tool needs it
sdk = stdenv.mkDerivation rec {
version = "10.9";
@ -95,8 +96,12 @@ let
propagatedBuildInputs = deps;
# Not going to bother being more precise than this...
__propagatedImpureHostDeps = (import ./impure-deps.nix).${name};
# allows building the symlink tree
__sandboxProfile = ''
(allow file-read* (subpath "/System/Library/Frameworks/${name}.framework"))
'';
__propagatedSandboxProfile = stdenv.lib.sandbox.importProfile (generateFrameworkProfile name);
meta = with stdenv.lib; {
description = "Apple SDK framework ${name}";
@ -159,6 +164,12 @@ in rec {
'';
});
CoreServices = stdenv.lib.overrideDerivation super.CoreServices (drv: {
__propagatedSandboxProfile = drv.__propagatedSandboxProfile ++ [''
(allow mach-lookup (global-name "com.apple.CoreServices.coreservicesd"))
''];
});
Security = stdenv.lib.overrideDerivation super.Security (drv: {
setupHook = ./security-setup-hook.sh;
});
@ -171,5 +182,5 @@ in rec {
frameworks = bareFrameworks // overrides bareFrameworks;
inherit sdk;
inherit sdk generateFrameworkProfile;
}

View File

@ -0,0 +1,64 @@
{ runCommand }:
# In a normal programming language, one might store a hashmap
# { library name -> runtime dependencies }.
# associative arrays were only recently added to bash, and even then, bash arrays cannot
# be multidimensional. instead, the filesystem is the hash table!
# once every dependency in the tree has been visited, a comprehensive list of libraries
# will exist inside ./build. then `find ./build -type f` will give you the
# dependency tree you need!
frameworkName:
let path = "/System/Library/Frameworks/${frameworkName}.framework";
in runCommand "${frameworkName}-profile.sb" {
# __noChroot lite
__sandboxProfile = ''
(allow file* (subpath "/"))
'';
# inconsistencies may exist between self and hydra
allowSubstitutes = false;
} ''
if [ ! -f "${path}/${frameworkName}" ]; then
touch $out
exit
fi
base=./build
find_deps () {
if [ -f "$base/$1" ]; then
return
fi
dependencies=$(otool -l -arch x86_64 $1 \
| grep 'LC_\w*_DYLIB' -A 2 \
| grep name \
| sed 's/^ *//' \
| cut -d' ' -f2)
mkdir -p $base/"$(dirname "$1")"
touch $base/"$1"
for dep in $dependencies; do
find_deps "$dep"
done
}
find_deps "${path}/${frameworkName}" "$out"
set -o noglob
profile="(allow file-read*"
for file in $(find $base -type f); do
filename=''${file/$base/}
case $filename in
/usr/lib/system*) ;;
/usr/lib/libSystem.dylib) ;;
/usr/lib/libSystem.B.dylib) ;;
/usr/lib/libobjc.A.dylib) ;;
/usr/lib/libobjc.dylib) ;;
/usr/lib/libauto.dylib) ;;
/usr/lib/libc++abi.dylib) ;;
/usr/lib/libDiagnosticMessagesClient.dylib) ;;
*) profile+=" (literal \"$filename\")" ;;
esac
done
profile+=" (literal \"${path}/${frameworkName}\")"
profile+=" (literal \"${path}/Versions/Current\")"
echo "$profile)" > $out
''

View File

@ -1,4 +1,4 @@
{ stdenv, appleDerivation, icu, dyld, libdispatch, launchd, libclosure }:
{ stdenv, appleDerivation, icu, dyld, libdispatch, launchd, libclosure, generateFrameworkProfile }:
# this project uses blocks, a clang-only extension
assert stdenv.cc.isClang;
@ -8,13 +8,7 @@ appleDerivation {
patches = [ ./add-cf-initialize.patch ./add-cfmachport.patch ./cf-bridging.patch ];
__propagatedImpureHostDeps = [
"/System/Library/Frameworks/CoreFoundation.framework"
"/usr/lib/libc++.1.dylib"
"/usr/lib/libc++abi.dylib"
"/usr/lib/libicucore.A.dylib"
"/usr/lib/libz.1.dylib"
];
__propagatedSandboxProfile = stdenv.lib.sandbox.importProfile (generateFrameworkProfile "CoreFoundation");
preBuild = ''
substituteInPlace Makefile \
@ -52,5 +46,7 @@ appleDerivation {
postInstall = ''
mv $out/System/* $out
rmdir $out/System
mv $out/Library/Frameworks/CoreFoundation.framework/Versions/A/PrivateHeaders/* \
$out/Library/Frameworks/CoreFoundation.framework/Versions/A/Headers
'';
}

View File

@ -1,13 +1,22 @@
{ stdenv, appleDerivation, fetchzip, version, bsdmake, perl, flex, yacc, writeScriptBin
}:
# this derivation sucks
# locale data was removed after adv_cmds-118, so our base is that because it's easier than
# replicating the bizarre bsdmake file structure
#
# sadly adv_cmds-118 builds a mklocale and colldef that generate files that our libc can no
# longer understand
#
# the more recent adv_cmds release is used for everything else in this package
let recentAdvCmds = fetchzip {
url = "http://opensource.apple.com/tarballs/adv_cmds/adv_cmds-158.tar.gz";
sha256 = "0z081kcprzg5jcvqivfnwvvv6wfxzkjg2jc2lagsf8c7j7vgm8nn";
};
in appleDerivation {
buildInputs = [ bsdmake perl yacc flex (writeScriptBin "lex" "exec ${flex}/bin/flex $@") ];
buildInputs = [ bsdmake perl yacc flex ];
patchPhase = ''
substituteInPlace BSDMakefile \
@ -19,8 +28,6 @@ in appleDerivation {
substituteInPlace Makefile --replace perl true
substituteInPlace colldef.tproj/BSDmakefile --replace "-ll" "-lfl"
for subproject in colldef mklocale monetdef msgdef numericdef timedef; do
substituteInPlace usr-share-locale.tproj/$subproject/BSDmakefile \
--replace /usr/share/locale "" \
@ -29,9 +36,28 @@ in appleDerivation {
done
'';
preBuild = ''
cp -r --no-preserve=all ${recentAdvCmds}/colldef .
pushd colldef
mv locale/collate.h .
flex -t -8 -i scan.l > scan.c
yacc -d parse.y
clang *.c -o colldef -lfl
popd
mv colldef/colldef colldef.tproj/colldef
cp -r --no-preserve=all ${recentAdvCmds}/mklocale .
pushd mklocale
flex -t -8 -i lex.l > lex.c
yacc -d yacc.y
clang *.c -o mklocale -lfl
popd
mv mklocale/mklocale mklocale.tproj/mklocale
'';
buildPhase = ''
bsdmake -C colldef.tproj
bsdmake -C mklocale.tproj
runHook preBuild
bsdmake -C usr-share-locale.tproj
clang ${recentAdvCmds}/ps/*.c -o ps
@ -39,6 +65,12 @@ in appleDerivation {
installPhase = ''
bsdmake -C usr-share-locale.tproj install DESTDIR="$locale/share/locale"
# need to get rid of runtime dependency on flex
# install -d 0755 $locale/bin
# install -m 0755 colldef.tproj/colldef $locale/bin
# install -m 0755 mklocale.tproj/mklocale $locale/bin
install -d 0755 $ps/bin
install ps $ps/bin/ps
'';

View File

@ -7,6 +7,10 @@ appleDerivation {
propagatedBuildInputs = [ Security ];
__propagatedSandboxProfile = ''
(allow mach-lookup (global-name "com.apple.SystemConfiguration.configd"))
'';
patchPhase = ''
substituteInPlace SystemConfiguration.fproj/SCNetworkReachabilityInternal.h \
--replace '#include <xpc/xpc.h>' ""

View File

@ -56,7 +56,9 @@ let
bootstrap_cmds = applePackage "bootstrap_cmds" "86" "0xr0296jm1r3q7kbam98h85g23qlfi763z54ahj563n636kyk2wb" {};
bsdmake = applePackage "bsdmake" "24" "11a9kkhz5bfgi1i8kpdkis78lhc6b5vxmhd598fcdgra1jw4iac2" {};
CarbonHeaders = applePackage "CarbonHeaders" "9A581" "1hc0yijlpwq39x5bic6nnywqp2m1wj1f11j33m2q7p505h1h740c" {};
CF = applePackage "CF" "855.17" "1sadmxi9fsvsmdyxvg2133sdzvkzwil5fvyyidxsyk1iyfzqsvln" {};
CF = applePackage "CF" "855.17" "1sadmxi9fsvsmdyxvg2133sdzvkzwil5fvyyidxsyk1iyfzqsvln" {
inherit (pkgs.darwin.apple_sdk) generateFrameworkProfile;
};
CommonCrypto = applePackage "CommonCrypto" "60049" "1azin6w7cnzl0iv8kd2qzgwcp6a45zy64y5z1i6jysjcl6xmlw2h" {};
configd = applePackage "configd" "453.19" "1gxakahk8gallf16xmhxhprdxkh3prrmzxnmxfvj0slr0939mmr2" {};
copyfile = applePackage "copyfile" "103.92.1" "15i2hw5aqx0fklvmq6avin5s00adacvzqc740vviwc2y742vrdcd" {};

View File

@ -30,6 +30,9 @@ name: version: sha256: args: let
'';
buildInputs = [
pkgs.gnustep-make
pkgs.darwin.apple_sdk.frameworks.AppKit
pkgs.darwin.apple_sdk.frameworks.Foundation
pkgs.darwin.cf-private
];
makeFlags = [
"-f${makeFile}"

View File

@ -14,6 +14,9 @@ appleDerivation {
substituteInPlace lib/debugging.cpp --replace PATH_MAX 1024
substituteInPlace lib/superblob.h --replace 'result->at' 'result->template at'
substituteInPlace lib/ccaudit.cpp --replace '<bsm/libbsm.h>' '"bsm/libbsm.h"'
substituteInPlace lib/powerwatch.h --replace \
'<IOKit/pwr_mgt/IOPMLibPrivate.h>' \
'"${osx_private_sdk}/PrivateSDK10.9.sparse.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/PrivateHeaders/pwr_mgt/IOPMLibPrivate.h"'
cp ${osx_private_sdk}/PrivateSDK10.9.sparse.sdk/usr/include/security_utilities/utilities_dtrace.h lib
cp -R ${osx_private_sdk}/PrivateSDK10.9.sparse.sdk/usr/local/include/bsm lib

View File

@ -156,11 +156,10 @@ let
"__impureHostDeps" "__propagatedImpureHostDeps"
"__sandboxProfile" "__propagatedSandboxProfile"])
// (let
# TODO: remove lib.unique once nix has a list canonicalization primitive
computedSandboxProfile =
lib.concatStrings (lib.unique (builtins.map (input: input.__propagatedSandboxProfile or "") (extraBuildInputs ++ buildInputs ++ nativeBuildInputs)));
lib.concatMap (input: input.__propagatedSandboxProfile or []) (extraBuildInputs ++ buildInputs ++ nativeBuildInputs);
computedPropagatedSandboxProfile =
lib.concatStrings (lib.unique (builtins.map (input: input.__propagatedSandboxProfile or "") (propagatedBuildInputs ++ propagatedNativeBuildInputs)));
lib.concatMap (input: input.__propagatedSandboxProfile or []) (propagatedBuildInputs ++ propagatedNativeBuildInputs);
in
{
builder = attrs.realBuilder or shell;
@ -178,8 +177,12 @@ let
propagatedNativeBuildInputs = propagatedNativeBuildInputs ++
(if crossConfig == null then propagatedBuildInputs else []);
} // ifDarwin {
__sandboxProfile = computedSandboxProfile + computedPropagatedSandboxProfile + __propagatedSandboxProfile + __sandboxProfile + __extraSandboxProfile;
__propagatedSandboxProfile = computedPropagatedSandboxProfile + __propagatedSandboxProfile;
# TODO: remove lib.unique once nix has a list canonicalization primitive
__sandboxProfile =
let profiles = [ __extraSandboxProfile ] ++ computedSandboxProfile ++ computedPropagatedSandboxProfile ++ [ __propagatedSandboxProfile __sandboxProfile ];
final = lib.concatStringsSep "\n" (lib.filter (x: x != "") (lib.unique profiles));
in final;
__propagatedSandboxProfile = lib.unique (computedPropagatedSandboxProfile ++ [ __propagatedSandboxProfile ]);
} // (if outputs' != [ "out" ] then {
outputs = outputs';
} else { })))) (

View File

@ -5,7 +5,9 @@
}:
let
libSystemProfile = builtins.readFile ./standard-sandbox.sb;
libSystemProfile = ''
(import "${./standard-sandbox.sb}")
'';
fetch = { file, sha256, executable ? true }: import <nix/fetchurl.nix> {
url = "http://tarballs.nixos.org/stdenv-darwin/x86_64/4f07c88d467216d9692fefc951deb5cd3c4cc722/${file}";
@ -253,7 +255,7 @@ in rec {
};
darwin = orig.darwin // {
inherit (darwin) dyld Libsystem cctools CF libiconv;
inherit (darwin) dyld Libsystem cctools libiconv;
};
};
@ -263,7 +265,9 @@ in rec {
name = "stdenv-darwin";
preHook = commonPreHook;
preHook = commonPreHook + ''
export PATH_LOCALE=${pkgs.darwin.locale}/share/locale
'';
__stdenvSandboxProfile = binShClosure + libSystemProfile;
__extraSandboxProfile = binShClosure + libSystemProfile;
@ -294,7 +298,7 @@ in rec {
coreutils ed diffutils gnutar gzip ncurses gnused bash gawk
gnugrep llvmPackages.clang-unwrapped patch pcre binutils-raw binutils gettext
]) ++ (with pkgs.darwin; [
dyld Libsystem CF cctools libiconv
dyld Libsystem CF cctools libiconv locale
]);
overrides = orig: persistent4 orig // {

View File

@ -7,7 +7,7 @@
(allow sysctl-read)
; IPC
(allow ipc-posix-sem)
(allow ipc-posix*)
; Unix sockets
(allow system-socket)
@ -33,6 +33,9 @@
; used for bootstrap builders
(allow process-exec* (literal "/bin/sh"))
; without this line clang cannot write to /dev/null, breaking some configure tests
(allow file-read-metadata (literal "/dev"))
; standard devices
(allow file*
(literal "/dev/null")
@ -51,15 +54,21 @@
; both are in libicucore and zoneinfo is in libsystem_c as well
(allow file-read* (subpath "/usr/share/icu") (subpath "/usr/share/zoneinfo"))
; no idea what this is
(allow file-read-data (literal "/dev/autofs_nowait"))
; lots of autoconf projects want to list this directory
(allow file-read-metadata (literal "/var") (literal "/private/var/tmp"))
; mute annoying failures
(deny file-read-metadata (with no-log)
(literal "/etc")
(subpath "/usr/bin"))
; send signals
(allow signal (target same-sandbox))
(deny process-exec* (with no-log)
(literal "/usr/bin/arch")
(literal "/usr/bin/hostinfo")
(literal "/usr/bin/uname"))
; allow getpwuid (for git and other packages)
(allow mach-lookup
(global-name "com.apple.system.notification_center")
(global-name "com.apple.system.opendirectoryd.libinfo"))
; mute annoying failures
(deny (with no-log) file-read-metadata (literal "/etc") (subpath "/usr/bin"))
(deny process-exec* (literal "/usr/bin/arch") (literal "/usr/bin/hostinfo") (literal "/usr/bin/uname"))

View File

@ -11349,7 +11349,7 @@ let
imagemagick = null;
acl = null;
gpm = null;
inherit (darwin.apple_sdk.frameworks) AppKit;
inherit (darwin.apple_sdk.frameworks) AppKit CoreWLAN GSS Kerberos ImageIO;
};
emacs24-nox = lowPrio (appendToName "nox" (emacs24.override {

View File

@ -8266,6 +8266,7 @@ let self = _self // overrides; _self = with self; {
url = mirror://cpan/authors/id/E/ET/ETHER/Net-HTTP-6.09.tar.gz;
sha256 = "52762b939d84806908ba544581c5708375f7938c3c0e496c128ca3fbc425e58d";
};
__sandboxProfile = stdenv.lib.sandbox.allowNetworkLocal;
propagatedBuildInputs = [ URI ];
meta = {
description = "Low-level HTTP connection (client)";

View File

@ -3759,6 +3759,8 @@ let
substituteInPlace test-requirements.txt --replace 'nose==1.3' 'nose'
'';
__sandboxProfile = pkgs.lib.sandbox.allowNetwork;
doCheck = !isPy3k; # lots of transient failures
checkPhase = ''
# Not worth the trouble
@ -6548,6 +6550,8 @@ let
sha256 = "02rknqarwy7p50693cqswbibqwgxzrfzdq4yhwqxbdmhbsmh0rk6";
};
__sandboxProfile = pkgs.lib.sandbox.allowNetwork;
# Only test dependencies
buildInputs = with self; [ pkgs.git gevent geventhttpclient mock fastimport ];