How to find the user that executed a program as root using Golang?

sudo creates the SUDO_UID/SUDO_GID and the SUDO_USER environment variables for this, which contains the user id, group id and username of the account invoking sudo. See e.g. here

So in Go you can read those environment variables with os.Getenv().

You might want to trust those variables only if running as root, i.e. if os.Geteuid() returns 0


Since anyone can set SUDO_UID, SUDO_GID and SUDO_USER, an attacker can just export those themselves and bypass the security you're trying to implement.

The way that I've found, is to find the pid of the Go program you're currently running, get the name of the user that owns that pid, then check if its root.

import (
    "fmt"
    "os"
    "os/exec"
    "strconv"
)

func main() {
    if getProcessOwner() == "root" {
        fmt.Println("You're sudo!")
    }
}

func getProcessOwner() string {
    stdout, err := exec.Command("ps", "-o", "user=", "-p", strconv.Itoa(os.Getpid())).Output()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    return string(stdout)
}

Tags:

Sudo

Username

Go