wafformatter.go 17 KB

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