diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..1446962 --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Copy to .env (never commit it) and fill in. +TELEGRAM_BOT_TOKEN=123456:ABC... +# Comma-separated Telegram chat IDs allowed to use the bot +ALLOWED_CHAT_IDS=8248249474 +LAPI_URL=http://10.0.0.11:8080 +# On the CrowdSec host: cscli bouncers add barbenoire +CROWDSEC_BOUNCER_KEY= +# On the CrowdSec host: cscli machines add barbenoire --password '' +CROWDSEC_MACHINE_ID=barbenoire +CROWDSEC_MACHINE_PASSWORD= +# Kuma Push URL for the "Barbenoire" monitor (bot heartbeat every 60 s); empty = off +KUMA_PUSH_URL= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85aed96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.env +.venv/ +__pycache__/ +.local/ +.cache/ +.config/ diff --git a/README.md b/README.md index 1c37aad..ad7628d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,43 @@ # barbenoire +Telegram bot on top of the homelab's **CrowdSec** Local API. +CrowdSec itself still sends the ban notifications (same bot token, `http` plugin); +this bot only adds commands. + +| Command | Reply | +|---|---| +| `/bans` | Active bans from the local CrowdSec (community blocklist not counted) | +| `/ip
` | Banned right now? Country, AS, alert history, CTI/Shodan links | +| `/unban
` | Lift a ban, after a ✅/❌ confirmation | +| `/stats` | Alerts over 24 h and 7 days, by scenario and country | + +Optional: a heartbeat to a Kuma Push monitor (`KUMA_PUSH_URL`). +It only answers the chat IDs in `ALLOWED_CHAT_IDS`. + +## CrowdSec credentials (on the CrowdSec host, LXC 101) + +```bash +cscli bouncers add barbenoire # -> CROWDSEC_BOUNCER_KEY (read current decisions) +cscli machines add barbenoire --password '' -f /dev/null # -> machine login (history + unban) +``` + +The bot talks to the LAPI at `http://10.0.0.11:8080` (reachable from VM 107). + +## Run locally + +```bash +python3 -m venv .venv && .venv/bin/pip install -r requirements.txt +cp .env.example .env # fill in token + CrowdSec credentials +.venv/bin/python app.py +``` + +## Deploy on Pterodactyl (python generic egg) + +Server `barbenoire` on node `wings`. Same variables as barberousse, with +`GIT_ADDRESS=https://forgejo.un-oeil.fr/un-oeil/barbenoire.git`. + +1. Set the variables, then **Reinstall** (clones the repo). +2. Files → create `.env` from `.env.example` (git-ignored). +3. Start. The console shows `Barbenoire starting (...)`. + +To update: push to Forgejo, then Restart the server. diff --git a/app.py b/app.py new file mode 100644 index 0000000..c64b51b --- /dev/null +++ b/app.py @@ -0,0 +1,216 @@ +"""Barbenoire: Telegram commands on top of CrowdSec (bans, history, unban).""" +from __future__ import annotations + +import html +import logging +import os +from collections import Counter +from functools import wraps + +import httpx +from dotenv import load_dotenv +from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update +from telegram.constants import ParseMode +from telegram.ext import Application, CallbackQueryHandler, CommandHandler, ContextTypes + +from lapi import Lapi, LapiError, valid_ip + +load_dotenv() +TOKEN = os.environ["TELEGRAM_BOT_TOKEN"] +ALLOWED = {int(x) for x in os.environ["ALLOWED_CHAT_IDS"].split(",") if x.strip()} +PUSH_URL = os.environ.get("KUMA_PUSH_URL", "").strip() +lapi = Lapi( + url=os.environ.get("LAPI_URL", "http://10.0.0.11:8080"), + bouncer_key=os.environ["CROWDSEC_BOUNCER_KEY"], + machine_id=os.environ["CROWDSEC_MACHINE_ID"], + machine_password=os.environ["CROWDSEC_MACHINE_PASSWORD"], +) + +logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.INFO) +logging.getLogger("httpx").setLevel(logging.WARNING) +log = logging.getLogger("barbenoire") + + +def restricted(func): + @wraps(func) + async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE): + chat = update.effective_chat + if chat is None or chat.id not in ALLOWED: + log.warning("ignored update from chat %s (%s)", chat and chat.id, update.effective_user) + if update.callback_query: + await update.callback_query.answer("Not allowed.") + return + try: + return await func(update, context) + except LapiError as e: + log.error("LAPI error: %s", e) + await update.effective_message.reply_text(f"⚠️ CrowdSec: {e}") + return wrapper + + +def esc(s) -> str: + return html.escape(str(s)) + + +def flag(cc: str | None) -> str: + cc = (cc or "").upper() + return "".join(chr(0x1F1E6 + ord(c) - 65) for c in cc) if len(cc) == 2 and cc.isalpha() else "🏴" + + +def short_duration(d: str | None) -> str: + """LAPI durations look like '3h59m12.345s'; drop the seconds part.""" + if not d: + return "?" + d = d.lstrip("-") + if "m" in d: # "3h59m12.3s" -> "3h59m", "12m3s" -> "12m" + return d[: d.index("m") + 1] + return d.split(".")[0].rstrip("s") + "s" + + +def ip_links(ip: str) -> InlineKeyboardMarkup: + return InlineKeyboardMarkup([[ + InlineKeyboardButton("CrowdSec CTI", url=f"https://app.crowdsec.net/cti/{ip}"), + InlineKeyboardButton("Shodan", url=f"https://www.shodan.io/host/{ip}"), + ]]) + + +async def reply(update: Update, text: str, markup=None): + await update.effective_message.reply_text( + text, parse_mode=ParseMode.HTML, disable_web_page_preview=True, reply_markup=markup) + + +@restricted +async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE): + await reply(update, ( + "🏴‍☠️ Barbenoire guards the gates (CrowdSec)\n\n" + "/bans: active bans from your CrowdSec\n" + "/ip <address>: is it banned, and its history\n" + "/unban <address>: lift a ban (asks to confirm)\n" + "/stats: bans over the last 24 h and 7 days" + )) + + +@restricted +async def cmd_bans(update: Update, context: ContextTypes.DEFAULT_TYPE): + alerts = await lapi.alerts(has_active_decision="true") + rows = [] + for a in alerts: + src = a.get("source") or {} + for d in a.get("decisions") or []: + if d.get("type") == "ban": + rows.append((a.get("created_at", ""), d.get("value"), src.get("cn"), d.get("scenario") or a.get("scenario"), + short_duration(d.get("duration")))) + if not rows: + await reply(update, "✅ No active bans from your CrowdSec (community blocklist not counted).") + return + rows.sort(reverse=True) + lines = [f"🚫 {len(rows)} active ban(s), latest first:"] + lines += [f"{flag(cn)} {esc(ip)} · {esc(sc)} · {left} left" for _, ip, cn, sc, left in rows[:10]] + if len(rows) > 10: + lines.append(f"… and {len(rows) - 10} more") + await reply(update, "\n".join(lines)) + + +@restricted +async def cmd_ip(update: Update, context: ContextTypes.DEFAULT_TYPE): + try: + ip = valid_ip(context.args[0]) if context.args else None + except ValueError: + ip = None + if not ip: + await reply(update, "Usage: /ip <address>") + return + decisions = await lapi.decisions_for_ip(ip) + history = await lapi.alerts(ip=ip, limit=10) + lines = [f"🔎 {esc(ip)}"] + if decisions: + for d in decisions: + lines.append(f"🚫 {esc(d.get('type'))} · {esc(d.get('origin'))} · {esc(d.get('scenario'))} · " + f"{short_duration(d.get('duration'))} left") + else: + lines.append("✅ Not banned right now") + if history: + src = history[0].get("source") or {} + lines.append(f"{flag(src.get('cn'))} {esc(src.get('cn') or '?')} · {esc(src.get('as_name') or '?')}") + lines.append(f"History ({len(history)} alert(s)):") + for a in history: + lines.append(f"• {esc(a.get('created_at', '')[:16].replace('T', ' '))} · {esc(a.get('scenario'))} " + f"· {a.get('events_count', '?')} events") + else: + lines.append("No alerts from your CrowdSec for this address.") + await reply(update, "\n".join(lines), markup=ip_links(ip)) + + +@restricted +async def cmd_unban(update: Update, context: ContextTypes.DEFAULT_TYPE): + try: + ip = valid_ip(context.args[0]) if context.args else None + except ValueError: + ip = None + if not ip: + await reply(update, "Usage: /unban <address>") + return + decisions = await lapi.decisions_for_ip(ip) + if not decisions: + await reply(update, f"✅ {esc(ip)} isn't banned.") + return + origins = ", ".join(sorted({str(d.get("origin")) for d in decisions})) + keyboard = InlineKeyboardMarkup([[ + InlineKeyboardButton("✅ Unban", callback_data=f"unban:{ip}"), + InlineKeyboardButton("❌ Cancel", callback_data="cancel"), + ]]) + await reply(update, f"Unban {esc(ip)}? ({len(decisions)} decision(s), origin: {esc(origins)})", keyboard) + + +@restricted +async def on_button(update: Update, context: ContextTypes.DEFAULT_TYPE): + query = update.callback_query + await query.answer() + if query.data == "cancel": + await query.edit_message_text("Cancelled.") + return + if query.data.startswith("unban:"): + ip = valid_ip(query.data.split(":", 1)[1]) + n = await lapi.delete_decisions(ip) + log.info("unbanned %s (%d decision(s)) on request of %s", ip, n, update.effective_user.id) + await query.edit_message_text( + f"🔓 {esc(ip)} unbanned ({n} decision(s) removed).", parse_mode=ParseMode.HTML) + + +@restricted +async def cmd_stats(update: Update, context: ContextTypes.DEFAULT_TYPE): + lines = ["📊 CrowdSec (local detections, community blocklist not counted)"] + for label, since in (("24 h", "24h"), ("7 days", "168h")): + alerts = await lapi.alerts(since=since, limit=5000) + ips = {(a.get("source") or {}).get("value") for a in alerts} + lines.append(f"\n{label}: {len(alerts)} alert(s), {len(ips)} address(es)") + for scenario, n in Counter(a.get("scenario") for a in alerts).most_common(5): + lines.append(f" • {esc(scenario)}: {n}") + countries = Counter((a.get("source") or {}).get("cn") for a in alerts).most_common(5) + if countries: + lines.append(" " + " ".join(f"{flag(cn)} {n}" for cn, n in countries)) + await reply(update, "\n".join(lines)) + + +async def job_heartbeat(context: ContextTypes.DEFAULT_TYPE): + try: + async with httpx.AsyncClient(timeout=10) as client: + await client.get(PUSH_URL, params={"status": "up", "msg": "OK"}) + except httpx.HTTPError as e: + log.warning("heartbeat failed: %s", e) + + +def main(): + app = Application.builder().token(TOKEN).build() + for name, fn in (("start", cmd_help), ("help", cmd_help), ("bans", cmd_bans), ("ip", cmd_ip), + ("unban", cmd_unban), ("stats", cmd_stats)): + app.add_handler(CommandHandler(name, fn)) + app.add_handler(CallbackQueryHandler(on_button)) + if PUSH_URL: + app.job_queue.run_repeating(job_heartbeat, interval=60, first=5, name="heartbeat") + log.info("Barbenoire starting (heartbeat=%s)", "on" if PUSH_URL else "off") + app.run_polling(allowed_updates=Update.ALL_TYPES) + + +if __name__ == "__main__": + main() diff --git a/lapi.py b/lapi.py new file mode 100644 index 0000000..7344571 --- /dev/null +++ b/lapi.py @@ -0,0 +1,71 @@ +"""Minimal async client for the CrowdSec Local API (LAPI). + +Reading current decisions uses a bouncer API key. Alert history and deleting decisions +need a machine (watcher) login, which returns a JWT that we refresh when it expires. +""" +from __future__ import annotations + +import ipaddress +from datetime import datetime, timedelta, timezone + +import httpx + + +class LapiError(Exception): + pass + + +def valid_ip(value: str) -> str: + """Return the normalised IP or raise ValueError (no ranges, single addresses only).""" + return str(ipaddress.ip_address(value.strip())) + + +class Lapi: + def __init__(self, url: str, bouncer_key: str, machine_id: str, machine_password: str): + self.client = httpx.AsyncClient(base_url=url.rstrip("/"), timeout=15) + self.bouncer_key = bouncer_key + self.machine_id = machine_id + self.machine_password = machine_password + self._jwt: str | None = None + self._jwt_expire = datetime.min.replace(tzinfo=timezone.utc) + + async def _machine_headers(self) -> dict[str, str]: + if self._jwt is None or datetime.now(timezone.utc) > self._jwt_expire - timedelta(minutes=2): + r = await self.client.post("/v1/watchers/login", json={ + "machine_id": self.machine_id, "password": self.machine_password, "scenarios": []}) + if r.status_code != 200: + raise LapiError(f"machine login failed: HTTP {r.status_code} {r.text[:200]}") + data = r.json() + self._jwt = data["token"] + try: + self._jwt_expire = datetime.fromisoformat(data["expire"].replace("Z", "+00:00")) + except (KeyError, ValueError): + self._jwt_expire = datetime.now(timezone.utc) + timedelta(minutes=30) + return {"Authorization": f"Bearer {self._jwt}"} + + async def _get(self, path: str, params: dict, machine: bool): + headers = await self._machine_headers() if machine else {"X-Api-Key": self.bouncer_key} + r = await self.client.get(path, params=params, headers=headers) + if r.status_code == 401 and machine: # token revoked/expired early: retry once + self._jwt = None + r = await self.client.get(path, params=params, headers=await self._machine_headers()) + if r.status_code != 200: + raise LapiError(f"GET {path}: HTTP {r.status_code} {r.text[:200]}") + return r.json() or [] + + async def decisions_for_ip(self, ip: str) -> list[dict]: + """Active decisions for one IP (all origins, including the community blocklist).""" + return await self._get("/v1/decisions", {"ip": ip}, machine=False) + + async def alerts(self, **params) -> list[dict]: + """Alerts from the local engine (CAPI blocklist excluded).""" + params.setdefault("include_capi", "false") + params.setdefault("limit", 500) + return await self._get("/v1/alerts", params, machine=True) + + async def delete_decisions(self, ip: str) -> int: + headers = await self._machine_headers() + r = await self.client.delete("/v1/decisions", params={"ip": ip}, headers=headers) + if r.status_code != 200: + raise LapiError(f"DELETE decisions: HTTP {r.status_code} {r.text[:200]}") + return int(r.json().get("nbDeleted", 0)) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..54d1b62 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +python-telegram-bot[job-queue]==21.11.1 +httpx>=0.27,<1 +python-dotenv>=1.0,<2