1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//go:build linux

package builder

import (
	"fmt"
	"os"
	"path/filepath"
)

// ChrootDirs holds the paths that SetupChrootDir creates.
type ChrootDirs struct {
	// Root is the host directory that becomes the sandbox root.
	Root string
	// BuildDir is the writable build directory inside the sandbox (/build).
	BuildDir string
}

// SetupChrootDir creates a temporary directory tree suitable for use as a
// sandbox chroot root.  The caller must call cleanup() when done (it removes
// the whole tree).
//
// It creates:
//
//	<root>/
//	  etc/          (needed so the launcher can chmod it)
//	  build/        (WorkingDir inside the sandbox, writable)
//	  nix/store/    (target for store bind-mounts)
//	  dev/          (synthesised by the launcher)
//	  proc/         (fresh procfs by the launcher)
//	  bin/          (caller binds the sandbox shell here)
//	  tmp/          (general tempdir inside the sandbox)
func SetupChrootDir() (dirs ChrootDirs, cleanup func(), err error) {
	root, err := os.MkdirTemp("", "gonix-chroot-*")
	if err != nil {
		return dirs, nil, fmt.Errorf("creating chroot root: %w", err)
	}

	cleanup = func() { os.RemoveAll(root) }

	subdirs := []string{
		"etc",
		"build",
		"nix/store",
		"dev",
		"proc",
		"bin",
		"tmp",
	}
	for _, d := range subdirs {
		if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
			cleanup()
			return dirs, nil, fmt.Errorf("creating chroot subdir %q: %w", d, err)
		}
	}

	// Write a minimal /etc/passwd and /etc/group so builders that call
	// getpwuid/getgrnam don't crash (e.g. busybox id).
	if err := os.WriteFile(filepath.Join(root, "etc/passwd"),
		[]byte("root:x:0:0:root:/root:/bin/sh\nnixbld:x:1000:100:Nix Builder:/build:/bin/sh\n"),
		0o644); err != nil {
		cleanup()
		return dirs, nil, err
	}
	if err := os.WriteFile(filepath.Join(root, "etc/group"),
		[]byte("root:x:0:\nnixbld:x:100:\n"),
		0o644); err != nil {
		cleanup()
		return dirs, nil, err
	}

	dirs = ChrootDirs{
		Root:     root,
		BuildDir: "/build",
	}
	return dirs, cleanup, nil
}