...
Run Format

Source file src/syscall/exec_linux.go

Documentation: syscall

     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.
     4  
     5  // +build linux
     6  
     7  package syscall
     8  
     9  import (
    10  	"runtime"
    11  	"unsafe"
    12  )
    13  
    14  // SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux.
    15  // See user_namespaces(7).
    16  type SysProcIDMap struct {
    17  	ContainerID int // Container ID.
    18  	HostID      int // Host ID.
    19  	Size        int // Size.
    20  }
    21  
    22  type SysProcAttr struct {
    23  	Chroot       string         // Chroot.
    24  	Credential   *Credential    // Credential.
    25  	Ptrace       bool           // Enable tracing.
    26  	Setsid       bool           // Create session.
    27  	Setpgid      bool           // Set process group ID to Pgid, or, if Pgid == 0, to new pid.
    28  	Setctty      bool           // Set controlling terminal to fd Ctty (only meaningful if Setsid is set)
    29  	Noctty       bool           // Detach fd 0 from controlling terminal
    30  	Ctty         int            // Controlling TTY fd
    31  	Foreground   bool           // Place child's process group in foreground. (Implies Setpgid. Uses Ctty as fd of controlling TTY)
    32  	Pgid         int            // Child's process group ID if Setpgid.
    33  	Pdeathsig    Signal         // Signal that the process will get when its parent dies (Linux only)
    34  	Cloneflags   uintptr        // Flags for clone calls (Linux only)
    35  	Unshareflags uintptr        // Flags for unshare calls (Linux only)
    36  	UidMappings  []SysProcIDMap // User ID mappings for user namespaces.
    37  	GidMappings  []SysProcIDMap // Group ID mappings for user namespaces.
    38  	// GidMappingsEnableSetgroups enabling setgroups syscall.
    39  	// If false, then setgroups syscall will be disabled for the child process.
    40  	// This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
    41  	// users this should be set to false for mappings work.
    42  	GidMappingsEnableSetgroups bool
    43  	AmbientCaps                []uintptr // Ambient capabilities (Linux only)
    44  }
    45  
    46  var (
    47  	none  = [...]byte{'n', 'o', 'n', 'e', 0}
    48  	slash = [...]byte{'/', 0}
    49  )
    50  
    51  // Implemented in runtime package.
    52  func runtime_BeforeFork()
    53  func runtime_AfterFork()
    54  func runtime_AfterForkInChild()
    55  
    56  // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
    57  // If a dup or exec fails, write the errno error to pipe.
    58  // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
    59  // In the child, this function must not acquire any locks, because
    60  // they might have been locked at the time of the fork. This means
    61  // no rescheduling, no malloc calls, and no new stack segments.
    62  // For the same reason compiler does not race instrument it.
    63  // The calls to RawSyscall are okay because they are assembly
    64  // functions that do not grow the stack.
    65  //go:norace
    66  func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err Errno) {
    67  	// Set up and fork. This returns immediately in the parent or
    68  	// if there's an error.
    69  	r1, err1, p, locked := forkAndExecInChild1(argv0, argv, envv, chroot, dir, attr, sys, pipe)
    70  	if locked {
    71  		runtime_AfterFork()
    72  	}
    73  	if err1 != 0 {
    74  		return 0, err1
    75  	}
    76  
    77  	// parent; return PID
    78  	pid = int(r1)
    79  
    80  	if sys.UidMappings != nil || sys.GidMappings != nil {
    81  		Close(p[0])
    82  		err := writeUidGidMappings(pid, sys)
    83  		var err2 Errno
    84  		if err != nil {
    85  			err2 = err.(Errno)
    86  		}
    87  		RawSyscall(SYS_WRITE, uintptr(p[1]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
    88  		Close(p[1])
    89  	}
    90  
    91  	return pid, 0
    92  }
    93  
    94  // forkAndExecInChild1 implements the body of forkAndExecInChild up to
    95  // the parent's post-fork path. This is a separate function so we can
    96  // separate the child's and parent's stack frames if we're using
    97  // vfork.
    98  //
    99  // This is go:noinline because the point is to keep the stack frames
   100  // of this and forkAndExecInChild separate.
   101  //
   102  //go:noinline
   103  //go:norace
   104  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) {
   105  	// Defined in linux/prctl.h starting with Linux 4.3.
   106  	const (
   107  		PR_CAP_AMBIENT       = 0x2f
   108  		PR_CAP_AMBIENT_RAISE = 0x2
   109  	)
   110  
   111  	// vfork requires that the child not touch any of the parent's
   112  	// active stack frames. Hence, the child does all post-fork
   113  	// processing in this stack frame and never returns, while the
   114  	// parent returns immediately from this frame and does all
   115  	// post-fork processing in the outer frame.
   116  	// Declare all variables at top in case any
   117  	// declarations require heap allocation (e.g., err1).
   118  	var (
   119  		err2   Errno
   120  		nextfd int
   121  		i      int
   122  	)
   123  
   124  	// Record parent PID so child can test if it has died.
   125  	ppid, _ := rawSyscallNoError(SYS_GETPID, 0, 0, 0)
   126  
   127  	// Guard against side effects of shuffling fds below.
   128  	// Make sure that nextfd is beyond any currently open files so
   129  	// that we can't run the risk of overwriting any of them.
   130  	fd := make([]int, len(attr.Files))
   131  	nextfd = len(attr.Files)
   132  	for i, ufd := range attr.Files {
   133  		if nextfd < int(ufd) {
   134  			nextfd = int(ufd)
   135  		}
   136  		fd[i] = int(ufd)
   137  	}
   138  	nextfd++
   139  
   140  	// Allocate another pipe for parent to child communication for
   141  	// synchronizing writing of User ID/Group ID mappings.
   142  	if sys.UidMappings != nil || sys.GidMappings != nil {
   143  		if err := forkExecPipe(p[:]); err != nil {
   144  			err1 = err.(Errno)
   145  			return
   146  		}
   147  	}
   148  
   149  	// About to call fork.
   150  	// No more allocation or calls of non-assembly functions.
   151  	runtime_BeforeFork()
   152  	locked = true
   153  	switch {
   154  	case runtime.GOARCH == "amd64" && sys.Cloneflags&CLONE_NEWUSER == 0:
   155  		r1, err1 = rawVforkSyscall(SYS_CLONE, uintptr(SIGCHLD|CLONE_VFORK|CLONE_VM)|sys.Cloneflags)
   156  	case runtime.GOARCH == "s390x":
   157  		r1, _, err1 = RawSyscall6(SYS_CLONE, 0, uintptr(SIGCHLD)|sys.Cloneflags, 0, 0, 0, 0)
   158  	default:
   159  		r1, _, err1 = RawSyscall6(SYS_CLONE, uintptr(SIGCHLD)|sys.Cloneflags, 0, 0, 0, 0, 0)
   160  	}
   161  	if err1 != 0 || r1 != 0 {
   162  		// If we're in the parent, we must return immediately
   163  		// so we're not in the same stack frame as the child.
   164  		// This can at most use the return PC, which the child
   165  		// will not modify, and the results of
   166  		// rawVforkSyscall, which must have been written after
   167  		// the child was replaced.
   168  		return
   169  	}
   170  
   171  	// Fork succeeded, now in child.
   172  
   173  	runtime_AfterForkInChild()
   174  
   175  	// Enable the "keep capabilities" flag to set ambient capabilities later.
   176  	if len(sys.AmbientCaps) > 0 {
   177  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_KEEPCAPS, 1, 0, 0, 0, 0)
   178  		if err1 != 0 {
   179  			goto childerror
   180  		}
   181  	}
   182  
   183  	// Wait for User ID/Group ID mappings to be written.
   184  	if sys.UidMappings != nil || sys.GidMappings != nil {
   185  		if _, _, err1 = RawSyscall(SYS_CLOSE, uintptr(p[1]), 0, 0); err1 != 0 {
   186  			goto childerror
   187  		}
   188  		r1, _, err1 = RawSyscall(SYS_READ, uintptr(p[0]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
   189  		if err1 != 0 {
   190  			goto childerror
   191  		}
   192  		if r1 != unsafe.Sizeof(err2) {
   193  			err1 = EINVAL
   194  			goto childerror
   195  		}
   196  		if err2 != 0 {
   197  			err1 = err2
   198  			goto childerror
   199  		}
   200  	}
   201  
   202  	// Session ID
   203  	if sys.Setsid {
   204  		_, _, err1 = RawSyscall(SYS_SETSID, 0, 0, 0)
   205  		if err1 != 0 {
   206  			goto childerror
   207  		}
   208  	}
   209  
   210  	// Set process group
   211  	if sys.Setpgid || sys.Foreground {
   212  		// Place child in process group.
   213  		_, _, err1 = RawSyscall(SYS_SETPGID, 0, uintptr(sys.Pgid), 0)
   214  		if err1 != 0 {
   215  			goto childerror
   216  		}
   217  	}
   218  
   219  	if sys.Foreground {
   220  		pgrp := int32(sys.Pgid)
   221  		if pgrp == 0 {
   222  			r1, _ = rawSyscallNoError(SYS_GETPID, 0, 0, 0)
   223  
   224  			pgrp = int32(r1)
   225  		}
   226  
   227  		// Place process group in foreground.
   228  		_, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSPGRP), uintptr(unsafe.Pointer(&pgrp)))
   229  		if err1 != 0 {
   230  			goto childerror
   231  		}
   232  	}
   233  
   234  	// Unshare
   235  	if sys.Unshareflags != 0 {
   236  		_, _, err1 = RawSyscall(SYS_UNSHARE, sys.Unshareflags, 0, 0)
   237  		if err1 != 0 {
   238  			goto childerror
   239  		}
   240  		// The unshare system call in Linux doesn't unshare mount points
   241  		// mounted with --shared. Systemd mounts / with --shared. For a
   242  		// long discussion of the pros and cons of this see debian bug 739593.
   243  		// The Go model of unsharing is more like Plan 9, where you ask
   244  		// to unshare and the namespaces are unconditionally unshared.
   245  		// To make this model work we must further mark / as MS_PRIVATE.
   246  		// This is what the standard unshare command does.
   247  		if sys.Unshareflags&CLONE_NEWNS == CLONE_NEWNS {
   248  			_, _, err1 = RawSyscall6(SYS_MOUNT, uintptr(unsafe.Pointer(&none[0])), uintptr(unsafe.Pointer(&slash[0])), 0, MS_REC|MS_PRIVATE, 0, 0)
   249  			if err1 != 0 {
   250  				goto childerror
   251  			}
   252  		}
   253  	}
   254  
   255  	// Chroot
   256  	if chroot != nil {
   257  		_, _, err1 = RawSyscall(SYS_CHROOT, uintptr(unsafe.Pointer(chroot)), 0, 0)
   258  		if err1 != 0 {
   259  			goto childerror
   260  		}
   261  	}
   262  
   263  	// User and groups
   264  	if cred := sys.Credential; cred != nil {
   265  		ngroups := uintptr(len(cred.Groups))
   266  		groups := uintptr(0)
   267  		if ngroups > 0 {
   268  			groups = uintptr(unsafe.Pointer(&cred.Groups[0]))
   269  		}
   270  		if !(sys.GidMappings != nil && !sys.GidMappingsEnableSetgroups && ngroups == 0) && !cred.NoSetGroups {
   271  			_, _, err1 = RawSyscall(_SYS_setgroups, ngroups, groups, 0)
   272  			if err1 != 0 {
   273  				goto childerror
   274  			}
   275  		}
   276  		_, _, err1 = RawSyscall(sys_SETGID, uintptr(cred.Gid), 0, 0)
   277  		if err1 != 0 {
   278  			goto childerror
   279  		}
   280  		_, _, err1 = RawSyscall(sys_SETUID, uintptr(cred.Uid), 0, 0)
   281  		if err1 != 0 {
   282  			goto childerror
   283  		}
   284  	}
   285  
   286  	for _, c := range sys.AmbientCaps {
   287  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_CAP_AMBIENT, uintptr(PR_CAP_AMBIENT_RAISE), c, 0, 0, 0)
   288  		if err1 != 0 {
   289  			goto childerror
   290  		}
   291  	}
   292  
   293  	// Chdir
   294  	if dir != nil {
   295  		_, _, err1 = RawSyscall(SYS_CHDIR, uintptr(unsafe.Pointer(dir)), 0, 0)
   296  		if err1 != 0 {
   297  			goto childerror
   298  		}
   299  	}
   300  
   301  	// Parent death signal
   302  	if sys.Pdeathsig != 0 {
   303  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_PDEATHSIG, uintptr(sys.Pdeathsig), 0, 0, 0, 0)
   304  		if err1 != 0 {
   305  			goto childerror
   306  		}
   307  
   308  		// Signal self if parent is already dead. This might cause a
   309  		// duplicate signal in rare cases, but it won't matter when
   310  		// using SIGKILL.
   311  		r1, _ = rawSyscallNoError(SYS_GETPPID, 0, 0, 0)
   312  		if r1 != ppid {
   313  			pid, _ := rawSyscallNoError(SYS_GETPID, 0, 0, 0)
   314  			_, _, err1 := RawSyscall(SYS_KILL, pid, uintptr(sys.Pdeathsig), 0)
   315  			if err1 != 0 {
   316  				goto childerror
   317  			}
   318  		}
   319  	}
   320  
   321  	// Pass 1: look for fd[i] < i and move those up above len(fd)
   322  	// so that pass 2 won't stomp on an fd it needs later.
   323  	if pipe < nextfd {
   324  		_, _, err1 = RawSyscall(_SYS_dup, uintptr(pipe), uintptr(nextfd), 0)
   325  		if err1 != 0 {
   326  			goto childerror
   327  		}
   328  		RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   329  		pipe = nextfd
   330  		nextfd++
   331  	}
   332  	for i = 0; i < len(fd); i++ {
   333  		if fd[i] >= 0 && fd[i] < int(i) {
   334  			if nextfd == pipe { // don't stomp on pipe
   335  				nextfd++
   336  			}
   337  			_, _, err1 = RawSyscall(_SYS_dup, uintptr(fd[i]), uintptr(nextfd), 0)
   338  			if err1 != 0 {
   339  				goto childerror
   340  			}
   341  			RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   342  			fd[i] = nextfd
   343  			nextfd++
   344  		}
   345  	}
   346  
   347  	// Pass 2: dup fd[i] down onto i.
   348  	for i = 0; i < len(fd); i++ {
   349  		if fd[i] == -1 {
   350  			RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   351  			continue
   352  		}
   353  		if fd[i] == int(i) {
   354  			// dup2(i, i) won't clear close-on-exec flag on Linux,
   355  			// probably not elsewhere either.
   356  			_, _, err1 = RawSyscall(SYS_FCNTL, uintptr(fd[i]), F_SETFD, 0)
   357  			if err1 != 0 {
   358  				goto childerror
   359  			}
   360  			continue
   361  		}
   362  		// The new fd is created NOT close-on-exec,
   363  		// which is exactly what we want.
   364  		_, _, err1 = RawSyscall(_SYS_dup, uintptr(fd[i]), uintptr(i), 0)
   365  		if err1 != 0 {
   366  			goto childerror
   367  		}
   368  	}
   369  
   370  	// By convention, we don't close-on-exec the fds we are
   371  	// started with, so if len(fd) < 3, close 0, 1, 2 as needed.
   372  	// Programs that know they inherit fds >= 3 will need
   373  	// to set them close-on-exec.
   374  	for i = len(fd); i < 3; i++ {
   375  		RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   376  	}
   377  
   378  	// Detach fd 0 from tty
   379  	if sys.Noctty {
   380  		_, _, err1 = RawSyscall(SYS_IOCTL, 0, uintptr(TIOCNOTTY), 0)
   381  		if err1 != 0 {
   382  			goto childerror
   383  		}
   384  	}
   385  
   386  	// Set the controlling TTY to Ctty
   387  	if sys.Setctty {
   388  		_, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSCTTY), 1)
   389  		if err1 != 0 {
   390  			goto childerror
   391  		}
   392  	}
   393  
   394  	// Enable tracing if requested.
   395  	// Do this right before exec so that we don't unnecessarily trace the runtime
   396  	// setting up after the fork. See issue #21428.
   397  	if sys.Ptrace {
   398  		_, _, err1 = RawSyscall(SYS_PTRACE, uintptr(PTRACE_TRACEME), 0, 0)
   399  		if err1 != 0 {
   400  			goto childerror
   401  		}
   402  	}
   403  
   404  	// Time to exec.
   405  	_, _, err1 = RawSyscall(SYS_EXECVE,
   406  		uintptr(unsafe.Pointer(argv0)),
   407  		uintptr(unsafe.Pointer(&argv[0])),
   408  		uintptr(unsafe.Pointer(&envv[0])))
   409  
   410  childerror:
   411  	// send error code on pipe
   412  	RawSyscall(SYS_WRITE, uintptr(pipe), uintptr(unsafe.Pointer(&err1)), unsafe.Sizeof(err1))
   413  	for {
   414  		RawSyscall(SYS_EXIT, 253, 0, 0)
   415  	}
   416  }
   417  
   418  // Try to open a pipe with O_CLOEXEC set on both file descriptors.
   419  func forkExecPipe(p []int) (err error) {
   420  	err = Pipe2(p, O_CLOEXEC)
   421  	// pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
   422  	// might not be implemented.
   423  	if err == ENOSYS {
   424  		if err = Pipe(p); err != nil {
   425  			return
   426  		}
   427  		if _, err = fcntl(p[0], F_SETFD, FD_CLOEXEC); err != nil {
   428  			return
   429  		}
   430  		_, err = fcntl(p[1], F_SETFD, FD_CLOEXEC)
   431  	}
   432  	return
   433  }
   434  
   435  // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
   436  func writeIDMappings(path string, idMap []SysProcIDMap) error {
   437  	fd, err := Open(path, O_RDWR, 0)
   438  	if err != nil {
   439  		return err
   440  	}
   441  
   442  	data := ""
   443  	for _, im := range idMap {
   444  		data = data + itoa(im.ContainerID) + " " + itoa(im.HostID) + " " + itoa(im.Size) + "\n"
   445  	}
   446  
   447  	bytes, err := ByteSliceFromString(data)
   448  	if err != nil {
   449  		Close(fd)
   450  		return err
   451  	}
   452  
   453  	if _, err := Write(fd, bytes); err != nil {
   454  		Close(fd)
   455  		return err
   456  	}
   457  
   458  	if err := Close(fd); err != nil {
   459  		return err
   460  	}
   461  
   462  	return nil
   463  }
   464  
   465  // writeSetgroups writes to /proc/PID/setgroups "deny" if enable is false
   466  // and "allow" if enable is true.
   467  // This is needed since kernel 3.19, because you can't write gid_map without
   468  // disabling setgroups() system call.
   469  func writeSetgroups(pid int, enable bool) error {
   470  	sgf := "/proc/" + itoa(pid) + "/setgroups"
   471  	fd, err := Open(sgf, O_RDWR, 0)
   472  	if err != nil {
   473  		return err
   474  	}
   475  
   476  	var data []byte
   477  	if enable {
   478  		data = []byte("allow")
   479  	} else {
   480  		data = []byte("deny")
   481  	}
   482  
   483  	if _, err := Write(fd, data); err != nil {
   484  		Close(fd)
   485  		return err
   486  	}
   487  
   488  	return Close(fd)
   489  }
   490  
   491  // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
   492  // for a process and it is called from the parent process.
   493  func writeUidGidMappings(pid int, sys *SysProcAttr) error {
   494  	if sys.UidMappings != nil {
   495  		uidf := "/proc/" + itoa(pid) + "/uid_map"
   496  		if err := writeIDMappings(uidf, sys.UidMappings); err != nil {
   497  			return err
   498  		}
   499  	}
   500  
   501  	if sys.GidMappings != nil {
   502  		// If the kernel is too old to support /proc/PID/setgroups, writeSetGroups will return ENOENT; this is OK.
   503  		if err := writeSetgroups(pid, sys.GidMappingsEnableSetgroups); err != nil && err != ENOENT {
   504  			return err
   505  		}
   506  		gidf := "/proc/" + itoa(pid) + "/gid_map"
   507  		if err := writeIDMappings(gidf, sys.GidMappings); err != nil {
   508  			return err
   509  		}
   510  	}
   511  
   512  	return nil
   513  }
   514  

View as plain text