diabolical-x5f-ingest-x5f-v2.txt
"""
DIABOLICAL Engine v2 - Real Ingest
X API (your own keys via env) + crt.sh CT-log + Recursive + Bayesian + ML + Performance
Manifest: albertlane.net | Provenance: https://albertlane.net
License: Proprietary - ALBERT LANE DIGITAL INFRASTRUCTURE
Status: MODEL / SCHEMATIC - Research + referral only. No accusation from score alone.
SAFETY: Never paste keys in chat. Use env vars only.
X: Official API v2 only. No scraping, no DM access, no private accounts.
CT: Public crt.sh only. No Cloudflare/Google/AWS internal logs.
Trafficking head: Referral only to NHTH 1-888-373-7888, Text HELP to 233733, DHS 1-866-347-2423, or 911 if emergency.
ENV:
X_BEARER_TOKEN=... # Required for X ingest
X_API_BASE=https://api.x.com/2
DIABOLICAL_CACHE_DIR=$HOME/tmp/diabolical-cache
USAGE (Termux):
export X_BEARER_TOKEN='...' # set in shell, never in file
python3 diabolical_ingest_v2.py --domain example.com --x-query "example.com" --depth 2 --max-nodes 300
python3 diabolical_ingest_v2.py --domain example.com --no-x --depth 2
python3 diabolical_ingest_v2.py --demo
PERFORMANCE: SQLite + disk cache for crt.sh (TTL 24h) + LRU, ThreadPool for DNS+CT batch, incremental graph, Bayesian O(1), ML batch predict
"""
import os, sys, json, time, math, re, hashlib, sqlite3, urllib.request, urllib.parse, urllib.error
from collections import defaultdict, Counter
from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple, Optional, Any
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
try:
import networkx as nx
HAS_NX = True
except ImportError:
HAS_NX = False
try:
from sklearn.ensemble import IsolationForest
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
HAS_SKLEARN = True
except ImportError:
HAS_SKLEARN = False
def env(key, default=""):
return os.environ.get(key, default)
CACHE_DIR = env("DIABOLICAL_CACHE_DIR", os.path.join(os.path.expanduser("~"), "tmp", "diabolical-cache"))
os.makedirs(CACHE_DIR, exist_ok=True)
CACHE_DB = os.path.join(CACHE_DIR, "ct_cache.sqlite")
X_BEARER = env("X_BEARER_TOKEN", "")
X_BASE = env("X_API_BASE", "https://api.x.com/2")
MAX_DEPTH = int(env("DIABOLICAL_MAX_DEPTH", "2"))
MAX_NODES = int(env("DIABOLICAL_MAX_NODES", "500"))
def salted_hash(v: str, salt="diabolical-v2") -> str:
if not v:
return ""
return hashlib.sha256((salt + v.strip().lower()).encode()).hexdigest()[:16]
def shingles(text: str, k=3) -> Set[str]:
words = re.findall(r"[a-z0-9]+", text.lower())
if len(words) < k:
return set([" ".join(words)]) if words else set()
return set(" ".join(words[i:i+k]) for i in range(len(words)-k+1))
def jaccard(a: Set[str], b: Set[str]) -> float:
if not a or not b:
return 0.0
return len(a & b) / len(a | b)
def log(msg: str):
print(f"[DIABOLICAL v2] {msg}", flush=True)
_cache_lock = threading.Lock()
def _db():
conn = sqlite3.connect(CACHE_DB, timeout=10)
conn.execute("CREATE TABLE IF NOT EXISTS ct_cache (key TEXT PRIMARY KEY, value TEXT, ts REAL)")
conn.execute("CREATE TABLE IF NOT EXISTS x_cache (key TEXT PRIMARY KEY, value TEXT, ts REAL)")
return conn
def cache_get(table: str, key: str, ttl: int = 86400):
try:
with _cache_lock:
conn = _db()
row = conn.execute(f"SELECT value, ts FROM {table} WHERE key=?", (key,)).fetchone()
conn.close()
if not row:
return None
val, ts = row
if time.time() - ts > ttl:
return None
return json.loads(val)
except Exception:
return None
def cache_set(table: str, key: str, value: Any):
try:
with _cache_lock:
conn = _db()
conn.execute(f"INSERT OR REPLACE INTO {table} (key, value, ts) VALUES (?,?,?)", (key, json.dumps(value), time.time()))
conn.commit()
conn.close()
except Exception as e:
log(f"cache set failed: {e}")
class XClient:
"""Official X API v2 only. Bearer token from env. Respects rate limits with backoff."""
def __init__(self, bearer: str = "", base: str = X_BASE):
self.bearer = bearer or X_BEARER
self.base = base.rstrip("/")
self._remaining = 999
self._reset_at = 0
def _headers(self):
return {"Authorization": f"Bearer {self.bearer}", "User-Agent": "DIABOLICAL-v2/1.0 albertlane.net"}
def _get(self, path: str, params: Dict) -> Dict:
if not self.bearer:
raise RuntimeError("X_BEARER_TOKEN not set. Export it in shell, do not paste in chat.")
cache_key = hashlib.sha256(json.dumps([path, params], sort_keys=True).encode()).hexdigest()
cached = cache_get("x_cache", cache_key, ttl=600)
if cached is not None:
log(f"X cache hit: {path}")
return cached
url = f"{self.base}{path}?{urllib.parse.urlencode(params)}"
for attempt in range(5):
if self._remaining <= 2 and time.time() < self._reset_at:
wait = self._reset_at - time.time() + 1
log(f"X rate limit, sleeping {wait:.0f}s")
time.sleep(wait)
req = urllib.request.Request(url, headers=self._headers())
try:
with urllib.request.urlopen(req, timeout=20) as resp:
self._remaining = int(resp.headers.get("x-rate-limit-remaining", "999"))
self._reset_at = int(resp.headers.get("x-rate-limit-reset", "0"))
data = json.loads(resp.read().decode())
cache_set("x_cache", cache_key, data)
return data
except urllib.error.HTTPError as e:
if e.code == 429:
wait = (2 ** attempt) * 5
log(f"X 429, backoff {wait}s attempt {attempt+1}/5")
time.sleep(wait)
continue
if e.code in (401, 403):
raise RuntimeError(f"X auth failed {e.code}: check X_BEARER_TOKEN scope and app permissions.")
raise RuntimeError(f"X API {e.code}")
except Exception as e:
if attempt == 4:
raise
time.sleep(2 ** attempt)
raise RuntimeError("X request failed after retries")
def search_recent(self, query: str, max_results: int = 50, next_token: str = "") -> Dict:
params = {"query": query, "max_results": str(min(100, max(10, max_results))), "tweet.fields": "created_at,author_id,public_metrics,entities,lang", "user.fields": "username,public_metrics,created_at", "expansions": "author_id"}
if next_token:
params["next_token"] = next_token
return self._get("/tweets/search/recent", params)
def search_all_pages(self, query: str, max_pages: int = 3, per_page: int = 50) -> List[Dict]:
out = []
token = ""
for page in range(max_pages):
data = self.search_recent(query, max_results=per_page, next_token=token)
tweets = data.get("data", []) or []
out.extend(tweets)
token = data.get("meta", {}).get("next_token", "")
log(f"X page {page+1}: {len(tweets)} tweets, total {len(out)}")
if not token:
break
time.sleep(1.0)
return out
@staticmethod
def normalize_tweets(raw_tweets: List[Dict], users_by_id: Dict[str, Dict] = None) -> List[Dict]:
users_by_id = users_by_id or {}
posts = []
for t in raw_tweets:
text = t.get("text", "")
if not text:
continue
domains = []
ents = t.get("entities", {}) or {}
for u in ents.get("urls", []) or []:
try:
dom = urllib.parse.urlparse(u.get("expanded_url", "")).netloc.lower().replace("www.", "")
if dom:
domains.append(dom)
except Exception:
pass
posts.append({"id": f"x_{t.get('id')}", "account_id": f"x_user_{t.get('author_id')}", "username": users_by_id.get(t.get("author_id"), {}).get("username", ""), "text": text, "created_at": t.get("created_at", ""), "domains": domains, "metrics": t.get("public_metrics", {}), "lang": t.get("lang", "")})
return posts
class CTClient:
"""Public crt.sh only. https://crt.sh/?q=%25.{domain}&output=json"""
def __init__(self):
self.base = "https://crt.sh"
def fetch_certs_for_domain(self, domain: str, use_cache=True) -> List[Dict]:
domain = domain.lower().strip().replace("www.", "")
if use_cache:
cached = cache_get("ct_cache", f"ct:{domain}", ttl=86400)
if cached is not None:
log(f"CT cache hit: {domain} ({len(cached)} certs)")
return cached
q = f"%25.{domain}"
url = f"{self.base}/?q={urllib.parse.quote(q)}&output=json"
log(f"CT fetch: {domain} -> crt.sh")
req = urllib.request.Request(url, headers={"User-Agent": "DIABOLICAL-v2 albertlane.net"})
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode())
except urllib.error.HTTPError as e:
if e.code == 404:
return []
raise RuntimeError(f"crt.sh HTTP {e.code} for {domain}")
except Exception as e:
log(f"crt.sh fetch failed for {domain}: {e} - returning empty, check network")
return []
cleaned = []
seen = set()
for c in data:
names_raw = c.get("name_value", "")
names = [n.strip().lower() for n in names_raw.split("\n") if n.strip()]
for n in names:
if n in seen:
continue
seen.add(n)
cleaned.append({"domain": n, "common_name": c.get("common_name", ""), "issuer": c.get("issuer_name", ""), "not_before": c.get("not_before", ""), "not_after": c.get("not_after", ""), "serial": c.get("serial_number", ""), "id": c.get("id", "")})
cache_set("ct_cache", f"ct:{domain}", cleaned)
log(f"CT done: {domain} -> {len(cleaned)} unique names")
return cleaned
def fetch_batch(self, domains: List[str], max_workers: int = 5) -> Dict[str, List[Dict]]:
out = {}
uniq = sorted(set(d.lower().strip().replace("www.", "") for d in domains if d))
log(f"CT batch: {len(uniq)} domains, {max_workers} workers")
with ThreadPoolExecutor(max_workers=max_workers) as ex:
futs = {ex.submit(self.fetch_certs_for_domain, d): d for d in uniq}
for fut in as_completed(futs):
d = futs[fut]
try:
out[d] = fut.result()
except Exception as e:
log(f"CT batch error {d}: {e}")
out[d] = []
return out
class DNSResolver:
def resolve(self, domain: str) -> Dict:
domain = domain.lower().strip()
result = {"domain": domain, "ips": [], "ns": [], "asn_hint": ""}
try:
import socket
_, _, ips = socket.gethostbyname_ex(domain)
result["ips"] = ips[:5]
except Exception:
pass
try:
import dns.resolver
try:
answers = dns.resolver.resolve(domain, "NS", lifetime=5)
result["ns"] = [str(a).rstrip(".").lower() for a in answers][:4]
except Exception:
pass
except ImportError:
pass
ns_joined = " ".join(result["ns"])
if "cloudflare" in ns_joined:
result["asn_hint"] = "AS13335 Cloudflare"
elif "awsdns" in ns_joined or "amazon" in ns_joined:
result["asn_hint"] = "AS16509 Amazon / Route53"
elif "googledomains" in ns_joined or "google" in ns_joined:
result["asn_hint"] = "AS15169 Google"
return result
def resolve_batch(self, domains: List[str], max_workers: int = 10) -> Dict[str, Dict]:
uniq = sorted(set(domains))
out = {}
with ThreadPoolExecutor(max_workers=max_workers) as ex:
futs = {ex.submit(self.resolve, d): d for d in uniq}
for fut in as_completed(futs):
d = futs[fut]
try:
out[d] = fut.result()
except Exception:
out[d] = {"domain": d, "ips": [], "ns": [], "asn_hint": ""}
return out
@dataclass
class GraphState:
nodes: Dict[str, Dict] = field(default_factory=dict)
edges: List[Tuple[str, str, str, float]] = field(default_factory=list)
visited: Set[str] = field(default_factory=set)
depth_map: Dict[str, int] = field(default_factory=dict)
posts: List[Dict] = field(default_factory=list)
domains: Set[str] = field(default_factory=set)
cert_to_domains: Dict[str, Set[str]] = field(default_factory=lambda: defaultdict(set))
ip_to_domains: Dict[str, Set[str]] = field(default_factory=lambda: defaultdict(set))
class RecursiveExpander:
"""Recursive: domain -> certs -> sibling domains -> IPs -> sibling domains, with budget."""
def __init__(self, ct: CTClient, dns: DNSResolver, max_depth=2, max_nodes=500):
self.ct = ct
self.dns = dns
self.max_depth = max_depth
self.max_nodes = max_nodes
self.graph = GraphState()
def _add_node(self, nid: str, ntype: str, **attrs):
if nid not in self.graph.nodes:
self.graph.nodes[nid] = {"id": nid, "type": ntype, **attrs}
return nid
def _add_edge(self, src: str, dst: str, etype: str, w=1.0):
self.graph.edges.append((src, dst, etype, w))
def expand_domain(self, domain: str, depth: int = 0):
domain = domain.lower().strip().replace("www.", "")
if domain in self.graph.visited:
return
if len(self.graph.nodes) >= self.max_nodes:
log(f"Budget hit max_nodes={self.max_nodes}, stopping at {domain}")
return
if depth > self.max_depth:
return
self.graph.visited.add(domain)
self.graph.domains.add(domain)
self.graph.depth_map[domain] = depth
dnode = self._add_node(f"DOMAIN:{domain}", "DOMAIN", domain=domain, depth=depth)
log(f"Expand depth {depth}: {domain} ({len(self.graph.nodes)} nodes)")
certs = self.ct.fetch_certs_for_domain(domain)
sibling_domains = set()
for c in certs[:100]:
cname = c["domain"]
if not cname or "*" in cname:
continue
cert_id = f"CERT:{salted_hash(c.get('serial','') + c.get('issuer',''))}"
self._add_node(cert_id, "CERT", issuer=c.get("issuer","")[:80], serial_hash=salted_hash(c.get("serial","")))
self._add_edge(dnode, cert_id, "USES_CERT")
sibling_domains.add(cname)
self.graph.cert_to_domains[cert_id].add(cname)
dns_info = self.dns.resolve(domain)
for ip in dns_info.get("ips", [])[:3]:
inode = self._add_node(f"IP:{ip}", "IP", ip=ip)
self._add_edge(dnode, inode, "RESOLVES_TO")
self.graph.ip_to_domains[ip].add(domain)
if dns_info.get("asn_hint"):
anode = self._add_node(f"ASN:{dns_info['asn_hint']}", "ASN", asn=dns_info["asn_hint"])
self._add_edge(inode, anode, "HOSTED_ON")
for ns in dns_info.get("ns", [])[:2]:
nnode = self._add_node(f"NS:{ns}", "NS", ns=ns)
self._add_edge(dnode, nnode, "USES_NS")
if depth < self.max_depth:
siblings_sorted = sorted(sibling_domains)[:8]
for sib in siblings_sorted:
if sib == domain:
continue
self.expand_domain(sib, depth+1)
def expand_from_x_posts(self, posts: List[Dict]):
for p in posts:
pid = p["id"]
aid = p["account_id"]
self._add_node(aid, "ACCOUNT", username=p.get("username",""))
self._add_node(pid, "POST", text_hash=hashlib.sha256(p["text"].encode()).hexdigest()[:12])
self._add_edge(pid, aid, "POSTED_BY")
sh = shingles(p["text"])
matched = None
for nid, n in list(self.graph.nodes.items()):
if n.get("type") == "TEMPLATE" and "shingles" in n:
if jaccard(sh, set(n["shingles"])) > 0.75:
matched = nid
break
if matched is None:
matched = f"TEMPLATE:{len([n for n in self.graph.nodes.values() if n['type']=='TEMPLATE'])+1}"
self._add_node(matched, "TEMPLATE", shingles=list(sh)[:10])
self._add_edge(pid, matched, "SHARES_TEMPLATE")
for dom in p.get("domains", []):
dnode = self._add_node(f"DOMAIN:{dom}", "DOMAIN", domain=dom)
self._add_edge(pid, dnode, "LINKS_TO")
self.graph.domains.add(dom)
self.graph.posts.append(p)
class BayesianRisk:
"""Beta-Binomial Bayesian updating. Prior Beta(alpha, beta). Each signal is evidence."""
def __init__(self, alpha_prior=2.0, beta_prior=8.0):
self.alpha = alpha_prior
self.beta = beta_prior
self.history = []
def update(self, signal_name: str, likelihood_success: float, weight: float = 1.0):
strength = 5.0 * weight
s = likelihood_success * strength
f = (1 - likelihood_success) * strength
self.alpha += s
self.beta += f
self.history.append((signal_name, round(likelihood_success,3), round(weight,3), round(self.mean(),3)))
return self.mean()
def mean(self) -> float:
return self.alpha / (self.alpha + self.beta)
def credible_interval(self):
var = (self.alpha * self.beta) / (((self.alpha + self.beta)**2) * (self.alpha + self.beta + 1))
sd = math.sqrt(var)
m = self.mean()
return (max(0.0, m - 1.96*sd), min(1.0, m + 1.96*sd))
def to_dict(self):
lo, hi = self.credible_interval()
return {"alpha": round(self.alpha,2), "beta": round(self.beta,2), "posterior_mean": round(self.mean(),3), "credible_95": [round(lo,3), round(hi,3)], "history": self.history}
class MLScorer:
"""Light ML: LogisticRegression for supervised, fallback to rule score if sklearn missing."""
def __init__(self):
self.scaler = None
self.model = None
self.is_trained = False
def features_from_cluster(self, feats: Dict[str, float]) -> List[float]:
keys = ["burst", "template_reuse", "coordination", "infra_reuse_norm", "movement", "shared_mgmt", "gov_links_norm", "cert_age_days_norm"]
return [float(feats.get(k, 0.0)) for k in keys]
def train_synthetic(self, n: int = 200):
if not HAS_SKLEARN:
log("sklearn not available, ML fallback to rule score. pip install scikit-learn")
return False
import random
random.seed(1)
X, y = [], []
for i in range(n):
if i % 2 == 0:
feats = {"burst": random.uniform(0.7,1.0), "template_reuse": random.uniform(0.6,1.0), "coordination": random.uniform(0.6,1.0), "infra_reuse_norm": random.uniform(0.5,1.0), "movement": random.uniform(0.4,1.0), "shared_mgmt": random.uniform(0.5,1.0), "gov_links_norm": random.uniform(0.0,0.5), "cert_age_days_norm": random.uniform(0.7,1.0)}
label = 1
else:
feats = {"burst": random.uniform(0.0,0.3), "template_reuse": random.uniform(0.0,0.3), "coordination": random.uniform(0.0,0.3), "infra_reuse_norm": random.uniform(0.0,0.3), "movement": random.uniform(0.0,0.3), "shared_mgmt": random.uniform(0.0,0.3), "gov_links_norm": random.uniform(0.0,0.3), "cert_age_days_norm": random.uniform(0.0,0.4)}
label = 0
X.append(self.features_from_cluster(feats))
y.append(label)
self.scaler = StandardScaler()
Xs = self.scaler.fit_transform(X)
self.model = LogisticRegression(max_iter=200)
self.model.fit(Xs, y)
self.is_trained = True
log(f"ML trained on synthetic {n} clusters")
return True
def predict(self, feats: Dict[str, float]) -> Dict:
if not HAS_SKLEARN or not self.is_trained:
rule = 0.20*feats.get("burst",0) + 0.20*feats.get("template_reuse",0) + 0.15*feats.get("coordination",0) + 0.15*feats.get("infra_reuse_norm",0) + 0.10*feats.get("movement",0) + 0.10*feats.get("shared_mgmt",0) + 0.05*feats.get("gov_links_norm",0) + 0.05*feats.get("cert_age_days_norm",0)
return {"ml_score": round(rule,3), "model": "rule-fallback", "trained": False}
vec = self.features_from_cluster(feats)
Xs = self.scaler.transform([vec])
proba = float(self.model.predict_proba(Xs)[0][1])
return {"ml_score": round(proba,3), "model": "logistic-synthetic", "trained": True}
def anomaly(self, feats_list: List[Dict]) -> List[float]:
if not HAS_SKLEARN or len(feats_list) < 10:
return [0.0]*len(feats_list)
X = [self.features_from_cluster(f) for f in feats_list]
clf = IsolationForest(contamination=0.1, random_state=1)
preds = clf.fit_predict(X)
scores = clf.decision_function(X)
return [round(float(1 - (s - min(scores)) / (max(scores)-min(scores)+1e-9)),3) if len(set(scores))>1 else 0.0 for s in scores]
class DiabolicalV2:
def __init__(self, max_depth=MAX_DEPTH, max_nodes=MAX_NODES):
self.ct = CTClient()
self.dns = DNSResolver()
self.x = XClient()
self.expander = RecursiveExpander(self.ct, self.dns, max_depth=max_depth, max_nodes=max_nodes)
self.ml = MLScorer()
self.bayesian_fraud = BayesianRisk(alpha_prior=2, beta_prior=8)
self.bayesian_traffic = BayesianRisk(alpha_prior=1, beta_prior=19)
def run(self, seed_domains: List[str], x_query: str = "", x_pages: int = 2, do_x: bool = True) -> Dict:
log(f"Run v2: domains={seed_domains}, x_query={x_query}, do_x={do_x}")
x_posts = []
if do_x and x_query:
try:
raw = self.x.search_all_pages(x_query, max_pages=x_pages, per_page=50)
x_posts = XClient.normalize_tweets(raw)
log(f"X normalized {len(x_posts)} posts")
self.expander.expand_from_x_posts(x_posts)
for p in x_posts:
for d in p.get("domains", []):
seed_domains.append(d)
except Exception as e:
log(f"X ingest failed (continuing CT only): {e}")
x_posts = []
uniq_domains = sorted(set(d.lower().strip().replace("www.","") for d in seed_domains if d))
log(f"Expanding {len(uniq_domains)} seed domains recursively depth={self.expander.max_depth}")
for d in uniq_domains:
self.expander.expand_domain(d, depth=0)
feats = self._compute_features()
log(f"Features: {feats}")
self.bayesian_fraud.update("burst", feats["burst"], weight=1.0)
self.bayesian_fraud.update("template_reuse", feats["template_reuse"], weight=1.0)
self.bayesian_fraud.update("coordination", feats["coordination"], weight=0.8)
self.bayesian_fraud.update("infra_reuse", feats["infra_reuse_norm"], weight=0.7)
self.bayesian_traffic.update("movement", feats["movement"], weight=1.0)
self.bayesian_traffic.update("shared_mgmt", feats["shared_mgmt"], weight=1.0)
self.bayesian_traffic.update("template_control", feats["template_reuse"], weight=0.6)
self.bayesian_traffic.update("infra_reuse", feats["infra_reuse_norm"], weight=0.5)
self.ml.train_synthetic(n=200)
ml_out = self.ml.predict(feats)
fraud_combined = round(0.6*self.bayesian_fraud.mean() + 0.4*ml_out["ml_score"], 3)
traffic_combined = round(0.7*self.bayesian_traffic.mean() + 0.3*ml_out["ml_score"], 3)
result = {
"seed_domains": uniq_domains,
"graph": {"nodes": len(self.expander.graph.nodes), "edges": len(self.expander.graph.edges), "domains": sorted(list(self.expander.graph.domains))[:50], "visited": sorted(list(self.expander.graph.visited))[:50]},
"x_posts": len(x_posts),
"features": feats,
"bayesian_fraud": self.bayesian_fraud.to_dict(),
"bayesian_trafficking": self.bayesian_traffic.to_dict(),
"ml": ml_out,
"combined": {"review_fraud": fraud_combined, "trafficking_risk": traffic_combined},
"action": {
"fraud": "LEVEL 0 log" if fraud_combined < 0.3 else "LEVEL 1 downrank" if fraud_combined < 0.5 else "LEVEL 2 verify" if fraud_combined < 0.7 else "LEVEL 3 human review" if fraud_combined < 0.85 else "LEVEL 4 human + corroboration",
"trafficking": "No action, log" if traffic_combined < 0.5 else "Human review queue, de-identified" if traffic_combined < 0.7 else "Human review + corroboration" if traffic_combined < 0.85 else "Referral packet to NHTH/DHS, NO public accusation"
},
"safety": "Scores are MODEL signals, not accusations. No names published. Referral only via human review.",
"referral_if_confirmed": "NHTH 1-888-373-7888, Text HELP to 233733, DHS 1-866-347-2423, or 911 if emergency"
}
return result
def _compute_features(self) -> Dict[str, float]:
g = self.expander.graph
post_nodes = [n for n in g.nodes.values() if n["type"]=="POST"]
template_reuse = 0.0
if post_nodes:
tmpl_counts = Counter(dst for src,dst,etype,_ in g.edges if etype=="SHARES_TEMPLATE")
if tmpl_counts:
template_reuse = max(tmpl_counts.values()) / max(1, len(post_nodes))
coord = 0.0
if post_nodes:
dom_counts = Counter(dst for src,dst,etype,_ in g.edges if etype=="LINKS_TO")
if dom_counts:
coord = max(dom_counts.values()) / max(1, len(post_nodes))
domains = list(g.domains)
certs = set(k for k in g.nodes if k.startswith("CERT:"))
ips = set(k for k in g.nodes if k.startswith("IP:"))
nss = set(k for k in g.nodes if k.startswith("NS:"))
D = max(1, len(domains))
reuse_raw = D / max(1, (len(certs)+len(ips)+len(nss)))
infra_norm = min(1.0, reuse_raw / 2.0)
movement = min(1.0, len(domains) / 10.0)
shared = min(1.0, len([n for n in g.nodes.values() if n["type"]=="ACCOUNT"]) / 20.0)
gov_links = len([n for n in g.nodes.values() if n["type"]=="GOV_CONTRACT"])
gov_norm = min(1.0, gov_links / 5.0)
cert_age_norm = 0.5
burst = min(1.0, len(post_nodes) / 50.0) if post_nodes else 0.1
return {"burst": round(burst,3), "template_reuse": round(template_reuse,3), "coordination": round(coord,3), "infra_reuse_norm": round(infra_norm,3), "infra_reuse_raw": round(reuse_raw,3), "movement": round(movement,3), "shared_mgmt": round(shared,3), "gov_links_norm": round(gov_norm,3), "cert_age_days_norm": round(cert_age_norm,3), "post_count": len(post_nodes), "domain_count": len(domains), "cert_count": len(certs), "ip_count": len(ips)}
def main():
import argparse
ap = argparse.ArgumentParser(description="DIABOLICAL v2 - Real X + crt.sh ingest")
ap.add_argument("--domain", action="append", dest="domains", default=[], help="Seed domain, repeatable")
ap.add_argument("--x-query", default="", help="X search query, e.g. 'example.com -is:retweet'")
ap.add_argument("--depth", type=int, default=MAX_DEPTH)
ap.add_argument("--max-nodes", type=int, default=MAX_NODES)
ap.add_argument("--no-x", action="store_true", help="Skip X, CT only")
ap.add_argument("--demo", action="store_true", help="Offline synthetic demo, no network")
ap.add_argument("--out", default="", help="Output JSON path")
args = ap.parse_args()
if args.demo:
log("Demo mode - synthetic, no network, no keys")
eng = DiabolicalV2(max_depth=1, max_nodes=100)
eng.expander._add_node("DOMAIN:example.com", "DOMAIN", domain="example.com")
eng.expander._add_node("CERT:abc", "CERT", issuer="Test")
eng.expander._add_edge("DOMAIN:example.com", "CERT:abc", "USES_CERT")
eng.expander.graph.domains.add("example.com")
fake_posts = [{"id": f"x_{i}", "account_id": f"x_user_{i}", "username": f"user{i}", "text": "Best service ever!!! Highly recommend!!! Call now", "domains": ["example.com"]} for i in range(12)]
eng.expander.expand_from_x_posts(fake_posts)
feats = eng._compute_features()
print(json.dumps({"demo": True, "features": feats, "graph_nodes": len(eng.expander.graph.nodes)}, indent=2))
return
domains = args.domains or []
if not domains and not args.x_query:
print("Need --domain and/or --x-query. Example: --domain example.com --x-query 'example.com'")
sys.exit(1)
eng = DiabolicalV2(max_depth=args.depth, max_nodes=args.max_nodes)
result = eng.run(seed_domains=domains, x_query=args.x_query, do_x=not args.no_x)
out = json.dumps(result, indent=2)
print(out)
if args.out:
open(args.out, "w").write(out)
log(f"Wrote {args.out}")
else:
ts = time.strftime("%Y%m%d-%H%M%S")
p = os.path.join(CACHE_DIR, f"diabolical-v2-{ts}.json")
open(p, "w").write(out)
log(f"Saved {p}")
if __name__ == "__main__":
main()