From 7bf306f022d351071a9389718540c54d5b79b667 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Wed, 9 Oct 2019 16:34:40 +0200 Subject: [PATCH] Generate and verify random "state" value This is for extra security during OAuth flow. --- auth/oauth.go | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/auth/oauth.go b/auth/oauth.go index 9a0f33f8a..63a9c1d01 100644 --- a/auth/oauth.go +++ b/auth/oauth.go @@ -1,6 +1,7 @@ package main import ( + "crypto/rand" "fmt" "io/ioutil" "net" @@ -10,8 +11,17 @@ import ( "os/exec" ) +func randomString(length int) (string, error) { + b := make([]byte, length/2) + _, err := rand.Read(b) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", b), nil +} + func main() { - state := "TODO" // replace with random unguessable value + state, _ := randomString(20) clientID := os.Getenv("GH_OAUTH_CLIENT_ID") clientSecret := os.Getenv("GH_OAUTH_CLIENT_SECRET") @@ -36,12 +46,15 @@ func main() { } http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer listener.Close() rq := r.URL.Query() + if state != rq.Get("state") { + fmt.Fprintf(w, "Error: state mismatch") + return + } code = rq.Get("code") - // TODO: rq.Get("state") w.Header().Add("content-type", "text/html") fmt.Fprintf(w, "

You have authenticated GitHub CLI. You may now close this page.

") - defer listener.Close() })) resp, err := http.PostForm("https://github.com/login/oauth/access_token",