"""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()