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.

428 lines
13 KiB

5 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
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
2 years ago
5 years ago
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
  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. "crypto/hmac"
  19. "crypto/sha1"
  20. "crypto/subtle"
  21. "encoding/base64"
  22. "fmt"
  23. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  24. "net"
  25. "net/http"
  26. "net/url"
  27. "path"
  28. "sort"
  29. "strconv"
  30. "strings"
  31. "time"
  32. )
  33. // Whitelist resource list that will be used in query string for signature-V2 calculation.
  34. // The list should be alphabetically sorted
  35. var resourceList = []string{
  36. "acl",
  37. "delete",
  38. "lifecycle",
  39. "location",
  40. "logging",
  41. "notification",
  42. "partNumber",
  43. "policy",
  44. "requestPayment",
  45. "response-cache-control",
  46. "response-content-disposition",
  47. "response-content-encoding",
  48. "response-content-language",
  49. "response-content-type",
  50. "response-expires",
  51. "torrent",
  52. "uploadId",
  53. "uploads",
  54. "versionId",
  55. "versioning",
  56. "versions",
  57. "website",
  58. }
  59. // Verify if request has valid AWS Signature Version '2'.
  60. func (iam *IdentityAccessManagement) isReqAuthenticatedV2(r *http.Request) (*Identity, s3err.ErrorCode) {
  61. if isRequestSignatureV2(r) {
  62. return iam.doesSignV2Match(r)
  63. }
  64. return iam.doesPresignV2SignatureMatch(r)
  65. }
  66. func (iam *IdentityAccessManagement) doesPolicySignatureV2Match(formValues http.Header) s3err.ErrorCode {
  67. accessKey := formValues.Get("AWSAccessKeyId")
  68. _, cred, found := iam.lookupByAccessKey(accessKey)
  69. if !found {
  70. return s3err.ErrInvalidAccessKeyID
  71. }
  72. policy := formValues.Get("Policy")
  73. signature := formValues.Get("Signature")
  74. if !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) {
  75. return s3err.ErrSignatureDoesNotMatch
  76. }
  77. return s3err.ErrNone
  78. }
  79. // Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
  80. // Signature = Base64( HMAC-SHA1( YourSecretKey, UTF-8-Encoding-Of( StringToSign ) ) );
  81. //
  82. // StringToSign = HTTP-Verb + "\n" +
  83. // Content-Md5 + "\n" +
  84. // Content-Type + "\n" +
  85. // Date + "\n" +
  86. // CanonicalizedProtocolHeaders +
  87. // CanonicalizedResource;
  88. //
  89. // CanonicalizedResource = [ "/" + Bucket ] +
  90. // <HTTP-Request-URI, from the protocol name up to the query string> +
  91. // [ subresource, if present. For example "?acl", "?location", "?logging", or "?torrent"];
  92. //
  93. // CanonicalizedProtocolHeaders = <described below>
  94. // doesSignV2Match - Verify authorization header with calculated header in accordance with
  95. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/auth-request-sig-v2.html
  96. // returns true if matches, false otherwise. if error is not nil then it is always false
  97. func validateV2AuthHeader(v2Auth string) (accessKey string, errCode s3err.ErrorCode) {
  98. if v2Auth == "" {
  99. return "", s3err.ErrAuthHeaderEmpty
  100. }
  101. // Verify if the header algorithm is supported or not.
  102. if !strings.HasPrefix(v2Auth, signV2Algorithm) {
  103. return "", s3err.ErrSignatureVersionNotSupported
  104. }
  105. // below is V2 Signed Auth header format, splitting on `space` (after the `AWS` string).
  106. // Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature
  107. authFields := strings.Split(v2Auth, " ")
  108. if len(authFields) != 2 {
  109. return "", s3err.ErrMissingFields
  110. }
  111. // Then will be splitting on ":", this will separate `AWSAccessKeyId` and `Signature` string.
  112. keySignFields := strings.Split(strings.TrimSpace(authFields[1]), ":")
  113. if len(keySignFields) != 2 {
  114. return "", s3err.ErrMissingFields
  115. }
  116. return keySignFields[0], s3err.ErrNone
  117. }
  118. func (iam *IdentityAccessManagement) doesSignV2Match(r *http.Request) (*Identity, s3err.ErrorCode) {
  119. v2Auth := r.Header.Get("Authorization")
  120. accessKey, apiError := validateV2AuthHeader(v2Auth)
  121. if apiError != s3err.ErrNone {
  122. return nil, apiError
  123. }
  124. // Access credentials.
  125. // Validate if access key id same.
  126. ident, cred, found := iam.lookupByAccessKey(accessKey)
  127. if !found {
  128. return nil, s3err.ErrInvalidAccessKeyID
  129. }
  130. // r.RequestURI will have raw encoded URI as sent by the client.
  131. tokens := strings.SplitN(r.RequestURI, "?", 2)
  132. encodedResource := tokens[0]
  133. encodedQuery := ""
  134. if len(tokens) == 2 {
  135. encodedQuery = tokens[1]
  136. }
  137. unescapedQueries, err := unescapeQueries(encodedQuery)
  138. if err != nil {
  139. return nil, s3err.ErrInvalidQueryParams
  140. }
  141. encodedResource, err = getResource(encodedResource, r.Host, iam.domain)
  142. if err != nil {
  143. return nil, s3err.ErrInvalidRequest
  144. }
  145. prefix := fmt.Sprintf("%s %s:", signV2Algorithm, cred.AccessKey)
  146. if !strings.HasPrefix(v2Auth, prefix) {
  147. return nil, s3err.ErrSignatureDoesNotMatch
  148. }
  149. v2Auth = v2Auth[len(prefix):]
  150. expectedAuth := signatureV2(cred, r.Method, encodedResource, strings.Join(unescapedQueries, "&"), r.Header)
  151. if !compareSignatureV2(v2Auth, expectedAuth) {
  152. return nil, s3err.ErrSignatureDoesNotMatch
  153. }
  154. return ident, s3err.ErrNone
  155. }
  156. // doesPresignV2SignatureMatch - Verify query headers with presigned signature
  157. // - http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html#RESTAuthenticationQueryStringAuth
  158. //
  159. // returns ErrNone if matches. S3 errors otherwise.
  160. func (iam *IdentityAccessManagement) doesPresignV2SignatureMatch(r *http.Request) (*Identity, s3err.ErrorCode) {
  161. // r.RequestURI will have raw encoded URI as sent by the client.
  162. tokens := strings.SplitN(r.RequestURI, "?", 2)
  163. encodedResource := tokens[0]
  164. encodedQuery := ""
  165. if len(tokens) == 2 {
  166. encodedQuery = tokens[1]
  167. }
  168. var (
  169. filteredQueries []string
  170. gotSignature string
  171. expires string
  172. accessKey string
  173. err error
  174. )
  175. var unescapedQueries []string
  176. unescapedQueries, err = unescapeQueries(encodedQuery)
  177. if err != nil {
  178. return nil, s3err.ErrInvalidQueryParams
  179. }
  180. // Extract the necessary values from presigned query, construct a list of new filtered queries.
  181. for _, query := range unescapedQueries {
  182. keyval := strings.SplitN(query, "=", 2)
  183. if len(keyval) != 2 {
  184. return nil, s3err.ErrInvalidQueryParams
  185. }
  186. switch keyval[0] {
  187. case "AWSAccessKeyId":
  188. accessKey = keyval[1]
  189. case "Signature":
  190. gotSignature = keyval[1]
  191. case "Expires":
  192. expires = keyval[1]
  193. default:
  194. filteredQueries = append(filteredQueries, query)
  195. }
  196. }
  197. // Invalid values returns error.
  198. if accessKey == "" || gotSignature == "" || expires == "" {
  199. return nil, s3err.ErrInvalidQueryParams
  200. }
  201. // Validate if access key id same.
  202. ident, cred, found := iam.lookupByAccessKey(accessKey)
  203. if !found {
  204. return nil, s3err.ErrInvalidAccessKeyID
  205. }
  206. // Make sure the request has not expired.
  207. expiresInt, err := strconv.ParseInt(expires, 10, 64)
  208. if err != nil {
  209. return nil, s3err.ErrMalformedExpires
  210. }
  211. // Check if the presigned URL has expired.
  212. if expiresInt < time.Now().UTC().Unix() {
  213. return nil, s3err.ErrExpiredPresignRequest
  214. }
  215. encodedResource, err = getResource(encodedResource, r.Host, iam.domain)
  216. if err != nil {
  217. return nil, s3err.ErrInvalidRequest
  218. }
  219. expectedSignature := preSignatureV2(cred, r.Method, encodedResource, strings.Join(filteredQueries, "&"), r.Header, expires)
  220. if !compareSignatureV2(gotSignature, expectedSignature) {
  221. return nil, s3err.ErrSignatureDoesNotMatch
  222. }
  223. return ident, s3err.ErrNone
  224. }
  225. // Escape encodedQuery string into unescaped list of query params, returns error
  226. // if any while unescaping the values.
  227. func unescapeQueries(encodedQuery string) (unescapedQueries []string, err error) {
  228. for _, query := range strings.Split(encodedQuery, "&") {
  229. var unescapedQuery string
  230. unescapedQuery, err = url.QueryUnescape(query)
  231. if err != nil {
  232. return nil, err
  233. }
  234. unescapedQueries = append(unescapedQueries, unescapedQuery)
  235. }
  236. return unescapedQueries, nil
  237. }
  238. // Returns "/bucketName/objectName" for path-style or virtual-host-style requests.
  239. func getResource(path string, host string, domain string) (string, error) {
  240. if domain == "" {
  241. return path, nil
  242. }
  243. // If virtual-host-style is enabled construct the "resource" properly.
  244. if strings.Contains(host, ":") {
  245. // In bucket.mydomain.com:9000, strip out :9000
  246. var err error
  247. if host, _, err = net.SplitHostPort(host); err != nil {
  248. return "", err
  249. }
  250. }
  251. if !strings.HasSuffix(host, "."+domain) {
  252. return path, nil
  253. }
  254. bucket := strings.TrimSuffix(host, "."+domain)
  255. return "/" + pathJoin(bucket, path), nil
  256. }
  257. // pathJoin - like path.Join() but retains trailing "/" of the last element
  258. func pathJoin(elem ...string) string {
  259. trailingSlash := ""
  260. if len(elem) > 0 {
  261. if strings.HasSuffix(elem[len(elem)-1], "/") {
  262. trailingSlash = "/"
  263. }
  264. }
  265. return path.Join(elem...) + trailingSlash
  266. }
  267. // Return the signature v2 of a given request.
  268. func signatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header) string {
  269. stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, "")
  270. signature := calculateSignatureV2(stringToSign, cred.SecretKey)
  271. return signature
  272. }
  273. // Return string to sign under two different conditions.
  274. // - if expires string is set then string to sign includes date instead of the Date header.
  275. // - if expires string is empty then string to sign includes date header instead.
  276. func getStringToSignV2(method string, encodedResource, encodedQuery string, headers http.Header, expires string) string {
  277. canonicalHeaders := canonicalizedAmzHeadersV2(headers)
  278. if len(canonicalHeaders) > 0 {
  279. canonicalHeaders += "\n"
  280. }
  281. date := expires // Date is set to expires date for presign operations.
  282. if date == "" {
  283. // If expires date is empty then request header Date is used.
  284. date = headers.Get("Date")
  285. }
  286. // From the Amazon docs:
  287. //
  288. // StringToSign = HTTP-Verb + "\n" +
  289. // Content-Md5 + "\n" +
  290. // Content-Type + "\n" +
  291. // Date/Expires + "\n" +
  292. // CanonicalizedProtocolHeaders +
  293. // CanonicalizedResource;
  294. stringToSign := strings.Join([]string{
  295. method,
  296. headers.Get("Content-MD5"),
  297. headers.Get("Content-Type"),
  298. date,
  299. canonicalHeaders,
  300. }, "\n")
  301. return stringToSign + canonicalizedResourceV2(encodedResource, encodedQuery)
  302. }
  303. // Return canonical resource string.
  304. func canonicalizedResourceV2(encodedResource, encodedQuery string) string {
  305. queries := strings.Split(encodedQuery, "&")
  306. keyval := make(map[string]string)
  307. for _, query := range queries {
  308. key := query
  309. val := ""
  310. index := strings.Index(query, "=")
  311. if index != -1 {
  312. key = query[:index]
  313. val = query[index+1:]
  314. }
  315. keyval[key] = val
  316. }
  317. var canonicalQueries []string
  318. for _, key := range resourceList {
  319. val, ok := keyval[key]
  320. if !ok {
  321. continue
  322. }
  323. if val == "" {
  324. canonicalQueries = append(canonicalQueries, key)
  325. continue
  326. }
  327. canonicalQueries = append(canonicalQueries, key+"="+val)
  328. }
  329. // The queries will be already sorted as resourceList is sorted, if canonicalQueries
  330. // is empty strings.Join returns empty.
  331. canonicalQuery := strings.Join(canonicalQueries, "&")
  332. if canonicalQuery != "" {
  333. return encodedResource + "?" + canonicalQuery
  334. }
  335. return encodedResource
  336. }
  337. // Return canonical headers.
  338. func canonicalizedAmzHeadersV2(headers http.Header) string {
  339. var keys []string
  340. keyval := make(map[string]string)
  341. for key := range headers {
  342. lkey := strings.ToLower(key)
  343. if !strings.HasPrefix(lkey, "x-amz-") {
  344. continue
  345. }
  346. keys = append(keys, lkey)
  347. keyval[lkey] = strings.Join(headers[key], ",")
  348. }
  349. sort.Strings(keys)
  350. var canonicalHeaders []string
  351. for _, key := range keys {
  352. canonicalHeaders = append(canonicalHeaders, key+":"+keyval[key])
  353. }
  354. return strings.Join(canonicalHeaders, "\n")
  355. }
  356. func calculateSignatureV2(stringToSign string, secret string) string {
  357. hm := hmac.New(sha1.New, []byte(secret))
  358. hm.Write([]byte(stringToSign))
  359. return base64.StdEncoding.EncodeToString(hm.Sum(nil))
  360. }
  361. // compareSignatureV2 returns true if and only if both signatures
  362. // are equal. The signatures are expected to be base64 encoded strings
  363. // according to the AWS S3 signature V2 spec.
  364. func compareSignatureV2(sig1, sig2 string) bool {
  365. // Decode signature string to binary byte-sequence representation is required
  366. // as Base64 encoding of a value is not unique:
  367. // For example "aGVsbG8=" and "aGVsbG8=\r" will result in the same byte slice.
  368. signature1, err := base64.StdEncoding.DecodeString(sig1)
  369. if err != nil {
  370. return false
  371. }
  372. signature2, err := base64.StdEncoding.DecodeString(sig2)
  373. if err != nil {
  374. return false
  375. }
  376. return subtle.ConstantTimeCompare(signature1, signature2) == 1
  377. }
  378. // Return signature-v2 for the presigned request.
  379. func preSignatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header, expires string) string {
  380. stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, expires)
  381. return calculateSignatureV2(stringToSign, cred.SecretKey)
  382. }