wafformatter.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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/idna"
  13. "golang.org/x/net/publicsuffix"
  14. "golang.org/x/sync/errgroup"
  15. "net"
  16. "slices"
  17. "strconv"
  18. "strings"
  19. )
  20. type WafFormatterService interface {
  21. Require(ctx context.Context, req v1.GlobalRequire) (RequireResponse, error)
  22. validateWafPortCount(ctx context.Context, hostId int) error
  23. validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error
  24. ConvertToWildcardDomain(ctx context.Context, domain string) (string, error)
  25. AppendWafIp(ctx context.Context, req []string, returnSourceIp string) ([]v1.IpInfo, error)
  26. WashIps(ctx context.Context, req []string) ([]string, error)
  27. PublishIpWhitelistTask(ips []string, action string, returnSourceIp string, color string)
  28. PublishDomainWhitelistTask(domain, ip, action string)
  29. findIpDifferences(oldIps, newIps []string) ([]string, []string)
  30. WashDeleteWafIp(ctx context.Context, backendList []string) ([]string, error)
  31. WashEditWafIp(ctx context.Context, newBackendList []string, oldBackendList []string) ([]string, []string, error)
  32. //cdn添加网站
  33. AddOrigin(ctx context.Context, req v1.WebJson) (int64, error)
  34. // 获取ip数量等于1的源站过白ip
  35. WashDelIps(ctx context.Context, ips []string) ([]string, error)
  36. // 判断域名是否是IDN,如果是,转换为 Punycode
  37. ConvertToPunycodeIfIDN(ctx context.Context, domain string) (isIDN bool, punycodeDomain string, err error)
  38. // 验证端口重复
  39. VerifyPort(ctx context.Context,protocol string, id int64, port string,hostId int64,domain string) error
  40. }
  41. func NewWafFormatterService(
  42. service *Service,
  43. globalRep repository.GlobalLimitRepository,
  44. hostRep repository.HostRepository,
  45. required RequiredService,
  46. parser ParserService,
  47. tcpforwardingRep repository.TcpforwardingRepository,
  48. udpForWardingRep repository.UdpForWardingRepository,
  49. webForwardingRep repository.WebForwardingRepository,
  50. mq *rabbitmq.RabbitMQ,
  51. host HostService,
  52. gatewayGroupRep repository.GatewayGroupRepository,
  53. gatewayGroupIpRep repository.GateWayGroupIpRepository,
  54. cdn CdnService,
  55. ) WafFormatterService {
  56. return &wafFormatterService{
  57. Service: service,
  58. globalRep: globalRep,
  59. hostRep: hostRep,
  60. required: required,
  61. parser: parser,
  62. tcpforwardingRep: tcpforwardingRep,
  63. udpForWardingRep: udpForWardingRep,
  64. webForwardingRep: webForwardingRep,
  65. host: host,
  66. mq: mq,
  67. gatewayGroupRep: gatewayGroupRep,
  68. gatewayGroupIpRep: gatewayGroupIpRep,
  69. cdn: cdn,
  70. }
  71. }
  72. type wafFormatterService struct {
  73. *Service
  74. globalRep repository.GlobalLimitRepository
  75. hostRep repository.HostRepository
  76. required RequiredService
  77. parser ParserService
  78. tcpforwardingRep repository.TcpforwardingRepository
  79. udpForWardingRep repository.UdpForWardingRepository
  80. webForwardingRep repository.WebForwardingRepository
  81. host HostService
  82. mq *rabbitmq.RabbitMQ
  83. gatewayGroupRep repository.GatewayGroupRepository
  84. gatewayGroupIpRep repository.GateWayGroupIpRepository
  85. cdn CdnService
  86. }
  87. type RequireResponse struct {
  88. model.GlobalLimit `json:"globalLimit" form:"globalLimit"`
  89. GatewayIps []string `json:"ips" form:"ips"`
  90. Tag string `json:"tag" form:"tag"`
  91. }
  92. func (s *wafFormatterService) Require(ctx context.Context, req v1.GlobalRequire) (RequireResponse, error) {
  93. var res RequireResponse
  94. // 获取全局配置信息
  95. globalLimit, err := s.globalRep.GetGlobalLimitByHostId(ctx, int64(req.HostId))
  96. if err != nil {
  97. return RequireResponse{}, err
  98. }
  99. if globalLimit != nil {
  100. res.GlobalLimit = *globalLimit
  101. }
  102. // 获取主机名
  103. domain, err := s.hostRep.GetDomainById(ctx, req.HostId)
  104. if err != nil {
  105. return RequireResponse{}, err
  106. }
  107. res.Tag = strconv.Itoa(req.Uid) + "_" + strconv.Itoa(req.HostId) + "_" + domain + "_" + req.Comment
  108. res.GatewayIps, err = s.gatewayGroupIpRep.GetGateWayGroupAllIpByGatewayGroupId(ctx, res.GatewayGroupId)
  109. if err != nil {
  110. return RequireResponse{}, err
  111. }
  112. return res, nil
  113. }
  114. func (s *wafFormatterService) validateWafPortCount(ctx context.Context, hostId int) error {
  115. congfig, err := s.host.GetGlobalLimitConfig(ctx, hostId)
  116. if err != nil {
  117. return err
  118. }
  119. tcpCount, err := s.tcpforwardingRep.GetTcpForwardingPortCountByHostId(ctx, hostId)
  120. if err != nil {
  121. return err
  122. }
  123. udpCount, err := s.udpForWardingRep.GetUdpForwardingPortCountByHostId(ctx, hostId)
  124. if err != nil {
  125. return err
  126. }
  127. webCount, err := s.webForwardingRep.GetWebForwardingPortCountByHostId(ctx, hostId)
  128. if err != nil {
  129. return err
  130. }
  131. if int64(congfig.PortCount) > tcpCount+udpCount+webCount {
  132. return nil
  133. }
  134. return fmt.Errorf("端口数量超出套餐限制,已配置%d个端口,套餐限制为%d个端口", tcpCount+udpCount+webCount, congfig.PortCount)
  135. }
  136. func (s *wafFormatterService) validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error {
  137. congfig, err := s.host.GetGlobalLimitConfig(ctx, req.HostId)
  138. if err != nil {
  139. return err
  140. }
  141. domainCount, domainSlice, err := s.webForwardingRep.GetWebForwardingDomainCountByHostId(ctx, req.HostId)
  142. if err != nil {
  143. return err
  144. }
  145. if req.Domain != "" {
  146. if !slices.Contains(domainSlice, req.Domain) {
  147. domainCount += 1
  148. if domainCount > int64(congfig.DomainCount) {
  149. return fmt.Errorf("域名数量已达到上限,已配置%d个域名,套餐限制为%d个域名", domainCount, congfig.DomainCount)
  150. }
  151. }
  152. }
  153. return nil
  154. }
  155. func (s *wafFormatterService) ConvertToWildcardDomain(ctx context.Context, domain string) (string, error) {
  156. // 1. 使用 EffectiveTLDPlusOne 获取可注册域名部分。
  157. // 例如,对于 "www.google.com",这将返回 "google.com"。
  158. // 对于 "a.b.c.tokyo.jp",这将返回 "c.tokyo.jp"。
  159. if domain == "" {
  160. return "", nil
  161. }
  162. registrableDomain, err := publicsuffix.EffectiveTLDPlusOne(domain)
  163. if err != nil {
  164. s.logger.Error("无效的域名", zap.String("domain", domain), zap.Error(err))
  165. // 如果域名无效(如 IP 地址、localhost),则返回错误。
  166. return "", nil
  167. }
  168. // 2. 比较原始域名和可注册域名。
  169. // 如果它们不相等,说明原始域名包含子域名。
  170. if domain != registrableDomain {
  171. // 3. 如果存在子域名,则用 "*." 加上可注册域名来构造通配符域名。
  172. return registrableDomain, nil
  173. }
  174. // 4. 如果原始域名和可注册域名相同(例如,输入就是 "google.com"),
  175. // 则说明没有子域名可替换,直接返回原始域名。
  176. return domain, nil
  177. }
  178. func (s *wafFormatterService) AppendWafIp(ctx context.Context, req []string, returnSourceIp string) ([]v1.IpInfo, error) {
  179. var ips []v1.IpInfo
  180. for _, v := range req {
  181. ips = append(ips, v1.IpInfo{
  182. FType: "0",
  183. FStartIp: v,
  184. FEndIp: v,
  185. FRemark: "宁波高防IP过白",
  186. FServerIp: returnSourceIp,
  187. })
  188. }
  189. return ips, nil
  190. }
  191. func (s *wafFormatterService) AppendWafIpByRemovePort(ctx context.Context, req []string) ([]v1.IpInfo, error) {
  192. var ips []v1.IpInfo
  193. for _, v := range req {
  194. ip, _, err := net.SplitHostPort(v)
  195. if err != nil {
  196. return nil, err
  197. }
  198. ips = append(ips, v1.IpInfo{
  199. FType: "0",
  200. FStartIp: ip,
  201. FEndIp: ip,
  202. FRemark: "宁波高防IP过白",
  203. FServerIp: "",
  204. })
  205. }
  206. return ips, nil
  207. }
  208. func (s *wafFormatterService) WashIps(ctx context.Context, req []string) ([]string, error) {
  209. var res []string
  210. for _, v := range req {
  211. res = append(res, v)
  212. }
  213. return res, nil
  214. }
  215. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  216. // It can handle different actions like "add" or "del".
  217. func (s *wafFormatterService) PublishDomainWhitelistTask(domain, ip, action string) {
  218. // Define message payload, including the action
  219. type domainTaskPayload struct {
  220. Domain string `json:"domain"`
  221. Ip string `json:"ip"`
  222. Action string `json:"action"`
  223. }
  224. payload := domainTaskPayload{
  225. Domain: domain,
  226. Ip: ip,
  227. Action: action,
  228. }
  229. // Serialize the message
  230. msgBody, err := json.Marshal(payload)
  231. if err != nil {
  232. 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))
  233. return
  234. }
  235. // Get task configuration
  236. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  237. if !ok {
  238. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  239. return
  240. }
  241. // Construct the routing key dynamically based on the action
  242. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  243. // Construct the amqp.Publishing message
  244. publishingMsg := amqp.Publishing{
  245. ContentType: "application/json",
  246. Body: msgBody,
  247. DeliveryMode: amqp.Persistent, // Persistent message
  248. }
  249. // Publish the message
  250. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  251. if err != nil {
  252. s.logger.Error("发布 域名 白名单任务到 MQ 失败", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  253. } else {
  254. s.logger.Info("成功将 域名 白名单任务发布到 MQ", zap.String("domain", domain), zap.String("action", action))
  255. }
  256. }
  257. func (s *wafFormatterService) PublishIpWhitelistTask(ips []string, action string, returnSourceIp string, color string) {
  258. // Define message payload, including the action
  259. type ipTaskPayload struct {
  260. Ips []string `json:"ips"`
  261. Action string `json:"action"`
  262. ReturnSourceIp string `json:"return_source_ip"`
  263. Color string `json:"color"`
  264. }
  265. payload := ipTaskPayload{
  266. Ips: ips,
  267. Action: action,
  268. ReturnSourceIp: returnSourceIp,
  269. Color: color,
  270. }
  271. // Serialize the message
  272. msgBody, err := json.Marshal(payload)
  273. if err != nil {
  274. s.logger.Error("序列化 IP 白名单任务消息失败", zap.Error(err), zap.Any("IPs", ips), zap.String("action", action), zap.String("color", color))
  275. return
  276. }
  277. // Get task configuration
  278. taskCfg, ok := s.mq.GetTaskConfig("ip_white")
  279. if !ok {
  280. s.logger.Error("无法获取“ip_white”任务配置")
  281. return
  282. }
  283. // Construct the routing key dynamically based on the action
  284. routingKey := fmt.Sprintf("task.ip_white.%s", action)
  285. // Construct the amqp.Publishing message
  286. publishingMsg := amqp.Publishing{
  287. ContentType: "application/json",
  288. Body: msgBody,
  289. DeliveryMode: amqp.Persistent, // Persistent message
  290. }
  291. // Publish the message
  292. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  293. if err != nil {
  294. s.logger.Error("发布 IP 白名单任务到 MQ 失败", zap.Error(err), zap.String("action", action), zap.String("color", color))
  295. } else {
  296. s.logger.Info("成功将 IP 白名单任务发布到 MQ", zap.String("action", action), zap.String("color", color))
  297. }
  298. }
  299. func (s *wafFormatterService) findIpDifferences(oldIps, newIps []string) ([]string, []string) {
  300. // 使用 map 实现 set,用于快速查找
  301. oldIpsSet := make(map[string]struct{}, len(oldIps))
  302. for _, ip := range oldIps {
  303. oldIpsSet[ip] = struct{}{}
  304. }
  305. newIpsSet := make(map[string]struct{}, len(newIps))
  306. for _, ip := range newIps {
  307. newIpsSet[ip] = struct{}{}
  308. }
  309. var addedIps []string
  310. // 查找新增的 IP:存在于 newIpsSet 但不存在于 oldIpsSet
  311. for ip := range newIpsSet {
  312. if _, found := oldIpsSet[ip]; !found {
  313. addedIps = append(addedIps, ip)
  314. }
  315. }
  316. var removedIps []string
  317. // 查找移除的 IP:存在于 oldIpsSet 但不存在于 newIpsSet
  318. for ip := range oldIpsSet {
  319. if _, found := newIpsSet[ip]; !found {
  320. removedIps = append(removedIps, ip)
  321. }
  322. }
  323. return addedIps, removedIps
  324. }
  325. func (s *wafFormatterService) WashDeleteWafIp(ctx context.Context, backendList []string) ([]string, error) {
  326. var res []string
  327. for _, v := range backendList {
  328. ip, _, err := net.SplitHostPort(v)
  329. if err != nil {
  330. return nil, err
  331. }
  332. res = append(res, ip)
  333. }
  334. return res, nil
  335. }
  336. func (s *wafFormatterService) WashEditWafIp(ctx context.Context, newBackendList []string, oldBackendList []string) ([]string, []string, error) {
  337. var oldIps []string
  338. var newIps []string
  339. for _, v := range oldBackendList {
  340. ip, _, err := net.SplitHostPort(v)
  341. if err != nil {
  342. return nil, nil, err
  343. }
  344. oldIps = append(oldIps, ip)
  345. }
  346. if newBackendList != nil {
  347. for _, v := range newBackendList {
  348. ip, _, err := net.SplitHostPort(v)
  349. if err != nil {
  350. return nil, nil, err
  351. }
  352. newIps = append(newIps, ip)
  353. }
  354. }
  355. addedIps, removedIps := s.findIpDifferences(oldIps, newIps)
  356. return addedIps, removedIps, nil
  357. }
  358. func (s *wafFormatterService) AddOrigin(ctx context.Context, req v1.WebJson) (int64, error) {
  359. ip, port, err := net.SplitHostPort(req.BackendList)
  360. if err != nil {
  361. return 0, fmt.Errorf("无效的后端地址: %s", err)
  362. }
  363. addr := v1.Addr{
  364. Protocol: req.ApiType,
  365. Host: ip,
  366. Port: port,
  367. }
  368. id, err := s.cdn.CreateOrigin(ctx, v1.Origin{
  369. Addr: addr,
  370. Weight: 10,
  371. Description: req.Comment,
  372. Host: req.Host,
  373. IsOn: true,
  374. TlsSecurityVerifyMode: "auto",
  375. })
  376. if err != nil {
  377. return 0, err
  378. }
  379. return id, nil
  380. }
  381. // 获取ip数量等于1的源站过白ip
  382. func (s *wafFormatterService) WashDelIps(ctx context.Context, ips []string) ([]string, error) {
  383. var udpIpCounts, tcpIpCounts, webIpCounts []v1.IpCountResult
  384. g, gCtx := errgroup.WithContext(ctx)
  385. // 1. 查询 IP 的数量
  386. g.Go(func() error {
  387. var err error
  388. udpIpCounts, err = s.udpForWardingRep.GetIpCountByIp(gCtx, ips)
  389. if err != nil {
  390. return fmt.Errorf("in udp repository: %w", err)
  391. }
  392. return nil
  393. })
  394. g.Go(func() error {
  395. var err error
  396. tcpIpCounts, err = s.tcpforwardingRep.GetIpCountByIp(gCtx, ips)
  397. if err != nil {
  398. return fmt.Errorf("in tcp repository: %w", err)
  399. }
  400. return nil
  401. })
  402. g.Go(func() error {
  403. var err error
  404. webIpCounts, err = s.webForwardingRep.GetIpCountByIp(gCtx, ips)
  405. if err != nil {
  406. return fmt.Errorf("in web repository: %w", err)
  407. }
  408. return nil
  409. })
  410. if err := g.Wait(); err != nil {
  411. return nil, err
  412. }
  413. // 2. 汇总所有计数结果
  414. totalCountMap := make(map[string]int)
  415. // 将多个 for 循环合并到一个函数中,可以显得更整洁(可选)
  416. accumulateCounts := func(counts []v1.IpCountResult) {
  417. for _, result := range counts {
  418. totalCountMap[result.Ip] += result.Count
  419. }
  420. }
  421. accumulateCounts(udpIpCounts)
  422. accumulateCounts(tcpIpCounts)
  423. accumulateCounts(webIpCounts)
  424. // 3. 筛选出总引用数小于 2 的 IP
  425. var ipsToDelist []string
  426. for _, ip := range ips {
  427. if totalCountMap[ip] < 2 {
  428. ipsToDelist = append(ipsToDelist, ip)
  429. }
  430. }
  431. return ipsToDelist, nil
  432. }
  433. // 判断域名是否为 中文域名,如果是,转换为 Punycode
  434. func (s *wafFormatterService) ConvertToPunycodeIfIDN(ctx context.Context, domain string) (isIDN bool, punycodeDomain string, err error) {
  435. // 使用 idna.ToASCII 将域名转换为 Punycode。
  436. // 这个函数同时会根据 IDNA 规范验证域名的合法性。
  437. punycodeDomain, err = idna.ToASCII(domain)
  438. if err != nil {
  439. // 如果转换出错,说明域名格式不符合 IDNA 标准。
  440. return false, "", fmt.Errorf("域名 '%s' 格式无效: %v", domain, err)
  441. }
  442. // 判断是否为 IDN 的关键:
  443. // 比较转换后的 Punycode 域名和原始域名(忽略大小写)。
  444. // 如果不相等,说明原始域名包含非 ASCII 字符,即为 IDN。
  445. isIDN = !strings.EqualFold(domain, punycodeDomain)
  446. return isIDN, punycodeDomain, nil
  447. }
  448. // 验证端口重复
  449. func (s *wafFormatterService) VerifyPort(ctx context.Context,protocol string, id int64, port string,hostId int64,domain string) error {
  450. errPortInUse := fmt.Errorf("端口 %s 已经被使用,无法添加", port)
  451. switch protocol {
  452. case "http", "https":
  453. domains, err := s.webForwardingRep.GetDomainByHostIdPort(ctx, hostId, port)
  454. if err != nil {
  455. return err
  456. }
  457. tcpCount, err := s.tcpforwardingRep.GetPortCount(ctx, hostId, port)
  458. if err != nil {
  459. return err
  460. }
  461. if tcpCount > 0 {
  462. return errPortInUse
  463. }
  464. for _, v := range domains {
  465. // 防住空域名修改为非空域名报错
  466. if v.Domain == "" && int64(v.Id) != id {
  467. return errPortInUse
  468. }
  469. if net.ParseIP(v.Domain) != nil {
  470. return errPortInUse
  471. }
  472. }
  473. // 确保添加新规则时,没有已有域名的规则
  474. if net.ParseIP(domain) != nil || domain == "" {
  475. if len(domains) > 0 {
  476. return errPortInUse
  477. }
  478. }
  479. return nil
  480. case "tcp":
  481. count, err := s.tcpforwardingRep.GetPortCount(ctx, hostId, port)
  482. if err != nil {
  483. return err
  484. }
  485. webCount, err := s.webForwardingRep.GetDomainByHostIdPort(ctx, hostId, port)
  486. if err != nil {
  487. return err
  488. }
  489. if count + int64(len(webCount)) > 0 {
  490. return errPortInUse
  491. }
  492. return nil
  493. case "udp":
  494. count, err := s.udpForWardingRep.GetPortCount(ctx, hostId, port)
  495. if err != nil {
  496. return err
  497. }
  498. if count > 0 {
  499. return errPortInUse
  500. }
  501. return nil
  502. default:
  503. return fmt.Errorf("不支持的协议类型:%s", protocol)
  504. }
  505. }