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.

777 lines
24 KiB

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