1 回答
TA贡献1943条经验 获得超7个赞
使用 os.Setuid/os.Setgid (example.go) 应该没问题:
package main
import (
"log"
"flag"
"os"
"os/exec"
"syscall"
)
func main() {
var oUid = flag.Int("uid", 0, "Run with User ID")
var oGid = flag.Int("gid", 0, "Run with Group ID")
flag.Parse()
// Get UID/GUID from args
var uid = *oUid
var gid = *oGid
// Run whoami
out, err := exec.Command("whoami").Output()
if err != nil {
log.Fatal(err)
return
}
// Output whoami
log.Println("Original UID/GID whoami:", string(out))
log.Println("Setting UID/GUID")
// Change privileges
err = syscall.Setgid(gid)
if err != nil {
log.Println("Cannot setgid")
log.Fatal(err)
return
}
err = syscall.Setuid(uid)
if err != nil {
log.Println("Cannot setuid")
log.Fatal(err)
return
}
// Execute whoami again
out, err = exec.Command("whoami").Output()
if err != nil {
log.Fatal(err)
return
}
log.Println("Changed UID/GID whoami:", string(out))
// Do some dangerous stuff
log.Println("Creating a executable file within /bin should fail...")
_, err = os.Create("/bin/should-fail")
if err == nil {
log.Println("Warning: operation did not fail")
return
}
log.Println("We are fine", err)
}
我还建议阅读有关正确设置 gid/uid 的信息(https://unix.stackexchange.com/questions/166817/using-the-setuid-bit-properly,在 C 中)。哦!它需要在 uid 之前设置 gid,因为如果您不这样做,示例将失败。
您应该example.go以 root 权限执行,并分别使用标志 -gid、-uid 为命令指定非特权 gid/uid。
sudo go run example.go -uid <unprivileged id> -gid <unprivileged id>
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报