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

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