forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mw_hmac.go
333 lines (275 loc) · 8.52 KB
/
mw_hmac.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"math"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/TykTechnologies/tyk/apidef"
)
const dateHeaderSpec = "Date"
const altHeaderSpec = "x-aux-date"
// HMACMiddleware will check if the request has a signature, and if the request is allowed through
type HMACMiddleware struct {
*BaseMiddleware
lowercasePattern *regexp.Regexp
}
func (hm *HMACMiddleware) GetName() string {
return "HMAC"
}
func (hm *HMACMiddleware) Init() {
hm.lowercasePattern = regexp.MustCompile(`%[a-f0-9][a-f0-9]`)
}
func (hm *HMACMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
token := r.Header.Get("Authorization")
if token == "" {
return hm.authorizationError(r)
}
// Clean it
token = stripSignature(token)
log.Debug(token)
// Separate out the field values
fieldValues, err := getFieldValues(token)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": err,
"header": token,
}).Error("Field extraction failed")
return hm.authorizationError(r)
}
// Generate a signature string
signatureString, err := generateHMACSignatureStringFromRequest(r, fieldValues)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": err,
"signature_string": signatureString,
}).Error("Signature string generation failed")
return hm.authorizationError(r)
}
// Get a session for the Key ID
secret, session, err := hm.getSecretAndSessionForKeyID(fieldValues.KeyID)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": err,
"keyID": fieldValues.KeyID,
}).Error("No HMAC secret for this key")
return hm.authorizationError(r)
}
// Create a signed string with the secret
encodedSignature := generateEncodedSignature(signatureString, secret)
// Compare
matchPass := false
if encodedSignature == fieldValues.Signature {
matchPass = true
}
// Check for lower case encoding (.Net issues, again)
if !matchPass {
isLower, lowerList := hm.hasLowerCaseEscaped(fieldValues.Signature)
if isLower {
log.Debug("--- Detected lower case encoding! ---")
upperedSignature := hm.replaceWithUpperCase(fieldValues.Signature, lowerList)
if encodedSignature == upperedSignature {
matchPass = true
encodedSignature = upperedSignature
}
}
}
if !matchPass {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"expected": encodedSignature,
"got": fieldValues.Signature,
}).Error("Signature string does not match!")
return hm.authorizationError(r)
}
// Check clock skew
_, dateVal := getDateHeader(r)
if !hm.checkClockSkew(dateVal) {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Error("Clock skew outside of acceptable bounds")
return hm.authorizationError(r)
}
// Set session state on context, we will need it later
switch hm.Spec.BaseIdentityProvidedBy {
case apidef.HMACKey, apidef.UnsetAuth:
ctxSetSession(r, &session)
ctxSetAuthToken(r, fieldValues.KeyID)
hm.setContextVars(r, fieldValues.KeyID)
}
// Everything seems in order let the request through
return nil, 200
}
func stripSignature(token string) string {
token = strings.TrimPrefix(token, "Signature")
token = strings.TrimPrefix(token, "signature")
return strings.TrimSpace(token)
}
func (hm *HMACMiddleware) hasLowerCaseEscaped(signature string) (bool, []string) {
foundList := hm.lowercasePattern.FindAllString(signature, -1)
return len(foundList) > 0, foundList
}
func (hm *HMACMiddleware) replaceWithUpperCase(originalSignature string, lowercaseList []string) string {
newSignature := originalSignature
for _, lStr := range lowercaseList {
asUpper := strings.ToUpper(lStr)
newSignature = strings.Replace(newSignature, lStr, asUpper, -1)
}
return newSignature
}
func (hm *HMACMiddleware) setContextVars(r *http.Request, token string) {
if !hm.Spec.EnableContextVars {
return
}
// Flatten claims and add to context
if cnt := ctxGetData(r); cnt != nil {
// Key data
cnt["token"] = token
ctxSetData(r, cnt)
}
}
func (hm *HMACMiddleware) authorizationError(r *http.Request) (error, int) {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Authorization field missing or malformed")
return errors.New("Authorization field missing, malformed or invalid"), 400
}
func (hm HMACMiddleware) checkClockSkew(dateHeaderValue string) bool {
// Reference layout for parsing time: "Mon Jan 2 15:04:05 MST 2006"
refDate := "Mon, 02 Jan 2006 15:04:05 MST"
tim, err := time.Parse(refDate, dateHeaderValue)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"date_string": tim,
}).Error("Date parsing failed")
return false
}
inSec := tim.UnixNano()
now := time.Now().UnixNano()
diff := now - inSec
in_ms := diff / 1000000
if hm.Spec.HmacAllowedClockSkew <= 0 {
return true
}
if math.Abs(float64(in_ms)) > hm.Spec.HmacAllowedClockSkew {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Debug("Difference is: ", math.Abs(float64(in_ms)))
return false
}
return true
}
type HMACFieldValues struct {
KeyID string
Algorthm string
Headers []string
Signature string
}
func (hm *HMACMiddleware) getSecretAndSessionForKeyID(keyId string) (string, SessionState, error) {
session, keyExists := hm.CheckSessionAndIdentityForValidKey(keyId)
if !keyExists {
return "", session, errors.New("Key ID does not exist")
}
if session.HmacSecret == "" || !session.HMACEnabled {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Info("API Requires HMAC signature, session missing HMACSecret or HMAC not enabled for key")
return "", session, errors.New("This key ID is invalid")
}
return session.HmacSecret, session, nil
}
func getDateHeader(r *http.Request) (string, string) {
auxHeaderVal := r.Header.Get(altHeaderSpec)
// Prefer aux if present
if auxHeaderVal != "" {
token := r.Header.Get("Authorization")
log.WithFields(logrus.Fields{
"prefix": "hmac",
"auth_header": token,
}).Warning("Using auxiliary header for this request")
return strings.ToLower(altHeaderSpec), auxHeaderVal
}
dateHeaderVal := r.Header.Get(dateHeaderSpec)
if dateHeaderVal != "" {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Debug("Got date header")
return strings.ToLower(dateHeaderSpec), dateHeaderVal
}
return "", ""
}
func getFieldValues(authHeader string) (*HMACFieldValues, error) {
set := HMACFieldValues{}
for _, element := range strings.Split(authHeader, ",") {
kv := strings.Split(element, "=")
if len(kv) != 2 {
return nil, errors.New("Header field value malformed (need two elements in field)")
}
key := strings.ToLower(kv[0])
value := strings.Trim(kv[1], `"`)
switch key {
case "keyid":
set.KeyID = value
case "algorithm":
set.Algorthm = value
case "headers":
set.Headers = strings.Split(value, " ")
case "signature":
set.Signature = value
default:
log.WithFields(logrus.Fields{
"prefix": "hmac",
"field": kv[0],
}).Warning("Invalid header field found")
return nil, errors.New("Header key is not valid, not in allowed parameter list")
}
}
// Date is the absolute minimum header set
if len(set.Headers) == 0 {
set.Headers = append(set.Headers, "date")
}
return &set, nil
}
// "Signature keyId="9876",algorithm="hmac-sha1",headers="x-test x-test-2",signature="queryEscape(base64(sig))"")
func generateHMACSignatureStringFromRequest(r *http.Request, fieldValues *HMACFieldValues) (string, error) {
signatureString := ""
for i, header := range fieldValues.Headers {
loweredHeader := strings.TrimSpace(strings.ToLower(header))
if loweredHeader == "(request-target)" {
requestHeaderField := "(request-target): " + strings.ToLower(r.Method) + " " + r.URL.Path
signatureString += requestHeaderField
} else {
// exception for dates and .Net oddness
headerVal := r.Header.Get(loweredHeader)
if loweredHeader == "date" {
loweredHeader, headerVal = getDateHeader(r)
}
headerField := strings.TrimSpace(loweredHeader) + ": " + strings.TrimSpace(headerVal)
signatureString += headerField
}
if i != len(fieldValues.Headers)-1 {
signatureString += "\n"
}
}
log.Debug("Generated sig string: ", signatureString)
return signatureString, nil
}
func generateEncodedSignature(signatureString, secret string) string {
key := []byte(secret)
h := hmac.New(sha1.New, key)
h.Write([]byte(signatureString))
encodedString := base64.StdEncoding.EncodeToString(h.Sum(nil))
return url.QueryEscape(encodedString)
}