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.

434 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. }
  121. b.ReportAllocs()
  122. b.ResetTimer()
  123. for i := 0; i < b.N; i++ {
  124. iam.getSignature("secret-key", t, "us-east-1", "s3", "random data")
  125. }
  126. }
  127. // Provides a fully populated http request instance, fails otherwise.
  128. func mustNewRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  129. req, err := newTestRequest(method, urlStr, contentLength, body)
  130. if err != nil {
  131. t.Fatalf("Unable to initialize new http request %s", err)
  132. }
  133. return req
  134. }
  135. // This is similar to mustNewRequest but additionally the request
  136. // is signed with AWS Signature V4, fails if not able to do so.
  137. func mustNewSignedRequest(method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  138. req := mustNewRequest(method, urlStr, contentLength, body, t)
  139. cred := &Credential{"access_key_1", "secret_key_1"}
  140. if err := signRequestV4(req, cred.AccessKey, cred.SecretKey); err != nil {
  141. t.Fatalf("Unable to initialized new signed http request %s", err)
  142. }
  143. return req
  144. }
  145. // This is similar to mustNewRequest but additionally the request
  146. // is presigned with AWS Signature V4, fails if not able to do so.
  147. func mustNewPresignedRequest(iam *IdentityAccessManagement, method string, urlStr string, contentLength int64, body io.ReadSeeker, t *testing.T) *http.Request {
  148. req := mustNewRequest(method, urlStr, contentLength, body, t)
  149. cred := &Credential{"access_key_1", "secret_key_1"}
  150. if err := preSignV4(iam, req, cred.AccessKey, cred.SecretKey, int64(10*time.Minute.Seconds())); err != nil {
  151. t.Fatalf("Unable to initialized new signed http request %s", err)
  152. }
  153. return req
  154. }
  155. // Returns new HTTP request object.
  156. func newTestRequest(method, urlStr string, contentLength int64, body io.ReadSeeker) (*http.Request, error) {
  157. if method == "" {
  158. method = "POST"
  159. }
  160. // Save for subsequent use
  161. var hashedPayload string
  162. var md5Base64 string
  163. switch {
  164. case body == nil:
  165. hashedPayload = getSHA256Hash([]byte{})
  166. default:
  167. payloadBytes, err := io.ReadAll(body)
  168. if err != nil {
  169. return nil, err
  170. }
  171. hashedPayload = getSHA256Hash(payloadBytes)
  172. md5Base64 = getMD5HashBase64(payloadBytes)
  173. }
  174. // Seek back to beginning.
  175. if body != nil {
  176. body.Seek(0, 0)
  177. } else {
  178. body = bytes.NewReader([]byte(""))
  179. }
  180. req, err := http.NewRequest(method, urlStr, body)
  181. if err != nil {
  182. return nil, err
  183. }
  184. if md5Base64 != "" {
  185. req.Header.Set("Content-Md5", md5Base64)
  186. }
  187. req.Header.Set("x-amz-content-sha256", hashedPayload)
  188. // Add Content-Length
  189. req.ContentLength = contentLength
  190. return req, nil
  191. }
  192. // getSHA256Hash returns SHA-256 hash in hex encoding of given data.
  193. func getSHA256Hash(data []byte) string {
  194. return hex.EncodeToString(getSHA256Sum(data))
  195. }
  196. // getMD5HashBase64 returns MD5 hash in base64 encoding of given data.
  197. func getMD5HashBase64(data []byte) string {
  198. return base64.StdEncoding.EncodeToString(getMD5Sum(data))
  199. }
  200. // getSHA256Hash returns SHA-256 sum of given data.
  201. func getSHA256Sum(data []byte) []byte {
  202. hash := sha256.New()
  203. hash.Write(data)
  204. return hash.Sum(nil)
  205. }
  206. // getMD5Sum returns MD5 sum of given data.
  207. func getMD5Sum(data []byte) []byte {
  208. hash := md5.New()
  209. hash.Write(data)
  210. return hash.Sum(nil)
  211. }
  212. // getMD5Hash returns MD5 hash in hex encoding of given data.
  213. func getMD5Hash(data []byte) string {
  214. return hex.EncodeToString(getMD5Sum(data))
  215. }
  216. var ignoredHeaders = map[string]bool{
  217. "Authorization": true,
  218. "Content-Type": true,
  219. "Content-Length": true,
  220. "User-Agent": true,
  221. }
  222. // Sign given request using Signature V4.
  223. func signRequestV4(req *http.Request, accessKey, secretKey string) error {
  224. // Get hashed payload.
  225. hashedPayload := req.Header.Get("x-amz-content-sha256")
  226. if hashedPayload == "" {
  227. return fmt.Errorf("Invalid hashed payload")
  228. }
  229. currTime := time.Now()
  230. // Set x-amz-date.
  231. req.Header.Set("x-amz-date", currTime.Format(iso8601Format))
  232. // Get header map.
  233. headerMap := make(map[string][]string)
  234. for k, vv := range req.Header {
  235. // If request header key is not in ignored headers, then add it.
  236. if _, ok := ignoredHeaders[http.CanonicalHeaderKey(k)]; !ok {
  237. headerMap[strings.ToLower(k)] = vv
  238. }
  239. }
  240. // Get header keys.
  241. headers := []string{"host"}
  242. for k := range headerMap {
  243. headers = append(headers, k)
  244. }
  245. sort.Strings(headers)
  246. region := "us-east-1"
  247. // Get canonical headers.
  248. var buf bytes.Buffer
  249. for _, k := range headers {
  250. buf.WriteString(k)
  251. buf.WriteByte(':')
  252. switch {
  253. case k == "host":
  254. buf.WriteString(req.URL.Host)
  255. fallthrough
  256. default:
  257. for idx, v := range headerMap[k] {
  258. if idx > 0 {
  259. buf.WriteByte(',')
  260. }
  261. buf.WriteString(v)
  262. }
  263. buf.WriteByte('\n')
  264. }
  265. }
  266. canonicalHeaders := buf.String()
  267. // Get signed headers.
  268. signedHeaders := strings.Join(headers, ";")
  269. // Get canonical query string.
  270. req.URL.RawQuery = strings.Replace(req.URL.Query().Encode(), "+", "%20", -1)
  271. // Get canonical URI.
  272. canonicalURI := EncodePath(req.URL.Path)
  273. // Get canonical request.
  274. // canonicalRequest =
  275. // <HTTPMethod>\n
  276. // <CanonicalURI>\n
  277. // <CanonicalQueryString>\n
  278. // <CanonicalHeaders>\n
  279. // <SignedHeaders>\n
  280. // <HashedPayload>
  281. //
  282. canonicalRequest := strings.Join([]string{
  283. req.Method,
  284. canonicalURI,
  285. req.URL.RawQuery,
  286. canonicalHeaders,
  287. signedHeaders,
  288. hashedPayload,
  289. }, "\n")
  290. // Get scope.
  291. scope := strings.Join([]string{
  292. currTime.Format(yyyymmdd),
  293. region,
  294. "s3",
  295. "aws4_request",
  296. }, "/")
  297. stringToSign := "AWS4-HMAC-SHA256" + "\n" + currTime.Format(iso8601Format) + "\n"
  298. stringToSign = stringToSign + scope + "\n"
  299. stringToSign = stringToSign + getSHA256Hash([]byte(canonicalRequest))
  300. date := sumHMAC([]byte("AWS4"+secretKey), []byte(currTime.Format(yyyymmdd)))
  301. regionHMAC := sumHMAC(date, []byte(region))
  302. service := sumHMAC(regionHMAC, []byte("s3"))
  303. signingKey := sumHMAC(service, []byte("aws4_request"))
  304. signature := hex.EncodeToString(sumHMAC(signingKey, []byte(stringToSign)))
  305. // final Authorization header
  306. parts := []string{
  307. "AWS4-HMAC-SHA256" + " Credential=" + accessKey + "/" + scope,
  308. "SignedHeaders=" + signedHeaders,
  309. "Signature=" + signature,
  310. }
  311. auth := strings.Join(parts, ", ")
  312. req.Header.Set("Authorization", auth)
  313. return nil
  314. }
  315. // preSignV4 presign the request, in accordance with
  316. // http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html.
  317. func preSignV4(iam *IdentityAccessManagement, req *http.Request, accessKeyID, secretAccessKey string, expires int64) error {
  318. // Presign is not needed for anonymous credentials.
  319. if accessKeyID == "" || secretAccessKey == "" {
  320. return errors.New("Presign cannot be generated without access and secret keys")
  321. }
  322. region := "us-east-1"
  323. date := time.Now().UTC()
  324. scope := getScope(date, region)
  325. credential := fmt.Sprintf("%s/%s", accessKeyID, scope)
  326. // Set URL query.
  327. query := req.URL.Query()
  328. query.Set("X-Amz-Algorithm", signV4Algorithm)
  329. query.Set("X-Amz-Date", date.Format(iso8601Format))
  330. query.Set("X-Amz-Expires", strconv.FormatInt(expires, 10))
  331. query.Set("X-Amz-SignedHeaders", "host")
  332. query.Set("X-Amz-Credential", credential)
  333. query.Set("X-Amz-Content-Sha256", unsignedPayload)
  334. // "host" is the only header required to be signed for Presigned URLs.
  335. extractedSignedHeaders := make(http.Header)
  336. extractedSignedHeaders.Set("host", req.Host)
  337. queryStr := strings.Replace(query.Encode(), "+", "%20", -1)
  338. canonicalRequest := getCanonicalRequest(extractedSignedHeaders, unsignedPayload, queryStr, req.URL.Path, req.Method)
  339. stringToSign := getStringToSign(canonicalRequest, date, scope)
  340. signature := iam.getSignature(secretAccessKey, date, region, "s3", stringToSign)
  341. req.URL.RawQuery = query.Encode()
  342. // Add signature header to RawQuery.
  343. req.URL.RawQuery += "&X-Amz-Signature=" + url.QueryEscape(signature)
  344. // Construct the final presigned URL.
  345. return nil
  346. }
  347. // EncodePath encode the strings from UTF-8 byte representations to HTML hex escape sequences
  348. //
  349. // This is necessary since regular url.Parse() and url.Encode() functions do not support UTF-8
  350. // non english characters cannot be parsed due to the nature in which url.Encode() is written
  351. //
  352. // This function on the other hand is a direct replacement for url.Encode() technique to support
  353. // pretty much every UTF-8 character.
  354. func EncodePath(pathName string) string {
  355. if reservedObjectNames.MatchString(pathName) {
  356. return pathName
  357. }
  358. var encodedPathname string
  359. for _, s := range pathName {
  360. if 'A' <= s && s <= 'Z' || 'a' <= s && s <= 'z' || '0' <= s && s <= '9' { // §2.3 Unreserved characters (mark)
  361. encodedPathname = encodedPathname + string(s)
  362. continue
  363. }
  364. switch s {
  365. case '-', '_', '.', '~', '/': // §2.3 Unreserved characters (mark)
  366. encodedPathname = encodedPathname + string(s)
  367. continue
  368. default:
  369. len := utf8.RuneLen(s)
  370. if len < 0 {
  371. // if utf8 cannot convert return the same string as is
  372. return pathName
  373. }
  374. u := make([]byte, len)
  375. utf8.EncodeRune(u, s)
  376. for _, r := range u {
  377. hex := hex.EncodeToString([]byte{r})
  378. encodedPathname = encodedPathname + "%" + strings.ToUpper(hex)
  379. }
  380. }
  381. }
  382. return encodedPathname
  383. }