wafformatter.go 13 KB

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