auth_signature_v2.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. 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 seprate `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. // returns ErrNone if matches. S3 errors otherwise.
  159. func (iam *IdentityAccessManagement) doesPresignV2SignatureMatch(r *http.Request) (*Identity, s3err.ErrorCode) {
  160. // r.RequestURI will have raw encoded URI as sent by the client.
  161. tokens := strings.SplitN(r.RequestURI, "?", 2)
  162. encodedResource := tokens[0]
  163. encodedQuery := ""
  164. if len(tokens) == 2 {
  165. encodedQuery = tokens[1]
  166. }
  167. var (
  168. filteredQueries []string
  169. gotSignature string
  170. expires string
  171. accessKey string
  172. err error
  173. )
  174. var unescapedQueries []string
  175. unescapedQueries, err = unescapeQueries(encodedQuery)
  176. if err != nil {
  177. return nil, s3err.ErrInvalidQueryParams
  178. }
  179. // Extract the necessary values from presigned query, construct a list of new filtered queries.
  180. for _, query := range unescapedQueries {
  181. keyval := strings.SplitN(query, "=", 2)
  182. if len(keyval) != 2 {
  183. return nil, s3err.ErrInvalidQueryParams
  184. }
  185. switch keyval[0] {
  186. case "AWSAccessKeyId":
  187. accessKey = keyval[1]
  188. case "Signature":
  189. gotSignature = keyval[1]
  190. case "Expires":
  191. expires = keyval[1]
  192. default:
  193. filteredQueries = append(filteredQueries, query)
  194. }
  195. }
  196. // Invalid values returns error.
  197. if accessKey == "" || gotSignature == "" || expires == "" {
  198. return nil, s3err.ErrInvalidQueryParams
  199. }
  200. // Validate if access key id same.
  201. ident, cred, found := iam.lookupByAccessKey(accessKey)
  202. if !found {
  203. return nil, s3err.ErrInvalidAccessKeyID
  204. }
  205. // Make sure the request has not expired.
  206. expiresInt, err := strconv.ParseInt(expires, 10, 64)
  207. if err != nil {
  208. return nil, s3err.ErrMalformedExpires
  209. }
  210. // Check if the presigned URL has expired.
  211. if expiresInt < time.Now().UTC().Unix() {
  212. return nil, s3err.ErrExpiredPresignRequest
  213. }
  214. encodedResource, err = getResource(encodedResource, r.Host, iam.domain)
  215. if err != nil {
  216. return nil, s3err.ErrInvalidRequest
  217. }
  218. expectedSignature := preSignatureV2(cred, r.Method, encodedResource, strings.Join(filteredQueries, "&"), r.Header, expires)
  219. if !compareSignatureV2(gotSignature, expectedSignature) {
  220. return nil, s3err.ErrSignatureDoesNotMatch
  221. }
  222. return ident, s3err.ErrNone
  223. }
  224. // Escape encodedQuery string into unescaped list of query params, returns error
  225. // if any while unescaping the values.
  226. func unescapeQueries(encodedQuery string) (unescapedQueries []string, err error) {
  227. for _, query := range strings.Split(encodedQuery, "&") {
  228. var unescapedQuery string
  229. unescapedQuery, err = url.QueryUnescape(query)
  230. if err != nil {
  231. return nil, err
  232. }
  233. unescapedQueries = append(unescapedQueries, unescapedQuery)
  234. }
  235. return unescapedQueries, nil
  236. }
  237. // Returns "/bucketName/objectName" for path-style or virtual-host-style requests.
  238. func getResource(path string, host string, domain string) (string, error) {
  239. if domain == "" {
  240. return path, nil
  241. }
  242. // If virtual-host-style is enabled construct the "resource" properly.
  243. if strings.Contains(host, ":") {
  244. // In bucket.mydomain.com:9000, strip out :9000
  245. var err error
  246. if host, _, err = net.SplitHostPort(host); err != nil {
  247. return "", err
  248. }
  249. }
  250. if !strings.HasSuffix(host, "."+domain) {
  251. return path, nil
  252. }
  253. bucket := strings.TrimSuffix(host, "."+domain)
  254. return "/" + pathJoin(bucket, path), nil
  255. }
  256. // pathJoin - like path.Join() but retains trailing "/" of the last element
  257. func pathJoin(elem ...string) string {
  258. trailingSlash := ""
  259. if len(elem) > 0 {
  260. if strings.HasSuffix(elem[len(elem)-1], "/") {
  261. trailingSlash = "/"
  262. }
  263. }
  264. return path.Join(elem...) + trailingSlash
  265. }
  266. // Return the signature v2 of a given request.
  267. func signatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header) string {
  268. stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, "")
  269. signature := calculateSignatureV2(stringToSign, cred.SecretKey)
  270. return signature
  271. }
  272. // Return string to sign under two different conditions.
  273. // - if expires string is set then string to sign includes date instead of the Date header.
  274. // - if expires string is empty then string to sign includes date header instead.
  275. func getStringToSignV2(method string, encodedResource, encodedQuery string, headers http.Header, expires string) string {
  276. canonicalHeaders := canonicalizedAmzHeadersV2(headers)
  277. if len(canonicalHeaders) > 0 {
  278. canonicalHeaders += "\n"
  279. }
  280. date := expires // Date is set to expires date for presign operations.
  281. if date == "" {
  282. // If expires date is empty then request header Date is used.
  283. date = headers.Get("Date")
  284. }
  285. // From the Amazon docs:
  286. //
  287. // StringToSign = HTTP-Verb + "\n" +
  288. // Content-Md5 + "\n" +
  289. // Content-Type + "\n" +
  290. // Date/Expires + "\n" +
  291. // CanonicalizedProtocolHeaders +
  292. // CanonicalizedResource;
  293. stringToSign := strings.Join([]string{
  294. method,
  295. headers.Get("Content-MD5"),
  296. headers.Get("Content-Type"),
  297. date,
  298. canonicalHeaders,
  299. }, "\n")
  300. return stringToSign + canonicalizedResourceV2(encodedResource, encodedQuery)
  301. }
  302. // Return canonical resource string.
  303. func canonicalizedResourceV2(encodedResource, encodedQuery string) string {
  304. queries := strings.Split(encodedQuery, "&")
  305. keyval := make(map[string]string)
  306. for _, query := range queries {
  307. key := query
  308. val := ""
  309. index := strings.Index(query, "=")
  310. if index != -1 {
  311. key = query[:index]
  312. val = query[index+1:]
  313. }
  314. keyval[key] = val
  315. }
  316. var canonicalQueries []string
  317. for _, key := range resourceList {
  318. val, ok := keyval[key]
  319. if !ok {
  320. continue
  321. }
  322. if val == "" {
  323. canonicalQueries = append(canonicalQueries, key)
  324. continue
  325. }
  326. canonicalQueries = append(canonicalQueries, key+"="+val)
  327. }
  328. // The queries will be already sorted as resourceList is sorted, if canonicalQueries
  329. // is empty strings.Join returns empty.
  330. canonicalQuery := strings.Join(canonicalQueries, "&")
  331. if canonicalQuery != "" {
  332. return encodedResource + "?" + canonicalQuery
  333. }
  334. return encodedResource
  335. }
  336. // Return canonical headers.
  337. func canonicalizedAmzHeadersV2(headers http.Header) string {
  338. var keys []string
  339. keyval := make(map[string]string)
  340. for key := range headers {
  341. lkey := strings.ToLower(key)
  342. if !strings.HasPrefix(lkey, "x-amz-") {
  343. continue
  344. }
  345. keys = append(keys, lkey)
  346. keyval[lkey] = strings.Join(headers[key], ",")
  347. }
  348. sort.Strings(keys)
  349. var canonicalHeaders []string
  350. for _, key := range keys {
  351. canonicalHeaders = append(canonicalHeaders, key+":"+keyval[key])
  352. }
  353. return strings.Join(canonicalHeaders, "\n")
  354. }
  355. func calculateSignatureV2(stringToSign string, secret string) string {
  356. hm := hmac.New(sha1.New, []byte(secret))
  357. hm.Write([]byte(stringToSign))
  358. return base64.StdEncoding.EncodeToString(hm.Sum(nil))
  359. }
  360. // compareSignatureV2 returns true if and only if both signatures
  361. // are equal. The signatures are expected to be base64 encoded strings
  362. // according to the AWS S3 signature V2 spec.
  363. func compareSignatureV2(sig1, sig2 string) bool {
  364. // Decode signature string to binary byte-sequence representation is required
  365. // as Base64 encoding of a value is not unique:
  366. // For example "aGVsbG8=" and "aGVsbG8=\r" will result in the same byte slice.
  367. signature1, err := base64.StdEncoding.DecodeString(sig1)
  368. if err != nil {
  369. return false
  370. }
  371. signature2, err := base64.StdEncoding.DecodeString(sig2)
  372. if err != nil {
  373. return false
  374. }
  375. return subtle.ConstantTimeCompare(signature1, signature2) == 1
  376. }
  377. // Return signature-v2 for the presigned request.
  378. func preSignatureV2(cred *Credential, method string, encodedResource string, encodedQuery string, headers http.Header, expires string) string {
  379. stringToSign := getStringToSignV2(method, encodedResource, encodedQuery, headers, expires)
  380. return calculateSignatureV2(stringToSign, cred.SecretKey)
  381. }