securitygosetuid

Golang dropping privileges (v1.7)


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


Solution

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