Загрузка данных


import time, os, subprocess

INTEL_LOG   = "/tmp/zeek_block_intel.log"
RULES_FILE  = "/usr/local/var/lib/suricata/rules/dynamic_block.rules"
SEEN_FILE   = "/usr/local/var/lib/suricata/rules/dynamic_block_seen.txt"
SID_START   = 2000000

# --- Шаблоны правил под каждый тип индикатора ---
def make_rule(itype, value, sid):
    if itype == "HTTP_HOST":
        return (
            f'drop http any any -> any any ('
            f'msg:"ZEEK BLOCK HTTP HOST {value}"; '
            f'flow:to_server; '
            f'http.host; content:"{value}"; nocase; '
            f'sid:{sid}; rev:1;)\n'
        )
    elif itype == "HTTP_USERAGENT":
        return (
            f'drop http any any -> any any ('
            f'msg:"ZEEK BLOCK UA {value}"; '
            f'flow:to_server; '
            f'http.user_agent; content:"{value}"; nocase; '
            f'sid:{sid}; rev:1;)\n'
        )
    elif itype == "FTP_PORT":
        return (
            f'drop tcp any any -> any 21 ('
            f'msg:"ZEEK BLOCK FTP port 21"; '
            f'flow:to_server; '
            f'sid:{sid}; rev:1;)\n'
        )
    return None

# --- Загрузка уже обработанных индикаторов ---
seen = set()
if os.path.exists(SEEN_FILE):
    with open(SEEN_FILE) as f:
        seen = set(line.strip() for line in f if line.strip())
    print(f"[*] Загружено {len(seen)} существующих индикаторов")

# Определяем следующий свободный SID
sid = SID_START + len(seen)

print("[*] Zeek→Suricata мост запущен. Ожидание индикаторов...")

while True:
    if os.path.exists(INTEL_LOG):
        with open(INTEL_LOG) as f:
            for line in f:
                indicator = line.strip()
                if not indicator or indicator in seen:
                    continue
                # Разбираем формат ТИП:значение
                if ':' not in indicator:
                    continue
                itype, value = indicator.split(':', 1)
                rule = make_rule(itype, value, sid)
                if not rule:
                    print(f"[!] Неизвестный тип: {itype}")
                    continue
                # Записываем правило
                with open(RULES_FILE, 'a') as rf:
                    rf.write(rule)
                # Сохраняем индикатор
                with open(SEEN_FILE, 'a') as sf:
                    sf.write(indicator + '\n')
                seen.add(indicator)
                sid += 1
                # Перезагружаем правила Suricata без остановки
                subprocess.run(["killall", "-HUP", "suricata"])
                print(f"[+] Новое правило: {rule.strip()}")

    time.sleep(2)