#!/usr/bin/python3
# Wombat-Email: reads the server's logs for a stretch of time and sums them up, for the daily glance
# (wombat-email-report: counts for yesterday) and the weekly report (wombat-email-weekly: the lists behind
# the counts). Installed by installer/95-report.sh as /usr/local/libexec/wombat-email-logstats.
#
#   wombat-email-logstats DAYS [--json]     the last DAYS full days (1 = yesterday), as JSON or as text
#
# Sources: the journal (Postfix, Dovecot, SSH), fail2ban's log, Rspamd's log, Apache's access log for the
# panel and webmail, and the panel's failed sign-ins. Usage like a mail server's weekly report (mail sent
# per user, received per mailbox, logins per user and where from), plus what logwatch showed (SSH, bans,
# refused mail, the web's probes).
import collections
import datetime
import glob
import gzip
import ipaddress
import json
import re
import subprocess
import sys

days = int(sys.argv[1]) if len(sys.argv) > 1 else 1
as_json = "--json" in sys.argv
today = datetime.date.today()
start = today - datetime.timedelta(days=days)
start_dt = datetime.datetime.combine(start, datetime.time())
end_dt = datetime.datetime.combine(today, datetime.time())


def local(ip):
    try:
        a = ipaddress.ip_address(ip)
        return a.is_loopback or a.is_private
    except ValueError:
        return False


def journal(*args):
    out = subprocess.run(["journalctl", "--since", start_dt.strftime("%Y-%m-%d %H:%M:%S"),
                          "--until", end_dt.strftime("%Y-%m-%d %H:%M:%S"), "-o", "cat", "--no-pager", "-q", *args],
                         capture_output=True, text=True, errors="replace").stdout
    return out.splitlines()


def files(pattern):
    """Lines of a log and its rotated copies (gzipped too)."""
    for path in sorted(glob.glob(pattern), reverse=True):
        opener = gzip.open if path.endswith(".gz") else open
        try:
            with opener(path, "rt", errors="replace") as f:
                yield from f
        except OSError:
            pass


s = {"days": days, "from": start.isoformat(), "to": (today - datetime.timedelta(days=1)).isoformat()}

# ---- mail: sent by users (authenticated submission), received into mailboxes, refused at the door
sent = collections.defaultdict(lambda: {"n": 0, "hosts": set()})
login_fail_mail = collections.Counter()
mail_users_tried = collections.Counter()
refused = collections.Counter()
refused_n = 0
viruses = 0
postfix = journal("-t", "postfix/submission/smtpd", "-t", "postfix/submissions/smtpd", "-t", "postfix/smtpd", "-t", "postfix/cleanup")
for line in postfix:
    m = re.search(r"client=\S*\[([^\]]+)\], sasl_method=\S+, sasl_username=(\S+)", line)
    if m:
        u = sent[m.group(2).lower()]
        u["n"] += 1
        u["hosts"].add("webmail" if local(m.group(1)) else m.group(1))
        continue
    m = re.search(r"\[([^\]]+)\]: SASL \S+ authentication failed.*?(?:sasl_username=(\S+))?$", line)
    if m:
        login_fail_mail[m.group(1)] += 1
        if m.group(2):
            mail_users_tried[m.group(2).lower()] += 1
        continue
    m = re.search(r"NOQUEUE: reject: RCPT from \S+: \d{3} \S+ (?:<[^>]*>: )?([^;]+);", line)
    if m:
        refused_n += 1
        reason = m.group(1)
        reason = re.sub(r"^(Client host|Sender address|Recipient address|Helo command) rejected: ", "", reason)
        reason = re.sub(r"\b\d{1,3}(\.\d{1,3}){3}\b", "<address>", reason)
        reason = re.sub(r"^not owned by user \S+", "a user sending as an address that isn't theirs", reason)
        reason = {"not logged in": "sending without logging in", "Relay access denied": "relaying to another server, not logged in"}.get(reason, reason)
        refused[reason[:90]] += 1
        continue
    if "virus found" in line:
        viruses += 1
s["sent"] = {u: {"n": v["n"], "hosts": sorted(v["hosts"])} for u, v in sent.items()}
received = collections.Counter()
for line in journal("-t", "postfix/lmtp"):
    m = re.search(r"to=<([^>]+)>.*status=sent", line)
    if m:
        received[m.group(1).lower()] += 1
s["received"] = dict(received)
s["refused"] = {"n": refused_n, "why": refused.most_common(12)}
s["viruses"] = viruses

# ---- logins: mail apps (IMAP) and sending, ssh, the panel; and the failed ones
imap = collections.defaultdict(lambda: collections.Counter())
login_fail_imap = collections.Counter()
for line in journal("-u", "dovecot"):
    m = re.search(r"imap-login: Logged in: user=<([^>]+)>.*?rip=([^,]+)", line)
    if m:
        imap[m.group(1).lower()]["webmail" if local(m.group(2)) else m.group(2)] += 1
        continue
    if re.search(r"(auth failed|password mismatch|unknown user)", line, re.I):
        m = re.search(r"rip=([^,\s]+)", line)
        if m:
            login_fail_imap[m.group(1)] += 1
s["imap"] = {u: dict(c) for u, c in imap.items()}
ssh_ok = collections.Counter()
ssh_fail = collections.Counter()
for line in journal("-t", "sshd", "-t", "sshd-session"):
    m = re.search(r"Accepted (\S+) for (\S+) from (\S+)", line)
    if m:
        ssh_ok[f"{m.group(2)} ({m.group(1)}) from {m.group(3)}"] += 1
        continue
    m = re.search(r"(?:Failed \S+ for (?:invalid user )?\S+|Invalid user \S* ?|authenticating user \S+) from (\S+)", line)
    if m:
        ssh_fail[m.group(1)] += 1
s["ssh"] = {"ok": dict(ssh_ok), "fail": sum(ssh_fail.values()), "fail_from": len(ssh_fail), "top": ssh_fail.most_common(10)}
panel_fail = collections.Counter()
for line in files("/var/log/wombat-email/panel-auth.log*"):
    m = re.match(r"(\d{4}-\d{2}-\d{2}) \S+ wombat-panel: failed sign-in \(([^)]+)\) from (\S+)", line)
    if m and s["from"] <= m.group(1) <= s["to"]:
        panel_fail[m.group(3)] += 1
panel_ok = 0
try:
    panel_ok = int(subprocess.run(["runuser", "-u", "postgres", "--", "psql", "-X", "-At", "-d", "wombat_email", "-c",
                                   f"SELECT count(*) FROM admin_log WHERE action = 'signed in' AND at >= '{start}' AND at < '{today}'"],
                                  capture_output=True, text=True).stdout.strip() or 0)
except (ValueError, OSError):
    pass
s["mail_fail"] = {"n": sum(login_fail_mail.values()) + sum(login_fail_imap.values()),
                  "from": len(set(login_fail_mail) | set(login_fail_imap)),
                  "top": (login_fail_mail + login_fail_imap).most_common(10), "users": mail_users_tried.most_common(10)}
s["panel"] = {"ok": panel_ok, "fail": sum(panel_fail.values()), "top": panel_fail.most_common(5)}

# ---- bans (fail2ban)
bans = collections.Counter()
banned = collections.Counter()
for line in files("/var/log/fail2ban.log*"):
    m = re.match(r"(\d{4}-\d{2}-\d{2}) .*\[(\S+)\] Ban (\S+)", line)
    if m and s["from"] <= m.group(1) <= s["to"]:
        bans[m.group(2)] += 1
        banned[m.group(3)] += 1
s["bans"] = {"n": sum(bans.values()), "jails": dict(bans), "top": banned.most_common(10)}

# ---- spam: Rspamd's verdicts on mail coming in
actions = collections.Counter()
for line in files("/var/log/rspamd/rspamd.log*"):
    if "rspamd_task_write_log" not in line or "(controller)" in line or not line[:10].isdigit() and not line[:4].isdigit():
        continue
    if s["from"] <= line[:10] <= s["to"]:
        m = re.search(r"\(default: \S \(([a-z ]+)\)", line)
        if m:
            actions[m.group(1)] += 1
s["spam"] = dict(actions)

# ---- web: the panel's and webmail's site; what robots try
requests = 0
probes = collections.Counter()
probers = collections.Counter()
NORMAL = {"/", "/favicon.ico", "/robots.txt", "/apple-touch-icon.png", "/apple-touch-icon-precomposed.png", "/sitemap.xml"}   # asked by browsers and search engines, not probes
months = {m: i for i, m in enumerate(["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], 1)}
for line in files("/var/log/apache2/wombat-email-access.log*"):
    m = re.match(r'(\S+) \S+ \S+ \[(\d{2})/(\w{3})/(\d{4}):[^\]]+\] "(\S+) (\S+)[^"]*" (\d{3})', line)
    if not m:
        continue
    day = f"{m.group(4)}-{months.get(m.group(3), 0):02d}-{m.group(2)}"
    if not (s["from"] <= day <= s["to"]):
        continue
    requests += 1
    if m.group(7) in ("400", "403", "404", "405", "444") and m.group(6).split("?")[0] not in NORMAL:
        probes[m.group(6).split("?")[0][:70]] += 1
        probers[m.group(1)] += 1
s["web"] = {"requests": requests, "refused": sum(probes.values()), "top": probes.most_common(15), "from": probers.most_common(10)}

if as_json:
    json.dump(s, sys.stdout)
    sys.exit(0)

# ---- as text, for the weekly report: every list
def table(rows, head=None, indent="  "):
    out = []
    if head:
        out.append(indent + head)
    for r in rows:
        out.append(indent + r)
    return out or [indent + "none"]

out = []
def section(title):
    out.extend(["", title, "-" * len(title)])

section("Mail sent by your users")
rows = sorted(s["sent"].items(), key=lambda x: -x[1]["n"])
out += table([f"{n['n']:>6}  {u}  (from {', '.join(n['hosts'][:4])}{' …' if len(n['hosts']) > 4 else ''})" for u, n in rows]) if rows else ["  none"]
section("Mail received, by mailbox")
out += table([f"{n:>6}  {u}" for u, n in received.most_common()]) if received else ["  none"]
section("Logins to mail apps (IMAP)")
out += table([f"{sum(c.values()):>6}  {u}  (from {', '.join(f'{h} {n}x' for h, n in c.most_common(4))})" for u, c in sorted(imap.items(), key=lambda x: -sum(x[1].values()))]) if imap else ["  none"]
section("SSH")
out += table([f"{n:>6}  {k}" for k, n in ssh_ok.most_common()]) if ssh_ok else ["  no logins"]
out.append(f"  {s['ssh']['fail']} failed tries from {s['ssh']['fail_from']} addresses; the most:")
out += table([f"{n:>6}  {ip}" for ip, n in s["ssh"]["top"]], indent="    ")
section("Failed logins to mail")
out.append(f"  {s['mail_fail']['n']} from {s['mail_fail']['from']} addresses; the most:")
out += table([f"{n:>6}  {ip}" for ip, n in s["mail_fail"]["top"]], indent="    ")
if s["mail_fail"]["users"]:
    out.append("  Names they tried:")
    out += table([f"{n:>6}  {u}" for u, n in s["mail_fail"]["users"]], indent="    ")
section("The panel")
out.append(f"  {panel_ok} sign-ins; {s['panel']['fail']} failed" + (" (" + ", ".join(f"{ip} {n}x" for ip, n in s["panel"]["top"]) + ")" if s["panel"]["top"] else ""))
section("Banned by fail2ban")
out.append(f"  {s['bans']['n']} bans: " + (", ".join(f"{j} {n}" for j, n in sorted(bans.items(), key=lambda x: -x[1])) or "none"))
if s["bans"]["top"]:
    out.append("  Banned most often:")
    out += table([f"{n:>6}  {ip}" for ip, n in s["bans"]["top"]], indent="    ")
section("Mail refused at the door")
out.append(f"  {refused_n} refused; why:")
out += table([f"{n:>6}  {why}" for why, n in s["refused"]["why"]], indent="    ")
section("Spam and viruses (Rspamd's verdicts on incoming mail)")
names = {"no action": "fine", "add header": "to the Spam folder", "rewrite subject": "subject marked", "greylist": "asked to retry later",
         "soft reject": "asked to retry later", "reject": "refused"}
out.append("  " + (", ".join(f"{n} {names.get(a, a)}" for a, n in sorted(actions.items(), key=lambda x: -x[1])) or "nothing scanned") + f"; {viruses} viruses")
section("The web (the panel and webmail)")
out.append(f"  {requests} requests; {s['web']['refused']} refused or not found, mostly robots looking for weak spots. What they tried most:")
out += table([f"{n:>6}  {p}" for p, n in s["web"]["top"]], indent="    ")
out.append("  From:")
out += table([f"{n:>6}  {ip}" for ip, n in s["web"]["from"]], indent="    ")
print("\n".join(out).lstrip("\n"))
