Skip to content

Commit

Permalink
Merge pull request #2 from justinas/master
Browse files Browse the repository at this point in the history
Use constant-time comparison for credentials
  • Loading branch information
elithrar committed Jun 4, 2014
2 parents 109e740 + 12a7749 commit 225ce11
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions basic_auth.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package httpauth

import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"fmt"
"net/http"
Expand Down Expand Up @@ -61,14 +64,22 @@ func (b *basicAuth) authenticate(r *http.Request) bool {
// Split on the first ":" character only, with any subsequent colons assumed to be part
// of the password. Note that the RFC2617 standard does not place any limitations on
// allowable characters in the password.
creds := strings.SplitN(string(str), ":", 2)
creds := bytes.SplitN(str, []byte(":"), 2)

// Equalize lengths of supplied and required credentials
// by hashing them
givenUser := sha256.Sum256(creds[0])
givenPass := sha256.Sum256(creds[1])
requiredUser := sha256.Sum256([]byte(b.opts.User))
requiredPass := sha256.Sum256([]byte(b.opts.Password))

if len(creds) != 2 {
return false
}

// Compare the supplied credentials to those set in our options
if creds[0] == b.opts.User && creds[1] == b.opts.Password {
if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 &&
subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 {
return true
}

Expand Down

0 comments on commit 225ce11

Please sign in to comment.