Repository navigation
Expand file tree
/
Copy pathclean_malware.py
More file actions
634 lines (573 loc) · 29.8 KB
/
Copy pathclean_malware.py
File metadata and controls
634 lines (573 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
clean_malware 1.0 - mass recursive cleanup of KNOWN malicious files (Python 3.6+, no pip).
What it cleans (by family signatures only, NOT by file names alone):
htaccess .htaccess "locks": deny all PHP except a list of names (template (py|exe|php|PHP|Php...),
allow-list of 6+ php names). Malicious blocks are cut out; if nothing else is left in the file,
the whole file is deleted. Legitimate rules next to them are kept.
backdoor PHP backdoors of the filefuns.php family: the BiaoJiOk marker or a goto loader with eval($a[N](...)).
filemanager (optional) standalone web file managers without authentication (like elp.php).
core (--replace-core --baseline-dir CLEAN_JOOMLA) core files modified relative to the original
are replaced with originals from a clean distribution of the SAME version (a copy of the modified file goes to quarantine).
Safe workflow:
1) python3 clean_malware.py /path/to/site # dry run: nothing is changed
2) python3 clean_malware.py /path/to/site --apply # move to quarantine (can be restored)
3) python3 clean_malware.py --restore /path/to/manifest.json # rollback
4) python3 clean_malware.py /path/to/site --apply --delete # delete permanently
Exit codes: 0 - success, 1 - startup error, 2 - some files could not be processed.
"""
import argparse
import base64
import csv
import fnmatch
import hashlib
import io
import json
import os
import re
import shutil
import stat
import sys
import time
from datetime import datetime
from pathlib import Path
VERSION = "1.0"
ALL_FAMILIES = ("htaccess", "backdoor", "filemanager")
MEDIA_EXT = {".flv", ".swf", ".mp3", ".mp4", ".avi", ".mov", ".wav", ".jpg", ".jpeg", ".png", ".gif", ".ico"}
INCLUDE_DECODED_RE = re.compile(r"""\b(?:include|require)(?:_once)?\s*\(?\s*base64_decode\s*\(\s*(['"])([A-Za-z0-9+/]+={0,2})\1\s*\)""")
MEDIA_NAME_RE = re.compile(r"^[\w .@()\-/\\]{1,120}\.(?:flv|swf|mp3|mp4|avi|mov|wav|jpe?g|png|gif|ico|bmp|webp|dat|bin|tmp)$", re.I)
MEDIA_PHP_RE = re.compile(br"<\?php\s[\s\S]{0,4000}?(?:eval|assert|base64_decode|gzinflate|system|shell_exec|passthru|exec|include|require|\$_(?:GET|POST|REQUEST|COOKIE))", re.I)
PHP_EXT = {".php", ".php3", ".php4", ".php5", ".php7", ".php8", ".phtml", ".pht", ".phar", ".inc"}
HTACCESS_NAME_RE = re.compile(r"^(?:\.htaccess(?:[._~-].*)?|htaccess(?:\.(?:txt|bak|old|orig|save|disabled|dist|sample))?)$")
MAX_HTACCESS = 512 * 1024
MAX_PHP = 2 * 1024 * 1024
CORE_PREFIXES = ("libraries/", "includes/", "administrator/includes/")
DEFAULT_CORE_EXT = ".php,.js,.html,.htm"
# --- .htaccess ---
_FM_TAIL = r"[ \t]*\r?\n?"
DENY_BLOCK_RE = re.compile(r"<FilesMatch\s+[\"'][^\"'\n]*(?:\(py\|exe\|php\|PHP\|Php|\bPHP\|Php\|PHp)[^\"'\n]*[\"']\s*>.*?</FilesMatch>" + _FM_TAIL, re.I | re.S)
# short allow-list (index.php|cache.php): removed ONLY together with a found deny block
SHORT_ALLOW_RE = re.compile(r"<FilesMatch\s+[\"']\^?\(?[\w.\-]+\.php(?:\|[\w.\-]+\.php)*\)?\$[\"']\s*>#?.*?</FilesMatch>" + _FM_TAIL, re.I | re.S)
ALLOW_BLOCK_RE = re.compile(r"<FilesMatch\s+[\"']\^?\((?:[\w.\-]+\.php\|){6,}[^\"'\n]*[\"']\s*>.*?</FilesMatch>" + _FM_TAIL, re.I | re.S)
REWRITE_BLOCK_RE = re.compile(
r"<IfModule\s+mod_rewrite\.c>\s*RewriteEngine\s+On\s*RewriteBase\s+/\s*RewriteRule\s+\^index\.php\$\s+-\s+\[L\]\s*"
r"RewriteCond\s+%\{REQUEST_FILENAME\}\s+!-f\s*RewriteCond\s+%\{REQUEST_FILENAME\}\s+!-d\s*"
r"RewriteRule\s+\.\s+index\.php\s+\[L\]\s*</IfModule>" + _FM_TAIL, re.I)
# --- PHP ---
MARKER_RE = re.compile(r"BiaoJiOk")
EVAL_ARR_RE = re.compile(r"\beval\s*\(\s*\$\w+\s*\[[^\]\n]{1,40}\]\s*\(")
GOTO_RE = re.compile(r"\bgoto\s+\w+\s*;")
ALPHABET_RE = re.compile(r"""\(\s*["'](?:~|\\176|\\x7e)["']\s*,\s*["'](?: |\\40|\\x20)["']\s*\)""", re.I)
JOOMLA_GUARD_RE = re.compile(r"defined\s*\(\s*['\"]_JEXEC['\"]")
REQUEST_RE = re.compile(r"\$_(?:GET|POST|REQUEST|FILES)\b")
FM_FEATURES = [re.compile(p) for p in (
r"\b(?:scandir|readdir|glob)\s*\(", r"\bmove_uploaded_file\s*\(", r"\b(?:unlink|rmdir)\s*\(",
r"\brename\s*\(", r"\b(?:fwrite|fputs|file_put_contents)\s*\(", r"\bfile_get_contents\s*\(",
r"\b(?:fileperms|chmod)\s*\(")]
# names from the malicious .htaccess: NOT removed by themselves, only listed for manual review
SUSPECT_NAMES = {"moderation.php", "system_log.php", "inputs.php", "chtmlfuns.php", "cjfuns.php", "classsmtps.php",
"classfuns.php", "comfunctions.php", "comdofuns.php", "connects.php", "copypaths.php", "delpaths.php",
"doiconvs.php", "epinyins.php", "filefuns.php", "gdftps.php", "hinfofuns.php", "hplfuns.php",
"memberfuns.php", "moddofuns.php", "onclickfuns.php", "phpzipincs.php", "qfunctions.php",
"qinfofuns.php", "schallfuns.php", "tempfuns.php", "txets.php", "thoms.php"}
def decode(raw):
try:
return raw.decode("utf-8")
except UnicodeDecodeError:
return raw.decode("latin-1") # lossless: can be written back via latin-1
def analyze_htaccess(raw):
"""-> (infected, cleaned_bytes, empty_after) """
text = raw.decode("latin-1")
t, n1 = DENY_BLOCK_RE.subn("", text)
t, n2 = ALLOW_BLOCK_RE.subn("", t)
if not (n1 or n2):
return False, raw, False
t = SHORT_ALLOW_RE.sub("", t)
t = REWRITE_BLOCK_RE.sub("", t) # the injected WordPress rewrite block is removed only in an infected file
rest = re.sub(r"(?m)^\s*#.*$", "", t).strip()
return True, t.encode("latin-1"), rest == ""
def looks_like_filemanager(text):
if JOOMLA_GUARD_RE.search(text) or not REQUEST_RE.search(text):
return False
return sum(1 for rx in FM_FEATURES if rx.search(text)) >= 5
def analyze_media(raw):
return bool(MEDIA_PHP_RE.search(raw))
def joomla_version(root):
"""Joomla version from the distribution files (J4/5: libraries/src/Version.php, J3: libraries/cms/version/version.php)."""
root = Path(root)
try:
t = (root / "libraries" / "src" / "Version.php").read_text(encoding="utf-8", errors="ignore")
parts = [re.search(r"%s_VERSION\s*=\s*(\d+)" % k, t) for k in ("MAJOR", "MINOR", "PATCH")]
if all(parts):
return ".".join(m.group(1) for m in parts)
except OSError:
pass
try:
t = (root / "libraries" / "cms" / "version" / "version.php").read_text(encoding="utf-8", errors="ignore")
rel = re.search(r"\$RELEASE\s*=\s*'([\d.]+)'", t)
dev = re.search(r"\$DEV_LEVEL\s*=\s*'(\d+)'", t)
if rel and dev:
return "%s.%s" % (rel.group(1), dev.group(1))
except OSError:
pass
return None
def build_core_baseline(clean_dir, exts):
"""{relative path: (sha256, absolute path)} for files of the clean distribution with the required extensions."""
base = {}
for root, _dirs, files in os.walk(clean_dir):
for n in files:
if os.path.splitext(n.lower())[1] in exts:
p = os.path.join(root, n)
try:
base[os.path.relpath(p, clean_dir).replace(os.sep, "/")] = (sha256_file(p), p)
except OSError:
pass
return base
def analyze_php(text, families):
low = text.lower()
if "backdoor" in families and len(text) < 1000: # a tiny index.php that includes a disguised payload
m = INCLUDE_DECODED_RE.search(text)
if m:
try:
dec = base64.b64decode(m.group(2) + "=" * (-len(m.group(2)) % 4)).decode("utf-8")
except Exception:
dec = ""
if dec and MEDIA_NAME_RE.match(dec):
return "backdoor", "includes disguised payload '%s'" % dec
if "backdoor" in families and "<?php" in low:
if MARKER_RE.search(text):
return "backdoor", "marker BiaoJiOk"
if EVAL_ARR_RE.search(text) and (len(GOTO_RE.findall(text)) >= 8 or ALPHABET_RE.search(text)):
return "backdoor", "obfuscated goto/eval loader"
if "filemanager" in families and looks_like_filemanager(text):
return "filemanager", "web file manager without authentication"
return None, ""
def load_whitelist(path):
hashes, paths = set(), []
with io.open(path, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.split("#", 1)[0].strip()
if not line:
continue
if re.match(r"^[0-9a-fA-F]{64}$", line):
hashes.add(line.lower())
else:
paths.append(re.sub(r"^(?:\./|/)+", "", line.replace("\\", "/")))
return hashes, paths
def path_whitelisted(rel, patterns):
for p in patterns:
if any(ch in p for ch in "*?["):
if fnmatch.fnmatch(rel, p):
return True
elif rel == p or rel.startswith(p.rstrip("/") + "/"):
return True
return False
# ---------------------------------------------------------------- file actions
def _force_writable(path):
try:
os.chmod(path, stat.S_IMODE(os.stat(path).st_mode) | stat.S_IWRITE | stat.S_IREAD)
except OSError:
pass
def with_fix_permissions(path, fn):
"""Run fn(); on PermissionError (a read-only file or a 0555 directory is a common malware trick)
temporarily open the permissions, retry and restore the directory permissions."""
try:
return fn()
except PermissionError:
parent = os.path.dirname(path)
try:
old = stat.S_IMODE(os.stat(parent).st_mode)
os.chmod(parent, old | stat.S_IWRITE | stat.S_IREAD | stat.S_IEXEC)
except OSError:
old = None
_force_writable(path)
try:
return fn()
finally:
if old is not None:
try:
os.chmod(parent, old)
except OSError:
pass
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def quarantine_copy(path, qdir, rel, suffix):
dest = Path(qdir) / (rel + suffix)
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, str(dest))
return dest
def do_remove(item, qdir, permanent):
"""Delete a file. Not permanent: first a copy goes to quarantine (with hash verification), then the file is deleted."""
path, entry = item["path"], {"rel": item["rel"], "original": item["path"], "family": item["family"],
"sha256": item["sha256"], "action": "quarantine"}
if not permanent:
dest = quarantine_copy(path, qdir, item["rel"], ".quarantine")
if sha256_file(str(dest)) != item["sha256"]:
raise IOError("the quarantine copy did not match by hash")
entry["quarantined"] = str(dest)
try:
with_fix_permissions(path, lambda: os.unlink(path))
except Exception:
try:
dest.unlink()
except OSError:
pass
raise
else:
entry["action"] = "delete"
with_fix_permissions(path, lambda: os.unlink(path))
return entry
def do_strip(item, qdir, permanent):
path, entry = item["path"], {"rel": item["rel"], "original": item["path"], "family": item["family"],
"sha256": item["sha256"], "action": "stripped"}
if not permanent:
dest = quarantine_copy(path, qdir, item["rel"], ".orig")
entry["quarantined"] = str(dest)
def write():
with open(path, "wb") as f:
f.write(item["new_bytes"])
with_fix_permissions(path, write)
return entry
def do_replace(item, qdir, permanent):
"""Write the original OVER the modified file (in place: owner and permissions are kept), verify the hash."""
path = item["path"]
entry = {"rel": item["rel"], "original": path, "family": item["family"], "sha256": item["sha256"],
"action": "replaced"}
backup = None
if not permanent:
backup = quarantine_copy(path, qdir, item["rel"], ".modified")
entry["quarantined"] = str(backup)
def write():
with open(item["src"], "rb") as f:
data = f.read()
with open(path, "wb") as g:
g.write(data)
try:
old_mode = stat.S_IMODE(os.stat(path).st_mode)
except OSError:
old_mode = None
try:
with_fix_permissions(path, write)
if sha256_file(path) != item["new_sha"]:
raise IOError("the hash did not match the original after the replacement")
if old_mode is not None: # restore the permissions (but remove write for "others": 0777 -> 0775)
try:
os.chmod(path, old_mode & ~0o002)
except OSError:
pass
except Exception:
if backup is not None: # rollback: restore what was there before
try:
with_fix_permissions(path, lambda: shutil.copyfile(str(backup), path))
except Exception:
pass
raise
return entry
# ---------------------------------------------------------------- restore
def restore(manifest_path, emit):
try:
data = json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
print("Could not read the manifest:", exc)
return 1
ok = fail = 0
for e in data.get("entries", []):
q, orig = e.get("quarantined"), e.get("original")
if not q or not orig or not os.path.isfile(q):
continue
try:
if e["action"] == "quarantine":
if os.path.lexists(orig):
print("[SKIPPED] already exists:", orig)
continue
def put():
os.makedirs(os.path.dirname(orig), exist_ok=True)
shutil.copy2(q, orig)
with_fix_permissions(orig, put)
os.unlink(q)
else: # stripped: restore the original content
with_fix_permissions(orig, lambda: shutil.copy2(q, orig))
print("[RESTORED]", orig)
ok += 1
except Exception as exc:
print("[ERROR]", orig, exc)
fail += 1
print("Restored: %d, errors: %d" % (ok, fail))
return 2 if fail else 0
# ---------------------------------------------------------------- main pass
def iter_candidates(start, excl_dirs, skip_abs, with_media=True, extra_ext=frozenset()):
for root, dirs, files in os.walk(start):
dirs[:] = [d for d in dirs if d not in excl_dirs and os.path.abspath(os.path.join(root, d)) not in skip_abs]
for n in files:
low = n.lower()
ext = os.path.splitext(low)[1]
if HTACCESS_NAME_RE.match(low) or ext in PHP_EXT or ext in extra_ext or (with_media and ext in MEDIA_EXT):
yield os.path.join(root, n), low
def build_parser():
ap = argparse.ArgumentParser(description="Mass cleanup of known malicious files, v" + VERSION)
ap.add_argument("start", nargs="?", default=".", help="site root")
ap.add_argument("--apply", action="store_true", help="perform the actions (without this flag only the plan is shown)")
ap.add_argument("--delete", action="store_true", help="delete permanently, without quarantine")
ap.add_argument("--families", default="htaccess,backdoor", help="comma-separated: htaccess,backdoor,filemanager")
ap.add_argument("--htaccess-mode", choices=("clean", "delete"), default="clean",
help="clean: cut out the malicious blocks, keep the rest (default); delete: delete the whole file")
ap.add_argument("--quarantine-dir", help="where to put the copies (by default next to the site, OUTSIDE its folder)")
ap.add_argument("--exclude-dir", default="", help="comma-separated folder names to leave alone")
ap.add_argument("--whitelist", help="file with SHA-256/paths/masks to leave alone")
ap.add_argument("--report", default="cleanup-report.csv", help="CSV report (cleanup-report.csv)")
ap.add_argument("--restore", metavar="MANIFEST", help="restore files from quarantine using manifest.json")
ap.add_argument("--replace-core", action="store_true",
help="replace modified core files with originals from --baseline-dir (clean Joomla of the SAME version)")
ap.add_argument("--baseline-dir", help="folder with a clean Joomla distribution (where index.php lives)")
ap.add_argument("--core-ext", default=DEFAULT_CORE_EXT, help="extensions to replace (default %s)" % DEFAULT_CORE_EXT)
ap.add_argument("--max-modified-percent", type=float, default=30.0,
help="if more than N%% of core files are modified, the replacement is cancelled (probably the wrong version), default 30")
ap.add_argument("--force-version", action="store_true", help="skip the version check and the modified-percent check (DANGEROUS)")
ap.add_argument("--no-media", action="store_true", help="do not check images/video for PHP code inside (faster)")
ap.add_argument("--progress-lines", action="store_true", help="service lines @@... for the GUI")
ap.add_argument("--version", action="version", version="clean_malware " + VERSION)
return ap
def main(argv=None):
args = build_parser().parse_args(argv)
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(errors="replace")
except Exception:
pass
def emit(tag, payload=""):
if args.progress_lines:
print("@@%s %s" % (tag, payload), flush=True)
if args.restore:
return restore(args.restore, emit)
start = os.path.abspath(args.start)
if not os.path.isdir(start):
print("Folder not found:", start)
return 1
if len(Path(start).parts) < 2:
print("Refused: a disk root was given, specify the site folder.")
return 1
families = set(f.strip() for f in args.families.split(",") if f.strip())
if not families or not families <= set(ALL_FAMILIES):
print("Unknown family. Allowed:", ",".join(ALL_FAMILIES))
return 1
core_base, core_ext, core_pkgs, core_matched, core_modified = None, set(), set(), 0, 0
extras = []
if args.replace_core:
if not args.baseline_dir or not os.path.isfile(os.path.join(args.baseline_dir, "index.php")):
print("--replace-core requires --baseline-dir with a clean Joomla (index.php must be there).")
return 1
site_v, clean_v = joomla_version(start), joomla_version(args.baseline_dir)
print("Joomla version: site %s | baseline %s" % (site_v or "undetermined", clean_v or "undetermined"))
if not args.force_version and (not site_v or not clean_v or site_v != clean_v):
print("REFUSED: the versions do not match or are undetermined. Replacing core files with files of a DIFFERENT version will break the site.")
print(" Download the Joomla %s distribution (full package) and pass it via --baseline-dir." % (site_v or "your version"))
return 1
core_ext = set(e.strip().lower() if e.strip().startswith(".") else "." + e.strip().lower()
for e in args.core_ext.split(",") if e.strip())
emit("PHASE", "baseline")
print("Building the baseline from '%s' …" % args.baseline_dir)
core_base = build_core_baseline(args.baseline_dir, core_ext)
core_pkgs = set("/".join(r.split("/")[:4]) for r in core_base if r.startswith("libraries/vendor/"))
print(" baseline files (%s): %d" % ("".join(sorted(core_ext)), len(core_base)))
families = families | {"core"}
wl_hashes, wl_paths = set(), []
if args.whitelist:
try:
wl_hashes, wl_paths = load_whitelist(args.whitelist)
except OSError as exc:
print("Cannot read the whitelist:", exc)
return 1
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if args.quarantine_dir:
qdir = Path(args.quarantine_dir).expanduser().resolve()
else:
parent = Path(start).parent
base = parent if os.access(str(parent), os.W_OK) else Path.cwd()
qdir = base / ("_quarantine_" + (Path(start).name or "site")) / stamp
skip_abs = {os.path.abspath(str(qdir)), os.path.abspath(str(qdir.parent))}
try:
qdir.relative_to(start)
if args.apply and not args.delete:
print("The quarantine must not be inside the site (its files would end up in the web root):", qdir)
return 1
except ValueError:
pass
excl = set(d.strip() for d in args.exclude_dir.split(",") if d.strip())
mode = "APPLY" if args.apply else "DRY RUN (nothing is changed)"
print("clean_malware %s | %s | %s" % (VERSION, mode, start))
print("Families: %s | .htaccess: %s | %s" % (",".join(sorted(families)), args.htaccess_mode,
"permanent deletion" if args.delete else "quarantine: %s" % qdir))
emit("PHASE", "walk")
candidates = list(iter_candidates(start, excl, skip_abs, not args.no_media, core_ext))
total = len(candidates)
emit("PROGRESS", "0 %d" % total)
plan, suspects, skipped_wl, read_err = [], [], 0, 0
for i, (path, low) in enumerate(candidates, 1):
if i % 200 == 0 or i == total:
emit("PROGRESS", "%d %d" % (i, total))
try:
if os.path.islink(path):
continue
st = os.stat(path)
rel = os.path.relpath(path, start).replace(os.sep, "/")
if path_whitelisted(rel, wl_paths):
skipped_wl += 1
continue
is_ht = bool(HTACCESS_NAME_RE.match(low))
is_media = os.path.splitext(low)[1] in MEDIA_EXT
if st.st_size > (MAX_HTACCESS if is_ht else MAX_PHP):
continue
with open(path, "rb") as f:
raw = f.read()
sha = hashlib.sha256(raw).hexdigest()
if sha in wl_hashes:
skipped_wl += 1
continue
ext = os.path.splitext(low)[1]
if core_base is not None and ext in core_ext:
if rel in core_base:
base_sha, base_path = core_base[rel]
core_matched += 1
if sha == base_sha:
continue # the file is identical to the original
reason = "modified vs clean Joomla"
if ext in PHP_EXT:
fam, why = analyze_php(decode(raw), families)
if fam:
reason += " + malicious code (%s)" % why
core_modified += 1
plan.append({"family": "core", "reason": reason, "action": "replace", "src": base_path,
"new_sha": base_sha, "path": path, "rel": rel, "sha256": sha,
"size": st.st_size, "mtime": st.st_mtime})
continue
if ext == ".php" and rel.startswith(CORE_PREFIXES) and not (
rel.startswith("libraries/vendor/") and "/".join(rel.split("/")[:4]) not in core_pkgs):
extras.append(rel) # an extra file in core folders: only report it
item = None
if is_media:
if "backdoor" in families and analyze_media(raw):
item = {"family": "backdoor", "reason": "PHP code inside a media file", "action": "remove"}
elif is_ht:
if "htaccess" in families:
infected, cleaned, empty = analyze_htaccess(raw)
if infected:
action = "remove" if (empty or args.htaccess_mode == "delete") else "strip"
item = {"family": "htaccess", "reason": "malicious FilesMatch lock", "action": action,
"new_bytes": cleaned}
else:
fam, reason = analyze_php(decode(raw), families)
if fam:
item = {"family": fam, "reason": reason, "action": "remove"}
elif low in SUSPECT_NAMES:
suspects.append(rel)
if item:
item.update(path=path, rel=rel, sha256=sha, size=st.st_size, mtime=st.st_mtime)
plan.append(item)
except OSError:
read_err += 1
if core_base is not None and core_modified and not args.force_version:
pct = 100.0 * core_modified / max(core_matched, 1)
print("\nCore files modified: %d of %d (%.1f%%)." % (core_modified, core_matched, pct))
if core_matched >= 50 and pct > args.max_modified_percent:
print("REPLACEMENT REFUSED: too many files modified (> %.0f%%). Most likely the version or the file set of the baseline is wrong." % args.max_modified_percent)
print(" Core replacement skipped. Check the distribution version or run with --force-version (DANGEROUS).")
plan = [it for it in plan if it["family"] != "core"]
core_modified = 0
fam_count = {}
for it in plan:
key = "%s/%s" % (it["family"], it["action"])
fam_count[key] = fam_count.get(key, 0) + 1
word = {"remove": "delete" if args.delete else "to quarantine", "strip": "clean the file", "replace": "replace with original"}
print("\nPlan: %d files" % len(plan))
for it in plan:
print(" [%-11s] %-22s %s (%s)" % (it["family"], word[it["action"]], it["rel"], it["reason"]))
if suspects:
print("\nThese names match the list from the malicious .htaccess, but have NO family signatures,"
" so they are not touched. Check them manually (%d):" % len(suspects))
for r in suspects[:100]:
print(" ", r)
if len(suspects) > 100:
print(" … and %d more" % (len(suspects) - 100))
if extras:
print("\nThe core folders contain files that are NOT in the clean Joomla (not touched, check manually): %d" % len(extras))
for r in extras[:100]:
print(" ", r)
if len(extras) > 100:
print(" … and %d more" % (len(extras) - 100))
results, removed, stripped, replaced, failed = [], 0, 0, 0, 0
manifest = {"version": VERSION, "start": start, "created": stamp, "entries": []}
if args.apply and plan:
emit("PHASE", "clean")
print("\nWorking…")
for n, it in enumerate(plan, 1):
status, err = "OK", ""
try:
if not os.path.exists(it["path"]):
status, err = "SKIP", "the file is already missing"
else:
if it["action"] == "remove":
entry = do_remove(it, qdir, args.delete)
removed += 1
emit("CLEANED", it["rel"])
elif it["action"] == "replace":
entry = do_replace(it, qdir, args.delete)
replaced += 1
emit("REPLACED", it["rel"])
else:
entry = do_strip(it, qdir, args.delete)
stripped += 1
emit("STRIPPED", it["rel"])
manifest["entries"].append(entry)
except Exception as exc:
status, err = "FAIL", str(exc)
failed += 1
results.append((it, status, err))
if status != "OK":
print(" [%s] %s %s" % (status, it["rel"], err))
if n % 50 == 0 or n == len(plan):
emit("PROGRESS", "%d %d" % (n, len(plan)))
if not args.delete and manifest["entries"]:
try:
qdir.mkdir(parents=True, exist_ok=True)
(qdir / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding="utf-8")
except OSError as exc:
print("Could not write manifest.json:", exc)
else:
results = [(it, "PLAN", "") for it in plan]
try:
with io.open(args.report, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["Status", "Family", "Action", "File", "Size", "Modified", "SHA-256", "Error"])
for it, status, err in results:
rel = it["rel"]
w.writerow([status, it["family"], it["action"], "'" + rel if rel[:1] in "=+-@" else rel, it["size"],
datetime.fromtimestamp(it["mtime"]).strftime("%Y-%m-%d %H:%M"), it["sha256"], err])
print("\nReport: %s" % os.path.abspath(args.report))
except OSError as exc:
print("Could not write the report:", exc)
summary = {"mode": "apply" if args.apply else "dry-run", "planned": len(plan), "removed": removed,
"stripped": stripped, "replaced": replaced, "extras": len(extras), "failed": failed, "suspects": len(suspects), "whitelisted": skipped_wl,
"families": fam_count, "permanent": bool(args.delete),
"quarantine": str(qdir) if (args.apply and not args.delete and manifest["entries"]) else ""}
print("\n" + "=" * 60)
if args.apply:
print("Deleted/moved: %d | .htaccess cleaned: %d | replaced with originals: %d | errors: %d" % (removed, stripped, replaced, failed))
if summary["quarantine"]:
print("Quarantine: %s (rollback: --restore %s)" % (qdir, qdir / "manifest.json"))
if failed:
print("Failed: check the owner/permissions; on Linux also `lsattr` (the immutable attribute is removed with `chattr -i`).")
print("IMPORTANT: change the passwords and find the cause of the compromise; the malware may have left copies under other names,")
print(" rerun scan_backdoors.py and check whether the files reappear (cron/processes).")
else:
print("Dry run only. Add --apply to execute (quarantine by default, can be rolled back).")
print("=" * 60)
emit("SUMMARY", json.dumps(summary, ensure_ascii=False))
emit("DONE")
return 2 if failed else 0
if __name__ == "__main__":
sys.exit(main())