1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 //sysnb raw_prctl(option int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err Errno)
14 //prctl(option _C_int, arg2 _C_long, arg3 _C_long, arg4 _C_long, arg5 _C_long) _C_int
16 //sysnb rawUnshare(flags int) (err Errno)
17 //unshare(flags _C_int) _C_int
19 //sysnb rawMount(source *byte, target *byte, fstype *byte, flags uintptr, data *byte) (err Errno)
20 //mount(source *byte, target *byte, fstype *byte, flags _C_long, data *byte) _C_int
22 // SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux.
23 // See user_namespaces(7).
24 type SysProcIDMap
struct {
25 ContainerID
int // Container ID.
26 HostID
int // Host ID.
30 type SysProcAttr
struct {
31 Chroot
string // Chroot.
32 Credential
*Credential
// Credential.
33 Ptrace
bool // Enable tracing.
34 Setsid
bool // Create session.
35 Setpgid
bool // Set process group ID to Pgid, or, if Pgid == 0, to new pid.
36 Setctty
bool // Set controlling terminal to fd Ctty (only meaningful if Setsid is set)
37 Noctty
bool // Detach fd 0 from controlling terminal
38 Ctty
int // Controlling TTY fd
39 Foreground
bool // Place child's process group in foreground. (Implies Setpgid. Uses Ctty as fd of controlling TTY)
40 Pgid
int // Child's process group ID if Setpgid.
41 Pdeathsig Signal
// Signal that the process will get when its parent dies (Linux only)
42 Cloneflags
uintptr // Flags for clone calls (Linux only)
43 Unshareflags
uintptr // Flags for unshare calls (Linux only)
44 UidMappings
[]SysProcIDMap
// User ID mappings for user namespaces.
45 GidMappings
[]SysProcIDMap
// Group ID mappings for user namespaces.
46 // GidMappingsEnableSetgroups enabling setgroups syscall.
47 // If false, then setgroups syscall will be disabled for the child process.
48 // This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
49 // users this should be set to false for mappings work.
50 GidMappingsEnableSetgroups
bool
51 AmbientCaps
[]uintptr // Ambient capabilities (Linux only)
55 none
= [...]byte{'n', 'o', 'n', 'e', 0}
56 slash
= [...]byte{'/', 0}
59 // Implemented in runtime package.
60 func runtime_BeforeFork()
61 func runtime_AfterFork()
62 func runtime_AfterForkInChild()
64 // Implemented in clone_linux.c
65 func rawClone(flags _C_ulong
, child_stack
*byte, ptid
*Pid_t
, ctid
*Pid_t
, regs unsafe
.Pointer
) _C_long
67 // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
68 // If a dup or exec fails, write the errno error to pipe.
69 // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
70 // In the child, this function must not acquire any locks, because
71 // they might have been locked at the time of the fork. This means
72 // no rescheduling, no malloc calls, and no new stack segments.
73 // For the same reason compiler does not race instrument it.
74 // The calls to RawSyscall are okay because they are assembly
75 // functions that do not grow the stack.
77 func forkAndExecInChild(argv0
*byte, argv
, envv
[]*byte, chroot
, dir
*byte, attr
*ProcAttr
, sys
*SysProcAttr
, pipe
int) (pid
int, err Errno
) {
78 // Set up and fork. This returns immediately in the parent or
79 // if there's an error.
80 r1
, err1
, p
, locked
:= forkAndExecInChild1(argv0
, argv
, envv
, chroot
, dir
, attr
, sys
, pipe
)
91 if sys
.UidMappings
!= nil || sys
.GidMappings
!= nil {
93 err
:= writeUidGidMappings(pid
, sys
)
98 RawSyscall(SYS_WRITE
, uintptr(p
[1]), uintptr(unsafe
.Pointer(&err2
)), unsafe
.Sizeof(err2
))
105 // forkAndExecInChild1 implements the body of forkAndExecInChild up to
106 // the parent's post-fork path. This is a separate function so we can
107 // separate the child's and parent's stack frames if we're using
110 // This is go:noinline because the point is to keep the stack frames
111 // of this and forkAndExecInChild separate.
115 func forkAndExecInChild1(argv0
*byte, argv
, envv
[]*byte, chroot
, dir
*byte, attr
*ProcAttr
, sys
*SysProcAttr
, pipe
int) (r1
uintptr, err1 Errno
, p
[2]int, locked
bool) {
116 // Defined in linux/prctl.h starting with Linux 4.3.
118 PR_CAP_AMBIENT
= 0x2f
119 PR_CAP_AMBIENT_RAISE
= 0x2
122 // vfork requires that the child not touch any of the parent's
123 // active stack frames. Hence, the child does all post-fork
124 // processing in this stack frame and never returns, while the
125 // parent returns immediately from this frame and does all
126 // post-fork processing in the outer frame.
127 // Declare all variables at top in case any
128 // declarations require heap allocation (e.g., err1).
136 // Record parent PID so child can test if it has died.
139 // Guard against side effects of shuffling fds below.
140 // Make sure that nextfd is beyond any currently open files so
141 // that we can't run the risk of overwriting any of them.
142 fd
:= make([]int, len(attr
.Files
))
143 nextfd
= len(attr
.Files
)
144 for i
, ufd
:= range attr
.Files
{
145 if nextfd
< int(ufd
) {
152 // Allocate another pipe for parent to child communication for
153 // synchronizing writing of User ID/Group ID mappings.
154 if sys
.UidMappings
!= nil || sys
.GidMappings
!= nil {
155 if err
:= forkExecPipe(p
[:]); err
!= nil {
161 // About to call fork.
162 // No more allocation or calls of non-assembly functions.
165 r2
= int(rawClone(_C_ulong(uintptr(SIGCHLD
)|sys
.Cloneflags
), nil, nil, nil, unsafe
.Pointer(nil)))
170 // If we're in the parent, we must return immediately
171 // so we're not in the same stack frame as the child.
172 // This can at most use the return PC, which the child
173 // will not modify, and the results of
174 // rawVforkSyscall, which must have been written after
175 // the child was replaced.
180 // Fork succeeded, now in child.
182 runtime_AfterForkInChild()
184 // Enable the "keep capabilities" flag to set ambient capabilities later.
185 if len(sys
.AmbientCaps
) > 0 {
186 _
, _
, err1
= RawSyscall6(SYS_PRCTL
, PR_SET_KEEPCAPS
, 1, 0, 0, 0, 0)
192 // Wait for User ID/Group ID mappings to be written.
193 if sys
.UidMappings
!= nil || sys
.GidMappings
!= nil {
194 if _
, _
, err1
= RawSyscall(SYS_CLOSE
, uintptr(p
[1]), 0, 0); err1
!= 0 {
197 r1
, _
, err1
= RawSyscall(SYS_READ
, uintptr(p
[0]), uintptr(unsafe
.Pointer(&err2
)), unsafe
.Sizeof(err2
))
201 if r1
!= unsafe
.Sizeof(err2
) {
220 if sys
.Setpgid || sys
.Foreground
{
221 // Place child in process group.
222 err1
= raw_setpgid(0, sys
.Pgid
)
229 pgrp
:= Pid_t(sys
.Pgid
)
234 // Place process group in foreground.
235 _
, err1
= raw_ioctl_ptr(sys
.Ctty
, TIOCSPGRP
, unsafe
.Pointer(&pgrp
))
242 if sys
.Unshareflags
!= 0 {
243 err1
= rawUnshare(int(sys
.Unshareflags
))
247 // The unshare system call in Linux doesn't unshare mount points
248 // mounted with --shared. Systemd mounts / with --shared. For a
249 // long discussion of the pros and cons of this see debian bug 739593.
250 // The Go model of unsharing is more like Plan 9, where you ask
251 // to unshare and the namespaces are unconditionally unshared.
252 // To make this model work we must further mark / as MS_PRIVATE.
253 // This is what the standard unshare command does.
254 if sys
.Unshareflags
&CLONE_NEWNS
== CLONE_NEWNS
{
255 err1
= rawMount(&none
[0], &slash
[0], nil, MS_REC|MS_PRIVATE
, nil)
264 err1
= raw_chroot(chroot
)
271 if cred
:= sys
.Credential
; cred
!= nil {
272 ngroups
:= len(cred
.Groups
)
273 var groups unsafe
.Pointer
275 groups
= unsafe
.Pointer(&cred
.Groups
[0])
277 if !(sys
.GidMappings
!= nil && !sys
.GidMappingsEnableSetgroups
&& ngroups
== 0) && !cred
.NoSetGroups
{
278 err1
= raw_setgroups(ngroups
, groups
)
283 _
, _
, err1
= RawSyscall(sys_SETGID
, uintptr(cred
.Gid
), 0, 0)
287 _
, _
, err1
= RawSyscall(sys_SETUID
, uintptr(cred
.Uid
), 0, 0)
293 for _
, c
:= range sys
.AmbientCaps
{
294 _
, _
, err1
= RawSyscall6(SYS_PRCTL
, PR_CAP_AMBIENT
, uintptr(PR_CAP_AMBIENT_RAISE
), c
, 0, 0, 0)
302 err1
= raw_chdir(dir
)
308 // Parent death signal
309 if sys
.Pdeathsig
!= 0 {
310 _
, err1
= raw_prctl(PR_SET_PDEATHSIG
, int(sys
.Pdeathsig
), 0, 0, 0)
315 // Signal self if parent is already dead. This might cause a
316 // duplicate signal in rare cases, but it won't matter when
321 err1
= raw_kill(pid
, sys
.Pdeathsig
)
328 // Pass 1: look for fd[i] < i and move those up above len(fd)
329 // so that pass 2 won't stomp on an fd it needs later.
331 err1
= raw_dup2(pipe
, nextfd
)
335 raw_fcntl(nextfd
, F_SETFD
, FD_CLOEXEC
)
339 for i
= 0; i
< len(fd
); i
++ {
340 if fd
[i
] >= 0 && fd
[i
] < int(i
) {
341 if nextfd
== pipe
{ // don't stomp on pipe
344 err1
= raw_dup2(fd
[i
], nextfd
)
348 raw_fcntl(nextfd
, F_SETFD
, FD_CLOEXEC
)
354 // Pass 2: dup fd[i] down onto i.
355 for i
= 0; i
< len(fd
); i
++ {
361 // dup2(i, i) won't clear close-on-exec flag on Linux,
362 // probably not elsewhere either.
363 _
, err1
= raw_fcntl(fd
[i
], F_SETFD
, 0)
369 // The new fd is created NOT close-on-exec,
370 // which is exactly what we want.
371 err1
= raw_dup2(fd
[i
], i
)
377 // By convention, we don't close-on-exec the fds we are
378 // started with, so if len(fd) < 3, close 0, 1, 2 as needed.
379 // Programs that know they inherit fds >= 3 will need
380 // to set them close-on-exec.
381 for i
= len(fd
); i
< 3; i
++ {
385 // Detach fd 0 from tty
387 _
, err1
= raw_ioctl(0, TIOCNOTTY
, 0)
393 // Set the controlling TTY to Ctty
395 _
, err1
= raw_ioctl(sys
.Ctty
, TIOCSCTTY
, sys
.Ctty
)
401 // Enable tracing if requested.
402 // Do this right before exec so that we don't unnecessarily trace the runtime
403 // setting up after the fork. See issue #21428.
405 err1
= raw_ptrace(_PTRACE_TRACEME
, 0, nil, nil)
412 err1
= raw_execve(argv0
, &argv
[0], &envv
[0])
415 // send error code on pipe
416 raw_write(pipe
, (*byte)(unsafe
.Pointer(&err1
)), int(unsafe
.Sizeof(err1
)))
422 // Try to open a pipe with O_CLOEXEC set on both file descriptors.
423 func forkExecPipe(p
[]int) (err error
) {
424 err
= Pipe2(p
, O_CLOEXEC
)
425 // pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
426 // might not be implemented.
428 if err
= Pipe(p
); err
!= nil {
431 if _
, err
= fcntl(p
[0], F_SETFD
, FD_CLOEXEC
); err
!= nil {
434 _
, err
= fcntl(p
[1], F_SETFD
, FD_CLOEXEC
)
439 // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
440 func writeIDMappings(path
string, idMap
[]SysProcIDMap
) error
{
441 fd
, err
:= Open(path
, O_RDWR
, 0)
447 for _
, im
:= range idMap
{
448 data
= data
+ itoa(im
.ContainerID
) + " " + itoa(im
.HostID
) + " " + itoa(im
.Size
) + "\n"
451 bytes
, err
:= ByteSliceFromString(data
)
457 if _
, err
:= Write(fd
, bytes
); err
!= nil {
462 if err
:= Close(fd
); err
!= nil {
469 // writeSetgroups writes to /proc/PID/setgroups "deny" if enable is false
470 // and "allow" if enable is true.
471 // This is needed since kernel 3.19, because you can't write gid_map without
472 // disabling setgroups() system call.
473 func writeSetgroups(pid
int, enable
bool) error
{
474 sgf
:= "/proc/" + itoa(pid
) + "/setgroups"
475 fd
, err
:= Open(sgf
, O_RDWR
, 0)
482 data
= []byte("allow")
484 data
= []byte("deny")
487 if _
, err
:= Write(fd
, data
); err
!= nil {
495 // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
496 // for a process and it is called from the parent process.
497 func writeUidGidMappings(pid
int, sys
*SysProcAttr
) error
{
498 if sys
.UidMappings
!= nil {
499 uidf
:= "/proc/" + itoa(pid
) + "/uid_map"
500 if err
:= writeIDMappings(uidf
, sys
.UidMappings
); err
!= nil {
505 if sys
.GidMappings
!= nil {
506 // If the kernel is too old to support /proc/PID/setgroups, writeSetGroups will return ENOENT; this is OK.
507 if err
:= writeSetgroups(pid
, sys
.GidMappingsEnableSetgroups
); err
!= nil && err
!= ENOENT
{
510 gidf
:= "/proc/" + itoa(pid
) + "/gid_map"
511 if err
:= writeIDMappings(gidf
, sys
.GidMappings
); err
!= nil {