aboutsummaryrefslogtreecommitdiffhomepage
path: root/container/init.go
blob: 0f888fadecaf18f84f77565eac066aeb2db385b4 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package container

import (
	"errors"
	"fmt"
	"log"
	"os"
	"os/exec"
	"os/signal"
	"path"
	"runtime"
	"strconv"
	. "syscall"
	"time"

	"hakurei.app/container/seccomp"
)

const (
	/* intermediate tmpfs mount point

	this path might seem like a weird choice, however there are many good reasons to use it:
	- the contents of this path is never exposed to the container:
	  the tmpfs root established here effectively becomes anonymous after pivot_root
	- it is safe to assume this path exists and is a directory:
	  this program will not work correctly without a proper /proc and neither will most others
	- this path belongs to the container init:
	  the container init is not any more privileged or trusted than the rest of the container
	- this path is only accessible by init and root:
	  the container init sets SUID_DUMP_DISABLE and terminates if that fails;

	it should be noted that none of this should become relevant at any point since the resulting
	intermediate root tmpfs should be effectively anonymous */
	intermediateHostPath = FHSProc + "self/fd"

	// setup params file descriptor
	setupEnv = "HAKUREI_SETUP"
)

type initParams struct {
	Params

	HostUid, HostGid int
	// extra files count
	Count int
	// verbosity pass through
	Verbose bool
}

func Init(prepare func(prefix string), setVerbose func(verbose bool)) {
	runtime.LockOSThread()
	prepare("init")

	if os.Getpid() != 1 {
		log.Fatal("this process must run as pid 1")
	}

	if err := SetPtracer(0); err != nil {
		msg.Verbosef("cannot enable ptrace protection via Yama LSM: %v", err)
		// not fatal: this program has no additional privileges at initial program start
	}

	var (
		params      initParams
		closeSetup  func() error
		setupFile   *os.File
		offsetSetup int
	)
	if f, err := Receive(setupEnv, &params, &setupFile); err != nil {
		if errors.Is(err, EBADF) {
			log.Fatal("invalid setup descriptor")
		}
		if errors.Is(err, ErrNotSet) {
			log.Fatal("HAKUREI_SETUP not set")
		}

		log.Fatalf("cannot decode init setup payload: %v", err)
	} else {
		if params.Ops == nil {
			log.Fatal("invalid setup parameters")
		}
		if params.ParentPerm == 0 {
			params.ParentPerm = 0755
		}

		setVerbose(params.Verbose)
		msg.Verbose("received setup parameters")
		closeSetup = f
		offsetSetup = int(setupFile.Fd() + 1)
	}

	// write uid/gid map here so parent does not need to set dumpable
	if err := SetDumpable(SUID_DUMP_USER); err != nil {
		log.Fatalf("cannot set SUID_DUMP_USER: %s", err)
	}
	if err := os.WriteFile(FHSProc+"self/uid_map",
		append([]byte{}, strconv.Itoa(params.Uid)+" "+strconv.Itoa(params.HostUid)+" 1\n"...),
		0); err != nil {
		log.Fatalf("%v", err)
	}
	if err := os.WriteFile(FHSProc+"self/setgroups",
		[]byte("deny\n"),
		0); err != nil && !os.IsNotExist(err) {
		log.Fatalf("%v", err)
	}
	if err := os.WriteFile(FHSProc+"self/gid_map",
		append([]byte{}, strconv.Itoa(params.Gid)+" "+strconv.Itoa(params.HostGid)+" 1\n"...),
		0); err != nil {
		log.Fatalf("%v", err)
	}
	if err := SetDumpable(SUID_DUMP_DISABLE); err != nil {
		log.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
	}

	oldmask := Umask(0)
	if params.Hostname != "" {
		if err := Sethostname([]byte(params.Hostname)); err != nil {
			log.Fatalf("cannot set hostname: %v", err)
		}
	}

	// cache sysctl before pivot_root
	LastCap()

	if err := Mount(zeroString, FHSRoot, zeroString, MS_SILENT|MS_SLAVE|MS_REC, zeroString); err != nil {
		log.Fatalf("cannot make / rslave: %v", err)
	}

	state := &setupState{Params: &params.Params}

	/* early is called right before pivot_root into intermediate root;
	this step is mostly for gathering information that would otherwise be difficult to obtain
	via library functions after pivot_root, and implementations are expected to avoid changing
	the state of the mount namespace */
	for i, op := range *params.Ops {
		if op == nil {
			log.Fatalf("invalid op %d", i)
		}

		if err := op.early(state); err != nil {
			msg.PrintBaseErr(err,
				fmt.Sprintf("cannot prepare op %d:", i))
			msg.BeforeExit()
			os.Exit(1)
		}
	}

	if err := Mount(SourceTmpfsRootfs, intermediateHostPath, FstypeTmpfs, MS_NODEV|MS_NOSUID, zeroString); err != nil {
		log.Fatalf("cannot mount intermediate root: %v", err)
	}
	if err := os.Chdir(intermediateHostPath); err != nil {
		log.Fatalf("cannot enter base path: %v", err)
	}

	if err := os.Mkdir(sysrootDir, 0755); err != nil {
		log.Fatalf("%v", err)
	}
	if err := Mount(sysrootDir, sysrootDir, zeroString, MS_SILENT|MS_BIND|MS_REC, zeroString); err != nil {
		log.Fatalf("cannot bind sysroot: %v", err)
	}

	if err := os.Mkdir(hostDir, 0755); err != nil {
		log.Fatalf("%v", err)
	}
	// pivot_root uncovers intermediateHostPath in hostDir
	if err := PivotRoot(intermediateHostPath, hostDir); err != nil {
		log.Fatalf("cannot pivot into intermediate root: %v", err)
	}
	if err := os.Chdir(FHSRoot); err != nil {
		log.Fatalf("%v", err)
	}

	/* apply is called right after pivot_root and entering the new root;
	this step sets up the container filesystem, and implementations are expected to keep the host root
	and sysroot mount points intact but otherwise can do whatever they need to;
	chdir is allowed but discouraged */
	for i, op := range *params.Ops {
		// ops already checked during early setup
		msg.Verbosef("%s %s", op.prefix(), op)
		if err := op.apply(state); err != nil {
			msg.PrintBaseErr(err,
				fmt.Sprintf("cannot apply op %d:", i))
			msg.BeforeExit()
			os.Exit(1)
		}
	}

	// setup requiring host root complete at this point
	if err := Mount(hostDir, hostDir, zeroString, MS_SILENT|MS_REC|MS_PRIVATE, zeroString); err != nil {
		log.Fatalf("cannot make host root rprivate: %v", err)
	}
	if err := Unmount(hostDir, MNT_DETACH); err != nil {
		log.Fatalf("cannot unmount host root: %v", err)
	}

	{
		var fd int
		if err := IgnoringEINTR(func() (err error) {
			fd, err = Open(FHSRoot, O_DIRECTORY|O_RDONLY, 0)
			return
		}); err != nil {
			log.Fatalf("cannot open intermediate root: %v", err)
		}
		if err := os.Chdir(sysrootPath); err != nil {
			log.Fatalf("%v", err)
		}

		if err := PivotRoot(".", "."); err != nil {
			log.Fatalf("cannot pivot into sysroot: %v", err)
		}
		if err := Fchdir(fd); err != nil {
			log.Fatalf("cannot re-enter intermediate root: %v", err)
		}
		if err := Unmount(".", MNT_DETACH); err != nil {
			log.Fatalf("cannot unmount intemediate root: %v", err)
		}
		if err := os.Chdir(FHSRoot); err != nil {
			log.Fatalf("%v", err)
		}

		if err := Close(fd); err != nil {
			log.Fatalf("cannot close intermediate root: %v", err)
		}
	}

	if _, _, errno := Syscall(SYS_PRCTL, PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0); errno != 0 {
		log.Fatalf("cannot clear the ambient capability set: %v", errno)
	}
	for i := uintptr(0); i <= LastCap(); i++ {
		if params.Privileged && i == CAP_SYS_ADMIN {
			continue
		}
		if _, _, errno := Syscall(SYS_PRCTL, PR_CAPBSET_DROP, i, 0); errno != 0 {
			log.Fatalf("cannot drop capability from bonding set: %v", errno)
		}
	}

	var keep [2]uint32
	if params.Privileged {
		keep[capToIndex(CAP_SYS_ADMIN)] |= capToMask(CAP_SYS_ADMIN)

		if _, _, errno := Syscall(SYS_PRCTL, PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, CAP_SYS_ADMIN); errno != 0 {
			log.Fatalf("cannot raise CAP_SYS_ADMIN: %v", errno)
		}
	}
	if err := capset(
		&capHeader{_LINUX_CAPABILITY_VERSION_3, 0},
		&[2]capData{{0, keep[0], keep[0]}, {0, keep[1], keep[1]}},
	); err != nil {
		log.Fatalf("cannot capset: %v", err)
	}

	if !params.SeccompDisable {
		rules := params.SeccompRules
		if len(rules) == 0 { // non-empty rules slice always overrides presets
			msg.Verbosef("resolving presets %#x", params.SeccompPresets)
			rules = seccomp.Preset(params.SeccompPresets, params.SeccompFlags)
		}
		if err := seccomp.Load(rules, params.SeccompFlags); err != nil {
			// this also indirectly asserts PR_SET_NO_NEW_PRIVS
			log.Fatalf("cannot load syscall filter: %v", err)
		}
		msg.Verbosef("%d filter rules loaded", len(rules))
	} else {
		msg.Verbose("syscall filter not configured")
	}

	extraFiles := make([]*os.File, params.Count)
	for i := range extraFiles {
		// setup fd is placed before all extra files
		extraFiles[i] = os.NewFile(uintptr(offsetSetup+i), "extra file "+strconv.Itoa(i))
	}
	Umask(oldmask)

	cmd := exec.Command(params.Path.String())
	cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
	cmd.Args = params.Args
	cmd.Env = params.Env
	cmd.ExtraFiles = extraFiles
	cmd.Dir = params.Dir.String()

	msg.Verbosef("starting initial program %s", params.Path)
	if err := cmd.Start(); err != nil {
		log.Fatalf("%v", err)
	}
	msg.Suspend()

	if err := closeSetup(); err != nil {
		log.Printf("cannot close setup pipe: %v", err)
		// not fatal
	}

	type winfo struct {
		wpid    int
		wstatus WaitStatus
	}
	info := make(chan winfo, 1)
	done := make(chan struct{})

	go func() {
		var (
			err     error
			wpid    = -2
			wstatus WaitStatus
		)

		// keep going until no child process is left
		for wpid != -1 {
			if err != nil {
				break
			}

			if wpid != -2 {
				info <- winfo{wpid, wstatus}
			}

			err = EINTR
			for errors.Is(err, EINTR) {
				wpid, err = Wait4(-1, &wstatus, 0, nil)
			}
		}
		if !errors.Is(err, ECHILD) {
			log.Printf("unexpected wait4 response: %v", err)
		}

		close(done)
	}()

	// handle signals to dump withheld messages
	sig := make(chan os.Signal, 2)
	signal.Notify(sig, os.Interrupt, CancelSignal)

	// closed after residualProcessTimeout has elapsed after initial process death
	timeout := make(chan struct{})

	r := 2
	for {
		select {
		case s := <-sig:
			if msg.Resume() {
				msg.Verbosef("%s after process start", s.String())
			} else {
				msg.Verbosef("got %s", s.String())
			}
			if s == CancelSignal && params.ForwardCancel && cmd.Process != nil {
				msg.Verbose("forwarding context cancellation")
				if err := cmd.Process.Signal(os.Interrupt); err != nil {
					log.Printf("cannot forward cancellation: %v", err)
				}
				continue
			}
			os.Exit(0)
		case w := <-info:
			if w.wpid == cmd.Process.Pid {
				// initial process exited, output is most likely available again
				msg.Resume()

				switch {
				case w.wstatus.Exited():
					r = w.wstatus.ExitStatus()
					msg.Verbosef("initial process exited with code %d", w.wstatus.ExitStatus())
				case w.wstatus.Signaled():
					r = 128 + int(w.wstatus.Signal())
					msg.Verbosef("initial process exited with signal %s", w.wstatus.Signal())
				default:
					r = 255
					msg.Verbosef("initial process exited with status %#x", w.wstatus)
				}

				go func() { time.Sleep(params.AdoptWaitDelay); close(timeout) }()
			}
		case <-done:
			msg.BeforeExit()
			os.Exit(r)
		case <-timeout:
			log.Println("timeout exceeded waiting for lingering processes")
			msg.BeforeExit()
			os.Exit(r)
		}
	}
}

const initName = "init"

// TryArgv0 calls [Init] if the last element of argv0 is "init".
func TryArgv0(v Msg, prepare func(prefix string), setVerbose func(verbose bool)) {
	if len(os.Args) > 0 && path.Base(os.Args[0]) == initName {
		msg = v
		Init(prepare, setVerbose)
		msg.BeforeExit()
		os.Exit(0)
	}
}