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

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