3, 'medium' => 2, 'low' => 1 ); return isset( $map[ $sev ] ) ? $map[ $sev ] : 0; } /** * Detection patterns for PHP files: regex, label, severity. */ public static function signatures() { return array( array( '~\beval\s*\(\s*(?:@\s*)?(?:base64_decode|gzinflate|gzuncompress|gzdecode|str_rot13|convert_uudecode)\s*\(~i', 'eval() of an encoded payload', 'high' ), array( '~\bgzinflate\s*\(\s*base64_decode\s*\(~i', 'gzinflate(base64_decode()) payload', 'high' ), array( '~\b(?:eval|assert|create_function)\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE|SERVER)\b~i', 'Executes request input as code', 'high' ), array( '~\b(?:system|shell_exec|passthru|exec|popen|proc_open|pcntl_exec)\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Runs a shell command from request input', 'high' ), array( '~\$_(?:GET|POST|REQUEST|COOKIE)\s*\[[^\]]{1,40}\]\s*\(~', 'Calls a function named by request input', 'high' ), array( '~preg_replace\s*\(\s*([\'"])(.)(?:(?!\1).){0,200}?\2[a-df-z]*e[a-z]*\1\s*,~i', 'preg_replace() with the /e modifier', 'high' ), array( '~(?:FilesMan|c99shell|r57shell|b374k|WSO_VERSION|Weevely|alfa-?shell|IndoXploit)~i', 'Known webshell signature', 'high' ), array( '~\b(?:include|require)(?:_once)?\s*\(?\s*[\'"][^\'"\r\n]*\.(?:jpe?g|png|gif|ico)[\'"]~i', 'Includes an image file as code', 'high' ), array( '~\beval\s*\(\s*\$\w+\s*\(\s*\$\w+\s*\(~i', 'eval() of nested variable-function calls (obfuscated payload)', 'medium' ), array( '~(?:\\\\x[0-9a-f]{2}){25,}~i', 'Long hex-escaped string (obfuscation)', 'medium', true ), array( '~(?:chr\(\s*\d+\s*\)\s*\.\s*){8,}~i', 'Obfuscated chr() chain', 'medium', true ), array( '~base64_decode\s*\(\s*[\'"][A-Za-z0-9+/=\s]{300,}[\'"]~', 'Large inline base64 payload', 'medium' ), array( '~file_put_contents\s*\([^;]{0,120}\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Writes a file using request input', 'medium' ), // Running request input in other ways. array( '~(?:=|\becho\b|\bprint\b|\breturn\b|\()\s*@?\s*`[^`\r\n]{0,120}\$_(?:GET|POST|REQUEST|COOKIE)\b[^`\r\n]{0,60}`\s*[;)]~', 'Runs a shell command (backticks) from request input', 'high' ), array( '~\b(?:call_user_func(?:_array)?|forward_static_call(?:_array)?|register_shutdown_function|register_tick_function)\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Calls a function named by request input', 'high' ), array( '~\barray_map\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'array_map() with a callback taken from request input', 'high' ), array( '~\b(?:array_filter|array_walk|array_reduce|usort|uasort|uksort)\s*\((?:[^;(),]|\([^;()]*\)){1,100},\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\s*\[~i', 'Array callback taken from request input', 'high' ), array( '~\b(?:include|require)(?:_once)?\s*\(?\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Includes a file named by request input', 'high' ), array( '~\b(?:include|require)(?:_once)?\s*\(?\s*[\'"](?:data:|expect:|php://input)~i', 'Includes code from a data:, expect: or php://input stream', 'high' ), array( '~\b(?:eval|assert)\s*\([^;]{0,40}php://input~i', 'Executes the raw request body', 'high' ), array( '~\beval\s*\(\s*(?:@\s*)?(?:file_get_contents|curl_exec|stream_get_contents|fgets|fread|file)\s*\(~i', 'eval() of downloaded or file content', 'high' ), array( '~\$(\w+)\s*=\s*(?:@\s*)?(?:base64_decode|gzinflate|gzuncompress|str_rot13|convert_uudecode)\s*\([^;]{0,3000}?\)\s*;(?:[^;]{0,200};){0,4}?[^;]{0,200}?\beval\s*\(\s*\$\1\b~is', 'Decodes a payload into a variable and evals it', 'high' ), array( '~\$(\w+)\s*=\s*\$_(?:GET|POST|REQUEST|COOKIE)\s*\[[^\]]+\]\s*;\s*(?:@\s*)?\$\1\s*\(~s', 'Calls a function whose name came from the request', 'high' ), array( '~\$\w+\s*=\s*[\'"][a-z_]{1,12}[\'"]\s*\.\s*[\'"][a-z_]{1,12}[\'"]\s*;\s*(?:@\s*)?\$\w+\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~is', 'Builds a function name from pieces and runs request input through it', 'high' ), array( '~\$\w+\s*=\s*[\'"](?:ev|as|sy|ex|pa|sh)[\'"]\s*\.\s*[\'"](?:al|sert|stem|ec|ssthru|ell_exec)[\'"]\s*;~i', 'Function name (eval/assert/system/exec...) split into pieces to hide it', 'high' ), array( '~\bstrrev\s*\(\s*[\'"](?:lave|tressa|metsys|cexe|urhtssap|cexe_llehs|edoced_46esab|etalfnizg)[\'"]\s*\)~i', 'Reversed function name (obfuscation)', 'high' ), array( '~\bstr_rot13\s*\(\s*[\'"](?:riny|nffreg|flfgrz|rkrp|cnffgueh|furyy_rkrp)[\'"]\s*\)~i', 'ROT13 function name (obfuscation)', 'high' ), array( '~base64_decode\s*\(\s*[\'"](?:ZXZhbA|YXNzZXJ0|c3lzdGVt|ZXhlYw|cGFzc3RocnU|c2hlbGxfZXhlYw|Y3JlYXRlX2Z1bmN0aW9u)[A-Za-z0-9+/=]{0,8}[\'"]\s*\)~', 'Base64-encoded function name (obfuscation)', 'high' ), array( '~[\'"](?:\\\\x[0-9a-f]{2}){4,}[\'"]\s*\(~i', 'Function called by a hex-escaped name (obfuscation)', 'high' ), array( '~(?:chr\(\s*\d+\s*\)\s*\.\s*){3,}chr\(\s*\d+\s*\)\s*\(~i', 'Function called by a name built with chr() (obfuscation)', 'high' ), array( '~\bmd5\s*\(\s*\$_(?:GET|POST|REQUEST|COOKIE)\s*\[[^\]]+\]\s*\)\s*={2,3}\s*[\'"][a-f0-9]{32}[\'"]~i', 'Password-protected backdoor (md5 gate on request input)', 'high' ), array( '~GIF8[79]a[^\r\n]{0,40}<\?php~', 'PHP code behind a fake GIF header', 'high' ), array( '~\bob_start\s*\(\s*[\'"](?:eval|assert|system|shell_exec|passthru|exec)[\'"]~i', 'Output buffer handler that runs code', 'high' ), array( '~(?:coinhive|CoinHive\.Anonymous|cryptonight|coin-hive|authedmine|webminepool)~i', 'Crypto-miner reference', 'high' ), // Weaker or more context-dependent signs. array( '~\bcreate_function\s*\(~i', 'create_function() (removed from PHP, often used to hide code)', 'medium' ), array( '~\bpreg_replace_callback\s*\([^;]{0,300}?\beval\s*\(~is', 'preg_replace_callback() that calls eval()', 'medium' ), array( '~\b(?:base64_decode|gzinflate|gzuncompress|str_rot13)\s*\(\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Decodes request input (common in webshells, also in some normal plugins)', 'low' ), array( '~\bextract\s*\(\s*\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'extract() on request input (lets visitors set any variable)', 'medium' ), array( '~\bmove_uploaded_file\s*\(\s*\$_FILES\s*\[[^\]]+\]\s*\[\s*[\'"]tmp_name[\'"]\s*\]\s*,\s*(?:\$_(?:GET|POST|REQUEST)\b|\$_FILES\s*\[[^\]]+\]\s*\[\s*[\'"]name[\'"]\s*\])~i', 'Saves an upload under a name the visitor chose (shell uploader)', 'medium' ), array( '~\b(?:fwrite|fputs)\s*\(\s*\$\w+\s*,\s*(?:@\s*)?\$_(?:GET|POST|REQUEST|COOKIE)\b~i', 'Writes request input to a file', 'medium' ), array( '~\bmail\s*\(\s*\$_(?:GET|POST|REQUEST)\b~i', 'mail() with a recipient taken from request input (spam relay)', 'medium' ), array( '~\bwp_(?:insert|create)_user\s*\([^;]{0,300}[\'"]administrator[\'"]~is', 'Creates an administrator account in code', 'medium' ), array( '~\bwp_set_current_user\s*\(\s*[1-9]\d*\s*\)[^;]*;[^;]{0,200}wp_set_auth_cookie~is', 'Logs in as a fixed user ID in code (login bypass)', 'medium' ), array( '~(?:goto\s+\w+;\s*[A-Za-z0-9_]+:\s*){6,}~', 'Chain of goto jumps (control-flow obfuscation)', 'medium', true ), array( '~<\?php[ \t]{120,}\S~', 'Code pushed far to the right of the opening tag to hide it', 'medium' ), array( '~(?:pastebin\.com/raw|hastebin\.com/raw|paste\.ee/r/|raw\.githubusercontent\.com/[^\'"\s]{0,120}\.(?:txt|php))~i', 'Fetches code from a paste site', 'medium', true ), array( '~hacked\s+by\s+[A-Za-z0-9_.\-]{2,}~i', 'Defacement signature ("hacked by")', 'medium' ), array( '~<(?:div|span|p)[^>]{0,80}(?:display\s*:\s*none|left\s*:\s*-\d{3,}px|text-indent\s*:\s*-\d{3,}px)[^>]{0,80}>\s*(?:]*>~i', 'Script inside an SVG image', 'medium', false, 'svg' ), array( '~]*\bon(?:load|error|click)\s*=~i', 'Event handler on an SVG image', 'medium', false, 'svg' ), array( '~]{0,300}(?:width|height)\s*=\s*[\'"]?[01](?:px)?[\'"\s>]~i', 'Hidden (zero-size) iframe', 'medium' ), array( '~]{0,300}style\s*=\s*[\'"][^\'"]*(?:display\s*:\s*none|visibility\s*:\s*hidden)~i', 'Hidden iframe', 'medium' ), array( '~]{0,80}http-equiv\s*=\s*[\'"]?refresh[\'"]?[^>]{0,120}url\s*=\s*https?://~i', 'Automatic redirect to another site', 'medium' ), ); } /** * Detection patterns for JavaScript files. */ public static function js_signatures() { return array( array( '~\beval\s*\(\s*(?:atob|unescape|decodeURIComponent)\s*\(~i', 'eval() of a decoded string', 'medium' ), array( '~document\.write\s*\(\s*unescape\s*\(~i', 'document.write(unescape()) injection', 'medium' ), array( '~(?:\\\\x[0-9a-f]{2}){25,}~i', 'Long hex-escaped string (obfuscation)', 'medium', true ), array( '~String\.fromCharCode\s*\((?:\s*\d+\s*,){30,}~', 'Long fromCharCode chain (obfuscation)', 'medium' ), array( '~(?:window\.)?location(?:\.href)?\s*=\s*(?:atob|unescape|String\.fromCharCode)\s*\(~i', 'Redirect to a decoded address', 'medium' ), array( '~(?:window\.)?location\.(?:replace|assign)\s*\(\s*(?:atob|unescape|String\.fromCharCode)\s*\(~i', 'Redirect to a decoded address', 'medium' ), array( '~\b(?:Function|setTimeout|setInterval)\s*\(\s*(?:atob|unescape)\s*\(~i', 'Runs a decoded string as code', 'medium' ), array( '~createElement\s*\(\s*[\'"]iframe[\'"]\s*\)[\s\S]{0,300}?(?:\.(?:width|height)\s*=\s*[\'"]?[01](?:px)?[\'"]?\s*[;,\n]|display\s*[:=]\s*[\'"]?none|visibility\s*[:=]\s*[\'"]?hidden)~i', 'Creates a hidden iframe (normal in some libraries, check the source)', 'low' ), array( '~document\.write\s*\(\s*[\'"]<(?:script|iframe)[^>]{0,200}\bsrc\s*=\s*[\\\\\'"]*https?://~i', 'Writes an external script or iframe into the page', 'low' ), array( '~eval\s*\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,\s*[dr]\s*\)~', 'Packed (p,a,c,k,e,d) script', 'low' ), array( '~(?:coinhive|CoinHive\.Anonymous|cryptonight|coin-hive|authedmine|webminepool)~i', 'Crypto-miner reference', 'high' ), ); } /** * Statements that are safe to cut out when they stand alone. * Each rule matches one complete statement, ending in a semicolon. */ public static function clean_rules() { $dec = '(?:base64_decode|gzinflate|gzuncompress|gzdecode|str_rot13|convert_uudecode)'; $bal = '\((?:[^()]++|\((?:[^()]++|\((?:[^()]++|\([^()]*\))*\))*\))*\)'; $req = '\$_(?:GET|POST|REQUEST|COOKIE|SERVER)'; return array( array( '~(?:@\s*)?\beval\s*\(\s*(?:@\s*)?' . $dec . '\s*' . $bal . '\s*\)\s*;~i', 'eval() of an encoded payload' ), array( '~(?:@\s*)?\b(?:eval|assert)\s*\(\s*(?:@\s*)?' . $req . '\s*\[[^\]]*\]\s*\)\s*;~i', 'eval() of request input' ), array( '~(?:@\s*)?\b(?:system|shell_exec|passthru|exec|popen)\s*\(\s*(?:@\s*)?' . $req . '\s*\[[^\]]*\]\s*\)\s*;~i', 'shell command from request input' ), array( '~(?:@\s*)?' . $req . '\s*\[[^\]]{1,40}\]\s*\(\s*(?:@\s*)?' . $req . '\s*\[[^\]]*\]\s*\)\s*;~i', 'function named by request input' ), array( '~(?:@\s*)?\b(?:include|require)(?:_once)?\s*\(?\s*[\'"][^\'"\r\n]*\.(?:jpe?g|png|gif|ico)[\'"]\s*\)?\s*;~i', 'include of an image file as code' ), ); } /** * Plain-language explanation for a finding label: what it is, why it matters, what to do. * rec = the button we recommend: clean | quarantine | safe | review | reinstall | delete. */ public static function advice( $label ) { $rules = array( array( '/^(eval\(\) of an encoded payload|gzinflate|Executes request input|Runs a shell command|Calls a function named by request|preg_replace\(\) with|Known webshell|Includes an image file)/', array( 'title' => 'Malicious code (backdoor)', 'what' => 'This PHP file contains code that either decodes hidden text and runs it, or runs whatever a visitor sends to it. Normal themes and plugins do not do this.', 'why' => 'Attackers plant this so they can come back later: upload more files, create admin users, send spam or redirect your visitors. Leaving it in place keeps the door open.', 'do' => 'Treat this as an urgent finding. Review the file and restore a trusted clean copy, or ask a qualified developer to investigate. Change compromised credentials and update WordPress, plugins and themes after confirming the cause.', 'rec' => 'clean', ) ), array( '/^PHP code hidden inside an image/', array( 'title' => 'PHP hidden inside a picture', 'what' => 'A file that pretends to be an image actually contains PHP code. A genuine image never contains PHP.', 'why' => 'This is a classic way to sneak a backdoor past upload filters. It becomes dangerous when another infected file includes it or the server runs it.', 'do' => 'Treat this as a suspicious file. Review it and isolate it if appropriate, but confirm the impact before making changes.', 'rec' => 'quarantine', ) ), array( '/^Page that prints server details/', array( 'title' => 'A page that prints your server details (phpinfo)', 'what' => 'This small PHP file only calls phpinfo(), which prints the PHP version, folder paths, extensions and settings of your server to anyone who opens it.', 'why' => 'It is usually a leftover from testing. Attackers use it to pick the right exploit for your exact setup.', 'do' => 'Remove public access to this file promptly. Use quarantine only after verifying that the file is not needed for legitimate maintenance.', 'rec' => 'quarantine', ) ), array( '/^Executable PHP file inside the uploads/', array( 'title' => 'PHP file in the uploads folder', 'what' => 'The uploads folder should hold only media such as pictures and PDFs. A PHP file here is not normal.', 'why' => 'Hackers upload scripts into uploads because it is writable. If the file runs, they control the site.', 'do' => 'Confirm whether a trusted plugin deliberately created the file. If not, investigate promptly and quarantine only after reviewing the consequences.', 'rec' => 'quarantine', ) ), array( '/^Server config (loads|makes)/', array( 'title' => 'Suspicious server configuration', 'what' => 'A .htaccess or .user.ini file tells the server to run extra PHP on every request, or to treat non-PHP files as PHP.', 'why' => 'Attackers use this to hide malware outside normal files, so even a clean-looking site keeps executing their code.', 'do' => 'Review the server configuration with your hosting provider before changing it. Removing .htaccess or .user.ini without review can break routing or security rules.', 'rec' => 'quarantine', ) ), array( '/^Broken file/', array( 'title' => 'Damaged file', 'what' => 'This file is not malware, it is broken: its code does not parse, it is cut off, empty, full of binary garbage or has invisible characters in front of it. Common causes are an interrupted upload or update, a full disk, a bad copy, or editing a file by hand.', 'why' => 'A broken PHP file can show the white screen of death or a fatal error as soon as WordPress loads it, and a damaged picture shows as a broken image. Invisible characters before the opening tag break logins, redirects and feeds.', 'do' => 'Restore a trusted clean version of the affected file from the original plugin or theme package, a WordPress core reinstall, or a verified backup.', 'rec' => 'repair', ) ), array( '/^WordPress core file missing/', array( 'title' => 'WordPress core file is missing', 'what' => 'A file expected in the official WordPress release is absent from this installation.', 'why' => 'An incomplete update, file deletion, or an unexpected change may have removed a core file.', 'do' => 'Back up the website and reinstall the matching WordPress version from Dashboard > Updates. Confirm file permissions and review related server logs.', 'rec' => 'reinstall', ) ), array( '/^WordPress core file differs/', array( 'title' => 'WordPress core file was modified', 'what' => 'This file is part of WordPress itself but its content is different from the official release.', 'why' => 'Core files should never be edited. A change is either an infection or an old edit by a developer.', 'do' => 'Go to Dashboard > Updates and press Re-install WordPress. It replaces every core file with a clean copy and does not touch your content, plugins or themes.', 'rec' => 'reinstall', ) ), array( '/^Unknown PHP file inside a WordPress core folder/', array( 'title' => 'Unknown PHP file in a core folder', 'what' => 'WordPress ships a fixed list of files in wp-admin and wp-includes. This PHP file is not on that list.', 'why' => 'Nothing legitimate adds PHP files to these folders. This is a common hiding place for backdoors.', 'do' => 'Investigate the unexpected file and compare with the official WordPress package. Reinstall WordPress from Dashboard > Updates after taking a verified backup.', 'rec' => 'quarantine', ) ), array( '/^Unknown file inside a WordPress core folder \(file name looks cut off\)/', array( 'title' => 'Leftover file with a cut-off name (usually harmless)', 'what' => 'This file sits in a WordPress core folder and its name is cut off (it has no .php ending). Some WordPress releases contain a few such files because the download package shortens very long file names.', 'why' => 'It is not code that runs and it contains no malware pattern. Other scanners list it as an "unknown file" because it is not on the official list.', 'do' => 'Check whether the file is part of a legitimate update or deployment process. If uncertain, compare with an official installation and review before removing anything.', 'rec' => 'safe', ) ), array( '/^Unknown file inside a WordPress core folder/', array( 'title' => 'Unknown file in a core folder', 'what' => 'This file is not part of the official WordPress release for your version, but it is not PHP code.', 'why' => 'Usually harmless (a leftover, a log, a stray copy), but attackers sometimes hide scripts or payloads with unusual file types.', 'do' => 'Check the file and compare with an official WordPress release. If unexpected, seek qualified assistance before removing it.', 'rec' => 'review', ) ), array( '/^PHP file in the site root/', array( 'title' => 'Extra PHP file in the site folder', 'what' => 'WordPress has a fixed set of PHP files in the main folder. This one is not on the list.', 'why' => 'It may be your own helper or test script, or a file an attacker left. Scripts left in the web folder can be run by anyone who guesses the address.', 'do' => 'Confirm who created the script and why it is present. If it is unexpected, seek a trusted clean version and consider quarantining the file after making a backup.', 'rec' => 'review', ) ), array( '/^Differs from the official wordpress.org copy/', array( 'title' => 'Plugin file changed', 'what' => 'This file belongs to a plugin from WordPress.org, but its content is different from the official release of the same version.', 'why' => 'Either someone edited the plugin (you, a developer, or an attacker) or the file was infected.', 'do' => 'If you did not intentionally modify this file, replace the plugin with a trusted package. If you or a developer changed it on purpose, document and review the modification.', 'rec' => 'reinstall', ) ), array( '/^File that is not in the official/', array( 'title' => 'Extra file inside a plugin', 'what' => 'This file is not part of the official WordPress.org package of the plugin.', 'why' => 'Plugins create some files while running (cache, config), which is normal. Attackers also add files inside plugin folders because nobody looks there.', 'do' => 'Read the file name and details. Compare with the plugin package and verify whether the file is an expected cache or configuration file. Quarantine only after checking its purpose.', 'rec' => 'review', ) ), array( '/^(Backup or database dump|Log or secret|Copy of wp-config|Zip archive)/', array( 'title' => 'Sensitive file that should not be in a web folder', 'what' => 'This is a backup, database dump, log, archive or copy of a configuration file stored where the web server can serve it.', 'why' => 'Such files can contain passwords, customer data or your database. Bots scan the internet for exactly these file names. If the label says "publicly downloadable", anyone can download it right now.', 'do' => 'If publicly accessible, remove the file from web access promptly using a verified backup and safe storage location. If the web test is inconclusive, verify your server access rules.', 'rec' => 'quarantine', ) ), array( '/^(eval\(\) of a decoded string|document\.write|Long fromCharCode)/', array( 'title' => 'Suspicious JavaScript', 'what' => 'This JavaScript file decodes a hidden string and runs it. Attackers inject this to redirect visitors or load fake ads.', 'why' => 'It runs in your visitors\' browsers, so it hurts them and your search ranking, even though your server is not affected.', 'do' => 'Compare the script with the original trusted plugin or theme distribution. If the file is unexpected, have it reviewed and consider quarantine.', 'rec' => 'review', ) ), array( '/^(eval\(\) of nested|Long hex|Obfuscated chr|Large inline base64|Writes a file using request)/', array( 'title' => 'Obfuscated or risky code', 'what' => 'This code is deliberately hard to read, or it writes files using data a visitor sends. Malware does this, but some commercial plugins also hide their licence checks the same way.', 'why' => 'We cannot be sure it is malware, and we do not want to break a working plugin by removing it.', 'do' => 'Inspect the plugin or theme source and compare the file to a trusted package. Do not dismiss obfuscated code without understanding it.', 'rec' => 'review', ) ), ); foreach ( $rules as $r ) { if ( preg_match( $r[0], (string) $label ) ) { return $r[1]; } } return array( 'title' => 'Needs a look', 'what' => 'This file matched one of our checks.', 'why' => 'We cannot say more automatically.', 'do' => 'Read the reason and inspect the file before taking action. Use a verified backup and do not assume that quarantine or recovery is always safe.', 'rec' => 'review', ); } /** * Which part of the site a path belongs to, for grouping. */ public static function area( $path ) { $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); if ( 0 === strpos( $path, $abs . 'wp-admin/' ) || 0 === strpos( $path, $abs . 'wp-includes/' ) ) { return 'WordPress core'; } $uploads = wp_get_upload_dir(); $roots = array( WP_PLUGIN_DIR => 'Plugin: ', WPMU_PLUGIN_DIR => 'Must-use plugins' ); foreach ( (array) ( $GLOBALS['wp_theme_directories'] ?? array( get_theme_root() ) ) as $root ) { $roots[ $root ] = 'Theme: '; } if ( ! empty( $uploads['basedir'] ) ) { $roots[ $uploads['basedir'] ] = 'Uploads'; } foreach ( $roots as $directory => $label ) { $root = trailingslashit( wp_normalize_path( $directory ) ); if ( 0 === strpos( $path, $root ) ) { if ( 'Plugin: ' === $label || 'Theme: ' === $label ) { return $label . explode( '/', substr( $path, strlen( $root ) ) )[0]; } return $label; } } if ( 0 === strpos( $path, $abs ) && false === strpos( substr( $path, strlen( $abs ) ), '/' ) ) { return 'Site root'; } return 'Other'; } /** * Printable, short excerpt for display. */ public static function snippet( $text, $len = 110 ) { $text = preg_replace( '/\s+/', ' ', (string) $text ); $text = preg_replace( '/[^\x20-\x7E]/', '?', $text ); $text = trim( $text ); if ( strlen( $text ) > $len ) { $text = substr( $text, 0, $len ) . '...'; } return $text; } /** * Scan text content. $kind is 'php' or 'js'. * * @return array[] Each: label, sev, line, snippet. */ public static function scan_string( $code, $kind = 'php' ) { $reasons = array(); $sigs = ( 'js' === $kind ) ? self::js_signatures() : ( ( 'svg' === $kind || 'html' === $kind ) ? self::markup_signatures() : self::signatures() ); if ( 'html' === $kind || 'svg' === $kind ) { $sigs = array_merge( $sigs, self::js_signatures() ); } $sink = null; foreach ( $sigs as $s ) { $m = array(); if ( isset( $s[4] ) && $s[4] !== $kind ) { continue; // This pattern is meant for another file type. } if ( 1 === preg_match( $s[0], $code, $m, PREG_OFFSET_CAPTURE ) ) { // Weak hints (hex strings, chr chains) are normal in crypto and data tables. // They only matter when the same file can also run or decode something. if ( ! empty( $s[3] ) ) { if ( null === $sink ) { $sink = ( 'js' === $kind || 'html' === $kind || 'svg' === $kind ) ? ( 1 === preg_match( '~\b(?:eval|Function|atob|unescape|document\.write)\s*\(~', $code ) ) : ( 1 === preg_match( '~\b(?:eval|assert|create_function|gzinflate|gzuncompress|str_rot13|base64_decode|system|shell_exec|passthru|popen|proc_open|call_user_func(?:_array)?)\s*\(|\$_(?:GET|POST|REQUEST|COOKIE)\b~i', $code ) ); } if ( ! $sink ) { continue; } } $off = (int) $m[0][1]; $reasons[] = array( 'label' => $s[1], 'sev' => $s[2], 'line' => substr_count( substr( $code, 0, $off ), "\n" ) + 1, 'snippet' => self::snippet( $m[0][0] ), ); } } return $reasons; } /** * PHP hidden inside something that claims to be an image. */ public static function scan_image_chunks( $head, $tail = '' ) { if ( preg_match( '~<\?php~i', $head . "\n" . $tail ) ) { return array( array( 'label' => 'PHP code hidden inside an image file', 'sev' => 'high', 'line' => 0, 'snippet' => '' ) ); } return array(); } /** * .htaccess / .user.ini checks. */ public static function scan_server_config( $content, $in_uploads = false ) { $reasons = array(); if ( preg_match( '~(auto_prepend_file|auto_append_file)~i', $content, $m ) ) { $reasons[] = array( 'label' => 'Server config loads a PHP file on every request (' . strtolower( $m[1] ) . ')', 'sev' => 'high', 'line' => 0, 'snippet' => self::snippet( $m[0] ) ); } if ( $in_uploads && preg_match( '~(?:AddType|AddHandler|SetHandler)\s+[^\r\n]*php~i', $content, $m ) ) { $reasons[] = array( 'label' => 'Server config makes non-PHP files run as PHP', 'sev' => 'high', 'line' => 0, 'snippet' => self::snippet( $m[0] ) ); } return $reasons; } /** * Files that are damaged rather than malicious: broken PHP, cut-off files, empty files, * binary garbage, invisible characters before 0 && $size < 524288 ) { $code = ( null === $code ) ? (string) @file_get_contents( $path ) : $code; // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged json_decode( $code ); if ( JSON_ERROR_NONE !== json_last_error() ) { $out[] = array( 'label' => 'Broken file: invalid JSON (' . $name . ')', 'sev' => 'medium', 'line' => 0, 'snippet' => json_last_error_msg() ); } return $out; } if ( ! in_array( $ext, array( 'php', 'phtml' ), true ) ) { return array(); } if ( 0 === (int) $size ) { return 'index.php' === $name ? array() : array( array( 'label' => 'Broken file: empty PHP file (0 bytes)', 'sev' => 'medium', 'line' => 0, 'snippet' => 'The file has no content at all. This usually means an upload or update was cut off.' ) ); } if ( $size > 2097152 ) { return array(); } $code = ( null === $code ) ? (string) @file_get_contents( $path ) : $code; // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( '' === $code ) { return array(); } $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); $core = 0 === strpos( $path, $abs . 'wp-admin/' ) || 0 === strpos( $path, $abs . 'wp-includes/' ) || 0 === strpos( $path, trailingslashit( wp_normalize_path( WPMU_PLUGIN_DIR ) ) ); // Everything after __halt_compiler() is data, not code (security plugins store their data this way). $code_part = $code; $halt = stripos( $code, '__halt_compiler' ); if ( false !== $halt && 1 === preg_match( '~__halt_compiler\s*\(\s*\)\s*;~i', substr( $code, $halt, 40 ) ) ) { $code_part = substr( $code, 0, $halt ); } if ( false !== strpos( $code_part, "\0" ) ) { $out[] = array( 'label' => 'Broken file: contains binary garbage (NUL bytes)', 'sev' => $core ? 'high' : 'medium', 'line' => 0, 'snippet' => 'Plain-text code should never contain NUL bytes. The file was damaged while being written or copied.' ); } if ( preg_match( '~^(?:\xEF\xBB\xBF|\s+)<\?php~', $code ) ) { $out[] = array( 'label' => 'Broken file: invisible characters before 'low', 'line' => 1, 'snippet' => 'A byte-order mark or blank space before the opening tag is sent to the browser first and causes "headers already sent" errors, broken logins and broken feeds.' ); } if ( defined( 'TOKEN_PARSE' ) ) { try { token_get_all( $code, TOKEN_PARSE ); } catch ( \Throwable $e ) { $msg = $e->getMessage(); $cut = ( false !== stripos( $msg, 'end of file' ) ); $out[] = array( 'label' => $cut ? 'Broken file: cut off before the end' : 'Broken file: PHP syntax error', 'sev' => $core ? 'high' : 'medium', 'line' => (int) $e->getLine(), 'snippet' => self::snippet( $msg . ' (PHP ' . PHP_VERSION . ')', 160 ), ); } } return $out; } private static function image_problem( $path, $ext, $size ) { $bad = function ( $what, $note ) { return array( array( 'label' => 'Broken file: ' . $what, 'sev' => 'low', 'line' => 0, 'snippet' => $note ) ); }; if ( 0 === $size ) { return $bad( 'empty image (0 bytes)', 'The picture file has no content. It shows as a broken image on the site.' ); } if ( $size > 52428800 ) { return array(); } $info = @getimagesize( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( ! $info ) { return $bad( 'damaged image', 'The picture header cannot be read, so browsers cannot show it.' ); } $fh = @fopen( $path, 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged if ( ! $fh ) { return array(); } $tail = ''; $head = (string) fread( $fh, 12 ); if ( 0 === fseek( $fh, -min( $size, 2048 ), SEEK_END ) ) { $tail = (string) fread( $fh, 2048 ); } fclose( $fh ); $cut = false; // Judge the picture by what it really is, not by its extension (a PNG named .jpg is common). $real = array( 1 => 'gif', 2 => 'jpg', 3 => 'png', 18 => 'webp' ); if ( isset( $info[2], $real[ (int) $info[2] ] ) ) { $ext = $real[ (int) $info[2] ]; } if ( 'jpg' === $ext || 'jpeg' === $ext ) { $cut = ( false === strpos( $tail, "\xFF\xD9" ) ); } elseif ( 'png' === $ext ) { $cut = ( false === strpos( $tail, 'IEND' ) ); } elseif ( 'gif' === $ext ) { $cut = ( ';' !== substr( rtrim( $tail, "\0" ), -1 ) ); } elseif ( 'webp' === $ext && 'RIFF' === substr( $head, 0, 4 ) ) { $decl = unpack( 'V', substr( $head, 4, 4 ) ); $cut = ( $decl && ( (int) $decl[1] + 8 ) > $size + 1 ); } return $cut ? $bad( 'incomplete image (cut off)', 'The picture ends before it should, so the bottom part is missing or grey. The upload or copy was interrupted.' ) : array(); } /** * True when picture bytes look complete (not cut off). Used to vet a replacement copy. */ public static function image_bytes_ok( $bytes, $ext ) { $size = strlen( $bytes ); if ( ! $size || ! @getimagesizefromstring( $bytes ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged return false; } $tail = substr( $bytes, -2048 ); if ( 'jpg' === $ext || 'jpeg' === $ext ) { return false !== strpos( $tail, "\xFF\xD9" ); } if ( 'png' === $ext ) { return false !== strpos( $tail, 'IEND' ); } if ( 'gif' === $ext ) { return ';' === substr( rtrim( $tail, "\0" ), -1 ); } if ( 'webp' === $ext && 'RIFF' === substr( $bytes, 0, 4 ) ) { $decl = unpack( 'V', substr( $bytes, 4, 4 ) ); return ! $decl || ( (int) $decl[1] + 8 ) <= $size + 1; } return true; } /** * True when the code parses on this PHP version. */ public static function parses_ok( $code ) { if ( ! defined( 'TOKEN_PARSE' ) ) { return false; } try { token_get_all( $code, TOKEN_PARSE ); return true; } catch ( \Throwable $e ) { return false; } } /** * True when a PHP file has no code left (only tags, comments, whitespace). */ public static function is_effectively_empty( $code ) { foreach ( token_get_all( $code ) as $tok ) { if ( ! is_array( $tok ) ) { return false; } if ( in_array( $tok[0], array( T_OPEN_TAG, T_CLOSE_TAG, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { continue; } if ( T_INLINE_HTML === $tok[0] && '' === trim( $tok[1] ) ) { continue; } return false; } return true; } /** * Cut out standalone malicious statements. * * @return array [ cleaned string, removed[] ]. On any doubt the original is returned untouched. */ public static function clean_string( $code ) { $removed = array(); $out = $code; foreach ( self::clean_rules() as $rule ) { $label = $rule[1]; $out = preg_replace_callback( $rule[0], function ( $m ) use ( &$removed, $label ) { $removed[] = array( 'label' => $label, 'snippet' => ADT_Shield_Engine::snippet( $m[0], 140 ) ); return ''; }, $out ); if ( null === $out ) { return array( $code, array() ); } } if ( ! $removed ) { return array( $code, array() ); } // Only trust the result when both versions are valid PHP. if ( ! self::parses_ok( $code ) || ! self::parses_ok( $out ) ) { return array( $code, array() ); } return array( $out, $removed ); } /** * Highest severity in a reasons list. */ public static function top_sev( array $reasons ) { $top = 'low'; foreach ( $reasons as $r ) { if ( self::sev_rank( $r['sev'] ) > self::sev_rank( $top ) ) { $top = $r['sev']; } } return $top; } }