Catalyst / admin/Synapse-NetscanXi 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Synapse-NetscanXi

public

Network Scanning, Vulnerability and Compliance Application

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Synapse-NetscanXi / NetscanXiVersion13 / app / alerts.py 2811 B · main
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
Alerting: webhook (Slack/Discord/generic) and SMTP email.
Configured via environment variables; all best-effort and non-fatal.

Env:
  NETSCAN_WEBHOOK_URL     generic/Slack/Discord-compatible webhook
  NETSCAN_ALERT_MIN_SEV   info|warn|critical (default warn)
  NETSCAN_SMTP_HOST/PORT/USER/PASS/FROM/TO   email config (optional)
"""

import json
import os
import smtplib
import urllib.request
from email.message import EmailMessage

SEV_ORDER = {"info": 0, "warn": 1, "critical": 2}


def _min_sev():
    return os.environ.get("NETSCAN_ALERT_MIN_SEV", "warn").lower()


def _filter(changes):
    threshold = SEV_ORDER.get(_min_sev(), 1)
    return [c for c in changes if SEV_ORDER.get(c.get("severity", "info"), 0) >= threshold]


def _format(target, changes):
    lines = [f"NetScan Xi: {len(changes)} notable change(s) on {target}", ""]
    for c in changes:
        marker = {"critical": "🔴", "warn": "🟠", "info": "🔵"}.get(c["severity"], "•")
        lines.append(f"{marker} {c['ip']}: {c['detail']}")
    return "\n".join(lines)


def send_webhook(text):
    url = os.environ.get("NETSCAN_WEBHOOK_URL")
    if not url:
        return False
    # Slack & Discord both accept a JSON body with a text/content field.
    payload = {"text": text, "content": text}
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data,
                                 headers={"Content-Type": "application/json"})
    try:
        urllib.request.urlopen(req, timeout=8)
        return True
    except Exception:
        return False


def send_email(subject, body):
    host = os.environ.get("NETSCAN_SMTP_HOST")
    to = os.environ.get("NETSCAN_SMTP_TO")
    if not host or not to:
        return False
    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = os.environ.get("NETSCAN_SMTP_FROM", "netscan-xi@localhost")
    msg["To"] = to
    msg.set_content(body)
    try:
        port = int(os.environ.get("NETSCAN_SMTP_PORT", "587"))
        with smtplib.SMTP(host, port, timeout=10) as s:
            s.starttls()
            user = os.environ.get("NETSCAN_SMTP_USER")
            pw = os.environ.get("NETSCAN_SMTP_PASS")
            if user and pw:
                s.login(user, pw)
            s.send_message(msg)
        return True
    except Exception:
        return False


def dispatch(target, changes):
    """Send alerts for notable changes. Returns dict of what fired."""
    notable = _filter(changes)
    if not notable:
        return {"sent": False, "reason": "no notable changes"}
    text = _format(target, notable)
    result = {
        "sent": True,
        "count": len(notable),
        "webhook": send_webhook(text),
        "email": send_email(f"NetScan Xi: {len(notable)} change(s) on {target}", text),
    }
    return result