auto_signature_v4_test.go 12 KB

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