#!/usr/bin/env python3

# Lokasi File ini pada Wazuh Server (192.168.160.70) : /var/ossec/integrations
import json
import sys
import os

try:
    import requests
except ImportError:
    print("Modul 'requests' yang dibutuhkan belum ter-install.")
    sys.exit(1)

# Untuk alasan keamanan, kredensial diubah menjadi placeholder
CHAT_ID = "<CHAT_ID_BOT_TELEGRAM>"
BOT_TOKEN = "<TOKEN_BOT_TELEGRAM>"

# Contoh: RULE_ID_WHITELIST = ["5712", "86601"]
RULE_ID_WHITELIST = ["86601"]

# Contoh: DESCRIPTION_KEYWORDS = ["brute force", "syn flood", "scan detected"]
DESCRIPTION_KEYWORDS = ["syn"]

# Filter : Hanya kirim notifikasi jika level alert lebih tinggi atau sama dengan nilai ini
MIN_ALERT_LEVEL = 3

# Filter : Hanya kirim notifikasi dari agen dengan nama ini
AGENT_NAME_FILTER = "KALI-LINUX"

# Membuat URL hook dari token
HOOK_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"

# Fungsi untuk kirim pesan
def send_message(msg):
    headers = {'Content-Type': 'application/json'}
    try:
        response = requests.post(HOOK_URL, headers=headers, data=json.dumps(msg), timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        log_to_file(f"Error sending to Telegram: {e}")

# Fungsi logging internal Wazuh
def log_to_file(message):
    log_path = os.path.join(os.path.dirname(sys.argv[0]), "..", "logs", "integrations.log")
    with open(log_path, "a") as f:
        f.write(f"{message}\n")

# Fungsi format pesan + detail
def format_message(alert):
    # Mengambil data dari JSON alert
    rule = alert.get('rule', {})
    agent = alert.get('agent', {})
    data = alert.get('data', {})
    suricata_alert_data = data.get('alert', {})

    description = rule.get('description', 'N/A')
    level = rule.get('level', 'N/A')
    agent_name = agent.get('name', 'N/A')
    rule_id = rule.get('id', 'N/A')
    timestamp = alert.get('timestamp', 'N/A')
    location = alert.get('location', 'N/A')

    # Mengambil IP dari beberapa kemungkinan field
    srcip = data.get('srcip') or data.get('src_ip', 'N/A')
    dstip = data.get('dstip') or data.get('dest_ip', 'N/A')

    # Mengambil grup dan jadikan string
    groups = rule.get('groups', [])
    rule_group = ", ".join(groups) if groups else 'N/A'

    # Mengambil kategori dari data Suricata
    category = suricata_alert_data.get('category', 'N/A')

    # Membuat format pesan teks
    msg_text = (
        f"*Suricata Alert Detected*\n\n"
        f"*Description*: {description}\n"
        f"*Level*: {level}\n"
        f"*Agent*: {agent_name}\n"
        f"*Rule ID*: {rule_id}\n"
        f"*Timestamp*: {timestamp}\n"
        f"*Source IP*: {srcip}\n"
        f"*Destination IP*: {dstip}\n"
        f"*Group*: {rule_group}\n"
        f"*Category*: {category}\n"
        f"*Location*: {location}"
    )
    return msg_text

# Logika Utama
def main():
    if len(sys.argv) < 2:
        log_to_file("Error: Alert file path not provided.")
        sys.exit(1)

    alert_file_path = sys.argv[1]

    try:
        with open(alert_file_path) as f:
            alert_json = json.load(f)
    except Exception as e:
        log_to_file(f"Error reading or decoding alert file: {e}")
        sys.exit(1)

    # Logika Filter
    # Filter Level
    if alert_json.get('rule', {}).get('level', 0) < MIN_ALERT_LEVEL:
        sys.exit(0)

    # Filter Nama Agent
    if AGENT_NAME_FILTER and alert_json.get('agent', {}).get('name') != AGENT_NAME_FILTER:
        sys.exit(0)

    # Filter Rule ID
    rule_id = alert_json.get('rule', {}).get('id')
    if RULE_ID_WHITELIST and rule_id not in RULE_ID_WHITELIST:
        sys.exit(0) # Berhenti kirim jika rule_id tidak ada di whitelist

    # Filter Deskripsi
    description = alert_json.get('rule', {}).get('description', '').lower()
    if DESCRIPTION_KEYWORDS and not any(keyword in description for keyword in DESCRIPTION_KEYWORDS):
        sys.exit(0) # Berhenti kirim jika tidak ada kata kunci yang cocok di deskripsi

    # Format dan kirim pesan
    message_text = format_message(alert_json)
    msg_data = {
        'chat_id': CHAT_ID,
        'text': message_text,
        'parse_mode': 'Markdown'
    }
    send_message(msg_data)

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        log_to_file(f"Unhandled exception in Telegram script: {e}")
        sys.exit(1)