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.

413 lines
12 KiB

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