/ nix / script / exe / fhs-run.hs
fhs-run.hs
 1  {-# LANGUAGE OverloadedStrings #-}
 2  
 3  {- |
 4  Run a command in a minimal FHS-like namespace.
 5  
 6  Usage: fhs-run COMMAND [ARGS...]
 7  
 8  Creates a namespace with:
 9  - /nix/store (read-only)
10  - /dev, /proc, /tmp
11  - Your home directory and current directory (read-write)
12  - Basic PATH including coreutils
13  -}
14  module Main where
15  
16  import Aleph.Script hiding (FilePath)
17  import qualified Aleph.Script.Tools.Bwrap as Bwrap
18  import Data.Function ((&))
19  import qualified Data.List as L
20  import System.Environment (getArgs)
21  
22  main :: IO ()
23  main = do
24      args <- getArgs
25      case args of
26          [] -> script $ do
27              echoErr "Usage: fhs-run COMMAND [ARGS...]"
28              echoErr ""
29              echoErr "Run COMMAND in a minimal FHS namespace."
30              echoErr ""
31              echoErr "Examples:"
32              echoErr "  fhs-run bash"
33              echoErr "  fhs-run python3 script.py"
34              exit 1
35          cmd -> script $ do
36              homeDir <- getEnvDefault "HOME" "/root"
37              cwd <- pwd
38  
39              let sandbox =
40                      Bwrap.defaults
41                          -- Core system
42                          & Bwrap.roBind "/nix/store" "/nix/store"
43                          & Bwrap.devBind "/dev" "/dev"
44                          & Bwrap.proc "/proc"
45                          & Bwrap.tmpfs "/tmp"
46                          & Bwrap.tmpfs "/run"
47                          -- Network/SSL
48                          & Bwrap.roBind "/etc/resolv.conf" "/etc/resolv.conf"
49                          & Bwrap.roBind "/etc/ssl" "/etc/ssl"
50                          -- User directories (read-write)
51                          & Bwrap.bind (unpack homeDir) (unpack homeDir)
52                          & Bwrap.bind cwd cwd
53                          & Bwrap.chdir cwd
54                          -- Environment
55                          & Bwrap.setenv "PATH" "/nix/store/bin:/usr/local/bin:/usr/bin:/bin"
56                          & Bwrap.setenv "HOME" homeDir
57                          & Bwrap.dieWithParent
58  
59              Bwrap.exec sandbox (map pack cmd)