Search code examples
gosudo

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


I'm creating a small program that requires privileged access to a network port below 1024, so it runs with sudo.

If part of what the utility will need to do requires knowing who the user is that invoked the application, I would need a way to query who the actual user is; using the OS/user method of getting the user points to "System Administrator" or other root user because it's running in a sudo context.

Is there a way in GoLang to pull the user who is running the application under sudo? (Go 1.4.2, running on OS X 10.10.3).


Solution

  • 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