Debian Codegraph @

aws/signer/v4/v4.go

raw
1 // Package v4 implements signing for AWS V4 signer
2 //
3 // Provides request signing for request that need to be signed with
4 // AWS V4 Signatures.
5 //
6 // # Standalone Signer
7 //
8 // Generally using the signer outside of the SDK should not require any additional
9 // logic when using Go v1.5 or higher. The signer does this by taking advantage
10 // of the URL.EscapedPath method. If your request URI requires additional escaping
11 // you may need to use the URL.Opaque to define what the raw URI should be sent
12 // to the service as.
13 //
14 // The signer will first check the URL.Opaque field, and use its value if set.
15 // The signer does require the URL.Opaque field to be set in the form of:
16 //
17 // "//<hostname>/<path>"
18 //
19 // // e.g.
20 // "//example.com/some/path"
21 //
22 // The leading "//" and hostname are required or the URL.Opaque escaping will
23 // not work correctly.
24 //
25 // If URL.Opaque is not set the signer will fallback to the URL.EscapedPath()
26 // method and using the returned value. If you're using Go v1.4 you must set
27 // URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with
28 // Go v1.5 the signer will fallback to URL.Path.
29 //
30 // AWS v4 signature validation requires that the canonical string's URI path
31 // element must be the URI escaped form of the HTTP request's path.
32 // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
33 //
34 // The Go HTTP client will perform escaping automatically on the request. Some
35 // of these escaping may cause signature validation errors because the HTTP
36 // request differs from the URI path or query that the signature was generated.
37 // https://golang.org/pkg/net/url/#URL.EscapedPath
38 //
39 // Because of this, it is recommended that when using the signer outside of the
40 // SDK that explicitly escaping the request prior to being signed is preferable,
41 // and will help prevent signature validation errors. This can be done by setting
42 // the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then
43 // call URL.EscapedPath() if Opaque is not set.
44 //
45 // If signing a request intended for HTTP2 server, and you're using Go 1.6.2
46 // through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the
47 // request URL. https://github.com/golang/go/issues/16847 points to a bug in
48 // Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP
49 // message. URL.Opaque generally will force Go to make requests with absolute URL.
50 // URL.RawPath does not do this, but RawPath must be a valid escaping of Path
51 // or url.EscapedPath will ignore the RawPath escaping.
52 //
53 // Test `TestStandaloneSign` provides a complete example of using the signer
54 // outside of the SDK and pre-escaping the URI path.
55 package v4
56
57 import (
58 "crypto/hmac"
59 "crypto/sha256"
60 "encoding/hex"
61 "fmt"
62 "io"
63 "io/ioutil"
64 "net/http"
65 "net/url"
66 "sort"
67 "strconv"
68 "strings"
69 "time"
70
71 "github.com/aws/aws-sdk-go/aws"
72 "github.com/aws/aws-sdk-go/aws/credentials"
73 "github.com/aws/aws-sdk-go/aws/request"
74 "github.com/aws/aws-sdk-go/internal/sdkio"
75 "github.com/aws/aws-sdk-go/private/protocol/rest"
76 )
77
78 const (
79 authorizationHeader = "Authorization"
80 authHeaderSignatureElem = "Signature="
81 signatureQueryKey = "X-Amz-Signature"
82
83 authHeaderPrefix = "AWS4-HMAC-SHA256"
84 timeFormat = "20060102T150405Z"
85 shortTimeFormat = "20060102"
86 awsV4Request = "aws4_request"
87
88 // emptyStringSHA256 is a SHA256 of an empty string
89 emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`
90 )
91
92 var ignoredHeaders = rules{
93 excludeList{
94 mapRule{
95 authorizationHeader: struct{}{},
96 "User-Agent": struct{}{},
97 "X-Amzn-Trace-Id": struct{}{},
98 },
99 },
100 }
101
102 // requiredSignedHeaders is a allow list for build canonical headers.
103 var requiredSignedHeaders = rules{
104 allowList{
105 mapRule{
106 "Cache-Control": struct{}{},
107 "Content-Disposition": struct{}{},
108 "Content-Encoding": struct{}{},
109 "Content-Language": struct{}{},
110 "Content-Md5": struct{}{},
111 "Content-Type": struct{}{},
112 "Expires": struct{}{},
113 "If-Match": struct{}{},
114 "If-Modified-Since": struct{}{},
115 "If-None-Match": struct{}{},
116 "If-Unmodified-Since": struct{}{},
117 "Range": struct{}{},
118 "X-Amz-Acl": struct{}{},
119 "X-Amz-Copy-Source": struct{}{},
120 "X-Amz-Copy-Source-If-Match": struct{}{},
121 "X-Amz-Copy-Source-If-Modified-Since": struct{}{},
122 "X-Amz-Copy-Source-If-None-Match": struct{}{},
123 "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{},
124 "X-Amz-Copy-Source-Range": struct{}{},
125 "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{},
126 "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{},
127 "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{},
128 "X-Amz-Expected-Bucket-Owner": struct{}{},
129 "X-Amz-Grant-Full-control": struct{}{},
130 "X-Amz-Grant-Read": struct{}{},
131 "X-Amz-Grant-Read-Acp": struct{}{},
132 "X-Amz-Grant-Write": struct{}{},
133 "X-Amz-Grant-Write-Acp": struct{}{},
134 "X-Amz-Metadata-Directive": struct{}{},
135 "X-Amz-Mfa": struct{}{},
136 "X-Amz-Request-Payer": struct{}{},
137 "X-Amz-Server-Side-Encryption": struct{}{},
138 "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{},
139 "X-Amz-Server-Side-Encryption-Context": struct{}{},
140 "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{},
141 "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{},
142 "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{},
143 "X-Amz-Storage-Class": struct{}{},
144 "X-Amz-Tagging": struct{}{},
145 "X-Amz-Website-Redirect-Location": struct{}{},
146 "X-Amz-Content-Sha256": struct{}{},
147 },
148 },
149 patterns{"X-Amz-Meta-"},
150 patterns{"X-Amz-Object-Lock-"},
151 }
152
153 // allowedHoisting is a allow list for build query headers. The boolean value
154 // represents whether or not it is a pattern.
155 var allowedQueryHoisting = inclusiveRules{
156 excludeList{requiredSignedHeaders},
157 patterns{"X-Amz-"},
158 }
159
160 // Signer applies AWS v4 signing to given request. Use this to sign requests
161 // that need to be signed with AWS V4 Signatures.
162 type Signer struct {
163 // The authentication credentials the request will be signed against.
164 // This value must be set to sign requests.
165 Credentials *credentials.Credentials
166
167 // Sets the log level the signer should use when reporting information to
168 // the logger. If the logger is nil nothing will be logged. See
169 // aws.LogLevelType for more information on available logging levels
170 //
171 // By default nothing will be logged.
172 Debug aws.LogLevelType
173
174 // The logger loging information will be written to. If there the logger
175 // is nil, nothing will be logged.
176 Logger aws.Logger
177
178 // Disables the Signer's moving HTTP header key/value pairs from the HTTP
179 // request header to the request's query string. This is most commonly used
180 // with pre-signed requests preventing headers from being added to the
181 // request's query string.
182 DisableHeaderHoisting bool
183
184 // Disables the automatic escaping of the URI path of the request for the
185 // siganture's canonical string's path. For services that do not need additional
186 // escaping then use this to disable the signer escaping the path.
187 //
188 // S3 is an example of a service that does not need additional escaping.
189 //
190 // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
191 DisableURIPathEscaping bool
192
193 // Disables the automatical setting of the HTTP request's Body field with the
194 // io.ReadSeeker passed in to the signer. This is useful if you're using a
195 // custom wrapper around the body for the io.ReadSeeker and want to preserve
196 // the Body value on the Request.Body.
197 //
198 // This does run the risk of signing a request with a body that will not be
199 // sent in the request. Need to ensure that the underlying data of the Body
200 // values are the same.
201 DisableRequestBodyOverwrite bool
202
203 // currentTimeFn returns the time value which represents the current time.
204 // This value should only be used for testing. If it is nil the default
205 // time.Now will be used.
206 currentTimeFn func() time.Time
207
208 // UnsignedPayload will prevent signing of the payload. This will only
209 // work for services that have support for this.
210 UnsignedPayload bool
211 }
212
213 // NewSigner returns a Signer pointer configured with the credentials and optional
214 // option values provided. If not options are provided the Signer will use its
215 // default configuration.
216 func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer {
217 v4 := &Signer{
218 Credentials: credentials,
219 }
220
221 for _, option := range options {
222 option(v4)
223 }
224
225 return v4
226 }
227
228 type signingCtx struct {
229 ServiceName string
230 Region string
231 Request *http.Request
232 Body io.ReadSeeker
233 Query url.Values
234 Time time.Time
235 ExpireTime time.Duration
236 SignedHeaderVals http.Header
237
238 DisableURIPathEscaping bool
239
240 credValues credentials.Value
241 isPresign bool
242 unsignedPayload bool
243
244 bodyDigest string
245 signedHeaders string
246 canonicalHeaders string
247 canonicalString string
248 credentialString string
249 stringToSign string
250 signature string
251 authorization string
252 }
253
254 // Sign signs AWS v4 requests with the provided body, service name, region the
255 // request is made to, and time the request is signed at. The signTime allows
256 // you to specify that a request is signed for the future, and cannot be
257 // used until then.
258 //
259 // Returns a list of HTTP headers that were included in the signature or an
260 // error if signing the request failed. Generally for signed requests this value
261 // is not needed as the full request context will be captured by the http.Request
262 // value. It is included for reference though.
263 //
264 // Sign will set the request's Body to be the `body` parameter passed in. If
265 // the body is not already an io.ReadCloser, it will be wrapped within one. If
266 // a `nil` body parameter passed to Sign, the request's Body field will be
267 // also set to nil. Its important to note that this functionality will not
268 // change the request's ContentLength of the request.
269 //
270 // Sign differs from Presign in that it will sign the request using HTTP
271 // header values. This type of signing is intended for http.Request values that
272 // will not be shared, or are shared in a way the header values on the request
273 // will not be lost.
274 //
275 // The requests body is an io.ReadSeeker so the SHA256 of the body can be
276 // generated. To bypass the signer computing the hash you can set the
277 // "X-Amz-Content-Sha256" header with a precomputed value. The signer will
278 // only compute the hash if the request header value is empty.
279 func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) {
280 return v4.signWithBody(r, body, service, region, 0, false, signTime)
281 }
282
283 // Presign signs AWS v4 requests with the provided body, service name, region
284 // the request is made to, and time the request is signed at. The signTime
285 // allows you to specify that a request is signed for the future, and cannot
286 // be used until then.
287 //
288 // Returns a list of HTTP headers that were included in the signature or an
289 // error if signing the request failed. For presigned requests these headers
290 // and their values must be included on the HTTP request when it is made. This
291 // is helpful to know what header values need to be shared with the party the
292 // presigned request will be distributed to.
293 //
294 // Presign differs from Sign in that it will sign the request using query string
295 // instead of header values. This allows you to share the Presigned Request's
296 // URL with third parties, or distribute it throughout your system with minimal
297 // dependencies.
298 //
299 // Presign also takes an exp value which is the duration the
300 // signed request will be valid after the signing time. This is allows you to
301 // set when the request will expire.
302 //
303 // The requests body is an io.ReadSeeker so the SHA256 of the body can be
304 // generated. To bypass the signer computing the hash you can set the
305 // "X-Amz-Content-Sha256" header with a precomputed value. The signer will
306 // only compute the hash if the request header value is empty.
307 //
308 // Presigning a S3 request will not compute the body's SHA256 hash by default.
309 // This is done due to the general use case for S3 presigned URLs is to share
310 // PUT/GET capabilities. If you would like to include the body's SHA256 in the
311 // presigned request's signature you can set the "X-Amz-Content-Sha256"
312 // HTTP header and that will be included in the request's signature.
313 func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) {
314 return v4.signWithBody(r, body, service, region, exp, true, signTime)
315 }
316
317 func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) {
318 currentTimeFn := v4.currentTimeFn
319 if currentTimeFn == nil {
320 currentTimeFn = time.Now
321 }
322
323 ctx := &signingCtx{
324 Request: r,
325 Body: body,
326 Query: r.URL.Query(),
327 Time: signTime,
328 ExpireTime: exp,
329 isPresign: isPresign,
330 ServiceName: service,
331 Region: region,
332 DisableURIPathEscaping: v4.DisableURIPathEscaping,
333 unsignedPayload: v4.UnsignedPayload,
334 }
335
336 for key := range ctx.Query {
337 sort.Strings(ctx.Query[key])
338 }
339
340 if ctx.isRequestSigned() {
341 ctx.Time = currentTimeFn()
342 ctx.handlePresignRemoval()
343 }
344
345 var err error
346 ctx.credValues, err = v4.Credentials.GetWithContext(requestContext(r))
347 if err != nil {
348 return http.Header{}, err
349 }
350
351 ctx.sanitizeHostForHeader()
352 ctx.assignAmzQueryValues()
353 if err := ctx.build(v4.DisableHeaderHoisting); err != nil {
354 return nil, err
355 }
356
357 // If the request is not presigned the body should be attached to it. This
358 // prevents the confusion of wanting to send a signed request without
359 // the body the request was signed for attached.
360 if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) {
361 var reader io.ReadCloser
362 if body != nil {
363 var ok bool
364 if reader, ok = body.(io.ReadCloser); !ok {
365 reader = ioutil.NopCloser(body)
366 }
367 }
368 r.Body = reader
369 }
370
371 if v4.Debug.Matches(aws.LogDebugWithSigning) {
372 v4.logSigningInfo(ctx)
373 }
374
375 return ctx.SignedHeaderVals, nil
376 }
377
378 func (ctx *signingCtx) sanitizeHostForHeader() {
379 request.SanitizeHostForHeader(ctx.Request)
380 }
381
382 func (ctx *signingCtx) handlePresignRemoval() {
383 if !ctx.isPresign {
384 return
385 }
386
387 // The credentials have expired for this request. The current signing
388 // is invalid, and needs to be request because the request will fail.
389 ctx.removePresign()
390
391 // Update the request's query string to ensure the values stays in
392 // sync in the case retrieving the new credentials fails.
393 ctx.Request.URL.RawQuery = ctx.Query.Encode()
394 }
395
396 func (ctx *signingCtx) assignAmzQueryValues() {
397 if ctx.isPresign {
398 ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix)
399 if ctx.credValues.SessionToken != "" {
400 ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken)
401 } else {
402 ctx.Query.Del("X-Amz-Security-Token")
403 }
404
405 return
406 }
407
408 if ctx.credValues.SessionToken != "" {
409 ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken)
410 }
411 }
412
413 // SignRequestHandler is a named request handler the SDK will use to sign
414 // service client request with using the V4 signature.
415 var SignRequestHandler = request.NamedHandler{
416 Name: "v4.SignRequestHandler", Fn: SignSDKRequest,
417 }
418
419 // SignSDKRequest signs an AWS request with the V4 signature. This
420 // request handler should only be used with the SDK's built in service client's
421 // API operation requests.
422 //
423 // This function should not be used on its own, but in conjunction with
424 // an AWS service client's API operation call. To sign a standalone request
425 // not created by a service client's API operation method use the "Sign" or
426 // "Presign" functions of the "Signer" type.
427 //
428 // If the credentials of the request's config are set to
429 // credentials.AnonymousCredentials the request will not be signed.
430 func SignSDKRequest(req *request.Request) {
431 SignSDKRequestWithCurrentTime(req, time.Now)
432 }
433
434 // BuildNamedHandler will build a generic handler for signing.
435 func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler {
436 return request.NamedHandler{
437 Name: name,
438 Fn: func(req *request.Request) {
439 SignSDKRequestWithCurrentTime(req, time.Now, opts...)
440 },
441 }
442 }
443
444 // SignSDKRequestWithCurrentTime will sign the SDK's request using the time
445 // function passed in. Behaves the same as SignSDKRequest with the exception
446 // the request is signed with the value returned by the current time function.
447 func SignSDKRequestWithCurrentTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) {
448 // If the request does not need to be signed ignore the signing of the
449 // request if the AnonymousCredentials object is used.
450 if req.Config.Credentials == credentials.AnonymousCredentials {
451 return
452 }
453
454 region := req.ClientInfo.SigningRegion
455 if region == "" {
456 region = aws.StringValue(req.Config.Region)
457 }
458
459 name := req.ClientInfo.SigningName
460 if name == "" {
461 name = req.ClientInfo.ServiceName
462 }
463
464 v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) {
465 v4.Debug = req.Config.LogLevel.Value()
466 v4.Logger = req.Config.Logger
467 v4.DisableHeaderHoisting = req.NotHoist
468 v4.currentTimeFn = curTimeFn
469 if name == "s3" {
470 // S3 service should not have any escaping applied
471 v4.DisableURIPathEscaping = true
472 }
473 // Prevents setting the HTTPRequest's Body. Since the Body could be
474 // wrapped in a custom io.Closer that we do not want to be stompped
475 // on top of by the signer.
476 v4.DisableRequestBodyOverwrite = true
477 })
478
479 for _, opt := range opts {
480 opt(v4)
481 }
482
483 curTime := curTimeFn()
484 signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(),
485 name, region, req.ExpireTime, req.ExpireTime > 0, curTime,
486 )
487 if err != nil {
488 req.Error = err
489 req.SignedHeaderVals = nil
490 return
491 }
492
493 req.SignedHeaderVals = signedHeaders
494 req.LastSignedAt = curTime
495 }
496
497 const logSignInfoMsg = `DEBUG: Request Signature:
498 ---[ CANONICAL STRING ]-----------------------------
499 %s
500 ---[ STRING TO SIGN ]--------------------------------
501 %s%s
502 -----------------------------------------------------`
503 const logSignedURLMsg = `
504 ---[ SIGNED URL ]------------------------------------
505 %s`
506
507 func (v4 *Signer) logSigningInfo(ctx *signingCtx) {
508 signedURLMsg := ""
509 if ctx.isPresign {
510 signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String())
511 }
512 msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg)
513 v4.Logger.Log(msg)
514 }
515
516 func (ctx *signingCtx) build(disableHeaderHoisting bool) error {
517 ctx.buildTime() // no depends
518 ctx.buildCredentialString() // no depends
519
520 if err := ctx.buildBodyDigest(); err != nil {
521 return err
522 }
523
524 unsignedHeaders := ctx.Request.Header
525 if ctx.isPresign {
526 if !disableHeaderHoisting {
527 urlValues := url.Values{}
528 urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends
529 for k := range urlValues {
530 ctx.Query[k] = urlValues[k]
531 }
532 }
533 }
534
535 ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders)
536 ctx.buildCanonicalString() // depends on canon headers / signed headers
537 ctx.buildStringToSign() // depends on canon string
538 ctx.buildSignature() // depends on string to sign
539
540 if ctx.isPresign {
541 ctx.Request.URL.RawQuery += "&" + signatureQueryKey + "=" + ctx.signature
542 } else {
543 parts := []string{
544 authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString,
545 "SignedHeaders=" + ctx.signedHeaders,
546 authHeaderSignatureElem + ctx.signature,
547 }
548 ctx.Request.Header.Set(authorizationHeader, strings.Join(parts, ", "))
549 }
550
551 return nil
552 }
553
554 // GetSignedRequestSignature attempts to extract the signature of the request.
555 // Returning an error if the request is unsigned, or unable to extract the
556 // signature.
557 func GetSignedRequestSignature(r *http.Request) ([]byte, error) {
558
559 if auth := r.Header.Get(authorizationHeader); len(auth) != 0 {
560 ps := strings.Split(auth, ", ")
561 for _, p := range ps {
562 if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 {
563 sig := p[len(authHeaderSignatureElem):]
564 if len(sig) == 0 {
565 return nil, fmt.Errorf("invalid request signature authorization header")
566 }
567 return hex.DecodeString(sig)
568 }
569 }
570 }
571
572 if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 {
573 return hex.DecodeString(sig)
574 }
575
576 return nil, fmt.Errorf("request not signed")
577 }
578
579 func (ctx *signingCtx) buildTime() {
580 if ctx.isPresign {
581 duration := int64(ctx.ExpireTime / time.Second)
582 ctx.Query.Set("X-Amz-Date", formatTime(ctx.Time))
583 ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10))
584 } else {
585 ctx.Request.Header.Set("X-Amz-Date", formatTime(ctx.Time))
586 }
587 }
588
589 func (ctx *signingCtx) buildCredentialString() {
590 ctx.credentialString = buildSigningScope(ctx.Region, ctx.ServiceName, ctx.Time)
591
592 if ctx.isPresign {
593 ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString)
594 }
595 }
596
597 func buildQuery(r rule, header http.Header) (url.Values, http.Header) {
598 query := url.Values{}
599 unsignedHeaders := http.Header{}
600 for k, h := range header {
601 if r.IsValid(k) {
602 query[k] = h
603 } else {
604 unsignedHeaders[k] = h
605 }
606 }
607
608 return query, unsignedHeaders
609 }
610 func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) {
611 var headers []string
612 headers = append(headers, "host")
613 for k, v := range header {
614 if !r.IsValid(k) {
615 continue // ignored header
616 }
617 if ctx.SignedHeaderVals == nil {
618 ctx.SignedHeaderVals = make(http.Header)
619 }
620
621 lowerCaseKey := strings.ToLower(k)
622 if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok {
623 // include additional values
624 ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...)
625 continue
626 }
627
628 headers = append(headers, lowerCaseKey)
629 ctx.SignedHeaderVals[lowerCaseKey] = v
630 }
631 sort.Strings(headers)
632
633 ctx.signedHeaders = strings.Join(headers, ";")
634
635 if ctx.isPresign {
636 ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders)
637 }
638
639 headerItems := make([]string, len(headers))
640 for i, k := range headers {
641 if k == "host" {
642 if ctx.Request.Host != "" {
643 headerItems[i] = "host:" + ctx.Request.Host
644 } else {
645 headerItems[i] = "host:" + ctx.Request.URL.Host
646 }
647 } else {
648 headerValues := make([]string, len(ctx.SignedHeaderVals[k]))
649 for i, v := range ctx.SignedHeaderVals[k] {
650 headerValues[i] = strings.TrimSpace(v)
651 }
652 headerItems[i] = k + ":" +
653 strings.Join(headerValues, ",")
654 }
655 }
656 stripExcessSpaces(headerItems)
657 ctx.canonicalHeaders = strings.Join(headerItems, "\n")
658 }
659
660 func (ctx *signingCtx) buildCanonicalString() {
661 ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1)
662
663 uri := getURIPath(ctx.Request.URL)
664
665 if !ctx.DisableURIPathEscaping {
666 uri = rest.EscapePath(uri, false)
667 }
668
669 ctx.canonicalString = strings.Join([]string{
670 ctx.Request.Method,
671 uri,
672 ctx.Request.URL.RawQuery,
673 ctx.canonicalHeaders + "\n",
674 ctx.signedHeaders,
675 ctx.bodyDigest,
676 }, "\n")
677 }
678
679 func (ctx *signingCtx) buildStringToSign() {
680 ctx.stringToSign = strings.Join([]string{
681 authHeaderPrefix,
682 formatTime(ctx.Time),
683 ctx.credentialString,
684 hex.EncodeToString(hashSHA256([]byte(ctx.canonicalString))),
685 }, "\n")
686 }
687
688 func (ctx *signingCtx) buildSignature() {
689 creds := deriveSigningKey(ctx.Region, ctx.ServiceName, ctx.credValues.SecretAccessKey, ctx.Time)
690 signature := hmacSHA256(creds, []byte(ctx.stringToSign))
691 ctx.signature = hex.EncodeToString(signature)
692 }
693
694 func (ctx *signingCtx) buildBodyDigest() error {
695 hash := ctx.Request.Header.Get("X-Amz-Content-Sha256")
696 if hash == "" {
697 includeSHA256Header := ctx.unsignedPayload ||
698 ctx.ServiceName == "s3" ||
699 ctx.ServiceName == "s3-object-lambda" ||
700 ctx.ServiceName == "glacier" ||
701 ctx.ServiceName == "s3-outposts"
702
703 s3Presign := ctx.isPresign &&
704 (ctx.ServiceName == "s3" ||
705 ctx.ServiceName == "s3-object-lambda")
706
707 if ctx.unsignedPayload || s3Presign {
708 hash = "UNSIGNED-PAYLOAD"
709 includeSHA256Header = !s3Presign
710 } else if ctx.Body == nil {
711 hash = emptyStringSHA256
712 } else {
713 if !aws.IsReaderSeekable(ctx.Body) {
714 return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body)
715 }
716 hashBytes, err := makeSha256Reader(ctx.Body)
717 if err != nil {
718 return err
719 }
720 hash = hex.EncodeToString(hashBytes)
721 }
722
723 if includeSHA256Header {
724 ctx.Request.Header.Set("X-Amz-Content-Sha256", hash)
725 }
726 }
727 ctx.bodyDigest = hash
728
729 return nil
730 }
731
732 // isRequestSigned returns if the request is currently signed or presigned
733 func (ctx *signingCtx) isRequestSigned() bool {
734 if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" {
735 return true
736 }
737 if ctx.Request.Header.Get("Authorization") != "" {
738 return true
739 }
740
741 return false
742 }
743
744 // unsign removes signing flags for both signed and presigned requests.
745 func (ctx *signingCtx) removePresign() {
746 ctx.Query.Del("X-Amz-Algorithm")
747 ctx.Query.Del("X-Amz-Signature")
748 ctx.Query.Del("X-Amz-Security-Token")
749 ctx.Query.Del("X-Amz-Date")
750 ctx.Query.Del("X-Amz-Expires")
751 ctx.Query.Del("X-Amz-Credential")
752 ctx.Query.Del("X-Amz-SignedHeaders")
753 }
754
755 func hmacSHA256(key []byte, data []byte) []byte {
756 hash := hmac.New(sha256.New, key)
757 hash.Write(data)
758 return hash.Sum(nil)
759 }
760
761 func hashSHA256(data []byte) []byte {
762 hash := sha256.New()
763 hash.Write(data)
764 return hash.Sum(nil)
765 }
766
767 func makeSha256Reader(reader io.ReadSeeker) (hashBytes []byte, err error) {
768 hash := sha256.New()
769 start, err := reader.Seek(0, sdkio.SeekCurrent)
770 if err != nil {
771 return nil, err
772 }
773 defer func() {
774 // ensure error is return if unable to seek back to start of payload.
775 _, err = reader.Seek(start, sdkio.SeekStart)
776 }()
777
778 // Use CopyN to avoid allocating the 32KB buffer in io.Copy for bodies
779 // smaller than 32KB. Fall back to io.Copy if we fail to determine the size.
780 size, err := aws.SeekerLen(reader)
781 if err != nil {
782 io.Copy(hash, reader)
783 } else {
784 io.CopyN(hash, reader, size)
785 }
786
787 return hash.Sum(nil), nil
788 }
789
790 const doubleSpace = " "
791
792 // stripExcessSpaces will rewrite the passed in slice's string values to not
793 // contain multiple side-by-side spaces.
794 func stripExcessSpaces(vals []string) {
795 var j, k, l, m, spaces int
796 for i, str := range vals {
797 // Trim trailing spaces
798 for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- {
799 }
800
801 // Trim leading spaces
802 for k = 0; k < j && str[k] == ' '; k++ {
803 }
804 str = str[k : j+1]
805
806 // Strip multiple spaces.
807 j = strings.Index(str, doubleSpace)
808 if j < 0 {
809 vals[i] = str
810 continue
811 }
812
813 buf := []byte(str)
814 for k, m, l = j, j, len(buf); k < l; k++ {
815 if buf[k] == ' ' {
816 if spaces == 0 {
817 // First space.
818 buf[m] = buf[k]
819 m++
820 }
821 spaces++
822 } else {
823 // End of multiple spaces.
824 spaces = 0
825 buf[m] = buf[k]
826 m++
827 }
828 }
829
830 vals[i] = string(buf[:m])
831 }
832 }
833
834 func buildSigningScope(region, service string, dt time.Time) string {
835 return strings.Join([]string{
836 formatShortTime(dt),
837 region,
838 service,
839 awsV4Request,
840 }, "/")
841 }
842
843 func deriveSigningKey(region, service, secretKey string, dt time.Time) []byte {
844 kDate := hmacSHA256([]byte("AWS4"+secretKey), []byte(formatShortTime(dt)))
845 kRegion := hmacSHA256(kDate, []byte(region))
846 kService := hmacSHA256(kRegion, []byte(service))
847 signingKey := hmacSHA256(kService, []byte(awsV4Request))
848 return signingKey
849 }
850
851 func formatShortTime(dt time.Time) string {
852 return dt.UTC().Format(shortTimeFormat)
853 }
854
855 func formatTime(dt time.Time) string {
856 return dt.UTC().Format(timeFormat)
857 }