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.

435 lines
12 KiB

5 years ago
5 years ago
5 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
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package s3api
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "testing"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  21. )
  22. // TestIsRequestPresignedSignatureV4 - Test validates the logic for presign signature version v4 detection.
  23. func TestIsRequestPresignedSignatureV4(t *testing.T) {
  24. testCases := []struct {
  25. inputQueryKey string
  26. inputQueryValue string
  27. expectedResult bool
  28. }{
  29. // Test case - 1.
  30. // Test case with query key ""X-Amz-Credential" set.
  31. {"", "", false},
  32. // Test case - 2.
  33. {"X-Amz-Credential", "", true},
  34. // Test case - 3.
  35. {"X-Amz-Content-Sha256", "", false},
  36. }
  37. for i, testCase := range testCases {
  38. // creating an input HTTP request.
  39. // Only the query parameters are relevant for this particular test.
  40. inputReq, err := http.NewRequest("GET", "http://example.com", nil)
  41. if err != nil {
  42. t.Fatalf("Error initializing input HTTP request: %v", err)
  43. }
  44. q := inputReq.URL.Query()
  45. q.Add(testCase.inputQueryKey, testCase.inputQueryValue)
  46. inputReq.URL.RawQuery = q.Encode()
  47. actualResult := isRequestPresignedSignatureV4(inputReq)
  48. if testCase.expectedResult != actualResult {
  49. t.Errorf("Test %d: Expected the result to `%v`, but instead got `%v`", i+1, testCase.expectedResult, actualResult)
  50. }
  51. }
  52. }
  53. // Tests is requested authenticated function, tests replies for s3 errors.
  54. func TestIsReqAuthenticated(t *testing.T) {
  55. option := S3ApiServerOption{}
  56. iam := NewIdentityAccessManagement(&option)
  57. iam.identities = []*Identity{
  58. {
  59. Name: "someone",
  60. Credentials: []*Credential{
  61. {
  62. AccessKey: "access_key_1",
  63. SecretKey: "secret_key_1",
  64. },
  65. },
  66. Actions: nil,
  67. },
  68. }
  69. // List of test cases for validating http request authentication.
  70. testCases := []struct {
  71. req *http.Request
  72. s3Error s3err.ErrorCode
  73. }{
  74. // When request is unsigned, access denied is returned.
  75. {mustNewRequest("GET", "http://127.0.0.1:9000", 0, nil, t), s3err.ErrAccessDenied},
  76. // When request is properly signed, error is none.
  77. {mustNewSignedRequest("GET", "http://127.0.0.1:9000", 0, nil, t), s3err.ErrNone},
  78. }
  79. // Validates all testcases.
  80. for i, testCase := range testCases {
  81. if _, s3Error := iam.reqSignatureV4Verify(testCase.req); s3Error != testCase.s3Error {
  82. io.ReadAll(testCase.req.Body)
  83. t.Fatalf("Test %d: Unexpected S3 error: want %d - got %d", i, testCase.s3Error, s3Error)
  84. }
  85. }
  86. }
  87. func TestCheckAdminRequestAuthType(t *testing.T) {
  88. option := S3ApiServerOption{}
  89. iam := NewIdentityAccessManagement(&option)
  90. iam.identities = []*Identity{
  91. {
  92. Name: "someone",
  93. Credentials: []*Credential{
  94. {
  95. AccessKey: "access_key_1",
  96. SecretKey: "secret_key_1",
  97. },
  98. },
  99. Actions: nil,
  100. },
  101. }
  102. testCases := []struct {
  103. Request *http.Request
  104. ErrCode s3err.ErrorCode
  105. }{
  106. {Request: mustNewRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: s3err.ErrAccessDenied},
  107. {Request: mustNewSignedRequest("GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: s3err.ErrNone},
  108. {Request: mustNewPresignedRequest(iam, "GET", "http://127.0.0.1:9000", 0, nil, t), ErrCode: s3err.ErrNone},
  109. }
  110. for i, testCase := range testCases {
  111. if _, s3Error := iam.reqSignatureV4Verify(testCase.Request); s3Error != testCase.ErrCode {
  112. t.Errorf("Test %d: Unexpected s3error returned wanted %d, got %d", i, testCase.ErrCode, s3Error)
  113. }
  114. }
  115. }
  116. func BenchmarkGetSignature(b *testing.B) {
  117. t := time.Now()
  118. iam := IdentityAccessManagement{
  119. hashes: make(map[string]*sync.Pool),
  120. hashCounters: make(map[string]*int32),
  121. }
  122. b.ReportAllocs()
  123. b.ResetTimer()
  124. for i := 0; i < b.N; i++ {
  125. iam.getSignature("secret-key", t, "us-east-1", "s3", "random data")
  126. }
  127. }
  128. // Provides a fully populated http request instance, fails otherwise.
  129. func mustNewRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  130. req, err := newTestRequest(method, urlStr, contentLength, body)
  131. if err != nil {
  132. t.Fatalf("Unable to initialize new http request %s", err)
  133. }
  134. return req
  135. }
  136. // This is similar to mustNewRequest but additionally the request
  137. // is signed with AWS Signature V4, fails if not able to do so.
  138. func mustNewSignedRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  139. req := mustNewRequest(method, urlStr, contentLength, body, t)
  140. cred := &Credential{"access_key_1", "secret_key_1"}
  141. if err := signRequestV4(req, cred.AccessKey, cred.SecretKey); err != nil {
  142. t.Fatalf("Unable to initialized new signed http request %s", err)
  143. }
  144. return req
  145. }
  146. // This is similar to mustNewRequest but additionally the request
  147. // is presigned with AWS Signature V4, fails if not able to do so.
  148. func mustNewPresignedRequest(iam *IdentityAccessManagement, method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  149. req := mustNewRequest(method, urlStr, contentLength, body, t)
  150. cred := &Credential{"access_key_1", "secret_key_1"}
  151. if err := preSignV4(iam, req, cred.AccessKey, cred.SecretKey, int64(10*time.Minute.Seconds())); err != nil {
  152. t.Fatalf("Unable to initialized new signed http request %s", err)
  153. }
  154. return req
  155. }
  156. // Returns new HTTP request object.
  157. func newTestRequest(method, urlStr string, contentLength int64, body io.ReadSeeker) (*http.Request, error) {
  158. if method == "" {
  159. method = "POST"
  160. }
  161. // Save for subsequent use
  162. var hashedPayload string
  163. var md5Base64 string
  164. switch {
  165. case body == nil:
  166. hashedPayload = getSHA256Hash([]byte{})
  167. default:
  168. payloadBytes, err := io.ReadAll(body)
  169. if err != nil {
  170. return nil, err
  171. }
  172. hashedPayload = getSHA256Hash(payloadBytes)
  173. md5Base64 = getMD5HashBase64(payloadBytes)
  174. }
  175. // Seek back to beginning.
  176. if body != nil {
  177. body.Seek(0, 0)
  178. } else {
  179. body = bytes.NewReader([]byte(""))
  180. }
  181. req, err := http.NewRequest(method, urlStr, body)
  182. if err != nil {
  183. return nil, err
  184. }
  185. if md5Base64 != "" {
  186. req.Header.Set("Content-Md5", md5Base64)
  187. }
  188. req.Header.Set("x-amz-content-sha256", hashedPayload)
  189. // Add Content-Length
  190. req.ContentLength = contentLength
  191. return req, nil
  192. }
  193. // getSHA256Hash returns SHA-256 hash in hex encoding of given data.
  194. func getSHA256Hash(data []byte) string {
  195. return hex.EncodeToString(getSHA256Sum(data))
  196. }
  197. // getMD5HashBase64 returns MD5 hash in base64 encoding of given data.
  198. func getMD5HashBase64(data []byte) string {
  199. return base64.StdEncoding.EncodeToString(getMD5Sum(data))
  200. }
  201. // getSHA256Hash returns SHA-256 sum of given data.
  202. func getSHA256Sum(data []byte) []byte {
  203. hash := sha256.New()
  204. hash.Write(data)
  205. return hash.Sum(nil)
  206. }
  207. // getMD5Sum returns MD5 sum of given data.
  208. func getMD5Sum(data []byte) []byte {
  209. hash := md5.New()
  210. hash.Write(data)
  211. return hash.Sum(nil)
  212. }
  213. // getMD5Hash returns MD5 hash in hex encoding of given data.
  214. func getMD5Hash(data []byte) string {
  215. return hex.EncodeToString(getMD5Sum(data))
  216. }
  217. var ignoredHeaders = map[string]bool{
  218. "Authorization": true,
  219. "Content-Type": true,
  220. "Content-Length": true,
  221. "User-Agent": true,
  222. }
  223. // Sign given request using Signature V4.
  224. func signRequestV4(req *http.Request, accessKey, secretKey string) error {
  225. // Get hashed payload.
  226. hashedPayload := req.Header.Get("x-amz-content-sha256")
  227. if hashedPayload == "" {
  228. return fmt.Errorf("Invalid hashed payload")
  229. }
  230. currTime := time.Now()
  231. // Set x-amz-date.
  232. req.Header.Set("x-amz-date", currTime.Format(iso8601Format))
  233. // Get header map.
  234. headerMap := make(map[string][]string)
  235. for k, vv := range req.Header {
  236. // If request header key is not in ignored headers, then add it.
  237. if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; !ok {
  238. headerMap[strings.ToLower(k)] = vv
  239. }
  240. }
  241. // Get header keys.
  242. headers := []string{"host"}
  243. for k := range headerMap {
  244. headers = append(headers, k)
  245. }
  246. sort.Strings(headers)
  247. region := "us-east-1"
  248. // Get canonical headers.
  249. var buf bytes.Buffer
  250. for _, k := range headers {
  251. buf.WriteString(k)
  252. buf.WriteByte(':')
  253. switch {
  254. case k == "host":
  255. buf.WriteString(req.URL.Host)
  256. fallthrough
  257. default:
  258. for idx, v := range headerMap[k] {
  259. if idx > 0 {
  260. buf.WriteByte(',')
  261. }
  262. buf.WriteString(v)
  263. }
  264. buf.WriteByte('\n')
  265. }
  266. }
  267. canonicalHeaders := buf.String()
  268. // Get signed headers.
  269. signedHeaders := strings.Join(headers, ";")
  270. // Get canonical query string.
  271. req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1)
  272. // Get canonical URI.
  273. canonicalURI := EncodePath(req.URL.Path)
  274. // Get canonical request.
  275. // canonicalRequest =
  276. // <HTTPMethod>\n
  277. // <CanonicalURI>\n
  278. // <CanonicalQueryString>\n
  279. // <CanonicalHeaders>\n
  280. // <SignedHeaders>\n
  281. // <HashedPayload>
  282. //
  283. canonicalRequest := strings.Join([]string{
  284. req.Method,
  285. canonicalURI,
  286. req.URL.RawQuery,
  287. canonicalHeaders,
  288. signedHeaders,
  289. hashedPayload,
  290. }, "\n")
  291. // Get scope.
  292. scope := strings.Join([]string{
  293. currTime.Format(yyyymmdd),
  294. region,
  295. "s3",
  296. "aws4_request",
  297. }, "/")
  298. stringToSign := "AWS4-HMAC-SHA256" + "\n" + currTime.Format(iso8601Format) + "\n"
  299. stringToSign = stringToSign + scope + "\n"
  300. stringToSign = stringToSign + getSHA256Hash([]byte(canonicalRequest))
  301. date := sumHMAC([]byte("AWS4"+secretKey), []byte(currTime.Format(yyyymmdd)))
  302. regionHMAC := sumHMAC(date, []byte(region))
  303. service := sumHMAC(regionHMAC, []byte("s3"))
  304. signingKey := sumHMAC(service, []byte("aws4_request"))
  305. signature := hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
  306. // final Authorization header
  307. parts := []string{
  308. "AWS4-HMAC-SHA256" + " Credential=" + accessKey + "/" + scope,
  309. "SignedHeaders=" + signedHeaders,
  310. "Signature=" + signature,
  311. }
  312. auth := strings.Join(parts, ", ")
  313. req.Header.Set("Authorization", auth)
  314. return nil
  315. }
  316. // preSignV4 presign the request, in accordance with
  317. // http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
  318. func preSignV4(iam *IdentityAccessManagement, req *http.Request, accessKeyID, secretAccessKey string, expires int64) error {
  319. // Presign is not needed for anonymous credentials.
  320. if accessKeyID == "" || secretAccessKey == "" {
  321. return errors.New("Presign cannot be generated without access and secret keys")
  322. }
  323. region := "us-east-1"
  324. date := time.Now().UTC()
  325. scope := getScope(date, region)
  326. credential := fmt.Sprintf("%s/%s", accessKeyID, scope)
  327. // Set URL query.
  328. query := req.URL.Query()
  329. query.Set("X-Amz-Algorithm", signV4Algorithm)
  330. query.Set("X-Amz-Date", date.Format(iso8601Format))
  331. query.Set("X-Amz-Expires", strconv.FormatInt(expires, 10))
  332. query.Set("X-Amz-SignedHeaders", "host")
  333. query.Set("X-Amz-Credential", credential)
  334. query.Set("X-Amz-Content-Sha256", unsignedPayload)
  335. // "host" is the only header required to be signed for Presigned URLs.
  336. extractedSignedHeaders := make(http.Header)
  337. extractedSignedHeaders.Set("host", req.Host)
  338. queryStr := strings.Replace(query.Encode(), "+", "%20", -1)
  339. canonicalRequest := getCanonicalRequest(extractedSignedHeaders, unsignedPayload, queryStr, req.URL.Path, req.Method)
  340. stringToSign := getStringToSign(canonicalRequest, date, scope)
  341. signature := iam.getSignature(secretAccessKey, date, region, "s3", stringToSign)
  342. req.URL.RawQuery = query.Encode()
  343. // Add signature header to RawQuery.
  344. req.URL.RawQuery += "&X-Amz-Signature=" + url.QueryEscape(signature)
  345. // Construct the final presigned URL.
  346. return nil
  347. }
  348. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  349. //
  350. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  351. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  352. //
  353. // This function on the other hand is a direct replacement for url.Encode() technique to support
  354. // pretty much every UTF-8 character.
  355. func EncodePath(pathName string) string {
  356. if reservedObjectNames.MatchString(pathName) {
  357. return pathName
  358. }
  359. var encodedPathname string
  360. for _, s := range pathName {
  361. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  362. encodedPathname = encodedPathname + string(s)
  363. continue
  364. }
  365. switch s {
  366. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  367. encodedPathname = encodedPathname + string(s)
  368. continue
  369. default:
  370. len := utf8.RuneLen(s)
  371. if len < 0 {
  372. // if utf8 cannot convert return the same string as is
  373. return pathName
  374. }
  375. u := make([]byte, len)
  376. utf8.EncodeRune(u, s)
  377. for _, r := range u {
  378. hex := hex.EncodeToString([]byte{r})
  379. encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
  380. }
  381. }
  382. }
  383. return encodedPathname
  384. }