Skip to content

Commit 9d5e839

Browse files
committed
fix: remove SHA256 from credential compare path
1 parent 1ccd3aa commit 9d5e839

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

server/auth_policy.go

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package server
22

33
import (
4-
"crypto/sha256"
54
"crypto/subtle"
65
"net"
76
)
@@ -59,8 +58,32 @@ func ValidateUserPassword(users map[string]string, username, password string) bo
5958
expectedPassword = invalidPasswordSentinel
6059
}
6160

62-
givenHash := sha256.Sum256([]byte(password))
63-
expectedHash := sha256.Sum256([]byte(expectedPassword))
64-
passwordMatches := subtle.ConstantTimeCompare(givenHash[:], expectedHash[:]) == 1
61+
passwordMatches := constantTimeStringEqual(password, expectedPassword)
6562
return userFound && passwordMatches
6663
}
64+
65+
func constantTimeStringEqual(a, b string) bool {
66+
ab := []byte(a)
67+
bb := []byte(b)
68+
69+
maxLen := len(ab)
70+
if len(bb) > maxLen {
71+
maxLen = len(bb)
72+
}
73+
74+
var diff byte
75+
for i := 0; i < maxLen; i++ {
76+
var av byte
77+
var bv byte
78+
if i < len(ab) {
79+
av = ab[i]
80+
}
81+
if i < len(bb) {
82+
bv = bb[i]
83+
}
84+
diff |= av ^ bv
85+
}
86+
87+
lengthsEqual := subtle.ConstantTimeEq(int32(len(ab)), int32(len(bb))) == 1
88+
return lengthsEqual && diff == 0
89+
}

0 commit comments

Comments
 (0)