auth_signature_v2.go 12 KB

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