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.

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