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