fix xsrf
This commit is contained in:
parent
204aec8135
commit
824f46979b
6 changed files with 69 additions and 103 deletions
|
|
@ -57,11 +57,11 @@ func (s *HTTPServer) Start() (err error) {
|
|||
if err != nil {
|
||||
return
|
||||
}
|
||||
opts := []jwt.JWTOption{jwt.WithBlacklist(s.DB), jwt.WithNonce()}
|
||||
if s.Config.Secret != "" {
|
||||
s.JWT, err = jwt.New(jwt.DefaultExpiry, s.DB, bytes.NewBufferString(s.Config.Secret))
|
||||
} else {
|
||||
s.JWT, err = jwt.New(jwt.DefaultExpiry, s.DB, nil)
|
||||
opts = append(opts, jwt.WithSecret(bytes.NewBufferString(s.Config.Secret)))
|
||||
}
|
||||
s.JWT, err = jwt.New(opts...)
|
||||
if err != nil {
|
||||
return errors.New("server: " + err.Error())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,14 +3,17 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"git.giftfish.de/ston1th/gowiki/pkg/log"
|
||||
"git.giftfish.de/ston1th/jwt/v3"
|
||||
)
|
||||
|
||||
const keySize = jwt.KeySize / 2
|
||||
const (
|
||||
keySize = 16
|
||||
fullSize = keySize * 2
|
||||
)
|
||||
|
||||
func genKey(length int) (bytes []byte) {
|
||||
bytes = make([]byte, length)
|
||||
|
|
@ -21,8 +24,10 @@ func genKey(length int) (bytes []byte) {
|
|||
}
|
||||
|
||||
func newXsrf(secret []byte) string {
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
rnd := genKey(keySize)
|
||||
return base64.RawURLEncoding.EncodeToString(append(rnd, xor(rnd, secret)...))
|
||||
mac.Write(rnd)
|
||||
return base64.RawURLEncoding.EncodeToString(append(rnd, mac.Sum(nil)[:keySize]...))
|
||||
}
|
||||
|
||||
func checkXsrf(xsrf string, secret []byte) bool {
|
||||
|
|
@ -30,20 +35,10 @@ func checkXsrf(xsrf string, secret []byte) bool {
|
|||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if len(t) != jwt.KeySize {
|
||||
if len(t) != fullSize {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare(secret, xor(t[keySize:], t[:keySize])) == 1
|
||||
}
|
||||
|
||||
func xor(a, b []byte) (c []byte) {
|
||||
n := len(a)
|
||||
if len(b) < n {
|
||||
return nil
|
||||
}
|
||||
c = make([]byte, n)
|
||||
for i := 0; i < n; i++ {
|
||||
c[i] = a[i] ^ b[i]
|
||||
}
|
||||
return
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
mac.Write(t[:keySize])
|
||||
return hmac.Equal(t[keySize:], mac.Sum(nil)[:keySize])
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue