Golang dropping privileges (v1.7)

5.7k views Asked by At

I want to make a custom webserver via golang. It needs root to bind to port 80. However I want to drop root as soon as possible. syscall.SetUid() returns "Not supported" as per ticket #1435.

I could always reroute port 80 to something else via iptables, however this opens up any non-root process to pose as my webserver - which I'd prefer not to be possible.

How do I drop privileges for my application (or alternatively solve this cleanly).

3

There are 3 answers

0
kostix On BEST ANSWER

I'd do what @JimB suggested:

The preferred method is to use linux capabilities to only allow your program to bind to the correct port without having full root capabilities.

On the other hand, on Linux there's another trick: you can use os/exec.Command() to execute /proc/self/exe while telling it to use alternative credentials in the SysProcAttr.Credential field of the os/exec.Cmd instance it generates.

See go doc os/exec.Cmd, go doc syscall.SysProcAttr and go doc syscall.Credential.

Make sure that when you make your program re-execute itself, you need to make sure the spawned one has its standard I/O streams connected to those of its parent, and all the necessary opened files are inherited as well.


Another alternatve worth mentioning is to not attempt to bind to port 80 at all and have a proper web server hanging there, and then reverse-proxy either a hostname-based virtual host or a particular URL path prefix (or prefixes) to your Go process listening on any TCP or Unix socket. Both Apache (2.4 at least) and Nginx can do that easily.

1
nervuri On

Since Go 1.16, syscall.Setuid() and related functions work properly, so you don't need C code anymore, as in Jon Jenkins' answer. You could do something like:

package main

import (
    "fmt"
    "log"
    "net"
    "net/http"
    "os/user"
    "strconv"
    "syscall"
)

func dropPrivileges(userToSwitchTo string) {

    // Lookup user and group IDs for the user we want to switch to.
    userInfo, err := user.Lookup(userToSwitchTo)
    if err != nil {
        log.Fatal(err)
    }
    // Convert group ID and user ID from string to int.
    gid, err := strconv.Atoi(userInfo.Gid)
    if err != nil {
        log.Fatal(err)
    }
    uid, err := strconv.Atoi(userInfo.Uid)
    if err != nil {
        log.Fatal(err)
    }
    // Unset supplementary group IDs.
    err = syscall.Setgroups([]int{})
    if err != nil {
        log.Fatal("Failed to unset supplementary group IDs: " + err.Error())
    }
    // Set group ID (real and effective).
    err = syscall.Setgid(gid)
    if err != nil {
        log.Fatal("Failed to set group ID: " + err.Error())
    }
    // Set user ID (real and effective).
    err = syscall.Setuid(uid)
    if err != nil {
        log.Fatal("Failed to set user ID: " + err.Error())
    }

}

func main() {

    // Listen for connections on a privileged port.
    listener, err := net.Listen("tcp", ":80")
    if err != nil {
        log.Fatal(err)
    }
    defer listener.Close()

    // Drop root privileges; run as user "www-data" from this point on.
    dropPrivileges("www-data")

    // Define HTTP request handler.
    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintln(w, "All good, root privileges have been dropped.")
    })

    // Start HTTP server.
    log.Fatal(http.Serve(listener, nil))
}

If you only want to change the user when the program is run with root privileges, remember to check not just the UID, but also the EUID, GID, EGID and supplementary GIDs.

1
Jon Jenkins On

I recently worked through this problem, and Go has all of the pieces you need. In this sample, I went one step further and implemented SSL. Essentially, you open the port, detect the UID, and if it's 0, look for the desired user, get the UID, and then use glibc calls to set the UID and GID of the process. I might emphasize that it's best to call your setuid code right after binding the port. The biggest difference when dropping privileges is that you can't use the http.ListenAndServe(TLS)? helper function - you have to manually set up your net.Listener separately, and then call setuid after the port is bound, but before calling http.Serve.

This way of doing it works well because you can, for example, run as UID != 0 in "development" mode on a high port without further considerations. Remember that this is just a stub - I recommend setting address, port, user, group, and TLS file names in a config file.

package main

import (
    "crypto/tls"
    "log"
    "net/http"
    "os/user"
    "strconv"
    "syscall"
)

import (
    //#include <unistd.h>
    //#include <errno.h>
    "C"
)

func main() {
    cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
    if err != nil {
        log.Fatalln("Can't load certificates!", err)
    }
    var tlsconf tls.Config
    tlsconf.Certificates = make([]tls.Certificate, 1)
    tlsconf.Certificates[0] = cert
    listener, err := tls.Listen("tcp4", "127.0.0.1:445", &tlsconf)
    if err != nil {
        log.Fatalln("Error opening port:", err)
    }
    if syscall.Getuid() == 0 {
        log.Println("Running as root, downgrading to user www-data")
        user, err := user.Lookup("www-data")
        if err != nil {
            log.Fatalln("User not found or other error:", err)
        }
        // TODO: Write error handling for int from string parsing
        uid, _ := strconv.ParseInt(user.Uid, 10, 32)
        gid, _ := strconv.ParseInt(user.Gid, 10, 32)
        cerr, errno := C.setgid(C.__gid_t(gid))
        if cerr != 0 {
            log.Fatalln("Unable to set GID due to error:", errno)
        }
        cerr, errno = C.setuid(C.__uid_t(uid))
        if cerr != 0 {
            log.Fatalln("Unable to set UID due to error:", errno)
        }
    }
    http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("Hello, world!"))
    })
    err = http.Serve(listener, nil)
    log.Fatalln(err)
}