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).
I'd do what @JimB suggested:
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 theSysProcAttr.Credential
field of theos/exec.Cmd
instance it generates.See
go doc os/exec.Cmd
,go doc syscall.SysProcAttr
andgo 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.