1. 程式人生 > >fork/exec /bin/sh: operation not permitted

fork/exec /bin/sh: operation not permitted

我在 ubuntu 18.04 系統下使用 go 語言執行 sh 命令,設定 uid、gid 報錯

	cmd := exec.Command("sh")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS | syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET,
	}
	cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(0), Gid: uint32(0)}

錯誤:2018/11/30 14:12:37 fork/exec /bin/bash: operation not permitted

問題產生原因: https://github.com/xianlubird/mydocker/issues/3

Linux kernel 在 3.19 以上的版本中對 user namespace 做了些修改,程式應該改為如下寫法:

	cmd := exec.Command("sh")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Cloneflags: syscall.CLONE_NEWUTS | syscall.CLONE_NEWIPC | syscall.CLONE_NEWPID | syscall.CLONE_NEWNS | syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET,
		UidMappings: []syscall.SysProcIDMap{
			{
				ContainerID: 0,
				HostID:      0,
				Size:        1,
			},
		},
		GidMappings: []syscall.SysProcIDMap{
			{
				ContainerID: 0,
				HostID:      0,
				Size:        1,
			},
		},
	}