wafformatter.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  8. "github.com/go-nunu/nunu-layout-advanced/pkg/rabbitmq"
  9. amqp "github.com/rabbitmq/amqp091-go"
  10. "github.com/spf13/cast"
  11. "go.uber.org/zap"
  12. "golang.org/x/net/publicsuffix"
  13. "net"
  14. "slices"
  15. "strconv"
  16. )
  17. type WafFormatterService interface {
  18. require(ctx context.Context, req v1.GlobalRequire, category string) (v1.GlobalRequire, error)
  19. sendFormData(ctx context.Context,addTokenUrl string,addSendUrl string,formData map[string]interface{}) (int, error)
  20. validateWafPortCount(ctx context.Context, hostId int) error
  21. validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error
  22. ConvertToWildcardDomain(ctx context.Context,domain string) (string, error)
  23. AppendWafIp(ctx context.Context, req []string) ([]v1.IpInfo, error)
  24. AppendWafIpByRemovePort(ctx context.Context, req []string) ([]v1.IpInfo, error)
  25. PublishIpWhitelistTask(ips []v1.IpInfo, action string)
  26. PublishDomainWhitelistTask(domain, ip, action string)
  27. }
  28. func NewWafFormatterService(
  29. service *Service,
  30. globalRep repository.GlobalLimitRepository,
  31. hostRep repository.HostRepository,
  32. required RequiredService,
  33. parser ParserService,
  34. tcpforwardingRep repository.TcpforwardingRepository,
  35. udpForWardingRep repository.UdpForWardingRepository,
  36. webForwardingRep repository.WebForwardingRepository,
  37. mq *rabbitmq.RabbitMQ,
  38. host HostService,
  39. ) WafFormatterService {
  40. return &wafFormatterService{
  41. Service: service,
  42. globalRep: globalRep,
  43. hostRep: hostRep,
  44. required: required,
  45. parser: parser,
  46. tcpforwardingRep: tcpforwardingRep,
  47. udpForWardingRep: udpForWardingRep,
  48. webForwardingRep: webForwardingRep,
  49. host : host,
  50. mq: mq,
  51. }
  52. }
  53. type wafFormatterService struct {
  54. *Service
  55. globalRep repository.GlobalLimitRepository
  56. hostRep repository.HostRepository
  57. required RequiredService
  58. parser ParserService
  59. tcpforwardingRep repository.TcpforwardingRepository
  60. udpForWardingRep repository.UdpForWardingRepository
  61. webForwardingRep repository.WebForwardingRepository
  62. host HostService
  63. mq *rabbitmq.RabbitMQ
  64. }
  65. func (s *wafFormatterService) require(ctx context.Context,req v1.GlobalRequire,category string) (v1.GlobalRequire, error) {
  66. RuleIds, err := s.globalRep.GetGlobalLimitByHostId(ctx, int64(req.HostId))
  67. if err != nil {
  68. return v1.GlobalRequire{}, err
  69. }
  70. req.WafGatewayGroupId = RuleIds.GatewayGroupId
  71. switch category {
  72. case "tcp":
  73. req.LimitRuleId = RuleIds.TcpLimitRuleId
  74. case "udp":
  75. req.LimitRuleId = RuleIds.UdpLimitRuleId
  76. case "web":
  77. req.LimitRuleId = RuleIds.WebLimitRuleId
  78. }
  79. domain, err := s.hostRep.GetDomainById(ctx, req.HostId)
  80. if err != nil {
  81. return v1.GlobalRequire{}, err
  82. }
  83. req.Tag = strconv.Itoa(req.Uid) + "_" + strconv.Itoa(req.HostId) + "_" + domain + "_" + req.Comment
  84. return req, nil
  85. }
  86. func (s *wafFormatterService) sendFormData(ctx context.Context,addTokenUrl string,addSendUrl string,formData map[string]interface{}) (int, error) {
  87. respBody, err := s.required.SendForm(ctx, addTokenUrl, addSendUrl, formData)
  88. if err != nil {
  89. return 0, err
  90. }
  91. // 解析响应内容中的 alert 消息
  92. res, err := s.parser.ParseAlert(string(respBody))
  93. if err != nil {
  94. return 0,err
  95. }
  96. if res != "" {
  97. return 0,fmt.Errorf(res)
  98. }
  99. ruleIdStr, err := s.parser.GetRuleIdByColumnName(ctx, respBody,formData["tag"].(string))
  100. if err != nil {
  101. return 0, err
  102. }
  103. ruleId, err := cast.ToIntE(ruleIdStr)
  104. if err != nil {
  105. return 0,err
  106. }
  107. return ruleId, nil
  108. }
  109. func (s *wafFormatterService) validateWafPortCount(ctx context.Context, hostId int) error {
  110. congfig, err := s.host.GetGlobalLimitConfig(ctx, hostId)
  111. if err != nil {
  112. return err
  113. }
  114. tcpCount, err := s.tcpforwardingRep.GetTcpForwardingPortCountByHostId(ctx, hostId)
  115. if err != nil {
  116. return err
  117. }
  118. udpCount, err := s.udpForWardingRep.GetUdpForwardingPortCountByHostId(ctx, hostId)
  119. if err != nil {
  120. return err
  121. }
  122. webCount, err := s.webForwardingRep.GetWebForwardingPortCountByHostId(ctx, hostId)
  123. if err != nil {
  124. return err
  125. }
  126. if int64(congfig.PortCount) > tcpCount + udpCount + webCount {
  127. return nil
  128. }
  129. return fmt.Errorf("端口数量超出套餐限制,已配置%d个端口,套餐限制为%d个端口", tcpCount+udpCount+webCount, congfig.PortCount)
  130. }
  131. func (s *wafFormatterService) validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error {
  132. congfig, err := s.host.GetGlobalLimitConfig(ctx, req.HostId)
  133. if err != nil {
  134. return err
  135. }
  136. domainCount, domainSlice, err := s.webForwardingRep.GetWebForwardingDomainCountByHostId(ctx, req.HostId)
  137. if err != nil {
  138. return err
  139. }
  140. if req.Domain != "" {
  141. if !slices.Contains(domainSlice, req.Domain) {
  142. domainCount += 1
  143. if domainCount > int64(congfig.DomainCount) {
  144. return fmt.Errorf("域名数量已达到上限,已配置%d个域名,套餐限制为%d个域名", domainCount, congfig.DomainCount)
  145. }
  146. }
  147. }
  148. return nil
  149. }
  150. func (s *wafFormatterService) ConvertToWildcardDomain(ctx context.Context, domain string) (string, error) {
  151. // 1. 使用 EffectiveTLDPlusOne 获取可注册域名部分。
  152. // 例如,对于 "www.google.com",这将返回 "google.com"。
  153. // 对于 "a.b.c.tokyo.jp",这将返回 "c.tokyo.jp"。
  154. registrableDomain, err := publicsuffix.EffectiveTLDPlusOne(domain)
  155. if err != nil {
  156. // 如果域名无效(如 IP 地址、localhost),则返回错误。
  157. return "", fmt.Errorf("无法处理 '%s': %w", domain, err)
  158. }
  159. // 2. 比较原始域名和可注册域名。
  160. // 如果它们不相等,说明原始域名包含子域名。
  161. if domain != registrableDomain {
  162. // 3. 如果存在子域名,则用 "*." 加上可注册域名来构造通配符域名。
  163. return registrableDomain, nil
  164. }
  165. // 4. 如果原始域名和可注册域名相同(例如,输入就是 "google.com"),
  166. // 则说明没有子域名可替换,直接返回原始域名。
  167. return domain, nil
  168. }
  169. func (s *wafFormatterService) AppendWafIp(ctx context.Context, req []string) ([]v1.IpInfo, error) {
  170. var ips []v1.IpInfo
  171. for _, v := range req {
  172. ips = append(ips, v1.IpInfo{
  173. FType: "0",
  174. FStartIp: v,
  175. FEndIp: v,
  176. FRemark: "宁波高防IP过白",
  177. FServerIp: "",
  178. })
  179. }
  180. return ips, nil
  181. }
  182. func (s *wafFormatterService) AppendWafIpByRemovePort(ctx context.Context, req []string) ([]v1.IpInfo, error) {
  183. var ips []v1.IpInfo
  184. for _, v := range req {
  185. ip, _, err := net.SplitHostPort(v)
  186. if err != nil {
  187. return nil, err
  188. }
  189. ips = append(ips, v1.IpInfo{
  190. FType: "0",
  191. FStartIp: ip,
  192. FEndIp: ip,
  193. FRemark: "宁波高防IP过白",
  194. FServerIp: "",
  195. })
  196. }
  197. return ips, nil
  198. }
  199. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  200. // It can handle different actions like "add" or "del".
  201. func (s *wafFormatterService) PublishDomainWhitelistTask(domain, ip, action string) {
  202. // Define message payload, including the action
  203. type domainTaskPayload struct {
  204. Domain string `json:"domain"`
  205. Ip string `json:"ip"`
  206. Action string `json:"action"`
  207. }
  208. payload := domainTaskPayload{
  209. Domain: domain,
  210. Ip: ip,
  211. Action: action,
  212. }
  213. // Serialize the message
  214. msgBody, err := json.Marshal(payload)
  215. if err != nil {
  216. s.logger.Error("Failed to serialize domain whitelist task message", zap.Error(err), zap.String("domain", domain), zap.String("ip", ip), zap.String("action", action))
  217. return
  218. }
  219. // Get task configuration
  220. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  221. if !ok {
  222. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  223. return
  224. }
  225. // Construct the routing key dynamically based on the action
  226. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  227. // Construct the amqp.Publishing message
  228. publishingMsg := amqp.Publishing{
  229. ContentType: "application/json",
  230. Body: msgBody,
  231. DeliveryMode: amqp.Persistent, // Persistent message
  232. }
  233. // Publish the message
  234. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  235. if err != nil {
  236. s.logger.Error("发布 域名 白名单任务到 MQ 失败", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  237. } else {
  238. s.logger.Info("成功将 域名 白名单任务发布到 MQ", zap.String("domain", domain), zap.String("action", action))
  239. }
  240. }
  241. func (s *wafFormatterService) PublishIpWhitelistTask(ips []v1.IpInfo, action string) {
  242. // Define message payload, including the action
  243. type ipTaskPayload struct {
  244. Ips []v1.IpInfo `json:"ips"`
  245. Action string `json:"action"`
  246. }
  247. payload := ipTaskPayload{
  248. Ips: ips,
  249. Action: action,
  250. }
  251. // Serialize the message
  252. msgBody, err := json.Marshal(payload)
  253. if err != nil {
  254. s.logger.Error("序列化 IP 白名单任务消息失败", zap.Error(err), zap.Any("IPs", ips), zap.String("action", action))
  255. return
  256. }
  257. // Get task configuration
  258. taskCfg, ok := s.mq.GetTaskConfig("ip_white")
  259. if !ok {
  260. s.logger.Error("无法获取“ip_white”任务配置")
  261. return
  262. }
  263. // Construct the routing key dynamically based on the action
  264. routingKey := fmt.Sprintf("task.ip_white.%s", action)
  265. // Construct the amqp.Publishing message
  266. publishingMsg := amqp.Publishing{
  267. ContentType: "application/json",
  268. Body: msgBody,
  269. DeliveryMode: amqp.Persistent, // Persistent message
  270. }
  271. // Publish the message
  272. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  273. if err != nil {
  274. s.logger.Error("发布 IP 白名单任务到 MQ 失败", zap.Error(err), zap.String("action", action))
  275. } else {
  276. s.logger.Info("成功将 IP 白名单任务发布到 MQ", zap.String("action", action))
  277. }
  278. }