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.

803 lines
24 KiB

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