Golang dropping privileges (v1.7)
Asked Answered
H

3

5

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).

Hickie answered 20/12, 2016 at 18:20 Comment(5)
The preferred method is to use linux capabilities to only allow your program to bind to the correct port without having full root capabilities.Holloman
That issue you link to actually has a number of possible workarounds/solutions IIRC.Numinous
Setuid did not work as expected for golang. Those workarounds were to make it's behaviour more consistent. However in the end they did not guarantee success, meaning you could still end up being root after a call to setuid. That's why the decision was made to disable the function altogether. About the linux-capabilities: What exactly would you suggest here?Hickie
@user2089648: What do you mean regarding capabilities? The idea is that you shouldn't rely on setuid at all (regardless of it being a Go program), and you should set CAP_NET_BIND_SERVICE for the application using setcap.Holloman
There is a fully worked example of successfully doing this in go in the libcap tree.Inhaul
R
4

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.

Ringler answered 21/12, 2016 at 6:30 Comment(0)
F
8

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)
}
Firebird answered 26/2, 2018 at 15:26 Comment(1)
According to this write up, using cgo to call C.setuid() didn't work 100% reliably until bug #42494 was fixed in go1.16.Inhaul
R
4

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.

Ringler answered 21/12, 2016 at 6:30 Comment(0)
P
3

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.

Playacting answered 23/2, 2023 at 13:26 Comment(1)
I cannot believe you just answered this, literally while I was sitting and staring at the other answers, wondering how to get C code into my Go code. You just dropped out of Heaven to save me! Thank you!Fullrigged

© 2022 - 2024 — McMap. All rights reserved.