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 9.4 kB

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

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