auto_signature_v4_test.go 12 KB

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