193 lines
5.8 KiB
Python
193 lines
5.8 KiB
Python
"""ETERNAL WordPress.org plugin firehose: plugins API + zip scan.
|
|
|
|
Anonymous. Browse rotation: updated -> new -> popular (per cycle), 5 pages
|
|
of 100. Each new plugin: download zip (cap 8MB), scan text files via
|
|
key_patterns.scan_text. seen=slug. mark_seen ONLY on success.
|
|
"""
|
|
import os
|
|
KF_BASE = os.path.dirname(os.path.abspath(__file__))
|
|
os.makedirs(os.path.join(KF_BASE, "data"), exist_ok=True)
|
|
import hashlib
|
|
import io
|
|
import sqlite3
|
|
import sys
|
|
import threading
|
|
import time
|
|
import zipfile
|
|
|
|
import requests
|
|
|
|
DB = os.environ.get("KF_DB") or os.path.join(KF_BASE, "data/keys.db")
|
|
LOG = os.path.join(KF_BASE, "data/wp_eternal.log")
|
|
SEEN_FILE = os.path.join(KF_BASE, "data/wp_seen.txt")
|
|
N_THREADS = 6
|
|
PAGES_PER_CYCLE = 5
|
|
ZIP_CAP = 8 * 1024 * 1024
|
|
FILE_CAP = 500_000
|
|
SLEEP = 90
|
|
BROWSES = ("updated", "new", "popular")
|
|
|
|
from key_patterns import scan_text
|
|
|
|
GARBAGE = ("xxxx", "your", "YOUR", "EXAMPLE", "example", "n0tr3al",
|
|
"placeholder", "CHANGEME", "changeme", "dummy", "DUMMY",
|
|
"abcdefghijklmnopqrst", "1234567890abcdef")
|
|
|
|
SCAN_EXT = (".php", ".js", ".json", ".txt", ".env", ".xml", ".yaml", ".yml",
|
|
".ini", ".cfg", ".po", ".csv")
|
|
|
|
UA = {"User-Agent": "keyfarm-wp/1.0"}
|
|
|
|
|
|
def log(msg):
|
|
line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {msg}\n"
|
|
with open(LOG, "a", encoding="utf-8") as f:
|
|
f.write(line)
|
|
|
|
|
|
conn = sqlite3.connect(DB, timeout=120, check_same_thread=False,
|
|
isolation_level=None)
|
|
lock = threading.Lock()
|
|
total = 0
|
|
|
|
|
|
def db_add(key, prov, repo):
|
|
global total
|
|
with lock:
|
|
conn.execute(
|
|
"INSERT INTO keys (hash, val, prov, status, found, repo) "
|
|
"VALUES (?,?,?,?,?,?) "
|
|
"ON CONFLICT(hash) DO UPDATE SET status='NEW', "
|
|
"found=excluded.found, repo=excluded.repo "
|
|
"WHERE keys.status IN ('DEAD','ERR')",
|
|
(hashlib.sha1(key.encode()).hexdigest()[:16],
|
|
key, prov, "NEW", "wp", repo))
|
|
total += 1
|
|
|
|
|
|
def load_seen():
|
|
s = set()
|
|
try:
|
|
with open(SEEN_FILE, encoding="utf-8") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line:
|
|
s.add(line)
|
|
except FileNotFoundError:
|
|
pass
|
|
return s
|
|
|
|
|
|
seen = load_seen()
|
|
|
|
|
|
def mark_seen(p):
|
|
seen.add(p)
|
|
with open(SEEN_FILE, "a", encoding="utf-8") as f:
|
|
f.write(p + "\n")
|
|
|
|
|
|
def work(slug, dl):
|
|
"""Fetch plugin zip, scan. -1 on final fail."""
|
|
n = 0
|
|
for attempt in (1, 2, 3):
|
|
try:
|
|
r = requests.get(dl, headers=UA, timeout=40, stream=True)
|
|
if r.status_code == 404:
|
|
return 0
|
|
if r.status_code != 200:
|
|
raise RuntimeError(f"http {r.status_code}")
|
|
cl = int(r.headers.get("Content-Length") or 0)
|
|
if cl > ZIP_CAP:
|
|
return 0
|
|
buf = r.content
|
|
if len(buf) > ZIP_CAP:
|
|
return 0
|
|
zf = zipfile.ZipFile(io.BytesIO(buf))
|
|
for m in zf.infolist():
|
|
if m.is_dir() or m.file_size > FILE_CAP:
|
|
continue
|
|
fn = m.filename.lower()
|
|
if not any(fn.endswith(e) for e in SCAN_EXT):
|
|
continue
|
|
text = zf.read(m).decode("utf-8", errors="ignore")
|
|
for prov, key in scan_text(text):
|
|
if isinstance(key, tuple):
|
|
key = key[0]
|
|
if any(g in key for g in GARBAGE) or len(key) < 30:
|
|
continue
|
|
db_add(key, prov, f"wordpress:{slug}")
|
|
n += 1
|
|
return n
|
|
except Exception:
|
|
if attempt == 3:
|
|
log(f" wp-err {slug}")
|
|
return -1
|
|
time.sleep(8)
|
|
return -1
|
|
|
|
|
|
def cycle():
|
|
global total
|
|
total = 0
|
|
browse = BROWSES[int(time.time() / SLEEP) % len(BROWSES)]
|
|
items = []
|
|
for page in range(1, PAGES_PER_CYCLE + 1):
|
|
params = {"action": "query_plugins", "request[per_page]": "100",
|
|
"request[page]": str(page), "request[browse]": browse}
|
|
for attempt in (1, 2, 3):
|
|
try:
|
|
r = requests.get("https://api.wordpress.org/plugins/info/1.2/",
|
|
params=params, headers=UA, timeout=40)
|
|
if r.status_code != 200:
|
|
raise RuntimeError(f"http {r.status_code}")
|
|
d = r.json()
|
|
break
|
|
except Exception as e:
|
|
if attempt == 3:
|
|
log(f"list-err browse={browse} page={page} "
|
|
f"{type(e).__name__}")
|
|
return
|
|
time.sleep(8)
|
|
for p in d.get("plugins") or []:
|
|
slug = p.get("slug")
|
|
dl = p.get("download_link")
|
|
if slug and dl and slug not in seen:
|
|
items.append((slug, dl))
|
|
|
|
ok = fail = 0
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
with ThreadPoolExecutor(max_workers=N_THREADS) as ex:
|
|
futs = {ex.submit(work, s, dl): s for s, dl in items}
|
|
for fut in as_completed(futs):
|
|
s = futs[fut]
|
|
try:
|
|
res = fut.result()
|
|
except Exception:
|
|
res = -1
|
|
if res == -1:
|
|
fail += 1 # NOT marked seen: retried next cycle
|
|
else:
|
|
ok += 1
|
|
mark_seen(s)
|
|
|
|
log(f"cycle: browse={browse} items={len(items)} ok={ok} "
|
|
f"fail={fail} +{total} keys")
|
|
|
|
|
|
def main():
|
|
log("wp_eternal started")
|
|
if "--once" in sys.argv:
|
|
cycle()
|
|
return
|
|
while True:
|
|
try:
|
|
cycle()
|
|
except Exception as e:
|
|
log(f"cycle-err {type(e).__name__}: {e}")
|
|
time.sleep(SLEEP)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|