Skip to content

Commit

Permalink
Merge pull request #5 from bouk/constant-time-compare
Browse files Browse the repository at this point in the history
Small security fixes
  • Loading branch information
tylerflint authored Jan 31, 2020
2 parents c2ebbac + f6d0792 commit 063a3fb
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions nanoauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
package nanoauth

import (
"crypto/subtle"
"crypto/tls"
"errors"
"net"
"net/http"
)
Expand All @@ -22,9 +24,6 @@ type Auth struct {
var (
// DefaultAuth is the default Auth object
DefaultAuth = &Auth{}

// whether or not to check auth tokens
check = true
)

func init() {
Expand All @@ -34,7 +33,7 @@ func init() {

// ServeHTTP is to implement the http.Handler interface. Also let clients know
// when I have no matching route listeners
func (self Auth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
func (self *Auth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
reqPath := req.URL.Path
skipOnce := false

Expand All @@ -51,14 +50,14 @@ func (self Auth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
skipOnce = true
}

if !skipOnce && check {
if !skipOnce {
auth := ""
if auth = req.Header.Get(self.Header); auth == "" {
// check form value (case sensitive) if header not set
auth = req.FormValue(self.Header)
}

if auth != self.Token {
if subtle.ConstantTimeCompare([]byte(auth), []byte(self.Token)) == 0 {
rw.WriteHeader(http.StatusUnauthorized)
return
}
Expand All @@ -69,6 +68,9 @@ func (self Auth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {

// ListenAndServeTLS starts a TLS listener and handles serving https
func (self *Auth) ListenAndServeTLS(addr, token string, h http.Handler, excludedPaths ...string) error {
if token == "" {
return errors.New("nanoauth: token missing")
}
config := &tls.Config{
Certificates: []tls.Certificate{*self.Certificate},
}
Expand All @@ -78,9 +80,6 @@ func (self *Auth) ListenAndServeTLS(addr, token string, h http.Handler, excluded
return err
}

if token == "" {
check = false
}
self.ExcludedPaths = excludedPaths
self.Token = token

Expand All @@ -95,14 +94,14 @@ func (self *Auth) ListenAndServeTLS(addr, token string, h http.Handler, excluded
// ListenAndServe starts a normal tcp listener and handles serving http while
// still validating the auth token.
func (self *Auth) ListenAndServe(addr, token string, h http.Handler, excludedPaths ...string) error {
if token == "" {
return errors.New("nanoauth: token missing")
}
httpListener, err := net.Listen("tcp", addr)
if err != nil {
return err
}

if token == "" {
check = false
}
self.ExcludedPaths = excludedPaths
self.Token = token

Expand Down

0 comments on commit 063a3fb

Please sign in to comment.