You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

752 lines
23 KiB

5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
  1. /*
  2. * The following code tries to reverse engineer the Amazon S3 APIs,
  3. * and is mostly copied from minio implementation.
  4. */
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  14. // implied. See the License for the specific language governing
  15. // permissions and limitations under the License.
  16. package s3api
  17. import (
  18. "bytes"
  19. "crypto/hmac"
  20. "crypto/sha256"
  21. "crypto/subtle"
  22. "encoding/hex"
  23. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  24. "net/http"
  25. "net/url"
  26. "regexp"
  27. "sort"
  28. "strconv"
  29. "strings"
  30. "time"
  31. "unicode/utf8"
  32. )
  33. func (iam *IdentityAccessManagement) reqSignatureV4Verify(r *http.Request) (*Identity, s3err.ErrorCode) {
  34. sha256sum := getContentSha256Cksum(r)
  35. switch {
  36. case isRequestSignatureV4(r):
  37. return iam.doesSignatureMatch(sha256sum, r)
  38. case isRequestPresignedSignatureV4(r):
  39. return iam.doesPresignedSignatureMatch(sha256sum, r)
  40. }
  41. return nil, s3err.ErrAccessDenied
  42. }
  43. // Streaming AWS Signature Version '4' constants.
  44. const (
  45. emptySHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
  46. streamingContentSHA256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"
  47. signV4ChunkedAlgorithm = "AWS4-HMAC-SHA256-PAYLOAD"
  48. // http Header "x-amz-content-sha256" == "UNSIGNED-PAYLOAD" indicates that the
  49. // client did not calculate sha256 of the payload.
  50. unsignedPayload = "UNSIGNED-PAYLOAD"
  51. )
  52. // Returns SHA256 for calculating canonical-request.
  53. func getContentSha256Cksum(r *http.Request) string {
  54. var (
  55. defaultSha256Cksum string
  56. v []string
  57. ok bool
  58. )
  59. // For a presigned request we look at the query param for sha256.
  60. if isRequestPresignedSignatureV4(r) {
  61. // X-Amz-Content-Sha256, if not set in presigned requests, checksum
  62. // will default to 'UNSIGNED-PAYLOAD'.
  63. defaultSha256Cksum = unsignedPayload
  64. v, ok = r.URL.Query()["X-Amz-Content-Sha256"]
  65. if !ok {
  66. v, ok = r.Header["X-Amz-Content-Sha256"]
  67. }
  68. } else {
  69. // X-Amz-Content-Sha256, if not set in signed requests, checksum
  70. // will default to sha256([]byte("")).
  71. defaultSha256Cksum = emptySHA256
  72. v, ok = r.Header["X-Amz-Content-Sha256"]
  73. }
  74. // We found 'X-Amz-Content-Sha256' return the captured value.
  75. if ok {
  76. return v[0]
  77. }
  78. // We couldn't find 'X-Amz-Content-Sha256'.
  79. return defaultSha256Cksum
  80. }
  81. // Verify authorization header - http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html
  82. func (iam *IdentityAccessManagement) doesSignatureMatch(hashedPayload string, r *http.Request) (*Identity, s3err.ErrorCode) {
  83. // Copy request.
  84. req := *r
  85. // Save authorization header.
  86. v4Auth := req.Header.Get("Authorization")
  87. // Parse signature version '4' header.
  88. signV4Values, err := parseSignV4(v4Auth)
  89. if err != s3err.ErrNone {
  90. return nil, err
  91. }
  92. // Extract all the signed headers along with its values.
  93. extractedSignedHeaders, errCode := extractSignedHeaders(signV4Values.SignedHeaders, r)
  94. if errCode != s3err.ErrNone {
  95. return nil, errCode
  96. }
  97. // Verify if the access key id matches.
  98. identity, cred, found := iam.lookupByAccessKey(signV4Values.Credential.accessKey)
  99. if !found {
  100. return nil, s3err.ErrInvalidAccessKeyID
  101. }
  102. // Extract date, if not present throw error.
  103. var date string
  104. if date = req.Header.Get(http.CanonicalHeaderKey("X-Amz-Date")); date == "" {
  105. if date = r.Header.Get("Date"); date == "" {
  106. return nil, s3err.ErrMissingDateHeader
  107. }
  108. }
  109. // Parse date header.
  110. t, e := time.Parse(iso8601Format, date)
  111. if e != nil {
  112. return nil, s3err.ErrMalformedDate
  113. }
  114. // Query string.
  115. queryStr := req.URL.Query().Encode()
  116. // Get canonical request.
  117. canonicalRequest := getCanonicalRequest(extractedSignedHeaders, hashedPayload, queryStr, req.URL.Path, req.Method)
  118. // Get string to sign from canonical request.
  119. stringToSign := getStringToSign(canonicalRequest, t, signV4Values.Credential.getScope())
  120. // Get hmac signing key.
  121. signingKey := getSigningKey(cred.SecretKey, signV4Values.Credential.scope.date, signV4Values.Credential.scope.region)
  122. // Calculate signature.
  123. newSignature := getSignature(signingKey, stringToSign)
  124. // Verify if signature match.
  125. if !compareSignatureV4(newSignature, signV4Values.Signature) {
  126. return nil, s3err.ErrSignatureDoesNotMatch
  127. }
  128. // Return error none.
  129. return identity, s3err.ErrNone
  130. }
  131. // credentialHeader data type represents structured form of Credential
  132. // string from authorization header.
  133. type credentialHeader struct {
  134. accessKey string
  135. scope struct {
  136. date time.Time
  137. region string
  138. service string
  139. request string
  140. }
  141. }
  142. // signValues data type represents structured form of AWS Signature V4 header.
  143. type signValues struct {
  144. Credential credentialHeader
  145. SignedHeaders []string
  146. Signature string
  147. }
  148. // Return scope string.
  149. func (c credentialHeader) getScope() string {
  150. return strings.Join([]string{
  151. c.scope.date.Format(yyyymmdd),
  152. c.scope.region,
  153. c.scope.service,
  154. c.scope.request,
  155. }, "/")
  156. }
  157. // Authorization: algorithm Credential=accessKeyID/credScope, \
  158. // SignedHeaders=signedHeaders, Signature=signature
  159. //
  160. func parseSignV4(v4Auth string) (sv signValues, aec s3err.ErrorCode) {
  161. // Replace all spaced strings, some clients can send spaced
  162. // parameters and some won't. So we pro-actively remove any spaces
  163. // to make parsing easier.
  164. v4Auth = strings.Replace(v4Auth, " ", "", -1)
  165. if v4Auth == "" {
  166. return sv, s3err.ErrAuthHeaderEmpty
  167. }
  168. // Verify if the header algorithm is supported or not.
  169. if !strings.HasPrefix(v4Auth, signV4Algorithm) {
  170. return sv, s3err.ErrSignatureVersionNotSupported
  171. }
  172. // Strip off the Algorithm prefix.
  173. v4Auth = strings.TrimPrefix(v4Auth, signV4Algorithm)
  174. authFields := strings.Split(strings.TrimSpace(v4Auth), ",")
  175. if len(authFields) != 3 {
  176. return sv, s3err.ErrMissingFields
  177. }
  178. // Initialize signature version '4' structured header.
  179. signV4Values := signValues{}
  180. var err s3err.ErrorCode
  181. // Save credentail values.
  182. signV4Values.Credential, err = parseCredentialHeader(authFields[0])
  183. if err != s3err.ErrNone {
  184. return sv, err
  185. }
  186. // Save signed headers.
  187. signV4Values.SignedHeaders, err = parseSignedHeader(authFields[1])
  188. if err != s3err.ErrNone {
  189. return sv, err
  190. }
  191. // Save signature.
  192. signV4Values.Signature, err = parseSignature(authFields[2])
  193. if err != s3err.ErrNone {
  194. return sv, err
  195. }
  196. // Return the structure here.
  197. return signV4Values, s3err.ErrNone
  198. }
  199. // parse credentialHeader string into its structured form.
  200. func parseCredentialHeader(credElement string) (ch credentialHeader, aec s3err.ErrorCode) {
  201. creds := strings.Split(strings.TrimSpace(credElement), "=")
  202. if len(creds) != 2 {
  203. return ch, s3err.ErrMissingFields
  204. }
  205. if creds[0] != "Credential" {
  206. return ch, s3err.ErrMissingCredTag
  207. }
  208. credElements := strings.Split(strings.TrimSpace(creds[1]), "/")
  209. if len(credElements) != 5 {
  210. return ch, s3err.ErrCredMalformed
  211. }
  212. // Save access key id.
  213. cred := credentialHeader{
  214. accessKey: credElements[0],
  215. }
  216. var e error
  217. cred.scope.date, e = time.Parse(yyyymmdd, credElements[1])
  218. if e != nil {
  219. return ch, s3err.ErrMalformedCredentialDate
  220. }
  221. cred.scope.region = credElements[2]
  222. cred.scope.service = credElements[3] // "s3"
  223. cred.scope.request = credElements[4] // "aws4_request"
  224. return cred, s3err.ErrNone
  225. }
  226. // Parse slice of signed headers from signed headers tag.
  227. func parseSignedHeader(signedHdrElement string) ([]string, s3err.ErrorCode) {
  228. signedHdrFields := strings.Split(strings.TrimSpace(signedHdrElement), "=")
  229. if len(signedHdrFields) != 2 {
  230. return nil, s3err.ErrMissingFields
  231. }
  232. if signedHdrFields[0] != "SignedHeaders" {
  233. return nil, s3err.ErrMissingSignHeadersTag
  234. }
  235. if signedHdrFields[1] == "" {
  236. return nil, s3err.ErrMissingFields
  237. }
  238. signedHeaders := strings.Split(signedHdrFields[1], ";")
  239. return signedHeaders, s3err.ErrNone
  240. }
  241. // Parse signature from signature tag.
  242. func parseSignature(signElement string) (string, s3err.ErrorCode) {
  243. signFields := strings.Split(strings.TrimSpace(signElement), "=")
  244. if len(signFields) != 2 {
  245. return "", s3err.ErrMissingFields
  246. }
  247. if signFields[0] != "Signature" {
  248. return "", s3err.ErrMissingSignTag
  249. }
  250. if signFields[1] == "" {
  251. return "", s3err.ErrMissingFields
  252. }
  253. signature := signFields[1]
  254. return signature, s3err.ErrNone
  255. }
  256. // doesPolicySignatureMatch - Verify query headers with post policy
  257. // - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
  258. // returns ErrNone if the signature matches.
  259. func (iam *IdentityAccessManagement) doesPolicySignatureV4Match(formValues http.Header) s3err.ErrorCode {
  260. // Parse credential tag.
  261. credHeader, err := parseCredentialHeader("Credential=" + formValues.Get("X-Amz-Credential"))
  262. if err != s3err.ErrNone {
  263. return s3err.ErrMissingFields
  264. }
  265. _, cred, found := iam.lookupByAccessKey(credHeader.accessKey)
  266. if !found {
  267. return s3err.ErrInvalidAccessKeyID
  268. }
  269. // Get signing key.
  270. signingKey := getSigningKey(cred.SecretKey, credHeader.scope.date, credHeader.scope.region)
  271. // Get signature.
  272. newSignature := getSignature(signingKey, formValues.Get("Policy"))
  273. // Verify signature.
  274. if !compareSignatureV4(newSignature, formValues.Get("X-Amz-Signature")) {
  275. return s3err.ErrSignatureDoesNotMatch
  276. }
  277. // Success.
  278. return s3err.ErrNone
  279. }
  280. // check query headers with presigned signature
  281. // - http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
  282. func (iam *IdentityAccessManagement) doesPresignedSignatureMatch(hashedPayload string, r *http.Request) (*Identity, s3err.ErrorCode) {
  283. // Copy request
  284. req := *r
  285. // Parse request query string.
  286. pSignValues, err := parsePreSignV4(req.URL.Query())
  287. if err != s3err.ErrNone {
  288. return nil, err
  289. }
  290. // Verify if the access key id matches.
  291. identity, cred, found := iam.lookupByAccessKey(pSignValues.Credential.accessKey)
  292. if !found {
  293. return nil, s3err.ErrInvalidAccessKeyID
  294. }
  295. // Extract all the signed headers along with its values.
  296. extractedSignedHeaders, errCode := extractSignedHeaders(pSignValues.SignedHeaders, r)
  297. if errCode != s3err.ErrNone {
  298. return nil, errCode
  299. }
  300. // Construct new query.
  301. query := make(url.Values)
  302. if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
  303. query.Set("X-Amz-Content-Sha256", hashedPayload)
  304. }
  305. query.Set("X-Amz-Algorithm", signV4Algorithm)
  306. now := time.Now().UTC()
  307. // If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the
  308. // request should still be allowed.
  309. if pSignValues.Date.After(now.Add(15 * time.Minute)) {
  310. return nil, s3err.ErrRequestNotReadyYet
  311. }
  312. if now.Sub(pSignValues.Date) > pSignValues.Expires {
  313. return nil, s3err.ErrExpiredPresignRequest
  314. }
  315. // Save the date and expires.
  316. t := pSignValues.Date
  317. expireSeconds := int(pSignValues.Expires / time.Second)
  318. // Construct the query.
  319. query.Set("X-Amz-Date", t.Format(iso8601Format))
  320. query.Set("X-Amz-Expires", strconv.Itoa(expireSeconds))
  321. query.Set("X-Amz-SignedHeaders", getSignedHeaders(extractedSignedHeaders))
  322. query.Set("X-Amz-Credential", cred.AccessKey+"/"+getScope(t, pSignValues.Credential.scope.region))
  323. // Save other headers available in the request parameters.
  324. for k, v := range req.URL.Query() {
  325. // Handle the metadata in presigned put query string
  326. if strings.Contains(strings.ToLower(k), "x-amz-meta-") {
  327. query.Set(k, v[0])
  328. }
  329. if strings.HasPrefix(strings.ToLower(k), "x-amz") {
  330. continue
  331. }
  332. query[k] = v
  333. }
  334. // Get the encoded query.
  335. encodedQuery := query.Encode()
  336. // Verify if date query is same.
  337. if req.URL.Query().Get("X-Amz-Date") != query.Get("X-Amz-Date") {
  338. return nil, s3err.ErrSignatureDoesNotMatch
  339. }
  340. // Verify if expires query is same.
  341. if req.URL.Query().Get("X-Amz-Expires") != query.Get("X-Amz-Expires") {
  342. return nil, s3err.ErrSignatureDoesNotMatch
  343. }
  344. // Verify if signed headers query is same.
  345. if req.URL.Query().Get("X-Amz-SignedHeaders") != query.Get("X-Amz-SignedHeaders") {
  346. return nil, s3err.ErrSignatureDoesNotMatch
  347. }
  348. // Verify if credential query is same.
  349. if req.URL.Query().Get("X-Amz-Credential") != query.Get("X-Amz-Credential") {
  350. return nil, s3err.ErrSignatureDoesNotMatch
  351. }
  352. // Verify if sha256 payload query is same.
  353. if req.URL.Query().Get("X-Amz-Content-Sha256") != "" {
  354. if req.URL.Query().Get("X-Amz-Content-Sha256") != query.Get("X-Amz-Content-Sha256") {
  355. return nil, s3err.ErrContentSHA256Mismatch
  356. }
  357. }
  358. /// Verify finally if signature is same.
  359. // Get canonical request.
  360. presignedCanonicalReq := getCanonicalRequest(extractedSignedHeaders, hashedPayload, encodedQuery, req.URL.Path, req.Method)
  361. // Get string to sign from canonical request.
  362. presignedStringToSign := getStringToSign(presignedCanonicalReq, t, pSignValues.Credential.getScope())
  363. // Get hmac presigned signing key.
  364. presignedSigningKey := getSigningKey(cred.SecretKey, pSignValues.Credential.scope.date, pSignValues.Credential.scope.region)
  365. // Get new signature.
  366. newSignature := getSignature(presignedSigningKey, presignedStringToSign)
  367. // Verify signature.
  368. if !compareSignatureV4(req.URL.Query().Get("X-Amz-Signature"), newSignature) {
  369. return nil, s3err.ErrSignatureDoesNotMatch
  370. }
  371. return identity, s3err.ErrNone
  372. }
  373. func contains(list []string, elem string) bool {
  374. for _, t := range list {
  375. if t == elem {
  376. return true
  377. }
  378. }
  379. return false
  380. }
  381. // preSignValues data type represents structued form of AWS Signature V4 query string.
  382. type preSignValues struct {
  383. signValues
  384. Date time.Time
  385. Expires time.Duration
  386. }
  387. // Parses signature version '4' query string of the following form.
  388. //
  389. // querystring = X-Amz-Algorithm=algorithm
  390. // querystring += &X-Amz-Credential= urlencode(accessKey + '/' + credential_scope)
  391. // querystring += &X-Amz-Date=date
  392. // querystring += &X-Amz-Expires=timeout interval
  393. // querystring += &X-Amz-SignedHeaders=signed_headers
  394. // querystring += &X-Amz-Signature=signature
  395. //
  396. // verifies if any of the necessary query params are missing in the presigned request.
  397. func doesV4PresignParamsExist(query url.Values) s3err.ErrorCode {
  398. v4PresignQueryParams := []string{"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Signature", "X-Amz-Date", "X-Amz-SignedHeaders", "X-Amz-Expires"}
  399. for _, v4PresignQueryParam := range v4PresignQueryParams {
  400. if _, ok := query[v4PresignQueryParam]; !ok {
  401. return s3err.ErrInvalidQueryParams
  402. }
  403. }
  404. return s3err.ErrNone
  405. }
  406. // Parses all the presigned signature values into separate elements.
  407. func parsePreSignV4(query url.Values) (psv preSignValues, aec s3err.ErrorCode) {
  408. var err s3err.ErrorCode
  409. // verify whether the required query params exist.
  410. err = doesV4PresignParamsExist(query)
  411. if err != s3err.ErrNone {
  412. return psv, err
  413. }
  414. // Verify if the query algorithm is supported or not.
  415. if query.Get("X-Amz-Algorithm") != signV4Algorithm {
  416. return psv, s3err.ErrInvalidQuerySignatureAlgo
  417. }
  418. // Initialize signature version '4' structured header.
  419. preSignV4Values := preSignValues{}
  420. // Save credential.
  421. preSignV4Values.Credential, err = parseCredentialHeader("Credential=" + query.Get("X-Amz-Credential"))
  422. if err != s3err.ErrNone {
  423. return psv, err
  424. }
  425. var e error
  426. // Save date in native time.Time.
  427. preSignV4Values.Date, e = time.Parse(iso8601Format, query.Get("X-Amz-Date"))
  428. if e != nil {
  429. return psv, s3err.ErrMalformedPresignedDate
  430. }
  431. // Save expires in native time.Duration.
  432. preSignV4Values.Expires, e = time.ParseDuration(query.Get("X-Amz-Expires") + "s")
  433. if e != nil {
  434. return psv, s3err.ErrMalformedExpires
  435. }
  436. if preSignV4Values.Expires < 0 {
  437. return psv, s3err.ErrNegativeExpires
  438. }
  439. // Check if Expiry time is less than 7 days (value in seconds).
  440. if preSignV4Values.Expires.Seconds() > 604800 {
  441. return psv, s3err.ErrMaximumExpires
  442. }
  443. // Save signed headers.
  444. preSignV4Values.SignedHeaders, err = parseSignedHeader("SignedHeaders=" + query.Get("X-Amz-SignedHeaders"))
  445. if err != s3err.ErrNone {
  446. return psv, err
  447. }
  448. // Save signature.
  449. preSignV4Values.Signature, err = parseSignature("Signature=" + query.Get("X-Amz-Signature"))
  450. if err != s3err.ErrNone {
  451. return psv, err
  452. }
  453. // Return structed form of signature query string.
  454. return preSignV4Values, s3err.ErrNone
  455. }
  456. // extractSignedHeaders extract signed headers from Authorization header
  457. func extractSignedHeaders(signedHeaders []string, r *http.Request) (http.Header, s3err.ErrorCode) {
  458. reqHeaders := r.Header
  459. // find whether "host" is part of list of signed headers.
  460. // if not return ErrUnsignedHeaders. "host" is mandatory.
  461. if !contains(signedHeaders, "host") {
  462. return nil, s3err.ErrUnsignedHeaders
  463. }
  464. extractedSignedHeaders := make(http.Header)
  465. for _, header := range signedHeaders {
  466. // `host` will not be found in the headers, can be found in r.Host.
  467. // but its alway necessary that the list of signed headers containing host in it.
  468. val, ok := reqHeaders[http.CanonicalHeaderKey(header)]
  469. if ok {
  470. for _, enc := range val {
  471. extractedSignedHeaders.Add(header, enc)
  472. }
  473. continue
  474. }
  475. switch header {
  476. case "expect":
  477. // Golang http server strips off 'Expect' header, if the
  478. // client sent this as part of signed headers we need to
  479. // handle otherwise we would see a signature mismatch.
  480. // `aws-cli` sets this as part of signed headers.
  481. //
  482. // According to
  483. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20
  484. // Expect header is always of form:
  485. //
  486. // Expect = "Expect" ":" 1#expectation
  487. // expectation = "100-continue" | expectation-extension
  488. //
  489. // So it safe to assume that '100-continue' is what would
  490. // be sent, for the time being keep this work around.
  491. // Adding a *TODO* to remove this later when Golang server
  492. // doesn't filter out the 'Expect' header.
  493. extractedSignedHeaders.Set(header, "100-continue")
  494. case "host":
  495. // Go http server removes "host" from Request.Header
  496. extractedSignedHeaders.Set(header, r.Host)
  497. case "transfer-encoding":
  498. for _, enc := range r.TransferEncoding {
  499. extractedSignedHeaders.Add(header, enc)
  500. }
  501. case "content-length":
  502. // Signature-V4 spec excludes Content-Length from signed headers list for signature calculation.
  503. // But some clients deviate from this rule. Hence we consider Content-Length for signature
  504. // calculation to be compatible with such clients.
  505. extractedSignedHeaders.Set(header, strconv.FormatInt(r.ContentLength, 10))
  506. default:
  507. return nil, s3err.ErrUnsignedHeaders
  508. }
  509. }
  510. return extractedSignedHeaders, s3err.ErrNone
  511. }
  512. // getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names
  513. func getSignedHeaders(signedHeaders http.Header) string {
  514. var headers []string
  515. for k := range signedHeaders {
  516. headers = append(headers, strings.ToLower(k))
  517. }
  518. sort.Strings(headers)
  519. return strings.Join(headers, ";")
  520. }
  521. // getScope generate a string of a specific date, an AWS region, and a service.
  522. func getScope(t time.Time, region string) string {
  523. scope := strings.Join([]string{
  524. t.Format(yyyymmdd),
  525. region,
  526. "s3",
  527. "aws4_request",
  528. }, "/")
  529. return scope
  530. }
  531. // getCanonicalRequest generate a canonical request of style
  532. //
  533. // canonicalRequest =
  534. // <HTTPMethod>\n
  535. // <CanonicalURI>\n
  536. // <CanonicalQueryString>\n
  537. // <CanonicalHeaders>\n
  538. // <SignedHeaders>\n
  539. // <HashedPayload>
  540. //
  541. func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string) string {
  542. rawQuery := strings.Replace(queryStr, "+", "%20", -1)
  543. encodedPath := encodePath(urlPath)
  544. canonicalRequest := strings.Join([]string{
  545. method,
  546. encodedPath,
  547. rawQuery,
  548. getCanonicalHeaders(extractedSignedHeaders),
  549. getSignedHeaders(extractedSignedHeaders),
  550. payload,
  551. }, "\n")
  552. return canonicalRequest
  553. }
  554. // getStringToSign a string based on selected query values.
  555. func getStringToSign(canonicalRequest string, t time.Time, scope string) string {
  556. stringToSign := signV4Algorithm + "\n" + t.Format(iso8601Format) + "\n"
  557. stringToSign = stringToSign + scope + "\n"
  558. canonicalRequestBytes := sha256.Sum256([]byte(canonicalRequest))
  559. stringToSign = stringToSign + hex.EncodeToString(canonicalRequestBytes[:])
  560. return stringToSign
  561. }
  562. // sumHMAC calculate hmac between two input byte array.
  563. func sumHMAC(key []byte, data []byte) []byte {
  564. hash := hmac.New(sha256.New, key)
  565. hash.Write(data)
  566. return hash.Sum(nil)
  567. }
  568. // getSigningKey hmac seed to calculate final signature.
  569. func getSigningKey(secretKey string, t time.Time, region string) []byte {
  570. date := sumHMAC([]byte("AWS4"+secretKey), []byte(t.Format(yyyymmdd)))
  571. regionBytes := sumHMAC(date, []byte(region))
  572. service := sumHMAC(regionBytes, []byte("s3"))
  573. signingKey := sumHMAC(service, []byte("aws4_request"))
  574. return signingKey
  575. }
  576. // getSignature final signature in hexadecimal form.
  577. func getSignature(signingKey []byte, stringToSign string) string {
  578. return hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
  579. }
  580. // getCanonicalHeaders generate a list of request headers with their values
  581. func getCanonicalHeaders(signedHeaders http.Header) string {
  582. var headers []string
  583. vals := make(http.Header)
  584. for k, vv := range signedHeaders {
  585. headers = append(headers, strings.ToLower(k))
  586. vals[strings.ToLower(k)] = vv
  587. }
  588. sort.Strings(headers)
  589. var buf bytes.Buffer
  590. for _, k := range headers {
  591. buf.WriteString(k)
  592. buf.WriteByte(':')
  593. for idx, v := range vals[k] {
  594. if idx > 0 {
  595. buf.WriteByte(',')
  596. }
  597. buf.WriteString(signV4TrimAll(v))
  598. }
  599. buf.WriteByte('\n')
  600. }
  601. return buf.String()
  602. }
  603. // Trim leading and trailing spaces and replace sequential spaces with one space, following Trimall()
  604. // in http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
  605. func signV4TrimAll(input string) string {
  606. // Compress adjacent spaces (a space is determined by
  607. // unicode.IsSpace() internally here) to one space and return
  608. return strings.Join(strings.Fields(input), " ")
  609. }
  610. // if object matches reserved string, no need to encode them
  611. var reservedObjectNames = regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
  612. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  613. //
  614. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  615. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  616. //
  617. // This function on the other hand is a direct replacement for url.Encode() technique to support
  618. // pretty much every UTF-8 character.
  619. func encodePath(pathName string) string {
  620. if reservedObjectNames.MatchString(pathName) {
  621. return pathName
  622. }
  623. var encodedPathname string
  624. for _, s := range pathName {
  625. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  626. encodedPathname = encodedPathname + string(s)
  627. continue
  628. }
  629. switch s {
  630. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  631. encodedPathname = encodedPathname + string(s)
  632. continue
  633. default:
  634. len := utf8.RuneLen(s)
  635. if len < 0 {
  636. // if utf8 cannot convert return the same string as is
  637. return pathName
  638. }
  639. u := make([]byte, len)
  640. utf8.EncodeRune(u, s)
  641. for _, r := range u {
  642. hex := hex.EncodeToString([]byte{r})
  643. encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
  644. }
  645. }
  646. }
  647. return encodedPathname
  648. }
  649. // compareSignatureV4 returns true if and only if both signatures
  650. // are equal. The signatures are expected to be HEX encoded strings
  651. // according to the AWS S3 signature V4 spec.
  652. func compareSignatureV4(sig1, sig2 string) bool {
  653. // The CTC using []byte(str) works because the hex encoding
  654. // is unique for a sequence of bytes. See also compareSignatureV2.
  655. return subtle.ConstantTimeCompare([]byte(sig1), []byte(sig2)) == 1
  656. }