github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/syscall/exec_linux.go (about)

     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, _, _ := RawSyscall(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  	// Enable tracing if requested.
   203  	if sys.Ptrace {
   204  		_, _, err1 = RawSyscall(SYS_PTRACE, uintptr(PTRACE_TRACEME), 0, 0)
   205  		if err1 != 0 {
   206  			goto childerror
   207  		}
   208  	}
   209  
   210  	// Session ID
   211  	if sys.Setsid {
   212  		_, _, err1 = RawSyscall(SYS_SETSID, 0, 0, 0)
   213  		if err1 != 0 {
   214  			goto childerror
   215  		}
   216  	}
   217  
   218  	// Set process group
   219  	if sys.Setpgid || sys.Foreground {
   220  		// Place child in process group.
   221  		_, _, err1 = RawSyscall(SYS_SETPGID, 0, uintptr(sys.Pgid), 0)
   222  		if err1 != 0 {
   223  			goto childerror
   224  		}
   225  	}
   226  
   227  	if sys.Foreground {
   228  		pgrp := int32(sys.Pgid)
   229  		if pgrp == 0 {
   230  			r1, _, err1 = RawSyscall(SYS_GETPID, 0, 0, 0)
   231  			if err1 != 0 {
   232  				goto childerror
   233  			}
   234  
   235  			pgrp = int32(r1)
   236  		}
   237  
   238  		// Place process group in foreground.
   239  		_, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSPGRP), uintptr(unsafe.Pointer(&pgrp)))
   240  		if err1 != 0 {
   241  			goto childerror
   242  		}
   243  	}
   244  
   245  	// Unshare
   246  	if sys.Unshareflags != 0 {
   247  		_, _, err1 = RawSyscall(SYS_UNSHARE, sys.Unshareflags, 0, 0)
   248  		if err1 != 0 {
   249  			goto childerror
   250  		}
   251  		// The unshare system call in Linux doesn't unshare mount points
   252  		// mounted with --shared. Systemd mounts / with --shared. For a
   253  		// long discussion of the pros and cons of this see debian bug 739593.
   254  		// The Go model of unsharing is more like Plan 9, where you ask
   255  		// to unshare and the namespaces are unconditionally unshared.
   256  		// To make this model work we must further mark / as MS_PRIVATE.
   257  		// This is what the standard unshare command does.
   258  		if sys.Unshareflags&CLONE_NEWNS == CLONE_NEWNS {
   259  			_, _, err1 = RawSyscall6(SYS_MOUNT, uintptr(unsafe.Pointer(&none[0])), uintptr(unsafe.Pointer(&slash[0])), 0, MS_REC|MS_PRIVATE, 0, 0)
   260  			if err1 != 0 {
   261  				goto childerror
   262  			}
   263  		}
   264  	}
   265  
   266  	// Chroot
   267  	if chroot != nil {
   268  		_, _, err1 = RawSyscall(SYS_CHROOT, uintptr(unsafe.Pointer(chroot)), 0, 0)
   269  		if err1 != 0 {
   270  			goto childerror
   271  		}
   272  	}
   273  
   274  	// User and groups
   275  	if cred := sys.Credential; cred != nil {
   276  		ngroups := uintptr(len(cred.Groups))
   277  		groups := uintptr(0)
   278  		if ngroups > 0 {
   279  			groups = uintptr(unsafe.Pointer(&cred.Groups[0]))
   280  		}
   281  		if !(sys.GidMappings != nil && !sys.GidMappingsEnableSetgroups && ngroups == 0) && !cred.NoSetGroups {
   282  			_, _, err1 = RawSyscall(_SYS_setgroups, ngroups, groups, 0)
   283  			if err1 != 0 {
   284  				goto childerror
   285  			}
   286  		}
   287  		_, _, err1 = RawSyscall(sys_SETGID, uintptr(cred.Gid), 0, 0)
   288  		if err1 != 0 {
   289  			goto childerror
   290  		}
   291  		_, _, err1 = RawSyscall(sys_SETUID, uintptr(cred.Uid), 0, 0)
   292  		if err1 != 0 {
   293  			goto childerror
   294  		}
   295  	}
   296  
   297  	for _, c := range sys.AmbientCaps {
   298  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_CAP_AMBIENT, uintptr(PR_CAP_AMBIENT_RAISE), c, 0, 0, 0)
   299  		if err1 != 0 {
   300  			goto childerror
   301  		}
   302  	}
   303  
   304  	// Chdir
   305  	if dir != nil {
   306  		_, _, err1 = RawSyscall(SYS_CHDIR, uintptr(unsafe.Pointer(dir)), 0, 0)
   307  		if err1 != 0 {
   308  			goto childerror
   309  		}
   310  	}
   311  
   312  	// Parent death signal
   313  	if sys.Pdeathsig != 0 {
   314  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_PDEATHSIG, uintptr(sys.Pdeathsig), 0, 0, 0, 0)
   315  		if err1 != 0 {
   316  			goto childerror
   317  		}
   318  
   319  		// Signal self if parent is already dead. This might cause a
   320  		// duplicate signal in rare cases, but it won't matter when
   321  		// using SIGKILL.
   322  		r1, _, _ = RawSyscall(SYS_GETPPID, 0, 0, 0)
   323  		if r1 != ppid {
   324  			pid, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
   325  			_, _, err1 := RawSyscall(SYS_KILL, pid, uintptr(sys.Pdeathsig), 0)
   326  			if err1 != 0 {
   327  				goto childerror
   328  			}
   329  		}
   330  	}
   331  
   332  	// Pass 1: look for fd[i] < i and move those up above len(fd)
   333  	// so that pass 2 won't stomp on an fd it needs later.
   334  	if pipe < nextfd {
   335  		_, _, err1 = RawSyscall(_SYS_dup, uintptr(pipe), uintptr(nextfd), 0)
   336  		if err1 != 0 {
   337  			goto childerror
   338  		}
   339  		RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   340  		pipe = nextfd
   341  		nextfd++
   342  	}
   343  	for i = 0; i < len(fd); i++ {
   344  		if fd[i] >= 0 && fd[i] < int(i) {
   345  			if nextfd == pipe { // don't stomp on pipe
   346  				nextfd++
   347  			}
   348  			_, _, err1 = RawSyscall(_SYS_dup, uintptr(fd[i]), uintptr(nextfd), 0)
   349  			if err1 != 0 {
   350  				goto childerror
   351  			}
   352  			RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   353  			fd[i] = nextfd
   354  			nextfd++
   355  		}
   356  	}
   357  
   358  	// Pass 2: dup fd[i] down onto i.
   359  	for i = 0; i < len(fd); i++ {
   360  		if fd[i] == -1 {
   361  			RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   362  			continue
   363  		}
   364  		if fd[i] == int(i) {
   365  			// dup2(i, i) won't clear close-on-exec flag on Linux,
   366  			// probably not elsewhere either.
   367  			_, _, err1 = RawSyscall(SYS_FCNTL, uintptr(fd[i]), F_SETFD, 0)
   368  			if err1 != 0 {
   369  				goto childerror
   370  			}
   371  			continue
   372  		}
   373  		// The new fd is created NOT close-on-exec,
   374  		// which is exactly what we want.
   375  		_, _, err1 = RawSyscall(_SYS_dup, uintptr(fd[i]), uintptr(i), 0)
   376  		if err1 != 0 {
   377  			goto childerror
   378  		}
   379  	}
   380  
   381  	// By convention, we don't close-on-exec the fds we are
   382  	// started with, so if len(fd) < 3, close 0, 1, 2 as needed.
   383  	// Programs that know they inherit fds >= 3 will need
   384  	// to set them close-on-exec.
   385  	for i = len(fd); i < 3; i++ {
   386  		RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   387  	}
   388  
   389  	// Detach fd 0 from tty
   390  	if sys.Noctty {
   391  		_, _, err1 = RawSyscall(SYS_IOCTL, 0, uintptr(TIOCNOTTY), 0)
   392  		if err1 != 0 {
   393  			goto childerror
   394  		}
   395  	}
   396  
   397  	// Set the controlling TTY to Ctty
   398  	if sys.Setctty {
   399  		_, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSCTTY), 1)
   400  		if err1 != 0 {
   401  			goto childerror
   402  		}
   403  	}
   404  
   405  	// Time to exec.
   406  	_, _, err1 = RawSyscall(SYS_EXECVE,
   407  		uintptr(unsafe.Pointer(argv0)),
   408  		uintptr(unsafe.Pointer(&argv[0])),
   409  		uintptr(unsafe.Pointer(&envv[0])))
   410  
   411  childerror:
   412  	// send error code on pipe
   413  	RawSyscall(SYS_WRITE, uintptr(pipe), uintptr(unsafe.Pointer(&err1)), unsafe.Sizeof(err1))
   414  	for {
   415  		RawSyscall(SYS_EXIT, 253, 0, 0)
   416  	}
   417  }
   418  
   419  // Try to open a pipe with O_CLOEXEC set on both file descriptors.
   420  func forkExecPipe(p []int) (err error) {
   421  	err = Pipe2(p, O_CLOEXEC)
   422  	// pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
   423  	// might not be implemented.
   424  	if err == ENOSYS {
   425  		if err = Pipe(p); err != nil {
   426  			return
   427  		}
   428  		if _, err = fcntl(p[0], F_SETFD, FD_CLOEXEC); err != nil {
   429  			return
   430  		}
   431  		_, err = fcntl(p[1], F_SETFD, FD_CLOEXEC)
   432  	}
   433  	return
   434  }
   435  
   436  // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
   437  func writeIDMappings(path string, idMap []SysProcIDMap) error {
   438  	fd, err := Open(path, O_RDWR, 0)
   439  	if err != nil {
   440  		return err
   441  	}
   442  
   443  	data := ""
   444  	for _, im := range idMap {
   445  		data = data + itoa(im.ContainerID) + " " + itoa(im.HostID) + " " + itoa(im.Size) + "\n"
   446  	}
   447  
   448  	bytes, err := ByteSliceFromString(data)
   449  	if err != nil {
   450  		Close(fd)
   451  		return err
   452  	}
   453  
   454  	if _, err := Write(fd, bytes); err != nil {
   455  		Close(fd)
   456  		return err
   457  	}
   458  
   459  	if err := Close(fd); err != nil {
   460  		return err
   461  	}
   462  
   463  	return nil
   464  }
   465  
   466  // writeSetgroups writes to /proc/PID/setgroups "deny" if enable is false
   467  // and "allow" if enable is true.
   468  // This is needed since kernel 3.19, because you can't write gid_map without
   469  // disabling setgroups() system call.
   470  func writeSetgroups(pid int, enable bool) error {
   471  	sgf := "/proc/" + itoa(pid) + "/setgroups"
   472  	fd, err := Open(sgf, O_RDWR, 0)
   473  	if err != nil {
   474  		return err
   475  	}
   476  
   477  	var data []byte
   478  	if enable {
   479  		data = []byte("allow")
   480  	} else {
   481  		data = []byte("deny")
   482  	}
   483  
   484  	if _, err := Write(fd, data); err != nil {
   485  		Close(fd)
   486  		return err
   487  	}
   488  
   489  	return Close(fd)
   490  }
   491  
   492  // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
   493  // for a process and it is called from the parent process.
   494  func writeUidGidMappings(pid int, sys *SysProcAttr) error {
   495  	if sys.UidMappings != nil {
   496  		uidf := "/proc/" + itoa(pid) + "/uid_map"
   497  		if err := writeIDMappings(uidf, sys.UidMappings); err != nil {
   498  			return err
   499  		}
   500  	}
   501  
   502  	if sys.GidMappings != nil {
   503  		// If the kernel is too old to support /proc/PID/setgroups, writeSetGroups will return ENOENT; this is OK.
   504  		if err := writeSetgroups(pid, sys.GidMappingsEnableSetgroups); err != nil && err != ENOENT {
   505  			return err
   506  		}
   507  		gidf := "/proc/" + itoa(pid) + "/gid_map"
   508  		if err := writeIDMappings(gidf, sys.GidMappings); err != nil {
   509  			return err
   510  		}
   511  	}
   512  
   513  	return nil
   514  }