Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add authenticated debug server #187

Merged
merged 6 commits into from
Oct 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cmd/launcher/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/kolide/kit/fs"
"github.com/kolide/kit/version"
"github.com/kolide/launcher/autoupdate"
"github.com/kolide/launcher/debug"
"github.com/kolide/launcher/osquery"
"github.com/kolide/launcher/service"
"github.com/kolide/osquery-go/plugin/config"
Expand Down Expand Up @@ -92,6 +93,10 @@ func main() {
logFatal(logger, "err", errors.Wrap(err, "detecting platform"))
}

debugAddrPath := filepath.Join(rootDirectory, "debug_addr")
debug.AttachDebugHandler(debugAddrPath, logger)
defer os.Remove(debugAddrPath)

httpClient := http.DefaultClient
if opts.insecureTLS {
httpClient = &http.Client{
Expand Down
182 changes: 182 additions & 0 deletions debug/debug.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package debug

import (
"context"
"html/template"
"io/ioutil"
"net"
"net/http"
nhpprof "net/http/pprof"
"net/url"
"os"
"os/signal"
"runtime/pprof"
"strings"
"syscall"

"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/google/uuid"
"github.com/pkg/errors"
)

const debugSignal = syscall.SIGUSR1
const debugPrefix = "/debug/"

// AttachDebugHandler will attach a signal handler that will toggle the debug
// server state when SIGUSR1 is sent to the process.
func AttachDebugHandler(addrPath string, logger log.Logger) {
sig := make(chan os.Signal, 1)
signal.Notify(sig, debugSignal)
go func() {
for {
// Start server on first signal
<-sig
serv, err := startDebugServer(addrPath, logger)
if err != nil {
level.Info(logger).Log(
"msg", "starting debug server",
"err", err,
)
continue
}

// Stop server on next signal
<-sig
if err := serv.Shutdown(context.Background()); err != nil {
level.Info(logger).Log(
"msg", "error shutting down debug server",
"err", err,
)
continue
}

level.Info(logger).Log(
"msg", "shutdown debug server",
)
}
}()
}

func startDebugServer(addrPath string, logger log.Logger) (*http.Server, error) {
// Generate new (random) token to use for debug server auth
token, err := uuid.NewRandom()
if err != nil {
return nil, errors.Wrap(err, "generating debug token")
}

// Start the debug server
r := http.NewServeMux()
registerAuthHandler(token.String(), r, logger)
serv := http.Server{
Handler: r,
}
// Allow the OS to pick an open port. Not intended to be a security
// mechanism, only intended to ensure we don't try to bind to an
// already used port.
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
return nil, errors.Wrap(err, "opening socket")
}

go func() {
if err := serv.Serve(listener); err != nil && err != http.ErrServerClosed {
level.Info(logger).Log("msg", "debug server failed", "err", err)
}
}()

url := url.URL{
Scheme: "http",
Host: listener.Addr().String(),
Path: "/debug/",
RawQuery: "token=" + token.String(),
}
addr := url.String()
// Write the address to a file for easy access by users
if err := ioutil.WriteFile(addrPath, []byte(addr), 0600); err != nil {
return nil, errors.Wrap(err, "writing debug address")
}

level.Info(logger).Log(
"msg", "debug server started",
"addr", addr,
)

return &serv, nil
}

// The below handler code is adapted from MIT licensed github.com/e-dard/netbug
func handler(token string, logger log.Logger) http.HandlerFunc {
info := struct {
Profiles []*pprof.Profile
Token string
}{
Profiles: pprof.Profiles(),
Token: url.QueryEscape(token),
}

return func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(r.URL.Path, "/")
switch name {
case "":
// Index page.
if err := indexTmpl.Execute(w, info); err != nil {
level.Info(logger).Log(
"msg", "error rendering debug template",
"err", err,
)
return
}
case "cmdline":
nhpprof.Cmdline(w, r)
case "profile":
nhpprof.Profile(w, r)
case "trace":
nhpprof.Trace(w, r)
case "symbol":
nhpprof.Symbol(w, r)
default:
// Provides access to all profiles under runtime/pprof
nhpprof.Handler(name).ServeHTTP(w, r)
}
}
}

func authHandler(token string, logger log.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.FormValue("token") == token {
handler(token, logger).ServeHTTP(w, r)
} else {
http.Error(w, "Request must include valid token.", http.StatusUnauthorized)
}
}
}

func registerAuthHandler(token string, mux *http.ServeMux, logger log.Logger) {
mux.Handle(debugPrefix, http.StripPrefix(debugPrefix, http.HandlerFunc(authHandler(token, logger))))
}

var indexTmpl = template.Must(template.New("index").Parse(`<html>
<head>
<title>Debug Information</title>
</head>
<br>
<body>
Profiles:<br>
<table>
{{range .Profiles}}
<tr><td align=right>{{.Count}}<td><a href="{{.Name}}?debug=1&token={{$.Token}}">{{.Name}}</a>
{{end}}
<tr><td align=right><td><a href="profile?token={{.Token}}">CPU</a>
<tr><td align=right><td><a href="trace?seconds=5&token={{.Token}}">5-second trace</a>
<tr><td align=right><td><a href="trace?seconds=30&token={{.Token}}">30-second trace</a>
</table>
<br>
Debug information:<br>
<table>
<tr><td align=right><td><a href="cmdline?token={{.Token}}">cmdline</a>
<tr><td align=right><td><a href="symbol?token={{.Token}}">symbol</a>
<tr><td align=right><td><a href="goroutine?debug=2&token={{.Token}}">full goroutine stack dump</a><br>
<table>
</body>
</html>`))
100 changes: 100 additions & 0 deletions debug/debug_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package debug

import (
"context"
"io/ioutil"
"net/http"
"syscall"
"testing"
"time"

"github.com/go-kit/kit/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func getDebugURL(t *testing.T, tokenPath string) string {
url, err := ioutil.ReadFile(tokenPath)
require.Nil(t, err)
return string(url)
}

func TestStartDebugServer(t *testing.T) {
t.Parallel()
tokenFile, err := ioutil.TempFile("", "kolide_debug_test")
require.Nil(t, err)

serv, err := startDebugServer(tokenFile.Name(), log.NewNopLogger())
require.Nil(t, err)

url := getDebugURL(t, tokenFile.Name())
resp, err := http.Get(url)
require.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()

err = serv.Shutdown(context.Background())
require.Nil(t, err)
}

func TestDebugServerUnauthorized(t *testing.T) {
t.Parallel()
tokenFile, err := ioutil.TempFile("", "kolide_debug_test")
require.Nil(t, err)

serv, err := startDebugServer(tokenFile.Name(), log.NewNopLogger())
require.Nil(t, err)

url := getDebugURL(t, tokenFile.Name())
resp, err := http.Get(url + "bad_token")
require.Nil(t, err)
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
resp.Body.Close()

err = serv.Shutdown(context.Background())
require.Nil(t, err)
}

func TestAttachDebugHandler(t *testing.T) {
t.Parallel()
tokenFile, err := ioutil.TempFile("", "kolide_debug_test")
require.Nil(t, err)

AttachDebugHandler(tokenFile.Name(), log.NewNopLogger())

// Start server
syscall.Kill(syscall.Getpid(), debugSignal)
time.Sleep(1 * time.Second)

url := getDebugURL(t, tokenFile.Name())
resp, err := http.Get(url)
require.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()

// Stop server
syscall.Kill(syscall.Getpid(), debugSignal)
time.Sleep(1 * time.Second)

resp, err = http.Get(url)
require.NotNil(t, err)

// Start server
syscall.Kill(syscall.Getpid(), debugSignal)
time.Sleep(1 * time.Second)

newUrl := getDebugURL(t, tokenFile.Name())
assert.NotEqual(t, url, newUrl)

resp, err = http.Get(newUrl)
require.Nil(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()

// Stop server
syscall.Kill(syscall.Getpid(), debugSignal)
time.Sleep(1 * time.Second)

resp, err = http.Get(url)
require.NotNil(t, err)
}