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