@@ -2,19 +2,16 @@ package encryption
22
33import (
44 "crypto/hmac"
5− "crypto/rand"
5+ // TODO (@NickMeves): Remove SHA1 signed cookie support in V7
66 "crypto/sha1" // #nosec G505
77 "crypto/sha256"
88 "encoding/base64"
99 "fmt"
1010 "hash"
11− "io"
1211 "net/http"
1312 "strconv"
1413 "strings"
1514 "time"
16−
17− "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
1815)
1916
2017// SecretBytes attempts to base64 decode the secret, if that fails it treats the secret as binary
@@ -69,40 +66,44 @@ func Validate(cookie *http.Cookie, seed string, expiration time.Duration) (value
6966}
7067
7168// SignedValue returns a cookie that is signed and can later be checked with Validate
72−func SignedValue(seed string, key string, value []byte, now time.Time) string {
69+func SignedValue(seed string, key string, value []byte, now time.Time) (string, error) {
7370 encodedValue := base64.URLEncoding.EncodeToString(value)
7471 timeStr := fmt.Sprintf("%d", now.Unix())
75− sig := cookieSignature(sha256.New, seed, key, encodedValue, timeStr)
72+ sig, err := cookieSignature(sha256.New, seed, key, encodedValue, timeStr)
73+ if err != nil {
74+ return "", err
75+ }
7676 cookieVal := fmt.Sprintf("%s|%s|%s", encodedValue, timeStr, sig)
77− return cookieVal
77+ return cookieVal, nil
7878}
7979
80−func cookieSignature(signer func() hash.Hash, args ...string) string {
80+func cookieSignature(signer func() hash.Hash, args ...string) (string, error) {
8181 h := hmac.New(signer, []byte(args[0]))
8282 for _, arg := range args[1:] {
8383 _, err := h.Write([]byte(arg))
84− // If signing fails, fail closed and return something that won't validate
8584 if err != nil {
86− garbage := make([]byte, 16)
87− if _, err := io.ReadFull(rand.Reader, garbage); err != nil {
88− logger.Fatal("HMAC & RNG functions both failing. Shutting down for security")
89− }
90− return base64.URLEncoding.EncodeToString(garbage)
85+ return "", err
9186 }
9287 }
9388 var b []byte
9489 b = h.Sum(b)
95− return base64.URLEncoding.EncodeToString(b)
90+ return base64.URLEncoding.EncodeToString(b), nil
9691}
9792
9893func checkSignature(signature string, args ...string) bool {
99− checkSig := cookieSignature(sha256.New, args...)
94+ checkSig, err := cookieSignature(sha256.New, args...)
95+ if err != nil {
96+ return false
97+ }
10098 if checkHmac(signature, checkSig) {
10199 return true
102100 }
103101
104− // TODO: After appropriate rollout window, remove support for SHA1
105− legacySig := cookieSignature(sha1.New, args...)
102+ // TODO (@NickMeves): Remove SHA1 signed cookie support in V7
103+ legacySig, err := cookieSignature(sha1.New, args...)
104+ if err != nil {
105+ return false
106+ }
106107 return checkHmac(signature, legacySig)
107108}
108109