-
Notifications
You must be signed in to change notification settings - Fork 3
/
hmacsha.go
205 lines (162 loc) · 5.31 KB
/
hmacsha.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
// Package hmac is the default implementation for generating and validating challenges. It uses SHA-512/256 to
// generate and validate challenges.
package hmac
import (
"context"
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"fmt"
"strings"
"sync"
"github.com/pkg/errors"
"authelia.com/provider/oauth2"
"authelia.com/provider/oauth2/x/errorsx"
)
type HMACStrategyConfigurator interface {
oauth2.TokenEntropyProvider
oauth2.GlobalSecretProvider
oauth2.RotatedGlobalSecretsProvider
oauth2.HMACHashingProvider
}
// HMACStrategy is responsible for generating and validating challenges.
type HMACStrategy struct {
sync.Mutex
Config HMACStrategyConfigurator
}
const (
// key should be at least 256 bit long, making it
minimumEntropy int = 32
// the secrets (client and global) should each have at least 16 characters making it harder to guess them
minimumSecretLength = 32
)
var b64 = base64.URLEncoding.WithPadding(base64.NoPadding)
// Generate generates a token and a matching signature or returns an error.
// This method implements rfc6819 Section 5.1.4.2.2: Use High Entropy for Secrets.
func (c *HMACStrategy) Generate(ctx context.Context) (string, string, error) {
c.Lock()
defer c.Unlock()
secret, err := c.Config.GetGlobalSecret(ctx)
if err != nil {
return "", "", err
}
if len(secret) < minimumSecretLength {
return "", "", errors.Errorf("secret for signing HMAC-SHA512/256 is expected to be 32 byte long, got %d byte", len(secret))
}
var signingKey [32]byte
copy(signingKey[:], secret)
entropy := c.Config.GetTokenEntropy(ctx)
if entropy < minimumEntropy {
entropy = minimumEntropy
}
// When creating secrets not intended for usage by human users (e.g.,
// client secrets or token handles), the authorization server should
// include a reasonable level of entropy in order to mitigate the risk
// of guessing attacks. The token value should be >=128 bits long and
// constructed from a cryptographically strong random or pseudo-random
// number sequence (see [RFC4086] for best current practice) generated
// by the authorization server.
tokenKey, err := RandomBytes(entropy)
if err != nil {
return "", "", errorsx.WithStack(err)
}
signature := c.generateHMAC(ctx, tokenKey, &signingKey)
encodedSignature := b64.EncodeToString(signature)
encodedToken := fmt.Sprintf("%s.%s", b64.EncodeToString(tokenKey), encodedSignature)
return encodedToken, encodedSignature, nil
}
func (c *HMACStrategy) GenerateHMACForString(ctx context.Context, text string) (string, error) {
var signingKey [32]byte
secrets, err := c.Config.GetGlobalSecret(ctx)
if err != nil {
return "", err
}
if len(secrets) < minimumSecretLength {
return "", errors.Errorf("secret for signing HMAC-SHA512/256 is expected to be 32 byte long, got %d byte", len(secrets))
}
copy(signingKey[:], secrets)
bytes := []byte(text)
hashBytes := c.generateHMAC(ctx, bytes, &signingKey)
b64 := base64.RawURLEncoding.EncodeToString(hashBytes)
return b64, nil
}
// Validate validates a token and returns its signature or an error if the token is not valid.
func (c *HMACStrategy) Validate(ctx context.Context, token string) (err error) {
var keys [][]byte
secrets, err := c.Config.GetGlobalSecret(ctx)
if err != nil {
return err
}
rotatedSecrets, err := c.Config.GetRotatedGlobalSecrets(ctx)
if err != nil {
return err
}
if len(secrets) > 0 {
keys = append(keys, secrets)
}
keys = append(keys, rotatedSecrets...)
for _, key := range keys {
if err = c.validate(ctx, key, token); err == nil {
return nil
} else if errors.Is(err, oauth2.ErrTokenSignatureMismatch) {
} else {
return err
}
}
if err == nil {
return errors.New("a secret for signing HMAC-SHA512/256 is expected to be defined, but none were")
}
return err
}
func (c *HMACStrategy) validate(ctx context.Context, secret []byte, token string) error {
if len(secret) < minimumSecretLength {
return errors.Errorf("secret for signing HMAC-SHA512/256 is expected to be 32 byte long, got %d byte", len(secret))
}
var signingKey [32]byte
copy(signingKey[:], secret)
split := strings.SplitN(token, ".", 3)
if len(split) != 2 {
return errorsx.WithStack(oauth2.ErrInvalidTokenFormat)
}
tokenKey := split[0]
tokenSignature := split[1]
if tokenKey == "" || tokenSignature == "" {
return errorsx.WithStack(oauth2.ErrInvalidTokenFormat)
}
decodedTokenSignature, err := b64.DecodeString(tokenSignature)
if err != nil {
return errorsx.WithStack(err)
}
decodedTokenKey, err := b64.DecodeString(tokenKey)
if err != nil {
return errorsx.WithStack(err)
}
expectedMAC := c.generateHMAC(ctx, decodedTokenKey, &signingKey)
if !hmac.Equal(expectedMAC, decodedTokenSignature) {
// Hash is invalid
return errorsx.WithStack(oauth2.ErrTokenSignatureMismatch)
}
return nil
}
func (c *HMACStrategy) Signature(token string) string {
split := strings.SplitN(token, ".", 3)
if len(split) != 2 {
return ""
}
return split[1]
}
func (c *HMACStrategy) generateHMAC(ctx context.Context, data []byte, key *[32]byte) []byte {
hasher := c.Config.GetHMACHasher(ctx)
if hasher == nil {
hasher = sha512.New512_256
}
h := hmac.New(hasher, key[:])
// sha512.digest.Write() always returns nil for err, the panic should never happen
_, err := h.Write(data)
if err != nil {
panic(err)
}
return h.Sum(nil)
}