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.

770 lines
24 KiB

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