Skip to content

Instantly share code, notes, and snippets.

@nsheridan
Last active August 22, 2016 10:07
Show Gist options
  • Save nsheridan/dc32082db92c6ff9eef80fd3561e7221 to your computer and use it in GitHub Desktop.
Save nsheridan/dc32082db92c6ff9eef80fd3561e7221 to your computer and use it in GitHub Desktop.
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/user"
"strconv"
"syscall"
)
var (
useTLS = flag.Bool("use_tls", false, "Use TLS")
port = flag.Int("port", 80, "Listener port")
)
func dropPrivileges(newUser string) error {
// Lookup privsep user
usr, err := user.Lookup(newUser)
if err != nil {
log.Fatal(err)
}
uid, err := strconv.Atoi(usr.Uid)
if err != nil {
log.Fatal(err)
}
gid, err := strconv.Atoi(usr.Gid)
if err != nil {
log.Fatal(err)
}
// Drop privileges
err = syscall.Setgid(gid)
if err != nil {
log.Fatal(err)
}
err = syscall.Setuid(uid)
if err != nil {
log.Fatal(err)
}
return err
}
func main() {
flag.Parse()
l, _ := net.Listen("tcp", fmt.Sprintf(":%d", *port))
tlsConfig := &tls.Config{}
if *useTLS {
var err error
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair("cert.pem", "key.pem")
if err != nil {
log.Fatal(err)
}
l = tls.NewListener(l, tlsConfig)
}
dropPrivileges("nobody")
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello! i am %d!\n", os.Getuid())
})
s := &http.Server{
Handler: mux,
}
s.Serve(l)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment