v4.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package s3auth
  15. import (
  16. "bytes"
  17. "crypto/hmac"
  18. "crypto/sha256"
  19. "encoding/hex"
  20. "io"
  21. "net/http"
  22. "sort"
  23. "strings"
  24. "time"
  25. "yunion.io/x/jsonutils"
  26. "yunion.io/x/pkg/errors"
  27. "yunion.io/x/pkg/util/streamutils"
  28. "yunion.io/x/pkg/util/timeutils"
  29. )
  30. // Signature and API related constants.
  31. const (
  32. signV4Algorithm = "AWS4-HMAC-SHA256"
  33. iso8601DateFormat = "20060102T150405Z"
  34. yyyymmdd = "20060102"
  35. unsignedPayload = "UNSIGNED-PAYLOAD"
  36. )
  37. // getScope generate a string of a specific date, an AWS region, and a
  38. // service.
  39. func getScope(location string, t time.Time) string {
  40. scope := strings.Join([]string{
  41. t.Format(yyyymmdd),
  42. location,
  43. "s3",
  44. "aws4_request",
  45. }, "/")
  46. return scope
  47. }
  48. // sum256 calculate sha256 sum for an input byte array.
  49. func sum256(data []byte) []byte {
  50. hash := sha256.New()
  51. hash.Write(data)
  52. return hash.Sum(nil)
  53. }
  54. // getStringToSign a string based on selected query values.
  55. func getStringToSignV4(t time.Time, location, canonicalRequest string) string {
  56. stringToSign := signV4Algorithm + "\n" + t.Format(iso8601DateFormat) + "\n"
  57. stringToSign += getScope(location, t) + "\n"
  58. stringToSign += hex.EncodeToString(sum256([]byte(canonicalRequest)))
  59. return stringToSign
  60. }
  61. // /
  62. // / Excerpts from @lsegal -
  63. // / https://github.com/aws/aws-sdk-js/issues/659#issuecomment-120477258.
  64. // /
  65. // / User-Agent:
  66. // /
  67. // / This is ignored from signing because signing this causes
  68. // / problems with generating pre-signed URLs (that are executed
  69. // / by other agents) or when customers pass requests through
  70. // / proxies, which may modify the user-agent.
  71. // /
  72. // / Content-Length:
  73. // /
  74. // / This is ignored from signing because generating a pre-signed
  75. // / URL should not provide a content-length constraint,
  76. // / specifically when vending a S3 pre-signed PUT URL. The
  77. // / corollary to this is that when sending regular requests
  78. // / (non-pre-signed), the signature contains a checksum of the
  79. // / body, which implicitly validates the payload length (since
  80. // / changing the number of bytes would change the checksum)
  81. // / and therefore this header is not valuable in the signature.
  82. // /
  83. // / Content-Type:
  84. // /
  85. // / Signing this header causes quite a number of problems in
  86. // / browser environments, where browsers like to modify and
  87. // / normalize the content-type header in different ways. There is
  88. // / more information on this in https://goo.gl/2E9gyy. Avoiding
  89. // / this field simplifies logic and reduces the possibility of
  90. // / future bugs.
  91. // /
  92. // / Authorization:
  93. // /
  94. // / Is skipped for obvious reasons
  95. // /
  96. var v4IgnoredHeaders = map[string]bool{
  97. "Authorization": true,
  98. "Content-Type": true,
  99. "Content-Length": true,
  100. "User-Agent": true,
  101. }
  102. // sumHMAC calculate hmac between two input byte array.
  103. func sumHMAC(key []byte, data []byte) []byte {
  104. hash := hmac.New(sha256.New, key)
  105. hash.Write(data)
  106. return hash.Sum(nil)
  107. }
  108. // getSigningKey hmac seed to calculate final signature.
  109. func getSigningKey(secret, loc string, t time.Time) []byte {
  110. date := sumHMAC([]byte("AWS4"+secret), []byte(t.Format(yyyymmdd)))
  111. location := sumHMAC(date, []byte(loc))
  112. service := sumHMAC(location, []byte("s3"))
  113. signingKey := sumHMAC(service, []byte("aws4_request"))
  114. return signingKey
  115. }
  116. // getSignature final signature in hexadecimal form.
  117. func getSignature(signingKey []byte, stringToSign string) string {
  118. return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
  119. }
  120. // getCanonicalRequest generate a canonical request of style.
  121. //
  122. // canonicalRequest =
  123. //
  124. // <HTTPMethod>\n
  125. // <CanonicalURI>\n
  126. // <CanonicalQueryString>\n
  127. // <CanonicalHeaders>\n
  128. // <SignedHeaders>\n
  129. // <HashedPayload>
  130. func getCanonicalRequest(req http.Request, signedHeaders []string) string {
  131. req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1)
  132. canonicalRequest := strings.Join([]string{
  133. req.Method,
  134. encodePath(req.URL.Path),
  135. req.URL.RawQuery,
  136. getCanonicalHeaders(req, signedHeaders),
  137. strings.Join(signedHeaders, ";"),
  138. getHashedPayload(req),
  139. }, "\n")
  140. return canonicalRequest
  141. }
  142. // Trim leading and trailing spaces and replace sequential spaces with one space, following Trimall()
  143. // in http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
  144. func signV4TrimAll(input string) string {
  145. // Compress adjacent spaces (a space is determined by
  146. // unicode.IsSpace() internally here) to one space and return
  147. return strings.Join(strings.Fields(input), " ")
  148. }
  149. // getCanonicalHeaders generate a list of request headers for
  150. // signature.
  151. func getCanonicalHeaders(req http.Request, signedHeaders []string) string {
  152. var buf bytes.Buffer
  153. // Save all the headers in canonical form <header>:<value> newline
  154. // separated for each header.
  155. for _, k := range signedHeaders {
  156. buf.WriteString(k)
  157. buf.WriteByte(':')
  158. switch {
  159. case k == "host":
  160. buf.WriteString(getHostAddr(req))
  161. fallthrough
  162. default:
  163. for idx, v := range req.Header[http.CanonicalHeaderKey(k)] {
  164. if idx > 0 {
  165. buf.WriteByte(',')
  166. }
  167. buf.WriteString(signV4TrimAll(v))
  168. }
  169. buf.WriteByte('\n')
  170. }
  171. }
  172. return buf.String()
  173. }
  174. // getSignedHeaders generate all signed request headers.
  175. // i.e lexically sorted, semicolon-separated list of lowercase
  176. // request header names.
  177. func getSignedHeaders(req http.Request, ignoredHeaders map[string]bool) []string {
  178. var headers []string
  179. hasHost := false
  180. hasContentHash := false
  181. for k := range req.Header {
  182. if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; ok {
  183. continue // Ignored header found continue.
  184. }
  185. if strings.EqualFold(k, "host") {
  186. hasHost = true
  187. } else if strings.EqualFold(k, "x-amz-content-sha256") {
  188. hasContentHash = true
  189. }
  190. headers = append(headers, strings.ToLower(k))
  191. }
  192. if !hasHost {
  193. headers = append(headers, "host")
  194. }
  195. if !hasContentHash {
  196. headers = append(headers, "x-amz-content-sha256")
  197. }
  198. sort.Strings(headers)
  199. return headers
  200. }
  201. // getHashedPayload get the hexadecimal value of the SHA256 hash of
  202. // the request payload.
  203. func getHashedPayload(req http.Request) string {
  204. hashedPayload := req.Header.Get("X-Amz-Content-Sha256")
  205. if hashedPayload == "" {
  206. // Presign does not have a payload, use S3 recommended value.
  207. hashedPayload = unsignedPayload
  208. }
  209. return hashedPayload
  210. }
  211. type SAccessKeyRequestV4 struct {
  212. SAccessKeyRequest
  213. Location string
  214. SignedHeaders []string
  215. SignDate time.Time
  216. }
  217. func NewV4Request() SAccessKeyRequestV4 {
  218. req := SAccessKeyRequestV4{}
  219. req.Algorithm = signV4Algorithm
  220. return req
  221. }
  222. // AWS4-HMAC-SHA256
  223. // Credential=xxxx/20190824/us-east-1/s3/aws4_request,SignedHeaders=date;host;x-amz-content-sha256;x-amz-date,Signature=27a135c6f51cc
  224. func decodeAuthHeaderV4(authStr string) (*SAccessKeyRequestV4, error) {
  225. req := NewV4Request()
  226. parts := strings.Split(authStr, ",")
  227. if len(parts) != 3 ||
  228. !strings.HasPrefix(parts[0], "Credential=") ||
  229. !strings.HasPrefix(parts[1], "SignedHeaders=") ||
  230. !strings.HasPrefix(parts[2], "Signature=") {
  231. return nil, errors.Error("illegal v4 auth header")
  232. }
  233. credParts := strings.Split(parts[0][len("Credential="):], "/")
  234. if len(credParts) != 5 {
  235. return nil, errors.Error("illegal v4 auth header Credential")
  236. }
  237. req.AccessKey = credParts[0]
  238. req.Location = credParts[2]
  239. req.SignedHeaders = strings.Split(parts[1][len("SignedHeaders="):], ";")
  240. sort.Strings(req.SignedHeaders)
  241. req.Signature = parts[2][len("Signature="):]
  242. return &req, nil
  243. }
  244. func (aksk *SAccessKeyRequestV4) ParseRequest(req http.Request, virtualHost bool) error {
  245. dateStr := req.Header.Get(http.CanonicalHeaderKey("x-amz-date"))
  246. if len(dateStr) == 0 {
  247. return errors.Error("missing x-amz-date")
  248. }
  249. dateSign, err := time.Parse(iso8601DateFormat, dateStr)
  250. if err != nil {
  251. return errors.Wrap(err, "time.Parse")
  252. }
  253. canonicalReq := getCanonicalRequest(req, aksk.SignedHeaders)
  254. aksk.SignDate = dateSign
  255. aksk.Request = getStringToSignV4(dateSign, aksk.Location, canonicalReq)
  256. return nil
  257. }
  258. func (aksk SAccessKeyRequestV4) Verify(secret string) error {
  259. signingKey := getSigningKey(secret, aksk.Location, aksk.SignDate)
  260. signature := getSignature(signingKey, aksk.Request)
  261. if signature != aksk.Signature {
  262. return errors.Error("signature mismatch")
  263. }
  264. return nil
  265. }
  266. func (aksk SAccessKeyRequestV4) Encode() string {
  267. return jsonutils.Marshal(aksk).String()
  268. }
  269. // GetCredential generate a credential string.
  270. func getCredential(accessKeyID, location string, t time.Time) string {
  271. scope := getScope(location, t)
  272. return accessKeyID + "/" + scope
  273. }
  274. // SignV4 sign the request before Do(), in accordance with
  275. // http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.
  276. func SignV4(req http.Request, accessKey, secretAccessKey, location string, body io.Reader) *http.Request {
  277. // Signature calculation is not needed for anonymous credentials.
  278. if accessKey == "" || secretAccessKey == "" {
  279. return &req
  280. }
  281. h := sha256.New()
  282. if body != nil {
  283. streamutils.StreamPipe(body, h, false, nil)
  284. }
  285. req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(h.Sum(nil)))
  286. // Initial time.
  287. t := time.Now().UTC()
  288. // Set x-amz-date.
  289. req.Header.Set("X-Amz-Date", t.Format(iso8601DateFormat))
  290. req.Header.Set("Date", timeutils.RFC2882Time(t))
  291. signedHeaders := getSignedHeaders(req, v4IgnoredHeaders)
  292. // Get canonical request.
  293. canonicalRequest := getCanonicalRequest(req, signedHeaders)
  294. // Get string to sign from canonical request.
  295. stringToSign := getStringToSignV4(t, location, canonicalRequest)
  296. // Get hmac signing key.
  297. signingKey := getSigningKey(secretAccessKey, location, t)
  298. // Get credential string.
  299. credential := getCredential(accessKey, location, t)
  300. // Calculate signature.
  301. signature := getSignature(signingKey, stringToSign)
  302. // If regular request, construct the final authorization header.
  303. parts := []string{
  304. signV4Algorithm + " Credential=" + credential,
  305. "SignedHeaders=" + strings.Join(signedHeaders, ";"),
  306. "Signature=" + signature,
  307. }
  308. // Set authorization header.
  309. auth := strings.Join(parts, ",")
  310. req.Header.Set("Authorization", auth)
  311. return &req
  312. }