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