Skip to content
项目

关于

A self-contained PHP webshell scanner that uses token analysis, hash filtering, machine learning, and entropy-based anomaly detection to hunt for backdoors, supports legacy PHP 4.3 to the very recent PHP 8, no dependencies required

安全与隐私

这些数字如何统计

可以做什么

  • Token-based detection – scans PHP tokens for known obfuscation, shell execution, file I/O, and credential-related functions (method names like $pdo->exec() and text inside strings/comments are ignored)
  • Structural detection – catches what name matching can't: calls through variables or superglobals ($_GET['a']($_GET['b'])), function names hidden in strings ('ba'.'se64_decode', "\x73ystem"), preg_replace with /e, backtick shell execution, payloads after __halt_compiler(), and giant single-line blobs
  • MD5 hash whitelist & blacklist – skip known-good files (e.g., from common frameworks) and auto-delete known-bad files
  • Shannon entropy calculation – per-file byte entropy detects heavily obfuscated or encoded content

实测星标增长

24小时
0
7天
0
15天
+1
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

SussyFinder

PRs Welcome

PHP web application that scans a directory for PHP and related files and analyses each one for malicious code.

It combines token-based pattern matching, statistical anomaly detection (Shannon entropy, robust Z-scores), and MD5 hash whitelist/blacklisting to help identify suspicious files in a web server environment.

⚠️ Use with caution – this tool can delete files identified as blacklisted. Always review flagged files before taking action.

Features

  • Recursive directory scanning for big sites: the file list comes a page at a time, each page within the host's time limit, and analysis starts on the first page while the rest is listed. Symlinked directories aren't followed (those inside the scanned directory are scanned at their real path; those leading outside are reported), and directories that can't be listed are reported instead of skipped silently

  • Built for shared hosting – several batches are analysed at once (at most MAX_PARALLEL), starting with one; when the host answers that it is busy (429, 503, 508, …) the page sends fewer at once and retries the batch later instead of splitting it up. When a request gets no answer at all (a reset connection, NS_ERROR_NET_RESET, a proxy or host cutting long requests off), the listing asks for pages half as big and half as long, and a batch is retried once, then split until the one file the server dies on is found and skipped by name

  • Token-based detection – scans PHP tokens for known obfuscation, shell execution, file I/O, and credential-related functions (method names like $pdo->exec() and text inside strings/comments are ignored)

  • Structural detection – catches what name matching can't: calls through variables or superglobals ($_GET['a']($_GET['b'])), function names hidden in strings ('ba'.'se64_decode', "\x73ystem"), preg_replace with /e, backtick shell execution, payloads after __halt_compiler(), and giant single-line blobs

  • MD5 hash whitelist & blacklist – skip known-good files (e.g., from common frameworks) and auto-delete known-bad files

  • Vendor checksums – a file byte-identical to an official release (WordPress core and wordpress.org plugins through WordPress's checksum APIs, and release files of 57 CMSs, frameworks and libraries in checksums.txt) is shown as VERIFIED and its threat score held below half the anomaly bar; an injected shell changes the hash, so nothing can hide this way (details)

  • Shannon entropy calculation – per-file byte entropy detects heavily obfuscated or encoded content

  • Tiny ML model: a 4 KB logistic regression over hashed token features, run in the browser. Its score adds points to the threat score, so it can lift a file the rules underrate; it never lowers a score.

  • Client-side statistical analysis – computes robust (median/MAD) Z-scores for size, mtime, tokens, suspicious token count, entropy and the ctime–mtime gap, plus residuals and file-owner rarity, to flag outliers

  • Interactive web interface with:

    • Sort by modification time, suspicious token count, Z-score, or residual

    • Filter to show only anomalies (a scan of more than 10,000 files starts on this filter)

    • The table draws 500 rows at a time and the next ones as you scroll down (infinite scroll); search, filters, sorting, the charts and Copy cover every row

    • Search: press / anywhere to jump to the search box (Esc clears it). Words must all match, in the path or a matched token; the ? button lists the rest:

      Query Finds
      eval base64, eval OR assert, eval -vendor both words, either one, eval but not vendor
      "wp-content/uploads", /\.(jpe?g|png)$/ exact text with spaces; a regular expression
      path: name: token: ext: md5: owner: dup: one property: path, file name, matched token, last extension, hash, owner id, a duplicate's original
      score:>=15 rules:>8 ml:>80 size:>100k entropy:>5.5 tokens:<20 hits:3..10 numbers, with >, >=, <, <= or a range a..b; ml is in %
      date:7d, date:2025-06, date:>=2025-01-01, date:2025-06-15T14..2025-06-15T16 changed in the last 7 days (h, w too); in a year, month, day, hour or minute; after or before it; a range
      near:"/path/to/shell.php", near:is:blacklisted, near:(is:critical ext:php)~6h files in the folder of that file, or of any file the query finds, or whose mtime or ctime is within an hour of one of theirs (~30m, ~6h, ~2d, ~1w sets the window); -near:… is everything else. ctime counts because an intruder can backdate a file's mtime with touch but not its ctime, and a file they edited and set back still has a new ctime. A time shared by more than 5% of the files (at least 200: a deploy, an update, a restore) is left out, and the search box's tooltip says so. Searching near: switches the filter to All Files, since the files around a shell are mostly not flagged
      dir:"/path/to/folder", (eval OR assert) -vendor files in exactly that folder; parentheses group
      is:critical -is:verified anomaly critical blacklisted verified duplicate htaccess unreadable gone mhr ml mlonly rare entropy

      A term that doesn't make sense (a broken regex, score:>x) outlines the box in red and its tooltip says why. When the severity filter hides files the search finds, the table says how many and offers to show them.

    • To see what else an intruder dropped or touched, search near:is:blacklisted -is:blacklisted -is:verified: everything around every blacklisted file, minus those files and official release files (near:"/path/to/one.php" for one file; combine it with ext:php and the rest). A blacklisted file is deleted by the scan that finds it, so this works in that scan's results. A blacklisted file is deleted by the scan that finds it, so this works in that scan's results (a later scan no longer has the file to look around).

    • One-click copy of results (with full details)

    • Click a file path to copy it; the 📋 icon copies its MD5 hash

    • Linked charts: drag a box on the Threat Matrix or Entropy chart, or click a timeline bar, to select those files (Ctrl/⌘ adds more); the table then shows only the selection, and Esc clears it. Charts fade whatever the table's filters hide, hovering a file in a chart highlights its table row (and the other way round), and the Threat Matrix zooms with the wheel, pans with Shift+drag and resets on double-click

  • Color-coded output – highlights blacklisted, unreadable, and suspicious files

  • Self-contained – single PHP file, no external dependencies

Statistical Analysis

SussyFinder uses several statistical techniques to identify files whose characteristics differ significantly from the rest of the scanned dataset.

Shannon Entropy

Shannon entropy measures the amount of information or randomness in a dataset. SussyFinder applies it to the raw bytes of each file (computed server-side).

The entropy is calculated as:

$$ H(X) = -\sum_{i=1}^{n} p(x_i)\log_2 p(x_i) $$

Where:

  • $H(X)$ = Shannon entropy
  • $p(x_i)$ = probability of symbol $x_i$
  • $n$ = number of unique symbols

The probability of each symbol is:

$$ p(x_i) = \frac{c_i}{N} $$

Where:

  • $c_i$ = number of occurrences of symbol $x_i$
  • $N$ = total number of characters

Higher entropy indicates a more diverse and less predictable character distribution, which can be useful for identifying encoded or obfuscated content.

For example:

Data Approximate Entropy
AAAAAA 0
ABCDEF $\approx 2.58$
Random/encoded data Higher

Plain PHP source sits around 4.5–5.2 bits/byte. SussyFinder treats a file as high-entropy above:

$$ \text{entropy} > 5.5 $$

Median and MAD

Mean and standard deviation are pulled toward the very outliers being hunted (and toward huge vendor files), which lets them hide. SussyFinder uses the median and the median absolute deviation (MAD) instead:

$$ \tilde{x} = \mathrm{median}(x_1, \dots, x_n) \qquad \mathrm{MAD} = \mathrm{median}(|x_i - \tilde{x}|) $$

The spread is scaled so it matches a standard deviation on normally distributed data:

$$ s = 1.4826 \times \mathrm{MAD} $$

When more than half the values tie (MAD = 0, e.g. most files match no suspicious tokens), the mean absolute deviation is used instead:

$$ s = 1.253314 \times \frac{1}{n}\sum_{i=1}^{n}|x_i - \tilde{x}| $$

Z-Score

SussyFinder uses robust (modified) Z-scores to determine how far a file's characteristics are from the rest of the dataset (Iglewicz & Hoaglin):

$$ Z = \frac{x-\tilde{x}}{s} $$

Where:

  • $x$ = observed value
  • $\tilde{x}$ = median
  • $s$ = scaled spread from above

SussyFinder calculates Z-scores for:

  • File size
  • Modification time
  • Total tokens
  • Suspicious token count
  • Shannon entropy
  • ctime − mtime gap: attackers backdate mtime with touch, but can't set ctime that way, so a planted file's gap stands out from its neighbours'. Gaps under a day (chmod, in-place edits) are ignored by flooring $s$ at 86400 seconds.

The default anomaly threshold is:

$$ Z > 3.5 $$

This threshold can be changed through the Z-threshold control in the web interface.

File Owner Rarity

A file owned by a user who owns less than 5% of the scanned files (e.g. the web-server user among FTP-deployed files) was probably written by the application, not deployed. With at least 20 files scanned, such files are marked RARE and flagged.

Residual Analysis

Residual analysis compares the observed suspicious-token count with the number that would be expected based on the average relationship between suspicious tokens and total tokens.

First, the average suspicious-token ratio is calculated:

$$ r = \frac{\overline{S}}{\overline{T}} $$

Where:

  • $S$ = suspicious token count
  • $T$ = total token count
  • $r$ = average suspicious-token ratio

For each file, the expected suspicious-token count is:

$$ E(S_i) = T_i \times r $$

The residual is then:

$$ R_i = S_i - E(S_i) $$

Where:

  • $R_i$ = residual
  • $S_i$ = observed suspicious-token count
  • $E(S_i)$ = expected suspicious-token count

A positive residual indicates that a file contains more suspicious tokens than expected for its total token count.

The residual is shown in each row and is available as a sort order, but it doesn't flag a file on its own. It counts every matched token equally, so long legitimate files full of routine calls (substr, implode, require) score high on it. The webshells it singles out tend to be ones that probe the server, and the Server Reconnaissance rule scores those directly.

Threat Score

SussyFinder also calculates a weighted threat score from matched tokens.

The general model is:

$$ \text{Score} = \sum_{i=1}^{n} w_i $$

Where:

  • $w_i$ = assigned weight of a matched token
  • $n$ = number of matched tokens

Example token weights include:

Category Example Weight
Critical RCE eval, exec, system, pcntl_exec 10.0
Obfuscation base64_decode, gzinflate 5.0
Suspicious I/O move_uploaded_file, $_FILES 2.0
User input $_GET, $_POST, $_COOKIE 0.5
Routine operations include, fopen, substr 0.1

Structural signals appear among the matched tokens with an @ prefix (no real PHP token can look like that):

Signal Meaning Weight
@input_call Calls a superglobal element: $_GET['a']($_GET['b']) 10.0
@assert_exec assert() of a string or request value: assert("eval(…)"), assert($_POST['c']) 10.0
@foreign_code ASP, JSP or Perl CGI code in a PHP-named file with no PHP 10.0
@preg_e preg_replace with the /e (eval) modifier 10.0
@callback_exec An execution function named as a string for a callback: array_map('assert', …) 10.0
@input_include include/require of a request value: include $_GET['f'] (file inclusion) 10.0
@wrapper_include include/require of a php:// or data: stream: include('php://input') 10.0
@com_exec new COM('WScript.Shell') / new DOTNET(…): Windows OLE command execution 10.0
` Backtick operator (shell execution) 10.0
@concat_name Function name hidden in a string (the name is added too) 5.0
@halt_payload Over 1 KiB of data after __halt_compiler() 5.0
@dyn_call Call through a variable or expression: $f(), (...)() 2.0
@long_line A line over 5000 characters 2.0

@input_call, @assert_exec, @preg_e, @foreign_code, @callback_exec, @input_include, @wrapper_include, @com_exec and the backtick count as Critical RCE tokens; @concat_name and @halt_payload as obfuscation. pcntl_exec is Critical because it replaces the process with a program. assert runs its argument as PHP, but only when that argument is a string or a request value: assert("eval(…)") and assert($_POST['c']) raise @assert_exec and count Critical, while a plain assert($x === 3) test assertion — the overwhelming benign use — keeps its low weight.

A function name counts as a call only where it is one — a global call like system(...), including \system(...). The same name as a class (new System(), System::run()), a namespace segment (namespace App\System;, use Vendor\Exec;) or a member ($db->exec(...)) is not a match. @callback_exec recovers the names that reach a callback instead of being written as a call, for the few functions almost never passed as a plain string (assert, create_function, shell_exec, passthru, proc_open, popen); common strings like 'system' or 'exec' are left to the other signals, as they are everywhere in legitimate configuration.

Additional multipliers are applied when combinations of suspicious behaviors are present.

Non-Critical Dampening

Obfuscation and suspicious-I/O tokens (e.g. base64_decode, gzinflate, move_uploaded_file) are common in legitimate code: compression libraries, mail clients, HTTP clients, media parsers and upload handlers. On their own they're a weak signal; they matter most in combination with a real execution primitive (see the multipliers below). When a file has no Critical RCE token, their weight is reduced:

$$ w_i' = 0.3 \times w_i $$

This does not apply to Routine-operations-tier tokens, and has no effect once a Critical RCE token is present in the file (the combination multipliers below take over instead).

Critical + Obfuscation

If a file contains both a critical execution token and an obfuscation token:

$$ \text{Score}' = 2.5 \times \text{Score} $$

Critical + Upload Handling

If a file contains both a critical execution token and upload-related functionality:

$$ \text{Score}' = 1.8 \times \text{Score} $$

Critical + User Input

If a file contains both a critical execution token and a user-input token:

$$ \text{Score}' = 2.0 \times \text{Score} $$

Upload Folder

Upload folders hold user files, so real code in one was almost always planted. A non-.htaccess file with more than 5 tokens inside an uploads directory gets:

$$ \text{Score}' = \text{Score} + 10 $$

Suspicious Path Bonus

Otherwise, if the file is located in directories such as:

  • upload
  • cache
  • tmp
  • images
  • media

and the score is already suspicious or entropy is high:

$$ \text{Score}' = \text{Score} + 5 $$

High-Entropy Bonus

For files with entropy above 5.5:

$$ \text{Score}' = \text{Score} + 3 $$

Server Reconnaissance

A webshell's header usually shows the server it landed on: the OS, the current user and uid, disk space, PHP settings. Legitimate code rarely asks for two of these at once. The calls counted are php_uname, phpinfo, get_cfg_var, get_current_user, getmyuid, getmygid, getmypid, getmyinode, posix_getuid, posix_geteuid, posix_getegid, posix_getlogin, disk_total_space, disk_free_space, diskfreespace and getlastmod. A file calling two or more different ones gets:

$$ \text{Score}' = \text{Score} + 6 $$

ML Points

Last, the ML model's score $P_{\mathrm{ML}}$ (see ML Model) adds points. They are added after the multipliers above, so they are never multiplied:

$$ \text{Score}' = \text{Score} + \left\lbrace \begin{array}{ll} 0 & P_{\mathrm{ML}} \leq 0.4 \ 8 \cdot \displaystyle\frac{P_{\mathrm{ML}} - 0.4}{0.8 - 0.4} & 0.4 < P_{\mathrm{ML}} < 0.8 \ 8 + 7 \cdot \displaystyle\frac{P_{\mathrm{ML}} - 0.8}{0.95 - 0.8} & P_{\mathrm{ML}} \geq 0.8 \end{array} \right. $$

The floor (ML_FLOOR 0.4) and the bar (ML_THRESHOLD 0.8) are set for recall: a missed webshell costs more than a false positive, so the model is believed sooner. Held out, lowering the bar from 0.9/0.6 to 0.8/0.4 caught 26 more of 1,581 standalone shells and lifted injected-shell detection from 85% to 91%, for benign false positives rising from 1.4% to 1.9% (test/run train reports the sweep). A file the model scores 0.8 or more reaches the anomaly / HIGH RISK bar of 8 on the ML alone, and a moderate ML score can lift a file with some rule evidence over it. Above the bar the points keep climbing, reaching the critical bar of 15 at 0.95 (ML_CRITICAL) and 17.3 at 1.0: the rule score grows with file size, one weight per matched needle, so a large CMS file collects points a small shell never does, and a confident model should outrank that. Held out, this puts 95.9% of standalone shells in critical instead of 72.9% (injected 72.8% to 84.9%), for benign files in critical rising from 0.3% to 0.6%; which files are flagged at all doesn't change. Each row shows the split (rules 3.2 + ML 4.0) and an ML +x badge when the model contributed.

The final score is rounded to two decimal places.

Anomaly Classification

A file is considered anomalous when one or more statistical or security conditions are satisfied.

Conceptually:

$$ \begin{array}{rl} \text{anomaly} = & \text{Score} \geq 8 \ & \lor \enspace Z_{\mathrm{entropy}} > T \ & \lor \enspace |Z_{\mathrm{mtime}}| > T \ & \lor \enspace |Z_{\mathrm{gap}}| > T \ & \lor \enspace \text{rare owner} \end{array} $$

Where:

  • $\text{Score}$ = the threat score above, including ML points
  • $Z_{\mathrm{gap}}$ = Z-score of the ctime − mtime gap
  • $T$ = configured Z-score threshold
  • $\lor$ = logical OR

SussyFinder additionally treats the following as anomalies:

  • Blacklisted files
  • Unreadable files

File size (Z_size), the suspicious-token count Z-score (Z_suspicious) and the residual are computed and shown in the interface, but none of them decides anomaly status. Tested against real webshells, none of them caught a webshell the other signals missed, and each flagged legitimate files: codebases routinely contain very large files, or files full of routine calls. The weighted threat score already covers "many suspicious tokens".

.htaccess files and byte-identical duplicates get their own badges and counters, but neither is flagged as an anomaly for that alone. A shared Apache config file or a stock duplicate (e.g. WordPress's many identical "Silence is golden" index.php stubs) isn't suspicious by itself. Only content and threat signals decide anomaly status.

Threat Matrix

The first chart plots the two parts of the threat score against each other. Its y-axis is the rule score on a log scale, because it runs from 0 to the thousands and the anomaly bar at 8 must stay visible. Its x-axis is the ML score. The dashed lines are the scanner's own bars (ANOMALY_SCORE 8 and ML_THRESHOLD 0.8), so each quadrant says which detector flags a file. Each dot is coloured by the file's verdict, as in the table: critical, anomaly or not flagged. Without a model, the x-axis shows the share of a file's tokens that are needles.

On held-out data, most shells land in the top right, where both detectors agree, and almost no legitimate files do. Most of the rules' false positives sit in the top left, so a file there is worth reading before acting on it. test/run train prints the current split of shells and legitimate files per quadrant, scored by models that never saw the file.

ML Model

A tiny machine-learning model gives a second opinion. It is a logistic regression with 2048 int8 weights, stored as a 4 KB file, ml-model.json, in this repository. Like the rest of the scoring it runs in plain JavaScript in the browser, with no WebAssembly or library needed.

For each file, PHP's mlFeatures() turns the token stream into a set of short feature strings:

  • token-type bigrams (T_VARIABLE (, T_EVAL (, …)
  • names of called functions and of variables
  • the shape of string literals: length bucket, base64-looking, \x.. escapes
  • bucketed longest-line length, token count and entropy

Each string is hashed into one of 2048 buckets with crc32, and the bucket set is sent as a 512-character hex bitmap (ml_features). The browser adds up the weights of the set bits:

$$ P_{\mathrm{ML}} = \sigma\left(b + s \sum_{i \in \text{set bits}} w_i\right) $$

$P_{\mathrm{ML}}$ is a ranking score from 0 to 1, not a calibrated probability. It is turned into threat points (see ML Points), so it can only raise a file's score, never lower it: the model can add flags but never clears one. .htaccess files aren't scored. The score appears in each row's details and as a sort order.

Per-unit scoring

A backdoor is usually injected into a legitimate file rather than dropped as its own file, and the surrounding legitimate code dilutes the whole-file feature set until the model stops seeing the shell. To counter that, mlFeatures() is run not only on the whole file but on each top-level function and class on its own, plus a head and a tail window where an inline shell pasted at the top or bottom of a file lands (mlFeatureUnits()), and the page scores every unit. With $\tau$ the unit floor (ML_UNIT_FLOOR):

$$ P_{\mathrm{ML}} = \max\left(P_{\text{whole file}},\ \max_{\text{unit } u}\ \lbrace P_u : P_u \ge \tau \rbrace\right) $$

A single function counts as a shell on its own only if it independently clears $\tau$ (the same bar a whole file clears to be flagged) — so a shell's own function stays visible however much benign code surrounds it, while a benign function that merely looks odd in isolation is ignored. Because the whole-file score is always one of the terms, this never lowers a file's score, so clean-file detection can't regress; it only lifts files whose shell was being diluted. Each unit is scored with its own entropy (not the whole file's), so a packed, high-entropy payload isolated in one unit still reads as high-entropy. The extra per-unit bitmaps travel in ml_units, alongside the whole-file ml_features. Files too small for surrounding code to dilute a shell (below ML_UNIT_MIN_FILE_TOKENS tokens) send no ml_units at all, and a file with no top-level functions or classes and too few tokens for a head/tail split sends none either, so the many tiny files in a scan stay light. The model itself is unchanged — same features, same ml-model.json — so an older install that doesn't send ml_units simply scores the whole file as before. test/run train and test/run bench report detection on injected shells beside the same shells on their own, which is where this earns its keep.

Where the model comes from

Like the whitelist and blacklist, the model isn't built into main.php. When the page loads, the server downloads ml-model.json from this repository over verified TLS. Retraining therefore updates every install without anyone replacing main.php.

  • Validation: the file must match a strict format (fixed keys, digits and hex only) before it reaches the page.
  • Version check: the file carries the feature version it was trained on (ML_FEATURE_VERSION). If that doesn't match the installed main.php, the model is refused, because those scores would be meaningless.
  • Failure: if the download fails, the file is malformed or the versions differ, the page shows a warning and ML is off for that scan. The server also skips ML feature extraction for that scan.
  • Self-hosting: to pin a model or work offline, set _ML_MODEL_URL_ to another URL or to a local file path.

To turn the model off, set _ML_ to false (see Configuration). The server then skips mlFeatures(), which saves a large share of the per-file analysis time and 512 bytes of JSON per file. The page shows no ML scores, badges or sort option, and detection falls back to the rules alone.

Training data

The samples live in test/corpora/: webshell collections in positive/ and legitimate frameworks and CMSs across many releases in noise/, one submodule each; .gitmodules lists them all. test/README.md maps the whole test tree.

Every sample is a git submodule pinned to an exact commit. Its folder sets its label: positive is a shell, noise is legitimate code. In .gitmodules, a sample entry can also carry family (corpora held out together in cross-validation, such as every WordPress release), subdir (the part of a repository that holds samples) and benchmark = true (part of the quick benchmark set). Git ignores these extra keys; the test tooling reads them. The samples are:

  • Webshells: public webshell collections, plus well-known standalone shells.
  • Legitimate code: frameworks and CMSs such as Laravel, Symfony, Drupal, Joomla, Magento, WordPress and Open Journal Systems, each across many releases from old to current. A project that keeps its core in a nested submodule (OJS and its pkp-lib) has that core added as a sample of its own, since samples are checked out without nested submodules.

Submodules aren't downloaded by a normal clone. Fetch what you need:

test/run setup            # the benchmark set
test/run setup --phtest   # the legacy PHP builds
test/run setup --all      # every sample (many GB)

Corpus submodules are marked shallow, so a corpus pinned to a branch tip downloads a single commit. Old releases pinned below the tip come with some history.

Warning: the webshell corpora are real, working shells. They are only read and tokenized, never executed, but keep the checkout out of any web root. Inside a directory your web server runs PHP from, they are live backdoors.

Before training, the data is cleaned by:

  • removing exact duplicates by MD5
  • removing .htaccess files
  • removing shell-collection files with no server code at all, such as README pages. A file counts as server code when it holds PHP or main.php's @foreign_code rule sees ASP, JSP or Perl CGI in it; the benchmark uses the same test
  • removing files listed in test/corpora/not-shells.txt: files that ship inside the webshell collections but aren't shells (libraries such as a bundled packer, configuration files, phpinfo() pages, include stubs). They are matched by MD5, so every copy is dropped from both training and the benchmark

Accuracy

test/run train reports 5-fold cross-validated rates, so every file is scored by a model that never saw it. Run it for current figures:

  • Near-identical shells (feature-set Jaccard ≥ 0.8) share a fold, so a variant of a training shell can't count as a detection.
  • Whole project families share a fold, for example every WordPress version. So false positives are always measured on projects the model never trained on.
  • Folds and the per-corpus cap of legitimate training files are chosen by hashes, not a random stream, so adding or reordering samples only moves the samples that changed, and results are comparable across commits.

test/run train also runs the harder injected test: each PHP shell inserted into a legitimate file of its own fold (a model that holds the shell out never saw the host's project family either), the way real backdoors arrive, built by test/php/inject.php. It prints detection on the injected files beside the same shells on their own, so the gap shows how much surrounding legitimate code hides a shell — the gap per-unit scoring is there to close. --augment also trains on those injected copies. test/run bench and test/run matrix run a smaller injected check over the benchmark set.

The five fold models and the final model train at the same time in worker threads. Extracted features are cached in test/corpora/.rows/, one file per sample commit, and re-extracted only when main.php's extractor or test/php/extract.php changes.

Things to keep in mind:

  • The score ranks files; it isn't a calibrated probability. A low score does not mean a file is safe.
  • The weights are public in ml-model.json, so a determined attacker can write a shell that scores low. The model is a second opinion beside the rules, not a replacement.
  • Every webshell comes from public collections, which lean towards older, well-known shells. There is no held-out set of new, unpublished shells.
  • ASP/JSP/CGI shells saved with a PHP name contain no PHP for either detector to read. The @foreign_code rule catches those instead.

Options:

  • --write: retrain on all the data and write ml-model.json. Bump ML_FEATURE_VERSION first whenever mlFeatures() or ML_BUCKETS changes, so older installs refuse the new model instead of mis-scoring with it.
  • --check DIR: report how many files in a directory you trust (for example your own codebase) the model would flag.
  • --by-family: print false positives per legitimate project family.
  • --list: print held-out misses and false positives.
  • --cap N: the maximum number of legitimate files per corpus used in training (default 2000, so huge projects don't drown out the rest).

Testing

Every test runs through one command, test/run; test/README.md explains the layout.

test/run                  # the commands
test/run setup            # fetch the benchmark samples (once)
test/run all              # unit + bench + ui, with a summary: run before a commit
  • test/run unit: unit tests in a few seconds, with no samples and no Docker. In PHP, it checks the structural detectors on snippets (calls through variables, names hidden in strings, preg_replace with /e, ASP/JSP/Perl in PHP-named files and more). It also checks which names the directory listing returns (a FIFO, a symlink leading outside, a non-UTF-8 name), that listing a page at a time returns the same files and that a made-up resume point stays inside the directory, and which ml-model.json files main.php accepts. In JS, it checks labelling, feature decoding, fold and cap stability, training, that the trainer's scorer equals main.php's mlScore(), and that moving the Z-threshold re-flags exactly like a full rescore.

  • test/run bench: the PHP self-check, then the real feature extraction and the real client-side scoring from main.php over the benchmark set (the samples marked benchmark = true in .gitmodules: webshells mixed with legitimate code). It prints detection and false-positive rates. Timestamps are zeroed because the corpora were copied at different times, so the ctime/mtime and owner signals aren't measured. Files in the webshell corpus with no server code at all aren't counted as missed shells; the run lists them by name. Its ml only line is in-sample for the model, so use test/run train for held-out rates. Options:

    • --list: print missed webshells and false positives
    • --tokens: print per-token webshell vs. benign counts, for tuning weights
    • --threshold 3.5: the Z-score threshold to evaluate (default: main.php's Z_THRESHOLD)
    • --no-ml: score with the rules alone
    • --dump rows.json: save every scored row, for analysis
  • test/run matrix: the same on every PHP version (test/run matrix --help lists the defaults; --php all adds PHTest's legacy builds) under each php.ini profile, in Docker:

    • default: the image's own php.ini
    • hardened: shared-hosting style, with no exec family, no cURL and no remote fopen
    • minimal: no json_encode, no json_decode and no cURL (as on PHP < 5.2)

    Each also gets a page/AJAX check. It ends with a table and lists files that match differently than on the newest PHP. test/run setup --docker pulls the images.

  • test/run ui: drives the page in headless Chrome with real mouse and keyboard events. It covers chart selection, hover linking, filters, the threshold control, zoom, HiDPI sizing and resizing, and checks that a file named a');alert(1);('.php runs no script and that a file on a local checksum list scans as verified. It runs search queries against the same conditions written out, and checks / and Esc and the infinite scroll. A second scan with tiny listing pages, three batches at once, fake busy (503) and failing (500) replies and a cancel-and-rescan must find exactly what a plain scan found. It scans a temporary copy of the samples with the whitelist and blacklist off, so nothing is deleted. It finds Chrome or Chromium on PATH or through CHROME_BIN, and skips when there is none (--require-browser makes that a failure).

  • test/run perf: times a scan through the real page in headless Chrome and measures the browser memory its results take, on a copy of whole benign releases (--files, --latency, --define MAX_PARALLEL=1, --main for an older main.php).

  • test/run train: see Accuracy.

  • test/run checksums: builds checksums.txt from the benign corpora (see Vendor Checksums); --write saves it. Rerun it after retraining the model or changing the rules, since which release files come near the anomaly bar depends on both.

Requirements

  • PHP 4.3 / 5.x / 7.x / 8.x (with token_get_all support); Malware Hash Registry lookups need PHP 5.2+
  • Web server (Apache, Nginx, etc.) or PHP built-in server
  • Internet access (optional) to fetch whitelist/blacklist from GitHub – can be disabled via constants

Usage

  1. Place main.php (or whatever you name it) in a web-accessible directory.

  2. Access the file through your browser.

  3. Enter the absolute or relative path of the directory you wish to scan.

  4. Click SEARCH – the tool will recursively scan and analyse every file whose name matches $pattern: PHP-like and SSI extensions (.php, .phtml, .inc, .shtml, …), names with php as an inner extension (x.php.jpg, shell.php., which Apache's AddHandler runs as PHP), .htaccess, .user.ini and php.ini.

  5. Review the results table – files with anomalies are marked with ⚠️.

  6. Use the control bar to sort, filter, or copy the results.

    • Blacklisted files are automatically deleted – ensure you trust the blacklist source.
  7. Click on any file path to copy it; the 📋 icon copies its MD5 hash.

  8. MHR SCAN looks the hashes up in Team Cymru's Malware Hash Registry and deletes files it flags. The server re-checks each file's current hash with MHR before deleting, so only confirmed matches are removed.

Configuration

Every setting is a constant at the top of main.php, defined with settingDefault(). Change it there, or leave main.php untouched and define the constant first, e.g. from a file named in php.ini's auto_prepend_file:

<?php
define('_BLACKLIST_', false);                    // never delete anything
define('_ML_MODEL_URL_', '/srv/ml-model.json');  // offline copy of the model
Setting Default Meaning
_WHITELIST_, _BLACKLIST_ true use the known-good / known-bad MD5 lists
_MHR_ true Malware Hash Registry lookups
_CHECKSUMS_ true show files identical to an official release as verified, their score held down (Vendor Checksums)
_MHR_USER_, _MHR_PASS_ empty MHR account, used when the page sends none
_ML_ true ML second opinion
_WHITELIST_URL_, _BLACKLIST_URL_, _ML_MODEL_URL_ this repository where the lists and the model come from (each may be a local file)
_MHR_URL_ https://hash.cymru.com/v2/submitHashes MHR endpoint
_CHECKSUMS_URL_, _WP_CORE_CHECKSUMS_URL_, _WP_PLUGIN_CHECKSUMS_URL_ this repository, api.wordpress.org, downloads.wordpress.org where the vendor checksums come from; the WordPress ones are templates with {version}, {locale}, {slug} (each may be a local file)
TIME_LIMIT 3600 seconds a request may run
LIST_PAGE_FILES 20000 files per listing request; a page also ends after 40% of max_execution_time (1–10 s). 0: the whole list in one request
MAX_PARALLEL 3 batches analysed at once, at most; 1 sends one at a time
TABLE_PAGE_ROWS 500 rows the table draws at a time, the next ones as you scroll; 0: all at once
ANOMALIES_ONLY_ABOVE 10000 a scan of more files starts on the "Only Anomalies" filter; 0: never
CACHE_DIR a sussyfinder-… folder in the system temp folder where downloaded lists, checksums and the model are kept until deleted ('': no cache)
HTTP_CONNECT_TIMEOUT, HTTP_TIMEOUT 10, 30 download timeouts in seconds
MHR_BATCH 1000 hashes per MHR request
LONG_LINE_BYTES, HALT_PAYLOAD_BYTES 5000, 1024 thresholds of the @long_line and @halt_payload signals

Which files are scanned ($pattern), the needles and their weights ($tokenTiers), and how they combine in the threat score ($tokenRoles) follow the settings. The page's scoring reads the weights and roles from the server, so they are defined in one place.

main.php copes with the host by itself: a function in disable_functions (set_time_limit, ini_set, cURL, json_encode) is skipped or replaced, downloads use cURL or else PHP's URL streams, and PHP 8's new tokens (namespaced names, attributes, &) and the host's short_open_tag are normalised, so PHP 7.4 and 8.x extract identical features.

Whitelist & Blacklist

  • Whitelist – MD5 sums of known-safe files (e.g., from popular frameworks). These files are skipped entirely to speed up scanning.
  • Blacklist – MD5 sums of known malware. Files matching these are automatically unlinked (deleted) and flagged in the output.

By default, both lists are fetched from:

  • https://raw.githubusercontent.com/Cvar1984/sussyfinder/main/whitelist.txt
  • https://raw.githubusercontent.com/Cvar1984/sussyfinder/main/blacklist.txt

You can turn either list off by setting _WHITELIST_ or _BLACKLIST_ to false (see Configuration). Downloads are kept in a cache folder until it is cleared, so batches and later scans don't download them again. It is a private folder of this install's own (sussyfinder- and a hash of its path) in the system temp folder, found the way the host allows: sys_get_temp_dir(), else upload_tmp_dir, TMPDIR / TMP / TEMP, /tmp (CACHE_DIR overrides it). On a shared host other accounts use the same temp folder, so the cache is only trusted when it belongs to the user PHP runs as and no one else can write to it; a folder someone else created is refused with a warning, since a planted blacklist would delete files. Refresh lists, next to the Scan button, deletes the cache, so the next scan pulls the latest lists and checksums, and offers to reload the page for the latest ML model; deleting the folder does the same. Its tooltip says what is cached and since when. Without a usable cache folder every batch downloads the lists again. Downloads ask for gzip where the host's cURL or PHP 5.4+ can decode it (whitelist, blacklist and checksums.txt: 0.6 MB instead of 1.5 MB). On a host that should not fetch them at all, point the URL settings at local copies. They stay on the server, so the browser can't substitute its own blacklist. Downloads use verified TLS, because the blacklist deletes files: a host without a CA bundle gets a warning and scans without the lists rather than trusting an unverified source.

Note: The provided whitelist is harvested from common frameworks and libraries. It is up to you to trust or modify it. For blacklist contributions, please provide source files when creating a pull request.

Vendor Checksums

Most false positives are vendor code: framework and CMS files that legitimately use eval, exec, base64_decode or dynamic calls. Rules and the model judge content, so they can't tell those apart from a shell; a checksum can. A file whose MD5 equals the one an official release ships at that path gets a VERIFIED badge naming the release, beside its other badges and matched tokens. Its threat score is held below half the anomaly bar: it saturates as $4 \cdot s/(s+4)$ of what its content scored ($s$), so a verified file is never flagged or critical, and verified files keep their order among themselves (7 becomes 2.55, 466 becomes 3.97). Its statistical triggers (entropy, dates, owner) don't count either, since its bytes are the vendor's. The blacklist and MHR still win: either lifts the file to 100. The badge's tooltip shows what the content scored.

The sources, in the order they are checked:

  • WordPress core: each install is found by walking up to wp-includes/version.php, whose $wp_version and $wp_local_package pick that version's checksums from api.wordpress.org (falling back to en_US). These APIs return JSON, read with json_decode() (PHP 5.2+, like the MHR lookup); an older PHP skips them and uses checksums.txt alone.
  • wordpress.org plugins: for a file under wp-content/plugins/<slug>/, the plugin's Version: header picks its checksums from downloads.wordpress.org. A premium plugin isn't there (a 404, asked once per scan) and is scanned as usual. Themes have no official checksums.
  • checksums.txt in this repository: release files of 57 platforms (Drupal, Joomla, Magento, PrestaShop, Laravel, Symfony and more), built by test/run checksums --write from the releases in the test corpora. It lists only the release files the scanner comes near flagging (flagged, or a threat score of at least 4): 14,217 files, 1.24 MB, so it downloads quickly; every other release file isn't flagged anyway. A file's path must end the way it does in the release (…/vendor/laravel/framework/src/Illuminate/…), so the release can be installed anywhere.

Why this can't hide a shell: injecting a shell into a vendor file changes its MD5; a shell dropped anywhere else isn't in any release; and making a file match an existing MD5 takes a second preimage, which is out of reach even for MD5 (its known weakness, collisions, needs the attacker to create both files). MD5 rather than SHA-256 because PHP 4.3 has no hash(). No MD5 that also occurs in the webshell corpora or the blacklist is ever listed.

What it doesn't cover: modified files, custom themes and code, premium plugins, and release versions no list has hashed; those are scanned as usual. What it does trust: an official release that was itself backdoored (hijacked or sold plugins have shipped malware). The badge names the release, so such a file is easy to look up.

Both WordPress sources are rows of $checksumSources in main.php's configuration: a marker file that identifies an install, where the version (and locale) are read, the manifest URL and the label. A platform that publishes per-file MD5s in the same JSON shape needs only another row. The checksums are cached like the hash lists, a missing one (a premium plugin's 404) too, until Refresh lists clears them. A host that doesn't answer is warned about once, and the scan carries on without that source. Turn it off with _CHECKSUMS_ set to false, or point the URLs at local copies on an offline host.

Screenshots

Charts Results table

The test samples are git submodules; see Training data for how to fetch them.

Security & Disclaimer

This tool is intended for system administrators and security researchers. It performs aggressive file operations (deletion) and may produce false positives. Always audit flagged files before any automatic action. The author is not responsible for any data loss or damage caused by the use of this software.

Protections built in: a CSRF check on every request (a custom header another site can't send), server-side MHR confirmation before any MHR deletion, verified TLS for list downloads, and file names treated as untrusted data in the page (an attacker who planted a file chooses its name).

Contributing

Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change. Please ensure tests are updated appropriately.

License

GNU General Public License v3.0

探索相关项目

加载中…