fix xsrf and added nonce

This commit is contained in:
ston1th 2025-10-15 22:51:08 +02:00
commit 809627b538
208 changed files with 7166 additions and 4278 deletions

View file

@ -3,25 +3,28 @@
package server
import (
"crypto/hmac"
"crypto/rand"
"crypto/subtle"
"crypto/sha256"
"encoding/base64"
"git.giftfish.de/ston1th/jwt/v3"
)
const keySize = jwt.KeySize / 2
const (
keySize = 16
fullSize = keySize * 2
)
func genKey(size int) (b []byte, err error) {
b = make([]byte, size)
_, err = rand.Reader.Read(b)
func genKey(length int) (bytes []byte) {
bytes = make([]byte, length)
rand.Read(bytes)
return
}
func newXsrf(secret []byte) (s string, err error) {
rnd, err := genKey(keySize)
s = base64.RawURLEncoding.EncodeToString(append(rnd, xor(rnd, secret)...))
return
func newXsrf(secret []byte) string {
mac := hmac.New(sha256.New, secret)
rnd := genKey(keySize)
mac.Write(rnd)
return base64.RawURLEncoding.EncodeToString(append(rnd, mac.Sum(nil)[:keySize]...))
}
func checkXsrf(xsrf string, secret []byte) bool {
@ -29,20 +32,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])
}