forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_HMAC.go
324 lines (269 loc) · 8.89 KB
/
middleware_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
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"github.com/Sirupsen/logrus"
"github.com/gorilla/context"
"math"
"net/http"
"net/url"
"strings"
"time"
)
const DateHeaderSpec string = "Date"
const AltHeaderSpec string = "x-aux-date"
const HMACClockSkewLimitInMs float64 = 1000
// HMACMiddleware will check if the request has a signature, and if the request is allowed through
type HMACMiddleware struct {
*TykMiddleware
}
// New lets you do any initializations 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
}
func (hm *HMACMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
authHeaderValue := r.Header.Get("Authorization")
if authHeaderValue == "" {
return hm.authorizationError(w, r)
}
// Clean it
authHeaderValue = stripSignature(authHeaderValue)
log.Debug(authHeaderValue)
// Separate out the field values
fieldValues, fErr := getFieldValues(authHeaderValue)
if fErr != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": fErr,
"header": authHeaderValue,
}).Error("Field extraction failed")
return hm.authorizationError(w, r)
}
// Generate a signature string
signatureString, sErr := generateHMACSignatureStringFromRequest(r, fieldValues)
if sErr != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": fErr,
"signature_string": signatureString,
}).Error("Signature string generation failed")
return hm.authorizationError(w, r)
}
// Get a session for the Key ID
thisSecret, thisSessionState, keyError := hm.getSecretAndSessionForKeyID(fieldValues.KeyID)
if keyError != nil {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"error": keyError,
"keyID": fieldValues.KeyID,
}).Error("No HMAC secret for this key")
return hm.authorizationError(w, r)
}
// Create a signed string with the secret
encodedSignature := generateEncodedSignature(signatureString, thisSecret)
// Compare
if encodedSignature != fieldValues.Signature {
log.WithFields(logrus.Fields{
"prefix": "hmac",
"expected": encodedSignature,
"got": fieldValues.Signature,
}).Error("Signature string does not match!")
return hm.authorizationError(w, 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(w, r)
}
// Set session state on context, we will need it later
context.Set(r, SessionData, thisSessionState)
context.Set(r, AuthHeaderValue, fieldValues.KeyID)
hm.setContextVars(r, fieldValues.KeyID)
// Everything seems in order let the request through
return nil, 200
}
func (hm *HMACMiddleware) setContextVars(r *http.Request, token string) {
// Flatten claims and add to context
if hm.Spec.EnableContextVars {
cnt, contextFound := context.GetOk(r, ContextData)
var contextDataObject map[string]interface{}
if contextFound {
// Key data
contextDataObject = cnt.(map[string]interface{})
contextDataObject["token"] = token
context.Set(r, ContextData, contextDataObject)
}
}
}
func (hm *HMACMiddleware) authorizationError(w http.ResponseWriter, 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.TykMiddleware.Spec.HmacAllowedClockSkew <= 0 {
return true
}
if math.Abs(float64(in_ms)) > hm.TykMiddleware.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) {
thisSessionState, keyExists := hm.TykMiddleware.CheckSessionAndIdentityForValidKey(keyId)
if !keyExists {
return "", thisSessionState, errors.New("Key ID does not exist")
}
if thisSessionState.HmacSecret == "" || thisSessionState.HMACEnabled == false {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Info("API Requires HMAC signature, session missing HMACSecret or HMAC not enabled for key")
return "", thisSessionState, errors.New("This key ID is invalid")
}
return thisSessionState.HmacSecret, thisSessionState, nil
}
func getDateHeader(r *http.Request) (string, string) {
auxHeaderVal := r.Header.Get(AltHeaderSpec)
dateHeaderVal := r.Header.Get(DateHeaderSpec)
// Prefer aux if present
if auxHeaderVal != "" {
authHeaderValue := r.Header.Get("Authorization")
log.WithFields(logrus.Fields{
"prefix": "hmac",
"auth_header": authHeaderValue,
}).Warning("Using auxiliary header for this request")
return strings.ToLower(AltHeaderSpec), auxHeaderVal
}
if dateHeaderVal != "" {
log.WithFields(logrus.Fields{
"prefix": "hmac",
}).Debug("Got date header")
return strings.ToLower(DateHeaderSpec), dateHeaderVal
}
return "", ""
}
var validKeyHeaders map[string]bool = map[string]bool{
"keyid": true,
"algorithm": true,
"headers": true,
"signature": true,
}
func isHeaderFieldKeyValid(key string) bool {
_, found := validKeyHeaders[key]
return found
}
func getFieldValues(authHeader string) (*HMACFieldValues, error) {
AsElements := strings.Split(authHeader, ",")
thisSet := HMACFieldValues{}
for _, element := range AsElements {
kv := strings.Split(element, "=")
log.Debug("Checking: ", kv)
if len(kv) < 2 {
return nil, errors.New("Header field value malformed (less than two elements in field)")
}
if len(kv) > 2 {
return nil, errors.New("Header field value malformed (more than two elements in field)")
}
key := strings.ToLower(kv[0])
if !isHeaderFieldKeyValid(key) {
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")
}
value := kv[1]
value = strings.Trim(value, "\"")
switch key {
case "keyid":
thisSet.KeyID = value
case "algorithm":
thisSet.Algorthm = value
case "headers":
thisSet.Headers = strings.Split(value, " ")
case "signature":
thisSet.Signature = value
}
}
// Date is the absolute minimum header set
if len(thisSet.Headers) == 0 {
thisSet.Headers = append(thisSet.Headers, "date")
}
return &thisSet, 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 string, secret string) string {
key := []byte(secret)
h := hmac.New(sha1.New, key)
h.Write([]byte(signatureString))
encodedString := base64.StdEncoding.EncodeToString(h.Sum(nil))
encodedString = url.QueryEscape(encodedString)
return encodedString
}
func generateAuthHeaderValue(fieldValues *HMACFieldValues) string {
authHeaderString := "Signature "
authHeaderString += "keyId=" + fieldValues.KeyID + ","
authHeaderString += "algorithm=" + fieldValues.Algorthm + ","
if len(fieldValues.Headers) > 0 {
headers := strings.Join(fieldValues.Headers, " ")
authHeaderString += "headers=" + headers
}
authHeaderString += ", signature=" + fieldValues.Signature
return authHeaderString
}