Skip to content

About

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

Topics

Resources

Code of conduct

Contributing

Stars

78 stars

Watchers

1 watching

Forks

Repository files navigation

SussyFinder

PRs Welcome

SussyFinder finds webshells and other malicious PHP on a web server. It is one PHP file: drop it on the host, open it in a browser, point it at a directory. The server reads and tokenizes every PHP-like file; the browser scores each one with weighted rules, a small ML model and statistics over the whole site, then lists the suspicious files first.

Keep an eye on:

  • It deletes files. A file whose MD5 is on the blacklist is deleted as soon as it is found. Set _BLACKLIST_ to false for a read-only scan.
  • It has no login. Anyone who can open the page can scan the server. Give it an unguessable name, protect it with HTTP auth, or remove it after use.
  • A flag is a lead, not proof. Legitimate code can look suspicious, and a determined attacker can write a shell that scores low. Read a flagged file before acting on it.
  • The test samples are live shells. Keep a checkout of this repository out of any web root.

Results

Charts

Search

How it works

flowchart LR
    subgraph Browser
        A[Scan] --> B[List files<br>page by page]
        B --> C[Send batches<br>in parallel]
        C --> D[Score each file<br>rules + ML]
        D --> E[Score the site<br>statistics]
        E --> F[Table, charts, search]
    end
    subgraph Server [main.php on the host]
        L[listFiles] -.-> B
        P[process: read, hash,<br>tokenize, extract features] -.-> C
        N[(Downloads: blacklist, whitelist,<br>checksums, ML model)] --> P
    end
Loading
  1. List. The server walks the directory and returns the files whose names match $pattern, a page at a time, so a big site never runs into the host's time limit.
  2. Process. Batches of files go back to the server, several at once. For each file it computes the MD5, skips whitelisted files and files identical to an official release, deletes blacklisted ones, and extracts the byte entropy, the matched needles and structural signals, and the ML feature bitmaps.
  3. Score. The browser turns each row into a threat score (rules plus ML points), then, once every file is in, compares each file with the rest of the site.
  4. Review. The worst files come first; badges say why each one is listed.

Everything a scan needs is in main.php, in numbered sections:

Section Role
1. Configuration settings, $pattern, needles ($tokenTiers), how they combine ($tokenRoles), checksum sources
2. Compatibility one place for every PHP version and host difference
3. Helpers request input, file deletion, warnings
4. Detection engine listing, tokenizer, needle matching, structural signals, entropy, ML features
5. Network downloads, the cache, hash lists, checksums, the model, MHR
6. Actions the AJAX endpoints: scan, process, mhr_check, mhr_unlink, clear_cache
7. Bootstrap runs the request
8. Page HTML, the scoring block and the interface

The repository:

main.php           the scanner
ml-model.json      model weights, downloaded by every install
checksums.txt      release-file checksums, downloaded by every install
whitelist.txt      known-good MD5s
blacklist.txt      known-bad MD5s
screenshots/       images for this file
test/              tests, benchmark and model training (test/README.md)

How a file is scored

flowchart TD
    F[File] --> W{Whitelisted or an<br>official release file?}
    W -- yes --> SK[Skipped]
    W -- no --> T
    T[Matched needles and signals] --> R[Rule score]
    M[ML features] --> P[ML score P] --> MP[ML points]
    R --> S[Threat score]
    MP --> S
    S --> K{Blacklist or MHR?}
    K -- yes --> H[Score 100]
    K -- no --> Z[Compared with the whole site]
    H --> Z
    Z --> X{Anomaly?}
Loading

Rule score

Each distinct needle $n$ matched in the file adds its weight $w_n$ from $tokenTiers. Needles are code tokens (eval, base64_decode, $_POST, ...) and structural signals prefixed with @:

Signal Meaning
@input_call calls a request value: $_GET['a']($_GET['b'])
@assert_exec assert() of a string or request value
@callback_exec an execution function passed by name: array_map('assert', ...)
@input_include, @wrapper_include include of a request value, or of a php:// or data: stream
@preg_e, `, @com_exec preg_replace with /e, backticks, new COM('WScript.Shell')
@foreign_code ASP, JSP or Perl CGI inside a PHP-named file
@concat_name a function name hidden in a string: 'ba'.'se64_decode'
@halt_payload, @long_line, @dyn_call data after __halt_compiler(), a giant line, a call through a variable

A name counts only as a global call, so $db->exec() or new System() does not match exec or system. The needles combine through $tokenRoles:

$$ S_{\mathrm{rules}} = m \sum_{n \in N} d_n w_n + b $$

  • $N$ is the set of distinct matched needles.
  • $d_n$ dampens obfuscation and upload needles when the file has no critical (execution) needle: compression, mail and upload code use them legitimately.
  • $m$ multiplies the score when a critical needle meets obfuscation, upload handling or user input.
  • $b$ adds bonuses: real code in an uploads folder, a suspicious folder (upload, cache, tmp, images, media) for a file that already scores, high entropy, and two or more server-reconnaissance calls (php_uname, get_current_user, ...).

ML score

mlFeatures() turns a file's tokens into short strings (token-type bigrams, called function and variable names, the shape of string literals, bucketed line length, token count and entropy) and hashes each into one of ML_BUCKETS buckets. The model is a small neural network over the set bits: one hidden layer of ReLU units $h_j$, whose first-layer weights $w_{ij}$ are stored as int8 with one scale $s_j$ per unit, and a sigmoid output:

$$ h_j = \max\left(0,\ b_j + s_j \sum_{i \in \mathrm{bits}} w_{ij}\right), \qquad P = \sigma\left(b_0 + \sum_j v_j h_j\right), \qquad \sigma(x) = \frac{1}{1 + e^{-x}} $$

A hidden layer lets features count together (a request value is ordinary, a request value next to eval is not), which a plain weighted sum can't express.

A shell injected into a large legitimate file is diluted by the code around it, so each top-level function and class, plus a head and a tail window, is also scored on its own. A unit counts only when it clears $\tau$ (ML_UNIT_FLOOR) by itself:

$$ P = \max\left(P_{\mathrm{file}},\ \max_u \left\lbrace P_u : P_u \ge \tau \right\rbrace\right) $$

$P$ becomes threat points, rising from nothing at ML_FLOOR ($p_0$) through the anomaly bar $A$ (ANOMALY_SCORE) at ML_THRESHOLD ($p_1$) to the critical bar $C$ (CRITICAL_SCORE) at ML_CRITICAL ($p_2$), and on:

$$ \mathrm{points}(P) = \left\lbrace \begin{array}{ll} 0 & P \le p_0 \\ A \displaystyle\frac{P - p_0}{p_1 - p_0} & p_0 < P < p_1 \\ A + (C - A) \displaystyle\frac{P - p_1}{p_2 - p_1} & P \ge p_1 \end{array} \right. $$

The model can only add points, never remove them. The thresholds favour recall: a missed shell costs more than a false positive.

Threat score

$$ S = R\left(S_{\mathrm{rules}}\right) + \mathrm{points}(P), \qquad R(x) = \left\lbrace \begin{array}{ll} x & x \le C \\ C + k \ln\left(1 + \displaystyle\frac{x - C}{k}\right) & x > C \end{array} \right. $$

The rule score grows with the number of needles a file matches, so a large framework file can collect hundreds of points. Above the critical bar $C$ it therefore counts only logarithmically ($k$ is RULE_SPREAD): flags don't change, but among critical files the ML score decides the order, so a confident shell isn't buried under big vendor files. Each row shows the split, for example rules 21.1 of 466 + ML 17.3. Files with equal scores are listed most recent first.

A blacklist or MHR match lifts the score to 100.

Site statistics

Entropy is measured over each file's bytes, where $p_i$ is the share of byte value $i$:

$$ H = -\sum_{i} p_i \log_2 p_i $$

Plain source stays below HIGH_ENTROPY; packed or encoded payloads go above it.

A file is compared with the rest of the site through robust Z-scores, built on the median $\tilde{x}$ so the outliers being hunted can't drag the baseline toward themselves:

$$ Z = \frac{x - \tilde{x}}{s}, \qquad s = 1.4826 \cdot \mathrm{median}\left( \left| x_i - \tilde{x} \right| \right) $$

When more than half the values are equal, $s = 1.2533 \cdot \frac{1}{n} \sum_i \left| x_i - \tilde{x} \right|$ instead. Z-scores are computed for size, modification time, tokens, suspicious-token count, entropy and the gap between ctime and mtime: an attacker can backdate mtime with touch but not ctime.

Anomaly

$$ \mathrm{anomaly} = \left(S \ge A\right) \lor \left(Z_{\mathrm{entropy}} > T\right) \lor \left(\left| Z_{\mathrm{mtime}} \right| > T\right) \lor \left(\left| Z_{\mathrm{gap}} \right| > T\right) \lor \mathrm{rare~owner} $$

$T$ is the Z-threshold in the page (default Z_THRESHOLD). A rare owner owns only a small share of the site's files, such as the web server user among files deployed over FTP. Blacklisted, MHR-flagged and unreadable files are always anomalies. Critical means $S \ge C$.

Search

Press / to search and Esc to clear; the ? button lists every form with clickable examples.

Query Finds
eval base64, eval OR assert, -vendor, (a OR b) all words, either word, without, groups
"exact text", /regex/ a phrase, a regular expression
path: name: dir: token: ext: md5: owner: one property
score:>=15 ml:>80 size:>100k entropy:>5.5 hits:3..10 numbers and ranges
date:7d, date:2025-06, date:>=2025-01-01 recent, a period, before or after
is:critical, is:anomaly, is:blacklisted, ... badges and flags
near:"/path/file.php", near:is:blacklisted~6h files in the same folder as the targets, or changed close to them in mtime or ctime

near:is:blacklisted -is:blacklisted shows what else an intruder dropped or edited. A time shared by a large part of the site (a deploy or a restore) says nothing and is skipped; the box's tooltip says so.

Hash lists, checksums and the model

  • Whitelist: known-good MD5s, skipped. Blacklist: known-bad MD5s, deleted. Both come from this repository; contributions to the blacklist should include the file.
  • Vendor checksums: a file identical to an official release file is skipped like a whitelisted one, unless the blacklist names it. WordPress core and wordpress.org plugin checksums come from WordPress's APIs; checksums.txt covers release files of other projects that the scanner comes near flagging. A path must end the way it does in the release, and changing one byte changes the MD5, so a shell can't hide behind a checksum. An official release that was itself backdoored is skipped too; set _CHECKSUMS_ to false for a full audit.
  • ML model: ml-model.json is downloaded like the lists, so a retrain reaches every install. A model trained for a different feature version (ML_FEATURE_VERSION), or in a format an older main.php doesn't read, is refused with a warning and ML scoring is off until main.php is updated.

Downloads use verified TLS, because the blacklist deletes files. They are kept in a private cache folder until Refresh lists clears it; on shared hosting a cache folder that another account could write to is refused.

Compatibility

main.php runs on PHP 4.3 and every later version, and adapts to the host by itself:

Situation What happens
Old PHP PHP 4 syntax only; missing functions are checked with functionAvailable() before use
Functions in disable_functions skipped or replaced (set_time_limit, ini_set, json_encode, cURL)
No json_encode / json_decode jsonEncode() writes JSON itself; MHR and the WordPress APIs need PHP 5.2+ and are skipped without them
No cURL downloads use PHP's URL streams
No CA bundle downloads are refused with a warning rather than trusted unverified
PHP 8 tokens, short_open_tag normalised, so every PHP version extracts the same features
Short max_execution_time the file list comes in pages that each end within the limit
Busy or throttled host fewer requests at once, retried after a wait
A file that crashes PHP its batch is split until that file is found and skipped by name
Names that aren't UTF-8 paths travel percent-encoded, byte for byte
Symlinks, FIFOs symlinked folders aren't followed, FIFOs are skipped
Shared temp folder the download cache is used only when it belongs to the PHP user

The page needs a current browser (ES2015 JavaScript).

Configuration

Every setting is a constant near the top of main.php, created with settingDefault(); the default and a short comment sit next to each. Either edit them there, or leave main.php untouched and define the constant before it runs:

<?php
// prepend.php, loaded through php.ini or .user.ini:
//   auto_prepend_file = /path/to/prepend.php
define('_BLACKLIST_', false);                   // never delete anything
define('_ML_MODEL_URL_', '/srv/ml-model.json'); // local copy of the model
Setting Meaning
_WHITELIST_, _BLACKLIST_, _CHECKSUMS_, _ML_, _MHR_ turn a feature on or off
_WHITELIST_URL_, _BLACKLIST_URL_, _CHECKSUMS_URL_, _ML_MODEL_URL_ where each download comes from: a URL or a local file
_WP_CORE_CHECKSUMS_URL_, _WP_PLUGIN_CHECKSUMS_URL_ WordPress checksum API templates ({version}, {locale}, {slug})
_MHR_URL_, _MHR_USER_, _MHR_PASS_ Malware Hash Registry endpoint and account
TIME_LIMIT, HTTP_CONNECT_TIMEOUT, HTTP_TIMEOUT request and download time limits
LIST_PAGE_FILES files per listing page; 0 lists everything at once
MAX_PARALLEL batches in flight at most; 1 sends one at a time
TABLE_PAGE_ROWS rows drawn at a time; 0 draws all
ANOMALIES_ONLY_ABOVE above this many files the table opens on "Only Anomalies"; 0 never
CACHE_DIR download cache folder; '' turns the cache off
MHR_BATCH, LONG_LINE_BYTES, HALT_PAYLOAD_BYTES MHR batch size and two signal thresholds

Next to the settings: $pattern (which file names are scanned), $tokenTiers (needle weights), $tokenRoles (how needles combine) and $checksumSources (where vendor checksums come from). The page reads all of them from the server.

Guide

What you need

  • PHP 4.3 or later with the tokenizer (built in on almost every PHP). PHP 5.2+ with OpenSSL for MHR lookups and WordPress checksums.
  • A web server, or PHP's built-in server (php -S, PHP 5.4+).
  • A current browser.
  • Read access to the files to scan, and write access to delete blacklisted ones.

Download main.php from this repository. Nothing else is needed; the lists and the model are fetched when a scan starts.

Shared hosting (cPanel, Plesk, FTP)

  1. Rename main.php to something unguessable, for example scan-7f3k2q.php.
  2. Upload it into the site's web root with the file manager or FTP.
  3. Open https://your-site/scan-7f3k2q.php, check the directory field (it starts at the script's own folder) and click Scan.
  4. Delete the file when you are done.

To keep it on the server, put it in a folder protected by HTTP auth (cPanel: Directory Privacy).

Linux

# Debian, Ubuntu
sudo apt install php-cli php-curl
# Fedora, RHEL
sudo dnf install php-cli
# Arch
sudo pacman -S php

mkdir ~/sussyfinder && cd ~/sussyfinder
curl -O https://raw.githubusercontent.com/Cvar1984/sussyfinder/main/main.php
php -S 127.0.0.1:8000

Open http://127.0.0.1:8000/main.php and enter the directory to scan, such as /var/www/html. Run php -S as a user that can read that directory; to let it delete blacklisted files it also needs write access.

On a remote server, keep the page private with an SSH tunnel instead of opening a port:

# on the server
php -S 127.0.0.1:8000
# on your computer
ssh -L 8000:127.0.0.1:8000 user@server

Then open http://127.0.0.1:8000/main.php locally.

To run it under Apache or Nginx instead, place it in a protected location of the document root; it needs no extra modules.

macOS

brew install php
mkdir ~/sussyfinder && cd ~/sussyfinder
curl -O https://raw.githubusercontent.com/Cvar1984/sussyfinder/main/main.php
php -S 127.0.0.1:8000

Open http://127.0.0.1:8000/main.php. To scan a folder under your home directory, grant your terminal Full Disk Access in System Settings if macOS blocks it.

Windows

  1. Download PHP (the Thread Safe zip) from windows.php.net and extract it, for example to C:\php.
  2. Copy php.ini-production to php.ini. Set extension_dir = "C:\php\ext" and remove the ; in front of extension=curl and extension=openssl, which the downloads need.
  3. Save main.php to a folder, for example C:\sussyfinder, then in PowerShell:
cd C:\sussyfinder
C:\php\php.exe -S 127.0.0.1:8000
  1. Open http://127.0.0.1:8000/main.php and enter a path such as C:\xampp\htdocs.

XAMPP, WampServer and Laragon work too: put main.php in their web root (htdocs or www) and open it through their local address.

Offline hosts

Download whitelist.txt, blacklist.txt, checksums.txt and ml-model.json from this repository, copy them to the host, and point the URL settings at them:

define('_WHITELIST_URL_', '/srv/sussyfinder/whitelist.txt');
define('_BLACKLIST_URL_', '/srv/sussyfinder/blacklist.txt');
define('_CHECKSUMS_URL_', '/srv/sussyfinder/checksums.txt');
define('_ML_MODEL_URL_', '/srv/sussyfinder/ml-model.json');
define('_MHR_', false);

Reading the results

  • Badges: CRITICAL and HIGH RISK with the score, ML +x when the model added points, BLACKLIST, MHR HIT, NOT READABLE, GONE (deleted or moved during the scan), HTACCESS, DUPLICATE.
  • Each row: the matched needles (critical ones highlighted), then size, tokens, entropy and the score split into rules and ML. Click a path to copy it; 📋 copies the MD5 and VT opens it on VirusTotal.
  • Filters and sorting apply to every file, not only the rows drawn so far.
  • Charts: drag a box on the Threat Matrix or Entropy chart, or click timeline bars (Ctrl or ⌘ adds), to select files; Esc clears the selection.
  • Copy puts every file the table shows on the clipboard, with its details.
  • MHR SCAN asks Team Cymru's Malware Hash Registry about every hash and deletes the files it confirms, after the server checks each file's current hash.
  • Refresh lists clears the download cache, so the next scan pulls the latest lists and checksums, and offers to reload the page for the latest model.

After a hit

  1. Read the flagged file; the matched needles show where to look.
  2. Search near:"<its path>" to list files in the same folder or changed at the same time.
  3. Remove the shell, then find how it got in: an outdated plugin, an upload form, a leaked password. Scan again afterwards.

Development

git clone https://github.com/Cvar1984/sussyfinder.git
cd sussyfinder
test/run setup     # fetch the benchmark samples
test/run all       # unit tests, benchmark and browser test
test/run train     # cross-validated model rates; --write retrains ml-model.json

The tests need Node.js and PHP; test/run matrix also needs Docker, test/run ui Chrome or Chromium. test/README.md describes every command, and RULES.md the code rules and the decisions behind the current design. The sample corpora are real shells: keep the checkout out of any web root.

Security and disclaimer

This tool deletes files and can report false positives. Audit flagged files before acting on them. The author is not responsible for data loss or damage caused by its use.

Built in: a CSRF header on every request, server-side MHR confirmation before an MHR deletion, verified TLS for downloads, an ownership check on the download cache, and file names treated as untrusted data in the page.

Contributing

Pull requests are welcome; open an issue first for larger changes. See CONTRIBUTING.md.

License

GNU General Public License v3.0

About

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

Topics

Resources

Code of conduct

Contributing

Stars

78 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages