rely on setcap rather than setuid/setgid

This commit is contained in:
Özgür Kesim 2016-03-04 09:16:30 +01:00
parent f30a09097d
commit 8373a55501

View File

@ -15,8 +15,11 @@ var (
cfile = flag.String("cert", "cert.pem", "Certificate file in PEM format") cfile = flag.String("cert", "cert.pem", "Certificate file in PEM format")
kfile = flag.String("key", "key.pem", "Key file in PEM format") kfile = flag.String("key", "key.pem", "Key file in PEM format")
port = flag.Int("port", 1234, "Port to bind to") port = flag.Int("port", 1234, "Port to bind to")
uid = flag.Int("uid", -1, "UID to run under") /*
gid = flag.Int("gid", -1, "GID to run under") Rather than using setuid/setgid we rely on setcap CAP_NET_BIND_SERVICE
uid = flag.Int("uid", -1, "UID to run under")
gid = flag.Int("gid", -1, "GID to run under")
*/
args []string args []string
nargs int nargs int
) )
@ -53,22 +56,28 @@ func main() {
} }
defer sock.Close() defer sock.Close()
// set uid/gid /*
if *gid >= 0 { The right way to handle/drop privileges is to start with a
err := setgid(*gid) // syscall.Setgid(*gid) low-privileged user and use setcap CAP_NET_BIND_SERVICE on the
if err != nil { binary to allow for the listen-operation.
fmt.Println("Couldn't setgid to", *gid, ":", err)
os.Exit(4)
}
}
if *uid >= 0 { // set uid/gid
err := setuid(*uid) // syscall.Setuid(*uid) if *gid >= 0 {
if err != nil { err := setgid(*gid) // syscall.Setgid(*gid)
fmt.Println("Couldn't setuid to", *uid, ":", err) if err != nil {
os.Exit(4) fmt.Println("Couldn't setgid to", *gid, ":", err)
os.Exit(4)
}
} }
}
if *uid >= 0 {
err := setuid(*uid) // syscall.Setuid(*uid)
if err != nil {
fmt.Println("Couldn't setuid to", *uid, ":", err)
os.Exit(4)
}
}
*/
// accept-loop // accept-loop
for { for {
@ -91,6 +100,7 @@ func handleConnection(conn net.Conn) {
cmd.Stdin = conn cmd.Stdin = conn
cmd.Stdout = conn cmd.Stdout = conn
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{}
// prepare environment according to tcp-environ(5) // prepare environment according to tcp-environ(5)
lh, lp, err := net.SplitHostPort(conn.LocalAddr().String()) lh, lp, err := net.SplitHostPort(conn.LocalAddr().String())