374 lines
18 KiB
Python
374 lines
18 KiB
Python
"""Private Mini App network audit. Network matches are signals, never identity or bans."""
|
|
import asyncio
|
|
from collections import OrderedDict
|
|
from contextlib import closing
|
|
import hashlib
|
|
import hmac
|
|
import ipaddress
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
import unicodedata
|
|
import logging
|
|
|
|
log = logging.getLogger("entry_telemetry")
|
|
|
|
from support_store import NotificationError
|
|
|
|
WINDOW = 86400
|
|
# Known shared reverse-proxy/WARP networks; operators may add their own NAT/relay ranges.
|
|
# Source: https://www.cloudflare.com/ips/ . This is suppression, not an IP blocklist.
|
|
SHARED_EGRESS = (
|
|
"103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "104.16.0.0/13",
|
|
"104.24.0.0/14", "108.162.192.0/18", "131.0.72.0/22", "141.101.64.0/18",
|
|
"162.158.0.0/15", "172.64.0.0/13", "173.245.48.0/20", "188.114.96.0/20",
|
|
"190.93.240.0/20", "197.234.240.0/22", "198.41.128.0/17", "2400:cb00::/32",
|
|
"2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
|
|
"2a06:98c0::/29", "2c0f:f248::/32",
|
|
)
|
|
|
|
|
|
class EntryError(Exception):
|
|
def __init__(self, status=503, code="entry_unavailable", message="Не удалось сохранить вход. Попробуй позже."):
|
|
super().__init__(code)
|
|
self.status, self.code, self.message = status, code, message
|
|
|
|
|
|
def canonical_ip(value):
|
|
if not isinstance(value, str) or not value or len(value) > 64 or "%" in value:
|
|
return None
|
|
try:
|
|
address = ipaddress.ip_address(value)
|
|
except ValueError:
|
|
return None
|
|
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
|
|
address = address.ipv4_mapped
|
|
return str(address)
|
|
|
|
|
|
def trusted_ip(remote, headers):
|
|
"""Only a loopback socket may carry Caddy's overwritten X-Real-IP. Never use XFF."""
|
|
peer = canonical_ip(remote)
|
|
if peer is None:
|
|
return None
|
|
if ipaddress.ip_address(peer).is_loopback:
|
|
return canonical_ip(headers.get("X-Real-IP", "")) or peer
|
|
return peer
|
|
|
|
|
|
def public_ip(value):
|
|
canonical = canonical_ip(value)
|
|
if canonical is None:
|
|
return None
|
|
address = ipaddress.ip_address(canonical)
|
|
if not address.is_global or any((address.is_multicast, address.is_reserved,
|
|
address.is_unspecified, address.is_loopback,
|
|
address.is_link_local, address.is_private)):
|
|
return None
|
|
return canonical
|
|
|
|
|
|
def delivery_enabled():
|
|
# The existing support switch is also a hard entry-delivery kill switch for old fixtures.
|
|
return all(os.environ.get(name, "1") != "0" for name in (
|
|
"IISHKO_NOTIFICATIONS_ENABLED", "IISHKO_SUPPORT_DELIVERY_ENABLED", "IISHKO_ENTRY_DELIVERY_ENABLED"))
|
|
|
|
|
|
def _label(value, length):
|
|
if not isinstance(value, str):
|
|
return ""
|
|
return "".join(char for char in value[:length * 4] if not unicodedata.category(char).startswith("C")).strip()[:length]
|
|
|
|
|
|
def _username(value):
|
|
return "@" + value if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_]{1,32}", value) else "без username"
|
|
|
|
|
|
def _networks(extra):
|
|
values = list(SHARED_EGRESS) + list(extra)
|
|
if len(values) > len(SHARED_EGRESS) + 64:
|
|
raise ValueError("entry_shared_ranges_limit")
|
|
result = []
|
|
for value in values:
|
|
network = ipaddress.ip_network(value, strict=False)
|
|
if network.version == 6 and network.prefixlen >= 96 and network.network_address.ipv4_mapped is not None:
|
|
network = ipaddress.ip_network(str(network.network_address.ipv4_mapped) + "/" + str(network.prefixlen - 96))
|
|
result.append(network)
|
|
return tuple(result)
|
|
|
|
|
|
class EntryTelemetry:
|
|
def __init__(self, path, secret, owners, *, lookup=None, clock=time.time,
|
|
retention=3 * WINDOW, max_visits=20000, max_user_ips=32, max_alerts=2000,
|
|
shared_cidrs=(), geo_cache_size=512, geo_cache_ttl=300,
|
|
lease_seconds=60, max_attempts=3):
|
|
if isinstance(secret, str):
|
|
secret = secret.encode("utf-8")
|
|
if not isinstance(secret, bytes) or not secret or len(secret) > 4096:
|
|
raise ValueError("entry_hmac_key_invalid")
|
|
self.key = hmac.new(secret, b"iishko-entry-audit-v1", hashlib.sha256).digest()
|
|
self.path, self.clock, self.lookup = str(path), clock, lookup
|
|
self.owners = tuple(sorted({uid for uid in owners if type(uid) is int and 0 < uid <= 2**63 - 1}))
|
|
if len(self.owners) > 64:
|
|
raise ValueError("entry_owners_limit")
|
|
self.retention = max(WINDOW, min(int(retention), 7 * WINDOW))
|
|
self.max_visits, self.max_user_ips, self.max_alerts = max_visits, max_user_ips, max_alerts
|
|
self.shared_ranges = _networks(shared_cidrs)
|
|
self.geo_cache_size, self.geo_cache_ttl = max(1, geo_cache_size), max(1, geo_cache_ttl)
|
|
self.geo_cache, self.geo_lock = OrderedDict(), threading.Lock()
|
|
self.lease_seconds, self.max_attempts = lease_seconds, max_attempts
|
|
|
|
def connect(self):
|
|
con = sqlite3.connect(Path(self.path).resolve().as_uri() + "?mode=rw", uri=True, timeout=0.5)
|
|
con.row_factory = sqlite3.Row
|
|
con.execute("PRAGMA foreign_keys=ON")
|
|
con.execute("PRAGMA secure_delete=ON")
|
|
return con
|
|
|
|
def init_db(self):
|
|
with closing(self.connect()) as con:
|
|
con.executescript("""
|
|
CREATE TABLE IF NOT EXISTS wa_entry_visits (
|
|
ip_hmac TEXT NOT NULL, uid INTEGER NOT NULL,
|
|
first_visit INTEGER NOT NULL, last_visit INTEGER NOT NULL,
|
|
country TEXT NOT NULL, city TEXT NOT NULL, geo_source TEXT NOT NULL,
|
|
shared_egress INTEGER NOT NULL, PRIMARY KEY(ip_hmac,uid)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS wa_entry_ip_time ON wa_entry_visits(ip_hmac,last_visit);
|
|
CREATE INDEX IF NOT EXISTS wa_entry_uid_time ON wa_entry_visits(uid,last_visit);
|
|
CREATE TABLE IF NOT EXISTS wa_entry_alerts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT, ip_hmac TEXT NOT NULL,
|
|
created_at INTEGER NOT NULL, accounts TEXT NOT NULL,
|
|
country TEXT NOT NULL, city TEXT NOT NULL, geo_source TEXT NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS wa_entry_alert_ip_time ON wa_entry_alerts(ip_hmac,created_at);
|
|
CREATE TABLE IF NOT EXISTS wa_entry_outbox (
|
|
alert_id INTEGER NOT NULL REFERENCES wa_entry_alerts(id) ON DELETE CASCADE,
|
|
owner_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
|
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0,
|
|
lease_until REAL NOT NULL DEFAULT 0, claim_token TEXT NOT NULL DEFAULT '',
|
|
PRIMARY KEY(alert_id,owner_id)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS wa_entry_pending ON wa_entry_outbox(status,next_attempt);
|
|
""")
|
|
self._prune(con, self.clock())
|
|
con.commit()
|
|
|
|
def ip_tag(self, ip):
|
|
return hmac.new(self.key, ("ip:" + ip).encode("ascii"), hashlib.sha256).hexdigest()
|
|
|
|
def _prune(self, con, now):
|
|
con.execute("DELETE FROM wa_entry_visits WHERE last_visit<=?", (now - self.retention,))
|
|
con.execute("DELETE FROM wa_entry_alerts WHERE created_at<=?", (now - self.retention,))
|
|
# A lost claim may have reached Telegram. Expiry is NOT permission to resend.
|
|
con.execute("UPDATE wa_entry_outbox SET status='uncertain',lease_until=0,claim_token='' "
|
|
"WHERE status='sending' AND lease_until<=?", (now,))
|
|
|
|
def prune(self):
|
|
with closing(self.connect()) as con:
|
|
self._prune(con, self.clock())
|
|
con.commit()
|
|
|
|
@staticmethod
|
|
def _eligible(con, uid):
|
|
row = con.execute("SELECT tg_id,username,banned,privacy_ok FROM users WHERE tg_id=?", (uid,)).fetchone()
|
|
if row is None or row["banned"] or row["privacy_ok"] != 1:
|
|
raise EntryError(403, "entry_forbidden", "Для входа нужен зарегистрированный аккаунт и согласие на приватность.")
|
|
return row
|
|
|
|
def _geo(self, ip, tag, now):
|
|
with self.geo_lock:
|
|
cached = self.geo_cache.get(tag)
|
|
if cached is not None and cached[0] > now:
|
|
self.geo_cache.move_to_end(tag)
|
|
return dict(cached[1])
|
|
value = None
|
|
if self.lookup is not None:
|
|
try:
|
|
value = self.lookup(ip)
|
|
except Exception:
|
|
pass # Missing/broken offline data is unknown, never a network fallback.
|
|
geo = {"country": "", "city": "", "source": "unknown"}
|
|
if isinstance(value, dict):
|
|
geo = {"country": _label(value.get("country"), 64),
|
|
"city": _label(value.get("city"), 96),
|
|
"source": _label(value.get("source"), 64) or "unknown"}
|
|
self.geo_cache[tag] = (now + self.geo_cache_ttl, dict(geo))
|
|
self.geo_cache.move_to_end(tag)
|
|
while len(self.geo_cache) > self.geo_cache_size:
|
|
self.geo_cache.popitem(last=False)
|
|
return geo
|
|
|
|
def record(self, uid, ip):
|
|
if type(uid) is not int or not 0 < uid <= 2**63 - 1:
|
|
raise EntryError(403, "entry_forbidden", "Не удалось подтвердить аккаунт.")
|
|
now = int(self.clock())
|
|
ban_uids = []
|
|
with closing(self.connect()) as con:
|
|
self._eligible(con, uid)
|
|
ip = public_ip(ip)
|
|
if ip is None:
|
|
return
|
|
tag = self.ip_tag(ip)
|
|
shared = any(ipaddress.ip_address(ip) in network for network in self.shared_ranges)
|
|
geo = self._geo(ip, tag, now)
|
|
con.execute("BEGIN IMMEDIATE")
|
|
self._eligible(con, uid) # Consent/ban changes cannot race the audit commit.
|
|
self._prune(con, now)
|
|
existing = con.execute("SELECT 1 FROM wa_entry_visits WHERE ip_hmac=? AND uid=?", (tag, uid)).fetchone()
|
|
if existing is None:
|
|
total = con.execute("SELECT COUNT(*) FROM wa_entry_visits").fetchone()[0]
|
|
own = con.execute("SELECT COUNT(*) FROM wa_entry_visits WHERE uid=?", (uid,)).fetchone()[0]
|
|
if total >= self.max_visits or own >= self.max_user_ips:
|
|
raise EntryError()
|
|
con.execute("INSERT INTO wa_entry_visits VALUES(?,?,?,?,?,?,?,?) "
|
|
"ON CONFLICT(ip_hmac,uid) DO UPDATE SET last_visit=excluded.last_visit,"
|
|
"country=excluded.country,city=excluded.city,geo_source=excluded.geo_source,"
|
|
"shared_egress=excluded.shared_egress",
|
|
(tag, uid, now, now, geo["country"], geo["city"], geo["source"], int(shared)))
|
|
recent = con.execute("SELECT 1 FROM wa_entry_alerts WHERE ip_hmac=? AND created_at>? LIMIT 1",
|
|
(tag, now - WINDOW)).fetchone()
|
|
if not shared and recent is None:
|
|
accounts = con.execute("SELECT v.uid,u.username FROM wa_entry_visits v JOIN users u ON u.tg_id=v.uid "
|
|
"WHERE v.ip_hmac=? AND v.last_visit>? AND COALESCE(u.banned,0)=0 "
|
|
"AND u.privacy_ok=1 ORDER BY v.first_visit,v.uid LIMIT 8", (tag, now - WINDOW)).fetchall()
|
|
if len(accounts) >= 2 and con.execute("SELECT COUNT(*) FROM wa_entry_alerts").fetchone()[0] < self.max_alerts:
|
|
payload = json.dumps([{"uid": row["uid"], "username": _username(row["username"])} for row in accounts],
|
|
ensure_ascii=False, separators=(",", ":"))
|
|
alert = con.execute("INSERT INTO wa_entry_alerts(ip_hmac,created_at,accounts,country,city,geo_source) "
|
|
"VALUES(?,?,?,?,?,?)", (tag, now, payload, geo["country"], geo["city"], geo["source"]))
|
|
con.executemany("INSERT INTO wa_entry_outbox(alert_id,owner_id) VALUES(?,?)",
|
|
[(alert.lastrowid, owner) for owner in self.owners])
|
|
ban_uids = [row["uid"] for row in accounts]
|
|
con.commit()
|
|
if ban_uids:
|
|
try:
|
|
import entry_autoban
|
|
if entry_autoban.enabled(): # opt-in; otherwise the alert above is the only effect
|
|
entry_autoban.ban_cluster(ban_uids, reason="entry_ip_collision")
|
|
except Exception:
|
|
log.exception("entry autoban failed")
|
|
|
|
def claim(self):
|
|
now = self.clock()
|
|
with closing(self.connect()) as con:
|
|
con.execute("BEGIN IMMEDIATE")
|
|
self._prune(con, now)
|
|
if not self.owners:
|
|
con.commit()
|
|
return None
|
|
slots = ",".join("?" for _ in self.owners)
|
|
row = con.execute("SELECT o.*,a.ip_hmac,a.created_at,a.accounts,a.country,a.city,a.geo_source "
|
|
"FROM wa_entry_outbox o JOIN wa_entry_alerts a ON a.id=o.alert_id "
|
|
"WHERE o.status='pending' AND o.next_attempt<=? AND o.attempts<? "
|
|
"AND o.owner_id IN (" + slots + ") ORDER BY a.created_at,o.alert_id,o.owner_id LIMIT 1",
|
|
(now, self.max_attempts, *self.owners)).fetchone()
|
|
if row is None:
|
|
con.commit()
|
|
return None
|
|
token = secrets.token_hex(16)
|
|
con.execute("UPDATE wa_entry_outbox SET status='sending',attempts=attempts+1,lease_until=?,claim_token=? "
|
|
"WHERE alert_id=? AND owner_id=?", (now + self.lease_seconds, token, row["alert_id"], row["owner_id"]))
|
|
con.commit()
|
|
return dict(row, attempts=row["attempts"] + 1, claim_token=token)
|
|
|
|
def finish(self, claim, status, *, retry_after=0):
|
|
if status not in ("sent", "failed", "uncertain", "pending"):
|
|
raise ValueError("entry_delivery_status_invalid")
|
|
delay = 0
|
|
if status == "pending":
|
|
if claim["attempts"] >= self.max_attempts:
|
|
status = "failed"
|
|
else:
|
|
retry = retry_after if type(retry_after) in (int, float) and math.isfinite(retry_after) else 0
|
|
delay = max(15 * 2 ** (claim["attempts"] - 1), min(self.retention, retry))
|
|
with closing(self.connect()) as con:
|
|
con.execute("UPDATE wa_entry_outbox SET status=?,next_attempt=?,lease_until=0,claim_token='' "
|
|
"WHERE alert_id=? AND owner_id=? AND status='sending' AND claim_token=?",
|
|
(status, self.clock() + delay, claim["alert_id"], claim["owner_id"], claim["claim_token"]))
|
|
con.commit()
|
|
|
|
|
|
def notification_text(claim, tags=()):
|
|
accounts = json.loads(claim["accounts"])
|
|
users = "\n".join("• UID %d · %s" % (row["uid"], row["username"]) for row in accounts[:8])
|
|
place = ", ".join(value for value in (claim["country"], claim["city"]) if value) or "неизвестно"
|
|
source = claim["geo_source"] or "unknown"
|
|
observed = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(claim["created_at"]))
|
|
text = ("Mini App: совпадение сети за 24 часа\nНаблюдение: %s\n%s\nПримерный регион: %s\nИсточник: %s\n"
|
|
"Сеть #%s. Совпадение IP не доказывает общего владельца: возможны Wi-Fi, NAT, VPN или relay. "
|
|
"Автобан применён автоматически (все аккаунты сети, кроме админов).\nГеоданные: IP Geolocation by DB-IP, CC BY 4.0 — https://db-ip.com" %
|
|
(observed, users, place, source, claim["ip_hmac"][:12]))[:3000]
|
|
# Operator tags always survive truncation: they are the fastest way to recognise a network.
|
|
marks = " · ".join(str(tag) for tag in list(tags or ())[:12] if tag)
|
|
if marks:
|
|
text += "\nТеги: " + marks
|
|
return text[:3400]
|
|
|
|
|
|
class EntryOutbox:
|
|
def __init__(self, store, sender, *, enabled=delivery_enabled, interval=5, batch=4, tags=None):
|
|
self.store, self.sender, self.enabled = store, sender, enabled
|
|
self.tag_source = tags
|
|
self.interval, self.batch = interval, max(1, min(int(batch), 16))
|
|
self.wake, self.stopping = asyncio.Event(), False
|
|
|
|
def _text(self, claim):
|
|
marks = ()
|
|
if self.tag_source is not None:
|
|
try:
|
|
marks = self.tag_source(claim["ip_hmac"]) or ()
|
|
except Exception:
|
|
log.exception("entry tags unavailable")
|
|
marks = ()
|
|
return notification_text(claim, marks)
|
|
|
|
def stop(self):
|
|
self.stopping = True
|
|
self.wake.set()
|
|
|
|
async def run_once(self):
|
|
for _ in range(self.batch):
|
|
if self.stopping or not self.enabled():
|
|
break
|
|
claim = await asyncio.to_thread(self.store.claim)
|
|
if claim is None:
|
|
break
|
|
if not self.enabled():
|
|
# No sender was entered; putting this exact claim back is safe.
|
|
await asyncio.to_thread(self.store.finish, claim, "pending")
|
|
break
|
|
try:
|
|
await self.sender(claim["owner_id"], self._text(claim), claim)
|
|
except asyncio.CancelledError:
|
|
await asyncio.shield(asyncio.to_thread(self.store.finish, claim, "uncertain"))
|
|
raise
|
|
except NotificationError as error:
|
|
status = "failed" if not error.retryable else (
|
|
"pending" if getattr(error, "delivery_rejected", False) else "uncertain")
|
|
await asyncio.to_thread(self.store.finish, claim, status, retry_after=error.retry_after)
|
|
except Exception:
|
|
await asyncio.to_thread(self.store.finish, claim, "uncertain")
|
|
else:
|
|
await asyncio.to_thread(self.store.finish, claim, "sent")
|
|
|
|
async def run(self):
|
|
while not self.stopping:
|
|
self.wake.clear()
|
|
try:
|
|
await self.run_once()
|
|
except (sqlite3.Error, OSError, ValueError):
|
|
pass # Never log token-bearing exception text or an entry payload.
|
|
if self.stopping:
|
|
break
|
|
try:
|
|
await asyncio.wait_for(self.wake.wait(), self.interval)
|
|
except asyncio.TimeoutError:
|
|
pass
|