1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-01-10 04:18:14 +02:00
oauth2-proxy/pkg/encryption/nonce.go
Nick Meves 7eeaea0b3f
Support nonce checks in OIDC Provider (#967)
* Set and verify a nonce with OIDC

* Create a CSRF object to manage nonces & cookies

* Add missing generic cookie unit tests

* Add config flag to control OIDC SkipNonce

* Send hashed nonces in authentication requests

* Encrypt the CSRF cookie

* Add clarity to naming & add more helper methods

* Make CSRF an interface and keep underlying nonces private

* Add ReverseProxy scope to cookie tests

* Align to new 1.16 SameSite cookie default

* Perform SecretBytes conversion on CSRF cookie crypto

* Make state encoding signatures consistent

* Mock time in CSRF struct via Clock

* Improve InsecureSkipNonce docstring
2021-04-21 10:33:27 +01:00

38 lines
964 B
Go

package encryption
import (
"crypto/hmac"
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/blake2b"
)
// Nonce generates a random 32-byte slice to be used as a nonce
func Nonce() ([]byte, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
// HashNonce returns the BLAKE2b 256-bit hash of a nonce
// NOTE: Error checking (G104) is purposefully skipped:
// - `blake2b.New256` has no error path with a nil signing key
// - `hash.Hash` interface's `Write` has an error signature, but
// `blake2b.digest.Write` does not use it.
/* #nosec G104 */
func HashNonce(nonce []byte) string {
hasher, _ := blake2b.New256(nil)
hasher.Write(nonce)
sum := hasher.Sum(nil)
return base64.RawURLEncoding.EncodeToString(sum)
}
// CheckNonce tests if a nonce matches the hashed version of it
func CheckNonce(nonce []byte, hashed string) bool {
return hmac.Equal([]byte(HashNonce(nonce)), []byte(hashed))
}