protector.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """Background protector: periodically checks protector_list entries and blocks offending dst_addr via advanced_acl.add_ip
  2. """
  3. from __future__ import annotations
  4. import threading
  5. import time
  6. from typing import Optional
  7. import advanced_acl
  8. from auth_session import load_config
  9. import protector_list
  10. from analysis_connections import find_high_connections_for_src_ports
  11. from log_util import get_logger
  12. logger = get_logger("protector")
  13. class ProtectorRunner:
  14. def __init__(self):
  15. cfg = load_config()
  16. self.interval = int(cfg.get("scan_interval", 60))
  17. self._stop = threading.Event()
  18. def run_once(self):
  19. items = protector_list.load_list()
  20. for entry in items:
  21. target = entry.get("target_ip")
  22. src_port = int(entry.get("src_port"))
  23. threshold = entry.get("threshold")
  24. try:
  25. res = find_high_connections_for_src_ports(target, src_port, threshold=threshold)
  26. except Exception as e:
  27. logger.exception(f"检查失败 {target}:{src_port} - {e}")
  28. continue
  29. matches = res.get("by_src_port", {}).get(int(src_port), [])
  30. if not matches:
  31. logger.info(f"{target}:{src_port} - 无异常连接")
  32. continue
  33. for m in matches:
  34. dst = m.get("dst_addr")
  35. # Call advanced_acl.add_ip to block
  36. try:
  37. # Do not pass custom comment here so add_ip will place the IP into Test_* groups
  38. # (comment was causing new rules to be named AutoBlock_..., not grouped).
  39. result = advanced_acl.add_ip(dst)
  40. # Support both legacy (resp, data) tuple and new dict result
  41. if isinstance(result, dict):
  42. added = result.get("added")
  43. rule = result.get("rule")
  44. row_id = result.get("row_id")
  45. msg = result.get("message")
  46. logger.info(f"已尝试阻断 {dst}, added={added}, rule={rule}, row_id={row_id}, msg={msg}")
  47. else:
  48. # assume (resp, data)
  49. resp, data = result
  50. logger.info(f"已尝试阻断 {dst}, 状态: {resp.status_code}, 返回: {data}")
  51. except Exception as e:
  52. logger.exception(f"阻断失败 {dst}: {e}")
  53. def start(self):
  54. self._stop.clear()
  55. def _loop():
  56. while not self._stop.is_set():
  57. try:
  58. self.run_once()
  59. except Exception:
  60. logger.exception("运行一次保护检查失败")
  61. # reload interval in case config changed
  62. try:
  63. cfg = load_config()
  64. self.interval = int(cfg.get("scan_interval", self.interval))
  65. except Exception:
  66. pass
  67. time.sleep(self.interval)
  68. t = threading.Thread(target=_loop, daemon=True)
  69. t.start()
  70. return t
  71. def stop(self):
  72. self._stop.set()
  73. def run_protector_blocking_once():
  74. pr = ProtectorRunner()
  75. pr.run_once()
  76. if __name__ == "__main__":
  77. r = ProtectorRunner()
  78. r.start()
  79. try:
  80. while True:
  81. time.sleep(1)
  82. except KeyboardInterrupt:
  83. r.stop()