| 1 |
package s3 |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/hex" |
| 5 |
"fmt" |
| 6 |
"net/http" |
| 7 |
"sort" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
) |
| 11 |
|
| 12 |
// signV4 signs req in place using AWS Signature V4. payloadHash is the hex-encoded SHA-256 |
| 13 |
// of the request body, or the literal string "UNSIGNED-PAYLOAD" for streaming uploads. |
| 14 |
// |
| 15 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html |
| 16 |
func (c *Client) signV4(req *http.Request, hash string) { |
| 17 |
now := time.Now().UTC() |
| 18 |
datestamp := now.Format("20060102") |
| 19 |
amzDate := now.Format("20060102T150405Z") |
| 20 |
|
| 21 |
// Required headers |
| 22 |
req.Header.Set("Host", c.config.HostHeader()) |
| 23 |
req.Header.Set("X-Amz-Date", amzDate) |
| 24 |
req.Header.Set("X-Amz-Content-Sha256", hash) |
| 25 |
|
| 26 |
// Canonical headers (all headers we set, sorted by lowercase key) |
| 27 |
signedKeys := make([]string, 0, len(req.Header)) |
| 28 |
canonHeaders := make(map[string]string, len(req.Header)) |
| 29 |
for k := range req.Header { |
| 30 |
lk := strings.ToLower(k) |
| 31 |
signedKeys = append(signedKeys, lk) |
| 32 |
canonHeaders[lk] = strings.TrimSpace(req.Header.Get(k)) |
| 33 |
} |
| 34 |
sort.Strings(signedKeys) |
| 35 |
signedHeadersStr := strings.Join(signedKeys, ";") |
| 36 |
var chBuf strings.Builder |
| 37 |
for _, k := range signedKeys { |
| 38 |
chBuf.WriteString(k) |
| 39 |
chBuf.WriteByte(':') |
| 40 |
chBuf.WriteString(canonHeaders[k]) |
| 41 |
chBuf.WriteByte('\n') |
| 42 |
} |
| 43 |
|
| 44 |
// Canonical request |
| 45 |
canonicalRequest := strings.Join([]string{ |
| 46 |
req.Method, |
| 47 |
canonicalURI(req.URL), |
| 48 |
canonicalQueryString(req.URL.Query()), |
| 49 |
chBuf.String(), |
| 50 |
signedHeadersStr, |
| 51 |
hash, |
| 52 |
}, "\n") |
| 53 |
|
| 54 |
// String to sign |
| 55 |
credentialScope := datestamp + "/" + c.config.Region + "/s3/aws4_request" |
| 56 |
stringToSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + credentialScope + "\n" + sha256Hex([]byte(canonicalRequest)) |
| 57 |
|
| 58 |
// Signing key |
| 59 |
signingKey := hmacSHA256(hmacSHA256(hmacSHA256(hmacSHA256( |
| 60 |
[]byte("AWS4"+c.config.SecretKey), []byte(datestamp)), |
| 61 |
[]byte(c.config.Region)), |
| 62 |
[]byte("s3")), |
| 63 |
[]byte("aws4_request")) |
| 64 |
|
| 65 |
signature := hex.EncodeToString(hmacSHA256(signingKey, []byte(stringToSign))) |
| 66 |
header := fmt.Sprintf( |
| 67 |
"AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s", |
| 68 |
c.config.AccessKey, credentialScope, signedHeadersStr, signature, |
| 69 |
) |
| 70 |
req.Header.Set("Authorization", header) |
| 71 |
} |