wafformatter.go 12 KB

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