Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xsrftoken: correct semantics of time vs now variable #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions xsrftoken/xsrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ func Generate(key, userID, actionID string) string {
return generateTokenAtTime(key, userID, actionID, time.Now())
}

// generateTokenAtTime is like Generate, but returns a token that expires 24 hours from now.
func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
// generateTokenAtTime is like Generate, but returns a token that expires 24 hours from the given time.
func generateTokenAtTime(key, userID, actionID string, t time.Time) string {
if len(key) == 0 {
panic("zero length xsrf secret key")
}
// Round time up and convert to milliseconds.
milliTime := (now.UnixNano() + 1e6 - 1) / 1e6
milliTime := (t.UnixNano() + 1e6 - 1) / 1e6

h := hmac.New(sha1.New, []byte(key))
fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), milliTime)
Expand All @@ -59,7 +59,7 @@ func Valid(token, key, userID, actionID string) bool {
}

// validTokenAtTime reports whether a token is valid at the given time.
func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
func validTokenAtTime(token, key, userID, actionID string, t time.Time) bool {
if len(key) == 0 {
panic("zero length xsrf secret key")
}
Expand All @@ -72,17 +72,17 @@ func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
if err != nil {
return false
}
issueTime := time.Unix(0, millis*1e6)
issueTime := t.Unix(0, millis*1e6)

// Check that the token is not expired.
if now.Sub(issueTime) >= Timeout {
if time.Sub(issueTime) >= Timeout {
return false
}

// Check that the token is not from the future.
// Allow 1 minute grace period in case the token is being verified on a
// machine whose clock is behind the machine that issued the token.
if issueTime.After(now.Add(1 * time.Minute)) {
if issueTime.After(t.Add(1 * time.Minute)) {
return false
}

Expand Down