forked from ory/fosite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signed_hmacsha.go
206 lines (161 loc) · 5.53 KB
/
signed_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
206
package hmac
import (
"crypto/hmac"
"crypto/rsa"
"crypto/sha512"
"fmt"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/kalrashubham49/fosite"
signingutils "github.com/kalrashubham49/fosite/signing_utils"
)
// HMACStrategy is responsible for generating and validating challenges.
type HMACStrategy struct {
TokenEntropy int
GlobalSecret []byte
RotatedGlobalSecrets [][]byte
PrivateKey *rsa.PrivateKey
sync.Mutex
}
// 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() (string, string, error) {
c.Lock()
defer c.Unlock()
if c.PrivateKey == nil {
return "", "", errors.Errorf("No Private Key Found")
}
if len(c.GlobalSecret) < minimumSecretLength {
return "", "", errors.Errorf("secret for signing HMAC-SHA256 is expected to be 32 byte long, got %d byte", len(c.GlobalSecret))
}
var signingKey [32]byte
copy(signingKey[:], c.GlobalSecret)
if c.TokenEntropy < minimumEntropy {
c.TokenEntropy = 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(c.TokenEntropy)
if err != nil {
return "", "", errors.WithStack(err)
}
signature := generateHMAC(tokenKey, &signingKey)
expiryTime := time.Now().Add(3600).UTC().Unix()
expiryTimeString := fmt.Sprintf("%v", expiryTime)
token := fmt.Sprintf("%s.%s.%s", string(tokenKey), expiryTimeString, string(signature))
encodedToken := b64.EncodeToString([]byte(token))
// Sign The Encoded token and Generate signature
signedSignature, err := signingutils.SignToken(encodedToken, c.PrivateKey)
if err != nil {
return "", "", errors.WithStack(err)
}
// Use Signing Utils to Sign the Encoded Token
encodedSignatureString := b64.EncodeToString(signedSignature)
signedToken := fmt.Sprintf("%s.%s", encodedToken, encodedSignatureString)
return signedToken, encodedSignatureString, nil
}
// Validate validates a token and returns its signature or an error if the token is not valid.
func (c *HMACStrategy) Validate(token string) (err error) {
var keys [][]byte
if len(c.GlobalSecret) > 0 {
keys = append(keys, c.GlobalSecret)
}
if len(c.RotatedGlobalSecrets) > 0 {
keys = append(keys, c.RotatedGlobalSecrets...)
}
for _, key := range keys {
if err = c.validate(key, token); err == nil {
return nil
} else if errors.Cause(err) == fosite.ErrTokenSignatureMismatch {
} else {
return err
}
}
if err == nil {
return errors.New("a secret for signing HMAC-SHA256 is expected to be defined, but none were")
}
return err
}
func (c *HMACStrategy) validate(secret []byte, token string) error {
if len(secret) < minimumSecretLength {
return errors.Errorf("secret for signing HMAC-SHA256 is expected to be 32 byte long, got %d byte", len(secret))
}
var signingKey [32]byte
copy(signingKey[:], secret)
split := strings.Split(token, ".")
if len(split) != 2 {
return errors.WithStack(fosite.ErrInvalidTokenFormat)
}
tokenKey := split[0]
tokenSignature := split[1]
if tokenKey == "" || tokenSignature == "" {
return errors.WithStack(fosite.ErrInvalidTokenFormat)
}
decodedTokenSignature, err := b64.DecodeString(tokenSignature)
if err != nil {
return errors.WithStack(err)
}
return signingutils.VerifySigning(&c.PrivateKey.PublicKey, token, decodedTokenSignature)
// decodedTokenKey, err := b64.DecodeString(tokenKey)
// if err != nil {
// return errors.WithStack(err)
// }
// // CHECK WITH LOKESH SIR======================
// // TODO: If verifier successfuly , do we still need to generate HMAC anc Check
// expectedMAC := generateHMAC(decodedTokenKey, &signingKey)
// if !hmac.Equal(expectedMAC, decodedTokenSignature) {
// // Hash is invalid
// return errors.WithStack(fosite.ErrTokenSignatureMismatch)
// }
// return nil
}
//Signature - Return Signature Out of HmacToken
func (c *HMACStrategy) Signature(token string) string {
split := strings.Split(token, ".")
// Changed Characters Limit to 3 , As we have added Expiry Time to Encoded Key
if len(split) != 2 {
return ""
}
return split[1]
}
//Valid - Check for Expiry of HMAC Token
func (c *HMACStrategy) Valid(token string) bool {
expiry, err := c.GetExpirationTime(token)
if err != nil {
return false
}
isExpired := time.Now().UTC().After(expiry)
// Returning Expiry Status of Token
return !isExpired
}
//GetExpirationTime - Get Expiration Time from Token in UTC
func (c *HMACStrategy) GetExpirationTime(token string) (time.Time, error) {
components := strings.Split(token, ".")
if len(components) != 2 {
return time.Now(), errors.New("Invalid Token")
}
encodedToken := components[0]
tokenData, err := b64.DecodeString(encodedToken)
if err != nil {
return time.Now(), errors.New("Invalid Token")
}
tokenString := string(tokenData)
tokenComponents := strings.Split(tokenString, ".")
expiry, err := time.Parse(time.Stamp, tokenComponents[1])
if err != nil {
return time.Now(), errors.New("Invalid Token")
}
return expiry, nil
}
func GenerateSignedHMAC(data []byte, key *[32]byte) []byte {
h := hmac.New(sha512.New512_256, key[:])
h.Write(data)
return h.Sum(nil)
}