auth_signature_v4.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. // Golang http server strips off 'Expect' header, if the
  573. // client sent this as part of signed headers we need to
  574. // handle otherwise we would see a signature mismatch.
  575. // `aws-cli` sets this as part of signed headers.
  576. //
  577. // According to
  578. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20
  579. // Expect header is always of form:
  580. //
  581. // Expect = "Expect" ":" 1#expectation
  582. // expectation = "100-continue" | expectation-extension
  583. //
  584. // So it safe to assume that '100-continue' is what would
  585. // be sent, for the time being keep this work around.
  586. // Adding a *TODO* to remove this later when Golang server
  587. // doesn't filter out the 'Expect' header.
  588. extractedSignedHeaders.Set(header, "100-continue")
  589. case "host":
  590. // Go http server removes "host" from Request.Header
  591. if forwardedHost := r.Header.Get("X-Forwarded-Host"); forwardedHost != "" {
  592. extractedSignedHeaders.Set(header, forwardedHost)
  593. } else {
  594. extractedSignedHeaders.Set(header, r.Host)
  595. }
  596. case "transfer-encoding":
  597. for _, enc := range r.TransferEncoding {
  598. extractedSignedHeaders.Add(header, enc)
  599. }
  600. case "content-length":
  601. // Signature-V4 spec excludes Content-Length from signed headers list for signature calculation.
  602. // But some clients deviate from this rule. Hence we consider Content-Length for signature
  603. // calculation to be compatible with such clients.
  604. extractedSignedHeaders.Set(header, strconv.FormatInt(r.ContentLength, 10))
  605. default:
  606. return nil, s3err.ErrUnsignedHeaders
  607. }
  608. }
  609. return extractedSignedHeaders, s3err.ErrNone
  610. }
  611. // getSignedHeaders generate a string i.e alphabetically sorted, semicolon-separated list of lowercase request header names
  612. func getSignedHeaders(signedHeaders http.Header) string {
  613. var headers []string
  614. for k := range signedHeaders {
  615. headers = append(headers, strings.ToLower(k))
  616. }
  617. sort.Strings(headers)
  618. return strings.Join(headers, ";")
  619. }
  620. // getScope generate a string of a specific date, an AWS region, and a service.
  621. func getScope(t time.Time, region string) string {
  622. scope := strings.Join([]string{
  623. t.Format(yyyymmdd),
  624. region,
  625. "s3",
  626. "aws4_request",
  627. }, "/")
  628. return scope
  629. }
  630. // getCanonicalRequest generate a canonical request of style
  631. //
  632. // canonicalRequest =
  633. //
  634. // <HTTPMethod>\n
  635. // <CanonicalURI>\n
  636. // <CanonicalQueryString>\n
  637. // <CanonicalHeaders>\n
  638. // <SignedHeaders>\n
  639. // <HashedPayload>
  640. func getCanonicalRequest(extractedSignedHeaders http.Header, payload, queryStr, urlPath, method string) string {
  641. rawQuery := strings.Replace(queryStr, "+", "%20", -1)
  642. encodedPath := encodePath(urlPath)
  643. canonicalRequest := strings.Join([]string{
  644. method,
  645. encodedPath,
  646. rawQuery,
  647. getCanonicalHeaders(extractedSignedHeaders),
  648. getSignedHeaders(extractedSignedHeaders),
  649. payload,
  650. }, "\n")
  651. return canonicalRequest
  652. }
  653. // getStringToSign a string based on selected query values.
  654. func getStringToSign(canonicalRequest string, t time.Time, scope string) string {
  655. stringToSign := signV4Algorithm + "\n" + t.Format(iso8601Format) + "\n"
  656. stringToSign = stringToSign + scope + "\n"
  657. canonicalRequestBytes := sha256.Sum256([]byte(canonicalRequest))
  658. stringToSign = stringToSign + hex.EncodeToString(canonicalRequestBytes[:])
  659. return stringToSign
  660. }
  661. // sumHMAC calculate hmac between two input byte array.
  662. func sumHMAC(key []byte, data []byte) []byte {
  663. hash := hmac.New(sha256.New, key)
  664. hash.Write(data)
  665. return hash.Sum(nil)
  666. }
  667. // getSigningKey hmac seed to calculate final signature.
  668. func getSigningKey(secretKey string, time string, region string, service string) []byte {
  669. date := sumHMAC([]byte("AWS4"+secretKey), []byte(time))
  670. regionBytes := sumHMAC(date, []byte(region))
  671. serviceBytes := sumHMAC(regionBytes, []byte(service))
  672. signingKey := sumHMAC(serviceBytes, []byte("aws4_request"))
  673. return signingKey
  674. }
  675. // getCanonicalHeaders generate a list of request headers with their values
  676. func getCanonicalHeaders(signedHeaders http.Header) string {
  677. var headers []string
  678. vals := make(http.Header)
  679. for k, vv := range signedHeaders {
  680. headers = append(headers, strings.ToLower(k))
  681. vals[strings.ToLower(k)] = vv
  682. }
  683. sort.Strings(headers)
  684. var buf bytes.Buffer
  685. for _, k := range headers {
  686. buf.WriteString(k)
  687. buf.WriteByte(':')
  688. for idx, v := range vals[k] {
  689. if idx > 0 {
  690. buf.WriteByte(',')
  691. }
  692. buf.WriteString(signV4TrimAll(v))
  693. }
  694. buf.WriteByte('\n')
  695. }
  696. return buf.String()
  697. }
  698. // Trim leading and trailing spaces and replace sequential spaces with one space, following Trimall()
  699. // in http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
  700. func signV4TrimAll(input string) string {
  701. // Compress adjacent spaces (a space is determined by
  702. // unicode.IsSpace() internally here) to one space and return
  703. return strings.Join(strings.Fields(input), " ")
  704. }
  705. // if object matches reserved string, no need to encode them
  706. var reservedObjectNames = regexp.MustCompile("^[a-zA-Z0-9-_.~/]+$")
  707. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  708. //
  709. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  710. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  711. //
  712. // This function on the other hand is a direct replacement for url.Encode() technique to support
  713. // pretty much every UTF-8 character.
  714. func encodePath(pathName string) string {
  715. if reservedObjectNames.MatchString(pathName) {
  716. return pathName
  717. }
  718. var encodedPathname string
  719. for _, s := range pathName {
  720. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  721. encodedPathname = encodedPathname + string(s)
  722. continue
  723. }
  724. switch s {
  725. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  726. encodedPathname = encodedPathname + string(s)
  727. continue
  728. default:
  729. len := utf8.RuneLen(s)
  730. if len < 0 {
  731. // if utf8 cannot convert return the same string as is
  732. return pathName
  733. }
  734. u := make([]byte, len)
  735. utf8.EncodeRune(u, s)
  736. for _, r := range u {
  737. hex := hex.EncodeToString([]byte{r})
  738. encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
  739. }
  740. }
  741. }
  742. return encodedPathname
  743. }
  744. // compareSignatureV4 returns true if and only if both signatures
  745. // are equal. The signatures are expected to be HEX encoded strings
  746. // according to the AWS S3 signature V4 spec.
  747. func compareSignatureV4(sig1, sig2 string) bool {
  748. // The CTC using []byte(str) works because the hex encoding
  749. // is unique for a sequence of bytes. See also compareSignatureV2.
  750. return subtle.ConstantTimeCompare([]byte(sig1), []byte(sig2)) == 1
  751. }