-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsrf.go
75 lines (54 loc) · 1.41 KB
/
csrf.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package csrf
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"time"
)
// Secret is the key to use when creating the sha256 hash
var Secret string
// MaxTokenAge is the time.Duration of how long the CSRF token should be valid
var MaxTokenAge time.Duration
// CreateToken generates the CSRF token based on sessionID
func CreateToken(sessionID string) string {
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
data := sessionID + timestamp
sha := generateHMAC(data)
return sha + "$" + timestamp
}
// ValidToken returns true if the token makes the sessionID and is within MaxTokenAge
func ValidToken(token, sessionID string) bool {
splitToken := strings.Split(token, "$")
if len(splitToken) != 2 {
fmt.Println("CSRF Token Missing Timestamp")
return false
}
sha := splitToken[0]
timestamp := splitToken[1]
data := sessionID + timestamp
newSha := generateHMAC(data)
if (newSha != sha) {
fmt.Println("CSRF Token Mismatch")
return false
}
milsec, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
fmt.Println(err)
return false
}
fullTime := time.Unix(milsec, 0)
if fullTime.Sub(time.Now()) > MaxTokenAge {
fmt.Println("CSRF Token Expired")
return false
}
return true
}
// generateHMAC returns hash
func generateHMAC(data string) string {
h := hmac.New(sha256.New, []byte(Secret))
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}