wafformatter.go 13 KB

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