登录
首页 >  Golang >  Go问答

执行 exec.Command 时,新用户命名空间中的凭据导致错误:“操作未授权”

来源:stackoverflow

时间:2024-02-24 10:42:26 429浏览 收藏

本篇文章给大家分享《执行 exec.Command 时,新用户命名空间中的凭据导致错误:“操作未授权”》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我想使用 linux 命名空间和 go 执行命令来实现一个简单的沙箱。 为了防止命令写入磁盘,使用 credential: &syscall.credential{uid: uint32(1), gid: uint32(1)} 作为另一个用户执行该命令。

但是,我收到此错误:“fork/exec /main:不允许操作”。

即使我将代码更改为 credential: &syscall.credential{uid: uint32(0), gid: uint32(0)},也会发生相同的错误。

container.go如下:

// +build linux
// +build go1.12

package main

import (
    "flag"
    "fmt"
    uuid "github.com/satori/go.uuid"
    "io/ioutil"
    "os"
    "os/exec"
    "os/user"
    "path/filepath"
    "strconv"
    "strings"
    "syscall"
    "time"

    "github.com/ZiheLiu/sandbox/sandbox"
    "github.com/docker/docker/pkg/reexec"
)

func init() {
    // register "justiceInit" => justiceInit() every time
    reexec.Register("justiceInit", justiceInit)

    /**
    * 0. `init()` adds key "justiceInit" in `map`;
    * 1. reexec.Init() seeks if key `os.Args[0]` exists in `registeredInitializers`;
    * 2. for the first time this binary is invoked, the key is os.Args[0], AKA "/path/to/clike_container",
         which `registeredInitializers` will return `false`;
    * 3. `main()` calls binary itself by reexec.Command("justiceInit", args...);
    * 4. for the second time this binary is invoked, the key is os.Args[0], AKA "justiceInit",
    *    which exists in `registeredInitializers`;
    * 5. the value `justiceInit()` is invoked, any hooks(like set hostname) before fork() can be placed here.
    */
    if reexec.Init() {
        os.Exit(0)
    }
}

func justiceInit() {
    command := os.Args[1]
    timeout, _ := strconv.ParseInt(os.Args[2], 10, 32)

    cmd := exec.Command(command)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    // set uid and gid as another user
    cmd.SysProcAttr = &syscall.SysProcAttr{
        Setpgid: true,
        Credential: &syscall.Credential{Uid: uint32(1), Gid: uint32(1)},
    }
    cmd.Env = []string{"PS1=[justice] # "}

    // got the error "fork/exec /Main: operation not permitted" here
    if err := cmd.Run(); err != nil {
        _, _ = os.Stderr.WriteString(fmt.Sprintf("%s\n", err.Error()))
    }
}

// logs will be printed to os.Stderr
func main() {
    command := flag.String("command", "./Main", "the command needed to be execute in sandbox")
    username := flag.String("username", "root", "the user to execute command")
    flag.Parse()

    u, err := user.Lookup(*username)
    if err != nil {
        _, _ = os.Stderr.WriteString(fmt.Sprintf("%s\n", err.Error()))
        os.Exit(0)
    }
    uid, _ := strconv.Atoi(u.Uid)
    gid, _ := strconv.Atoi(u.Gid)

    cmd := reexec.Command("justiceInit", *basedir, *command, *timeout)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.SysProcAttr = &syscall.SysProcAttr{
        Cloneflags: syscall.CLONE_NEWNS |
            syscall.CLONE_NEWUTS |
            syscall.CLONE_NEWIPC |
            syscall.CLONE_NEWPID |
            syscall.CLONE_NEWNET |
            syscall.CLONE_NEWUSER,
        UidMappings: []syscall.SysProcIDMap{
            {
                ContainerID: 0,
                HostID:      os.Getuid(),
                Size:        1,
            },
            {
                ContainerID: 1,
                HostID:      uid,
                Size:        1,
            },
        },
        GidMappings: []syscall.SysProcIDMap{
            {
                ContainerID: 0,
                HostID:      os.Getgid(),
                Size:        1,
            },
            {
                ContainerID: 1,
                HostID:      gid,
                Size:        1,
            },
        },
    }

    if err := cmd.Run(); err != nil {
        _, _ = os.Stderr.WriteString(fmt.Sprintf("%s\n", err.Error()))
    }

    os.Exit(0)
}

当我运行 sudo ./container -command='/main' -username='nobody' 时,出现错误“fork/exec /main:不允许操作”。

justiceinit的用户命名空间中的用户应该是root,但不能使用credential设置uid和gid。

我是 linux 和命名空间的新手。也许我误解了什么。我应该如何修复这个错误?非常感谢!


解决方案


根据@charles duffy的建议,我追踪了cmd.run()的源代码,发现:

type sysprocattr struct {
    uidmappings  []sysprocidmap // user id mappings for user namespaces.
    gidmappings  []sysprocidmap // group id mappings for user namespaces.
    // gidmappingsenablesetgroups enabling setgroups syscall.
    // if false, then setgroups syscall will be disabled for the child process.
    // this parameter is no-op if gidmappings == nil. otherwise for unprivileged
    // users this should be set to false for mappings work.
    gidmappingsenablesetgroups bool
}

因此,如果 gidmappingsenablesetgroups 的默认值为 false,则子进程 justiceinit 无论是否具有 root 权限,都没有权限使用 setgroups syscall。

因此,当我在函数 main 中将 cmd.sysprocattr.gidmappingsenablesetgroups 设置为 true 时,如下所示,它起作用了!

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
    // ...
    GidMappingsEnableSetgroups: true,
}

终于介绍完啦!小伙伴们,这篇关于《执行 exec.Command 时,新用户命名空间中的凭据导致错误:“操作未授权”》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>