-
Notifications
You must be signed in to change notification settings - Fork 149
/
auth_middleware.go
316 lines (255 loc) · 7.89 KB
/
auth_middleware.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
package s3
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"html/template"
"net/http"
"sort"
"strings"
"time"
"github.com/minio/minio-go/v7/pkg/s3utils"
)
// Signature and API related constants.
const (
unsignedPayload = "UNSIGNED-PAYLOAD"
signV4Algorithm = "AWS4-HMAC-SHA256"
iso8601DateFormat = "20060102T150405Z"
yyyymmdd = "20060102"
)
type credential struct {
AccessKeyID string
Time string
Location string
Service string
Request string
}
func parseCredential(str string) (credential, error) {
parts := strings.Split(str, "/")
if len(parts) != 5 {
return credential{}, fmt.Errorf("invalid credential format")
}
return credential{
AccessKeyID: parts[0],
Time: parts[1],
Location: parts[2],
Service: parts[3],
Request: parts[4],
}, nil
}
func AuthMiddleware(accessKeyID, secretAccessKey string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, rq *http.Request) {
if err := verifySignature(*rq, accessKeyID, secretAccessKey); err != nil {
authorizedError(w, err)
return
}
handler.ServeHTTP(w, rq)
})
}
func authorizedError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusUnauthorized)
w.Header().Set("Content-Type", "application/xml")
if err := template.Must(template.New("xml").Parse(`<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>Unauthorized</Code>
<Message>{{ .Error }} </Message>
</Error>`)).Execute(w, map[string]string{"Error": err.Error()}); err != nil {
return
}
}
// sum256 calculate sha256 sum for an input byte array.
func sum256(data []byte) []byte {
hash := sha256.New()
hash.Write(data)
return hash.Sum(nil)
}
// sumHMAC calculate hmac between two input byte array.
func sumHMAC(key []byte, data []byte) []byte {
hash := hmac.New(sha256.New, key)
hash.Write(data)
return hash.Sum(nil)
}
func getHashedPayload(req http.Request) string {
hashedPayload := req.Header.Get("X-Amz-Content-Sha256")
if hashedPayload == "" {
// Presign does not have a payload, use S3 recommended value.
hashedPayload = unsignedPayload
}
return hashedPayload
}
func headerExists(key string, headers []string) bool {
for _, k := range headers {
if k == key {
return true
}
}
return false
}
// getHostAddr returns host header if available, otherwise returns host from URL
func getHostAddr(req *http.Request) string {
host := req.Header.Get("host")
if host != "" && req.Host != host {
return host
}
if req.Host != "" {
return req.Host
}
return req.URL.Host
}
// Trim leading and trailing spaces and replace sequential spaces with one space, following Trimall()
// in http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
func signV4TrimAll(input string) string {
// Compress adjacent spaces (a space is determined by
// unicode.IsSpace() internally here) to one space and return
return strings.Join(strings.Fields(input), " ")
}
func getCanonicalHeaders(req http.Request, signedHeaders string) string {
headers := []string{}
vals := make(map[string][]string)
for _, k := range strings.Split(signedHeaders, ";") {
lk := strings.ToLower(k)
headers = append(headers, lk)
vals[lk] = req.Header.Values(k)
}
if !headerExists("host", headers) {
headers = append(headers, "host")
}
sort.Strings(headers)
var buf bytes.Buffer
// Save all the headers in canonical form <header>:<value> newline
// separated for each header.
for _, k := range headers {
buf.WriteString(k)
buf.WriteByte(':')
switch {
case k == "host":
buf.WriteString(getHostAddr(&req))
buf.WriteByte('\n')
default:
for idx, v := range vals[k] {
if idx > 0 {
buf.WriteByte(',')
}
buf.WriteString(signV4TrimAll(v))
}
buf.WriteByte('\n')
}
}
return buf.String()
}
// getSigningKey hmac seed to calculate final signature.
func getSigningKey(secret, loc string, t time.Time, serviceType string) []byte {
date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
location := sumHMAC(date, []byte(loc))
service := sumHMAC(location, []byte(serviceType))
signingKey := sumHMAC(service, []byte("aws4_request"))
return signingKey
}
// getSignature final signature in hexadecimal form.
func getSignature(signingKey []byte, stringToSign string) string {
return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
}
// getScope generate a string of a specific date, an AWS region, and a
// service.
func getScope(location string, t time.Time, serviceType string) string {
scope := strings.Join([]string{
t.Format(yyyymmdd),
location,
serviceType,
"aws4_request",
}, "/")
return scope
}
// getCredential generate a credential string.
func getCredential(accessKeyID, location string, t time.Time, serviceType string) string {
scope := getScope(location, t, serviceType)
return accessKeyID + "/" + scope
}
// getCanonicalRequest generate a canonical request of style.
//
// canonicalRequest =
//
// <HTTPMethod>\n
// <CanonicalURI>\n
// <CanonicalQueryString>\n
// <CanonicalHeaders>\n
// <SignedHeaders>\n
// <HashedPayload>
func getCanonicalRequest(req http.Request, signedHeaders string, hashedPayload string) string {
req.URL.RawQuery = strings.ReplaceAll(req.URL.Query().Encode(), "+", "%20")
canonicalRequest := strings.Join([]string{
req.Method,
s3utils.EncodePath(req.URL.Path),
req.URL.RawQuery,
getCanonicalHeaders(req, signedHeaders),
signedHeaders,
hashedPayload,
}, "\n")
return canonicalRequest
}
// getStringToSignV4 a string based on selected query values.
func getStringToSignV4(t time.Time, location, canonicalRequest, serviceType string) string {
stringToSign := signV4Algorithm + "\n" + t.Format(iso8601DateFormat) + "\n"
stringToSign = stringToSign + getScope(location, t, serviceType) + "\n"
stringToSign += hex.EncodeToString(sum256([]byte(canonicalRequest)))
return stringToSign
}
// verifySignature - verify signature for S3 version '4'
func verifySignature(req http.Request, accessKeyID string, secretAccessKey string) error {
auth := req.Header.Get("Authorization")
if auth == "" {
return fmt.Errorf("header Authorization is missing")
}
auth = strings.TrimPrefix(auth, signV4Algorithm+" ")
parts := strings.Split(auth, ", ")
if len(parts) != 3 {
return fmt.Errorf("invalid Authorization header")
}
credentialPart := strings.SplitN(parts[0], "=", 2)
if len(credentialPart) != 2 {
return fmt.Errorf("invalid Authorization header")
}
credentialStr := credentialPart[1]
signedHeadersPart := strings.SplitN(parts[1], "=", 2)
if len(signedHeadersPart) != 2 {
return fmt.Errorf("invalid Authorization header")
}
signedHeaders := signedHeadersPart[1]
parsedSignaturePart := strings.SplitN(parts[2], "=", 2)
if len(parsedSignaturePart) != 2 {
return fmt.Errorf("invalid Authorization header")
}
parsedSignature := parsedSignaturePart[1]
hashedPayload := getHashedPayload(req)
amzDate := req.Header.Get("X-Amz-Date")
if amzDate == "" {
return fmt.Errorf("header X-Amz-Date is missing")
}
t, err := time.Parse(iso8601DateFormat, amzDate)
if err != nil {
return err
}
credential, err := parseCredential(credentialStr)
if err != nil {
return err
}
// Get canonical request
canonicalRequest := getCanonicalRequest(req, signedHeaders, hashedPayload)
// Get string to sign from canonical request.
stringToSign := getStringToSignV4(t, credential.Location, canonicalRequest, credential.Service)
// Get hmac signing key.
signingKey := getSigningKey(secretAccessKey, credential.Location, t, credential.Service)
// Get credential string.
computedCredential := getCredential(accessKeyID, credential.Location, t, credential.Service)
// Calculate parsedSignature.
computedSignature := getSignature(signingKey, stringToSign)
if computedCredential != credentialStr {
return fmt.Errorf("access denied: credential does not match")
}
if computedSignature != parsedSignature {
return fmt.Errorf("access denied: signature does not match")
}
return nil
}