You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

aws_auth.go 8.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package http
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/aws/aws-sdk-go-v2/aws"
  14. v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
  15. "github.com/aws/aws-sdk-go-v2/credentials"
  16. "github.com/gin-gonic/gin"
  17. "gitlink.org.cn/cloudream/common/consts/errorcode"
  18. "gitlink.org.cn/cloudream/common/pkgs/logger"
  19. "gitlink.org.cn/cloudream/storage/client/internal/config"
  20. )
  21. const (
  22. AuthRegion = "any"
  23. AuthService = "jcs"
  24. AuthorizationHeader = "Authorization"
  25. )
  26. type AWSAuth struct {
  27. cred aws.Credentials
  28. signer *v4.Signer
  29. }
  30. func NewAWSAuth(accessKey string, secretKey string) (*AWSAuth, error) {
  31. prod := credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")
  32. cred, err := prod.Retrieve(context.TODO())
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &AWSAuth{
  37. cred: cred,
  38. signer: v4.NewSigner(),
  39. }, nil
  40. }
  41. func (a *AWSAuth) Auth(c *gin.Context) {
  42. authorizationHeader := c.GetHeader(AuthorizationHeader)
  43. if authorizationHeader == "" {
  44. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "authorization header is missing"))
  45. return
  46. }
  47. _, headers, reqSig, err := parseAuthorizationHeader(authorizationHeader)
  48. if err != nil {
  49. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "invalid Authorization header format"))
  50. return
  51. }
  52. // 限制请求体大小
  53. rd := io.LimitReader(c.Request.Body, config.Cfg().MaxHTTPBodySize)
  54. body, err := io.ReadAll(rd)
  55. if err != nil {
  56. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "read request body failed"))
  57. return
  58. }
  59. timestamp, err := time.Parse("20060102T150405Z", c.GetHeader("X-Amz-Date"))
  60. if err != nil {
  61. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date header format"))
  62. return
  63. }
  64. if time.Now().After(timestamp.Add(5 * time.Minute)) {
  65. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "X-Amz-Date is expired"))
  66. return
  67. }
  68. payloadHash := sha256.Sum256(body)
  69. hexPayloadHash := hex.EncodeToString(payloadHash[:])
  70. // 构造验签用的请求
  71. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  72. if err != nil {
  73. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  74. return
  75. }
  76. for _, h := range headers {
  77. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  78. }
  79. verifyReq.Host = c.Request.Host
  80. verifyReq.ContentLength = c.Request.ContentLength
  81. signer := v4.NewSigner()
  82. err = signer.SignHTTP(context.TODO(), a.cred, verifyReq, hexPayloadHash, AuthService, AuthRegion, timestamp)
  83. if err != nil {
  84. logger.Warnf("sign request: %v", err)
  85. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  86. return
  87. }
  88. verifySig := getSignatureFromAWSHeader(verifyReq)
  89. if !strings.EqualFold(verifySig, reqSig) {
  90. logger.Warnf("signature mismatch, input header: %s, verify: %s", authorizationHeader, verifySig)
  91. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  92. return
  93. }
  94. c.Request.Body = io.NopCloser(bytes.NewReader(body))
  95. c.Next()
  96. }
  97. func (a *AWSAuth) AuthWithoutBody(c *gin.Context) {
  98. authorizationHeader := c.GetHeader(AuthorizationHeader)
  99. if authorizationHeader == "" {
  100. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "authorization header is missing"))
  101. return
  102. }
  103. _, headers, reqSig, err := parseAuthorizationHeader(authorizationHeader)
  104. if err != nil {
  105. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "invalid Authorization header format"))
  106. return
  107. }
  108. timestamp, err := time.Parse("20060102T150405Z", c.GetHeader("X-Amz-Date"))
  109. if err != nil {
  110. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date header format"))
  111. return
  112. }
  113. if time.Now().After(timestamp.Add(5 * time.Minute)) {
  114. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "X-Amz-Date is expired"))
  115. return
  116. }
  117. // 构造验签用的请求
  118. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  119. if err != nil {
  120. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  121. return
  122. }
  123. for _, h := range headers {
  124. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  125. }
  126. verifyReq.Host = c.Request.Host
  127. verifyReq.ContentLength = c.Request.ContentLength
  128. err = a.signer.SignHTTP(context.TODO(), a.cred, verifyReq, "", AuthService, AuthRegion, timestamp)
  129. if err != nil {
  130. logger.Warnf("sign request: %v", err)
  131. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  132. return
  133. }
  134. verifySig := getSignatureFromAWSHeader(verifyReq)
  135. if !strings.EqualFold(verifySig, reqSig) {
  136. logger.Warnf("signature mismatch, input header: %s, verify: %s", authorizationHeader, verifySig)
  137. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  138. return
  139. }
  140. c.Next()
  141. }
  142. func (a *AWSAuth) PresignedAuth(c *gin.Context) {
  143. query := c.Request.URL.Query()
  144. signature := query.Get("X-Amz-Signature")
  145. query.Del("X-Amz-Signature")
  146. if signature == "" {
  147. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing X-Amz-Signature query parameter"))
  148. return
  149. }
  150. // alg := c.Request.URL.Query().Get("X-Amz-Algorithm")
  151. // cred := c.Request.URL.Query().Get("X-Amz-Credential")
  152. date := query.Get("X-Amz-Date")
  153. expiresStr := query.Get("X-Expires")
  154. expires, err := strconv.ParseInt(expiresStr, 10, 64)
  155. if err != nil {
  156. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Expires format"))
  157. return
  158. }
  159. signedHeaders := strings.Split(query.Get("X-Amz-SignedHeaders"), ";")
  160. c.Request.URL.RawQuery = query.Encode()
  161. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  162. if err != nil {
  163. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  164. return
  165. }
  166. for _, h := range signedHeaders {
  167. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  168. }
  169. verifyReq.Host = c.Request.Host
  170. timestamp, err := time.Parse("20060102T150405Z", date)
  171. if err != nil {
  172. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date format"))
  173. return
  174. }
  175. if time.Now().After(timestamp.Add(time.Duration(expires) * time.Second)) {
  176. c.AbortWithStatusJSON(http.StatusUnauthorized, Failed(errorcode.Unauthorized, "request expired"))
  177. return
  178. }
  179. signer := v4.NewSigner()
  180. uri, _, err := signer.PresignHTTP(context.TODO(), a.cred, verifyReq, "", AuthService, AuthRegion, timestamp)
  181. if err != nil {
  182. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  183. return
  184. }
  185. verifySig := getSignatureFromAWSQuery(uri)
  186. if !strings.EqualFold(verifySig, signature) {
  187. logger.Warnf("signature mismatch, input: %s, verify: %s", signature, verifySig)
  188. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  189. return
  190. }
  191. c.Next()
  192. }
  193. // 解析 Authorization 头部
  194. func parseAuthorizationHeader(authorizationHeader string) (string, []string, string, error) {
  195. if !strings.HasPrefix(authorizationHeader, "AWS4-HMAC-SHA256 ") {
  196. return "", nil, "", fmt.Errorf("invalid Authorization header format")
  197. }
  198. authorizationHeader = strings.TrimPrefix(authorizationHeader, "AWS4-HMAC-SHA256")
  199. parts := strings.Split(authorizationHeader, ",")
  200. if len(parts) != 3 {
  201. return "", nil, "", fmt.Errorf("invalid Authorization header format")
  202. }
  203. var credential, signedHeaders, signature string
  204. for _, part := range parts {
  205. part = strings.TrimSpace(part)
  206. if strings.HasPrefix(part, "Credential=") {
  207. credential = strings.TrimPrefix(part, "Credential=")
  208. }
  209. if strings.HasPrefix(part, "SignedHeaders=") {
  210. signedHeaders = strings.TrimPrefix(part, "SignedHeaders=")
  211. }
  212. if strings.HasPrefix(part, "Signature=") {
  213. signature = strings.TrimPrefix(part, "Signature=")
  214. }
  215. }
  216. if credential == "" || signedHeaders == "" || signature == "" {
  217. return "", nil, "", fmt.Errorf("missing necessary parts in Authorization header")
  218. }
  219. headers := strings.Split(signedHeaders, ";")
  220. return credential, headers, signature, nil
  221. }
  222. func getSignatureFromAWSHeader(req *http.Request) string {
  223. auth := req.Header.Get(AuthorizationHeader)
  224. idx := strings.Index(auth, "Signature=")
  225. if idx == -1 {
  226. return ""
  227. }
  228. return auth[idx+len("Signature="):]
  229. }
  230. func getSignatureFromAWSQuery(uri string) string {
  231. idx := strings.Index(uri, "X-Amz-Signature=")
  232. if idx == -1 {
  233. return ""
  234. }
  235. andIdx := strings.Index(uri[idx:], "&")
  236. if andIdx == -1 {
  237. return uri[idx+len("X-Amz-Signature="):]
  238. }
  239. return uri[idx+len("X-Amz-Signature=") : andIdx]
  240. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。