wafformatter.go 13 KB

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