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.

441 lines
13 KiB

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