wafformatter.go 13 KB

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