forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_check_HMAC_signature.go
421 lines (357 loc) · 11.8 KB
/
middleware_check_HMAC_signature.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import "net/http"
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"math"
"net/url"
"sort"
"strings"
"time"
)
// Test key: 53ac07777cbb8c2d530000021a42331a43bd45555d5c923bdb36fc8a
// TODO: change these to real values
const DateHeaderSpec string = "Date"
const HMACClockSkewLimitInMs float64 = 300
// HMACMiddleware will check if the request has a signature, and if the request is allowed through
type HMACMiddleware struct {
TykMiddleware
}
func (hm *HMACMiddleware) authorizationError(w http.ResponseWriter, r *http.Request) (error, int) {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Authorization field missing or malformed")
return errors.New("Authorization field missing, malformed or invalid"), 400
}
// New lets you do any initialisations for the object can be done here
func (hm *HMACMiddleware) New() {}
// GetConfig retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (hm *HMACMiddleware) GetConfig() (interface{}, error) {
return nil, nil
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (hm *HMACMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
log.Debug("HMAC middleware activated")
authHeaderValue := r.Header.Get("Authorization")
if authHeaderValue == "" {
return hm.authorizationError(w, r)
}
log.Debug("Got auth header")
if r.Header.Get(DateHeaderSpec) == "" {
log.Debug("Date missing")
return hm.authorizationError(w, r)
}
isOutOftime := hm.checkClockSkew(r.Header.Get(DateHeaderSpec))
if isOutOftime == false {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Date is out of allowed range.")
handler := ErrorHandler{hm.TykMiddleware}
handler.HandleError(w, r, "Date is out of allowed range.", 400)
return errors.New("Date is out of allowed range."), 400
}
log.Debug("Got date")
// Extract the keyId:
splitTypes := strings.Split(authHeaderValue, " ")
if len(splitTypes) != 2 {
return hm.authorizationError(w, r)
}
log.Debug("Found two fields")
if strings.ToLower(splitTypes[0]) != "signature" {
return hm.authorizationError(w, r)
}
log.Debug("Found signature value field")
splitValues := strings.Split(splitTypes[1], ",")
if len(splitValues) != 3 {
log.Debug("Comma length is wrong - got: ", splitValues)
return hm.authorizationError(w, r)
}
log.Debug("Found 2 commas - getting elements of signature")
// extract the keyId, algorithm and signature
keyId := ""
algorithm := ""
signature := ""
for _, v := range splitValues {
splitKeyValuePair := strings.Split(v, "=")
if len(splitKeyValuePair) != 2 {
log.Debug("Equals length is wrong - got: ", splitKeyValuePair)
return hm.authorizationError(w, r)
}
if strings.ToLower(splitKeyValuePair[0]) == "keyid" {
keyId = strings.Trim(splitKeyValuePair[1], "\"")
}
if strings.ToLower(splitKeyValuePair[0]) == "algorithm" {
algorithm = strings.Trim(splitKeyValuePair[1], "\"")
}
if strings.ToLower(splitKeyValuePair[0]) == "signature" {
signature = strings.Trim(splitKeyValuePair[1], "\"")
}
}
log.Debug("Extracted values... checking validity")
// None may be empty
if keyId == "" || algorithm == "" || signature == "" {
return hm.authorizationError(w, r)
}
log.Debug("Key is valid: ", keyId)
log.Debug("algo is valid: ", algorithm)
log.Debug("signature isn't empty: ", signature)
// Check if API key valid
thisSessionState, keyExists :=hm.TykMiddleware.CheckSessionAndIdentityForValidKey(keyId)
if !keyExists {
return hm.authorizationError(w, r)
}
log.Debug("Found key in session store")
// Set session state on context, we will need it later
context.Set(r, SessionData, thisSessionState)
context.Set(r, AuthHeaderValue, keyId)
if thisSessionState.HmacSecret == "" || thisSessionState.HMACEnabled == false {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("API Requires HMAC signature, session missing HMACSecret or HMAC not enabled for key")
return errors.New("This key is invalid"), 400
}
log.Debug("Sessionstate is HMAC enabled")
ourSignature := hm.generateSignatureFromRequest(r, thisSessionState.HmacSecret)
log.Debug("Our Signature: ", ourSignature)
compareTo, err := url.QueryUnescape(signature)
if err != nil {
return hm.authorizationError(w, r)
}
log.Debug("Request Signature: ", compareTo)
if ourSignature != compareTo {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": r.RemoteAddr,
}).Info("Request signature is invalid")
// Fire Authfailed Event
AuthFailed(hm.TykMiddleware, r, keyId)
return errors.New("Request signature is invalid"), 400
}
log.Debug("Signature matches")
// Everything seems in order let the request through
return nil, 200
}
// New creates a new HttpHandler for the alice middleware package, key implementation is here https://web-payments.org/specs/ED/http-signatures/2014-02-01/
//func (hm HMACMiddleware) New() func(http.Handler) http.Handler {
// aliceHandler := func(h http.Handler) http.Handler {
// thisHandler := func(w http.ResponseWriter, r *http.Request) {
//
// log.Debug("HMAC middleware activated")
//
// authHeaderValue := r.Header.Get("Authorization")
// if authHeaderValue == "" {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Got auth header")
//
// if r.Header.Get(DateHeaderSpec) == "" {
// log.Debug("Date missing")
// hm.authorizationError(w, r)
// return
// }
//
// isOutOftime := hm.checkClockSkew(r.Header.Get(DateHeaderSpec))
// if isOutOftime == false {
// log.WithFields(logrus.Fields{
// "path": r.URL.Path,
// "origin": r.RemoteAddr,
// }).Info("Date is out of allowed range.")
//
// handler := ErrorHandler{hm.TykMiddleware}
// handler.HandleError(w, r, "Date is out of allowed range.", 400)
// return
// }
//
// log.Debug("Got date")
//
// // Extract the keyId:
// splitTypes := strings.Split(authHeaderValue, " ")
// if len(splitTypes) != 2 {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Found two fields")
//
// if strings.ToLower(splitTypes[0]) != "signature" {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Found signature value field")
//
// splitValues := strings.Split(splitTypes[1], ",")
// if len(splitValues) != 3 {
// log.Debug("Comma length is wrong - got: ", splitValues)
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Found 2 commas - getting elements of signature")
//
// // extract the keyId, algorithm and signature
// keyId := ""
// algorithm := ""
// signature := ""
// for _, v := range splitValues {
// splitKeyValuePair := strings.Split(v, "=")
// if len(splitKeyValuePair) != 2 {
// hm.authorizationError(w, r)
// log.Debug("Equals length is wrong - got: ", splitKeyValuePair)
// return
// }
// if strings.ToLower(splitKeyValuePair[0]) == "keyid" {
// keyId = strings.Trim(splitKeyValuePair[1], "\"")
// }
// if strings.ToLower(splitKeyValuePair[0]) == "algorithm" {
// algorithm = strings.Trim(splitKeyValuePair[1], "\"")
// }
// if strings.ToLower(splitKeyValuePair[0]) == "signature" {
// signature = strings.Trim(splitKeyValuePair[1], "\"")
// }
// }
//
// log.Debug("Extracted values... checking validity")
//
// // None may be empty
// if keyId == "" || algorithm == "" || signature == "" {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Key is valid: ", keyId)
// log.Debug("algo is valid: ", algorithm)
// log.Debug("signature isn't empty: ", signature)
//
// // Check if API key valid
// keyExists, thisSessionState := authManager.IsKeyAuthorised(keyId)
// if !keyExists {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Found key in session store")
//
// // Set session state on context, we will need it later
// context.Set(r, SessionData, thisSessionState)
// context.Set(r, AuthHeaderValue, keyId)
//
// if thisSessionState.HmacSecret == "" || thisSessionState.HMACEnabled == false {
// log.WithFields(logrus.Fields{
// "path": r.URL.Path,
// "origin": r.RemoteAddr,
// }).Info("API Requires HMAC signature, session missing HMACSecret or HMAC not enabled for key")
//
// handler := ErrorHandler{hm.TykMiddleware}
// handler.HandleError(w, r, "This key is invalid", 400)
// return
// }
//
// log.Debug("Sessionstate is HMAC enabled")
//
// ourSignature := hm.generateSignatureFromRequest(r, thisSessionState.HmacSecret)
// log.Debug("Our Signature: ", ourSignature)
//
// compareTo, err := url.QueryUnescape(signature)
//
// if err != nil {
// hm.authorizationError(w, r)
// return
// }
//
// log.Debug("Request Signature: ", compareTo)
// if ourSignature != compareTo {
// log.WithFields(logrus.Fields{
// "path": r.URL.Path,
// "origin": r.RemoteAddr,
// }).Info("Request signature is invalid")
//
// handler := ErrorHandler{hm.TykMiddleware}
// handler.HandleError(w, r, "Request signature is invalid", 400)
// return
// }
//
// log.Debug("Signature matches")
//
// // Everything seems in order let the request through
// h.ServeHTTP(w, r)
// }
// return http.HandlerFunc(thisHandler)
// }
// return aliceHandler
//}
func (hm HMACMiddleware) parseFormParams(values url.Values) string {
kvValues := map[string]string{}
keys := []string{}
log.Debug("Parsing header values")
for k, v := range values {
log.Debug("Form parser - processing key: ", k)
log.Debug("Form parser - processing value: ", v)
encodedKey := url.QueryEscape(k)
encodedVals := []string{}
for _, raw_value := range v {
encodedVals = append(encodedVals, url.QueryEscape(raw_value))
}
joined_vals := strings.Join(encodedVals, "|")
kvPair := encodedKey + "=" + joined_vals
kvValues[k] = kvPair
keys = append(keys, k)
}
// sort the keys in alphabetical order
sort.Strings(keys)
sortedKvs := []string{}
// Put the prepared key value params in order according to above sort
for _, sk := range keys {
sortedKvs = append(sortedKvs, kvValues[sk])
}
// Join the kv's up as per spec
prepared_params := strings.Join(sortedKvs, "&")
return prepared_params
}
// Generates our signature - based on: https://web-payments.org/specs/ED/http-signatures/2014-02-01/#page-3 HMAC signing
func (hm HMACMiddleware) generateSignatureFromRequest(r *http.Request, secret string) string {
//method := strings.ToUpper(r.Method)
//base_url := url.QueryEscape(r.URL.RequestURI())
date_header := url.QueryEscape(r.Header.Get(DateHeaderSpec))
// Not using form params for now, just date string
//params := url.QueryEscape(hm.parseFormParams(r.Form))
// Prep the signature string
signatureString := strings.ToLower(DateHeaderSpec) + ":" + date_header
log.Debug("Signature string before encoding: ", signatureString)
// Encode it
key := []byte(secret)
h := hmac.New(sha1.New, key)
h.Write([]byte(signatureString))
encodedString := base64.StdEncoding.EncodeToString(h.Sum(nil))
log.Debug("Encoded signature string: ", encodedString)
log.Debug("URL Encoded: ", url.QueryEscape(encodedString))
// Return as base64
return encodedString
}
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.Error("Date parsing failed")
return false
}
inSec := tim.UnixNano()
now := time.Now().UnixNano()
diff := now - inSec
in_ms := diff / 1000000
if math.Abs(float64(in_ms)) > HMACClockSkewLimitInMs {
log.Debug("Difference is: ", math.Abs(float64(in_ms)))
return false
}
return true
}