From ad57a9391f9a9b7f12a2a3377b3b2ab77ab760fc Mon Sep 17 00:00:00 2001 From: Vikrum Nijjar Date: Tue, 22 Jul 2014 17:17:31 -0700 Subject: [PATCH] Fixed timing attack in cookie validation. - Changed from using string == to hmac.Equal - See more details here: http://verboselogging.com/2012/08/20/a-timing-attack-in-action --- cookies.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/cookies.go b/cookies.go index 1faf480..ffa0004 100644 --- a/cookies.go +++ b/cookies.go @@ -18,7 +18,7 @@ func validateCookie(cookie *http.Cookie, seed string) (string, bool) { return "", false } sig := cookieSignature(seed, cookie.Name, parts[0], parts[1]) - if parts[2] == sig { + if checkHmac(parts[2], sig) { ts, err := strconv.Atoi(parts[1]) if err == nil && int64(ts) > time.Now().Add(time.Duration(24)*7*time.Hour*-1).Unix() { // it's a valid cookie. now get the contents @@ -48,3 +48,14 @@ func cookieSignature(args ...string) string { b = h.Sum(b) return base64.URLEncoding.EncodeToString(b) } + +func checkHmac(input, expected string) bool { + inputMAC, err1 := base64.URLEncoding.DecodeString(input) + if err1 == nil { + expectedMAC, err2 := base64.URLEncoding.DecodeString(expected) + if err2 == nil { + return hmac.Equal(inputMAC, expectedMAC) + } + } + return false +}