$path, 'sev' => $sev, 'reasons' => array() ); } $f[ $path ]['reasons'][] = $reason; if ( ADT_Shield_Engine::sev_rank( $sev ) > ADT_Shield_Engine::sev_rank( $f[ $path ]['sev'] ) ) { $f[ $path ]['sev'] = $sev; } } private static function reason( $label, $sev, $line = 0, $snippet = '' ) { return array( 'label' => $label, 'sev' => $sev, 'line' => $line, 'snippet' => $snippet ); } /** * Which folder tree a scan covers. Returns array( scope, root ) or WP_Error. */ public static function scope_info( $scope, $root_in = '' ) { $scope = in_array( $scope, array( 'content', 'site', 'server' ), true ) ? $scope : 'site'; $content = trailingslashit( wp_normalize_path( WP_CONTENT_DIR ) ); $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); if ( 'server' === $scope ) { $scope = 'site'; } if ( 'content' === $scope ) { return array( 'scope' => 'content', 'root' => $content ); } return array( 'scope' => 'site', 'root' => $abs ); } /** * Backups, dumps, logs and copies of config files that should not sit in a web folder. */ public static function sensitive_kind( $name, $in_uploads, $path = '' ) { $l = strtolower( $name ); // Developer fixtures and package leftovers are not data leaks. if ( preg_match( '#/(vendor|node_modules|tests?|testdata|fixtures|\.git)/#i', $path ) || 'wp-config-sample.php' === $l ) { return ''; } if ( preg_match( '/\.(sql|sql\.gz|sql\.zip|bak|old|orig|save|swp|tar|tar\.gz|tgz|rar|7z|wpress|dump)$/', $l ) || '~' === substr( $l, -1 ) ) { return 'Backup or database dump file in a web folder'; } if ( in_array( $l, array( 'error_log', 'php_errorlog', 'php_error.log', 'debug.log', '.env', '.git-credentials', 'id_rsa' ), true ) ) { return 'Log or secret file in a web folder'; } if ( 'wp-config.php' !== $l && preg_match( '/^wp-config.*\.(php|txt|bak|old|save|orig)$/', $l ) ) { return 'Copy of wp-config.php in a web folder'; } if ( ! $in_uploads && '.zip' === substr( $l, -4 ) && ! self::is_plugin_or_theme_path( $path ) ) { return 'Zip archive in a web folder'; } return ''; } private static function is_plugin_or_theme_path( $p ) { return 0 === strpos( $p, trailingslashit( wp_normalize_path( WP_PLUGIN_DIR ) ) ) || 0 === strpos( ADT_Shield_Engine::area( $p ), 'Theme: ' ); } private static function is_upload_path( $p, $uploads ) { return 0 === strpos( $p, $uploads ); } /** * Previous editions used different quarantine folders. Resolve a known ID * from either location without moving or changing existing records. * A duplicated ID is ambiguous, so refuse it rather than choose a file. */ private static function quarantine_locations() { $uploads = wp_get_upload_dir(); return array_unique( array( wp_normalize_path( WP_CONTENT_DIR . '/adt-shield-quarantine' ), wp_normalize_path( untrailingslashit( $uploads['basedir'] ) . '/adt-shield-quarantine' ), ) ); } private static function is_cut_off_name( $rel, $ext, array $sums ) { if ( '' === $ext && strlen( basename( $rel ) ) > 40 ) { return true; } if ( strlen( basename( $rel ) ) < 8 ) { return false; } foreach ( $sums as $k => $v ) { if ( strlen( $k ) > strlen( $rel ) && 0 === strpos( $k, $rel ) ) { return true; } } return false; } public static function file_list() { $info = self::scope_info( 'site' ); $f = self::build_list( $info ); unset( $f['truncated'] ); return array_values( $f ); } private static function budget() { $max = (int) ini_get( 'max_execution_time' ); if ( $max <= 0 ) { return 10; } return (int) max( 2, min( 10, floor( $max / 3 ) ) ); } /* --------------------------------------------------------------------- * Core integrity * ------------------------------------------------------------------ */ private static function fetch_core_checksums( $version, $locale ) { $url = 'https://api.wordpress.org/core/checksums/1.0/?' . http_build_query( array( 'version' => $version, 'locale' => $locale ), '', '&' ); $res = wp_remote_get( $url, array( 'timeout' => 20 ) ); if ( is_wp_error( $res ) || 200 !== wp_remote_retrieve_response_code( $res ) ) { return null; } $body = json_decode( wp_remote_retrieve_body( $res ), true ); if ( ! is_array( $body ) || empty( $body['checksums'] ) || ! is_array( $body['checksums'] ) ) { return null; } return $body['checksums']; } /** * Compares every official core file (any type) with the release, and lists files in * wp-admin / wp-includes that are not part of the release. * * @param array|null $sums Test hook: checksums to use instead of asking api.wordpress.org. */ /** * Syntax and cut-off check of WordPress core PHP files, no internet needed. */ private static function core_offline_integrity() { $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); $found = array(); $deadline = microtime( true ) + 25; foreach ( array( 'wp-admin', 'wp-includes' ) as $dir ) { if ( ! is_dir( $abs . $dir ) ) { continue; } try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $abs . $dir, FilesystemIterator::SKIP_DOTS ) ); foreach ( $it as $f ) { if ( microtime( true ) > $deadline ) { return $found; } if ( ! $f->isFile() || 'php' !== strtolower( $f->getExtension() ) ) { continue; } $p = wp_normalize_path( $f->getPathname() ); foreach ( ADT_Shield_Engine::corruption_reasons( $p ) as $r ) { $found[] = array( 'path' => $p, 'sev' => $r['sev'], 'reason' => $r ); } // Without the official list, a clear backdoor signature is still worth reporting. if ( filesize( $p ) <= self::MAX_SIZE ) { foreach ( ADT_Shield_Engine::scan_string( (string) file_get_contents( $p ), 'php' ) as $r ) { if ( 'high' === $r['sev'] ) { $found[] = array( 'path' => $p, 'sev' => 'high', 'reason' => $r ); break; } } } } } catch ( \Throwable $e ) { return $found; } } return $found; } private static function core_check( $sums = null ) { global $wp_version; $out = array( 'status' => 'unavailable', 'version' => $wp_version, 'findings' => array(), 'verified' => 0, 'unknown' => 0 ); if ( null === $sums ) { $sums = self::fetch_core_checksums( $wp_version, get_locale() ); if ( null === $sums && 'en_US' !== get_locale() ) { $sums = self::fetch_core_checksums( $wp_version, 'en_US' ); } } if ( null === $sums ) { // Offline: the official release cannot be compared, but damaged core files can still be found. $out['findings'] = self::core_offline_integrity(); return $out; } $out['status'] = 'ok'; $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); $php = ADT_Shield_Engine::php_exts(); foreach ( $sums as $rel => $md5 ) { if ( 0 === strpos( $rel, 'wp-content/' ) || 'wp-config-sample.php' === $rel ) { continue; } $full = $abs . $rel; if ( ! is_file( $full ) ) { $is_php = in_array( strtolower( pathinfo( $rel, PATHINFO_EXTENSION ) ), $php, true ); $level = $is_php ? 'high' : 'medium'; $out['status'] = 'mismatch'; $out['findings'][] = array( 'path' => $full, 'sev' => $level, 'reason' => self::reason( 'WordPress core file missing from installation', $level ), ); continue; } $out['verified']++; if ( md5_file( $full ) !== $md5 ) { $is_php = in_array( strtolower( pathinfo( $rel, PATHINFO_EXTENSION ) ), $php, true ); $out['status'] = 'mismatch'; $out['findings'][] = array( 'path' => $full, 'sev' => $is_php ? 'high' : 'medium', 'reason' => self::reason( 'WordPress core file differs from the official release', $is_php ? 'high' : 'medium' ) ); } } // Files inside the core folders that are not part of the release, of ANY type. foreach ( array( 'wp-admin', 'wp-includes' ) as $dir ) { $base = $abs . $dir; if ( ! is_dir( $base ) ) { continue; } try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $it as $file ) { if ( ! $file->isFile() || $file->isLink() ) { continue; } $p = wp_normalize_path( $file->getPathname() ); $rel = substr( $p, strlen( $abs ) ); if ( isset( $sums[ $rel ] ) ) { continue; } $ext = strtolower( pathinfo( $p, PATHINFO_EXTENSION ) ); $is_php = in_array( $ext, $php, true ); $out['status'] = 'mismatch'; $out['unknown']++; if ( $is_php ) { $label = 'Unknown PHP file inside a WordPress core folder'; $sev = 'high'; } elseif ( self::is_cut_off_name( $rel, $ext, $sums ) ) { $label = 'Unknown file inside a WordPress core folder (file name looks cut off)'; $sev = 'low'; } else { $label = 'Unknown file inside a WordPress core folder'; $sev = 'medium'; } $out['findings'][] = array( 'path' => $p, 'sev' => $sev, 'reason' => self::reason( $label, $sev ) ); } } catch ( Exception $e ) { continue; } } // Unknown PHP files in the site root. $root = glob( $abs . '*.php' ); if ( is_array( $root ) ) { foreach ( $root as $p ) { $rel = basename( $p ); if ( ! isset( $sums[ $rel ] ) && 'wp-config.php' !== $rel ) { $out['status'] = 'mismatch'; $out['findings'][] = array( 'path' => wp_normalize_path( $p ), 'sev' => 'medium', 'reason' => self::reason( 'PHP file in the site root that is not part of WordPress', 'medium' ) ); } } } return $out; } /* --------------------------------------------------------------------- * Plugin integrity (wordpress.org plugins only) * ------------------------------------------------------------------ */ private static function plugin_queue() { if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $q = array(); foreach ( get_plugins() as $file => $data ) { if ( false === strpos( $file, '/' ) ) { continue; } $slug = dirname( $file ); $ver = isset( $data['Version'] ) ? $data['Version'] : ''; if ( in_array( $slug, array( 'adt-shield', 'adnanthemes-malware-scanner' ), true ) || ! preg_match( '/^[A-Za-z0-9._-]+$/', $slug ) || ! preg_match( '/^[A-Za-z0-9._+-]+$/', $ver ) ) { continue; } $q[] = array( $slug, $ver ); } return $q; } private static function check_plugin( array $item, array &$findings ) { list( $slug, $ver ) = $item; $res = wp_remote_get( 'https://downloads.wordpress.org/plugin-checksums/' . rawurlencode( $slug ) . '/' . rawurlencode( $ver ) . '.json', array( 'timeout' => 15 ) ); if ( is_wp_error( $res ) || 200 !== wp_remote_retrieve_response_code( $res ) ) { return false; } $json = json_decode( wp_remote_retrieve_body( $res ), true ); if ( ! is_array( $json ) || empty( $json['files'] ) || ! is_array( $json['files'] ) ) { return false; } $base = trailingslashit( wp_normalize_path( WP_PLUGIN_DIR ) ) . $slug . '/'; foreach ( $json['files'] as $rel => $info ) { if ( ! in_array( strtolower( pathinfo( $rel, PATHINFO_EXTENSION ) ), array( 'php', 'js' ), true ) || ! isset( $info['md5'] ) ) { continue; } $full = $base . $rel; if ( ! is_file( $full ) ) { continue; } $valid = (array) $info['md5']; if ( ! in_array( md5_file( $full ), $valid, true ) ) { self::add_finding( $findings, $full, 'medium', self::reason( 'Differs from the official wordpress.org copy of ' . $slug . ' ' . $ver, 'medium' ) ); } } if ( is_dir( $base ) ) { try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $it as $file ) { if ( ! $file->isFile() || $file->isLink() ) { continue; } $p = wp_normalize_path( $file->getPathname() ); if ( ! in_array( strtolower( pathinfo( $p, PATHINFO_EXTENSION ) ), array_merge( ADT_Shield_Engine::php_exts(), array( 'js' ) ), true ) ) { continue; } $rel = substr( $p, strlen( $base ) ); if ( ! isset( $json['files'][ $rel ] ) ) { // Harmless "silence is golden" index stubs that plugins create at runtime. if ( filesize( $p ) < 512 && ADT_Shield_Engine::is_effectively_empty( (string) file_get_contents( $p ) ) ) { continue; } self::add_finding( $findings, $p, 'medium', self::reason( 'File that is not in the official ' . $slug . ' ' . $ver . ' package', 'medium' ) ); } } } catch ( Exception $e ) { return true; } } return true; } /* --------------------------------------------------------------------- * File list + content scan * ------------------------------------------------------------------ */ private static function build_list( array $info ) { $files = array(); $up = wp_get_upload_dir(); $roots = array_merge( array( $info['root'], WP_PLUGIN_DIR, WPMU_PLUGIN_DIR, $up['basedir'] ), (array) ( $GLOBALS['wp_theme_directories'] ?? array( get_theme_root() ) ) ); if ( 'site' === $info['scope'] ) { $roots[] = WP_CONTENT_DIR; } $abs0 = trailingslashit( wp_normalize_path( ABSPATH ) ); $max = 'server' === $info['scope'] ? 120000 : self::MAX_FILES; $uploads = trailingslashit( wp_normalize_path( $up['basedir'] ) ); $skip = array( $abs0 . 'wp-admin/', $abs0 . 'wp-includes/', trailingslashit( wp_normalize_path( ADT_SHIELD_DIR ) ), ); foreach ( self::quarantine_locations() as $qdir ) { $skip[] = trailingslashit( $qdir ); } if ( class_exists( 'ADT_Shield_Backup' ) ) { $skip[] = trailingslashit( wp_normalize_path( ADT_Shield_Backup::dir() ) ); } if ( class_exists( 'ADT_Shield_Package' ) ) { $skip[] = trailingslashit( wp_normalize_path( ADT_Shield_Package::work_dir() ) ); } $visited = array(); foreach ( $roots as $root ) { if ( ! $root || ! is_dir( $root ) || ! is_readable( $root ) ) { continue; } $content = untrailingslashit( wp_normalize_path( $root ) ); try { $filter = new RecursiveCallbackFilterIterator( new RecursiveDirectoryIterator( $content, FilesystemIterator::SKIP_DOTS ), function ( $current ) use ( $skip ) { if ( $current->isLink() ) { return false; } if ( $current->isDir() ) { $name = $current->getFilename(); if ( 'node_modules' === $name || '.git' === $name || '.svn' === $name ) { return false; } $p = trailingslashit( wp_normalize_path( $current->getPathname() ) ); // Other sites' copies of this scanner hold the detection signatures; skip them. if ( ( 0 === strpos( $name, 'adt-shield' ) || 'adnanthemes-malware-scanner' === $name ) && 0 === strpos( $p, trailingslashit( wp_normalize_path( WP_PLUGIN_DIR ) ) ) ) { return false; } return ! in_array( $p, $skip, true ); } return true; } ); $it = new RecursiveIteratorIterator( $filter, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $it as $file ) { if ( ! $file->isFile() ) { continue; } $p = wp_normalize_path( $file->getPathname() ); $name = $file->getFilename(); $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ); $in_up = self::is_upload_path( $p, $uploads ); $take = in_array( $ext, ADT_Shield_Engine::php_exts(), true ) || 'js' === $ext || '' !== self::sensitive_kind( $name, $in_up, $p ) || '.htaccess' === $name || '.user.ini' === $name || in_array( $ext, array( 'svg', 'html', 'htm' ), true ) || in_array( $ext, ADT_Shield_Engine::img_exts(), true ); if ( $take ) { if ( isset( $visited[ $p ] ) ) { continue; } $visited[ $p ] = true; $files[] = $p; if ( count( $files ) >= $max ) { $files['truncated'] = true; break 2; } } } } catch ( Exception $e ) { // Unreadable folder: carry on with what we have. unset( $e ); } } if ( 'content' === $info['scope'] ) { foreach ( array( '.htaccess', '.user.ini' ) as $n ) { if ( is_file( $abs0 . $n ) ) { $files[] = $abs0 . $n; } } } return $files; } public static function scan_file( $path, $uploads ) { $size = @filesize( $path ); if ( false === $size ) { return array(); } $name = basename( $path ); $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ); $in_uploads = self::is_upload_path( $path, $uploads ); $reasons = array(); $sens = self::sensitive_kind( $name, $in_uploads, $path ); if ( '' !== $sens ) { return array( self::reason( $sens, 'medium' ) ); } if ( $in_uploads && in_array( $ext, ADT_Shield_Engine::php_exts(), true ) ) { $silent = false; if ( $size < 120 ) { $tiny = (string) @file_get_contents( $path ); $silent = ( false !== stripos( $tiny, 'silence is golden' ) ); } if ( ! $silent ) { $reasons[] = self::reason( 'Executable PHP file inside the uploads folder', 'medium' ); } } if ( 'php' === $ext && $size < 4096 && ! self::is_plugin_or_theme_path( $path ) ) { $tiny = (string) @file_get_contents( $path ); if ( preg_match( '~\bphpinfo\s*\(~i', $tiny ) ) { $reasons[] = self::reason( 'Page that prints server details (phpinfo)', 'medium' ); } } if ( in_array( $ext, ADT_Shield_Engine::img_exts(), true ) ) { $fh = @fopen( $path, 'rb' ); if ( $fh ) { $head = (string) fread( $fh, 4096 ); $tail = ''; if ( $size > 8192 && 0 === fseek( $fh, -4096, SEEK_END ) ) { $tail = (string) fread( $fh, 4096 ); } fclose( $fh ); $reasons = array_merge( $reasons, ADT_Shield_Engine::scan_image_chunks( $head, $tail ) ); } return array_merge( $reasons, ADT_Shield_Engine::corruption_reasons( $path ) ); } if ( '.htaccess' === $name || '.user.ini' === $name ) { if ( $size <= 262144 ) { $reasons = array_merge( $reasons, ADT_Shield_Engine::scan_server_config( (string) @file_get_contents( $path ), $in_uploads ) ); } return $reasons; } if ( $size > self::MAX_SIZE || ( 'js' === $ext && $size > 1048576 ) ) { return $reasons; } $code = @file_get_contents( $path ); if ( false === $code ) { return $reasons; } $kind = 'php'; if ( 'js' === $ext ) { $kind = 'js'; } elseif ( 'svg' === $ext ) { $kind = 'svg'; } elseif ( 'html' === $ext || 'htm' === $ext ) { $kind = 'html'; } $found = ADT_Shield_Engine::scan_string( $code, $kind ); if ( in_array( $ext, array( 'php', 'phtml' ), true ) ) { $found = array_merge( $found, ADT_Shield_Engine::corruption_reasons( $path, $code ) ); } return array_merge( $reasons, $found ); } /* --------------------------------------------------------------------- * Scan lifecycle * ------------------------------------------------------------------ */ public static function start( $scope = null, $root_in = '' ) { if ( null === $scope ) { $scope = get_option( self::OPT_SCOPE, 'site' ); $root_in = (string) get_option( self::OPT_SROOT, '' ); } $info = self::scope_info( $scope, $root_in ); if ( is_wp_error( $info ) ) { if ( 'content' !== $scope && 'site' !== $scope ) { $info = self::scope_info( 'site' ); } else { return $info; } } $files = self::build_list( $info ); $trunc = ! empty( $files['truncated'] ); unset( $files['truncated'] ); $core = self::core_check(); $findings = array(); foreach ( $core['findings'] as $c ) { self::add_finding( $findings, $c['path'], $c['sev'], $c['reason'] ); } $state = array( 'phase' => 'plugins', 'pq' => self::plugin_queue(), 'pi' => 0, 'fi' => 0, 'ftotal' => count( $files ), 'findings' => $findings, 'core' => array( 'status' => $core['status'], 'version' => $core['version'] ), 'plugins_checked' => 0, 'core_verified' => $core['verified'], 'core_unknown' => $core['unknown'], 'st' => array( 'php' => 0, 'js' => 0, 'img' => 0, 'cfg' => 0, 'sens' => 0, 'mk' => 0 ), 'sq' => array(), 'wi' => 0, 'scanned' => 0, 'started' => time(), 'scope' => $info['scope'], 'root' => $info['root'], 'truncated' => $trunc, 'aq' => ADT_Shield_Checks::initial_tasks(), 'aqt' => count( ADT_Shield_Checks::initial_tasks() ), 'aqd' => 0, 'issues' => array(), 'sn' => array(), ); update_option( self::OPT_FILES, $files, false ); update_option( self::OPT_STATE, $state, false ); return $state; } public static function process( $budget = 8 ) { $state = get_option( self::OPT_STATE ); if ( ! is_array( $state ) ) { return self::progress( null ); } if ( 'done' === $state['phase'] ) { return self::progress( $state ); } $files = null; $uploadu = wp_get_upload_dir(); $uploads = trailingslashit( wp_normalize_path( $uploadu['basedir'] ) ); $t0 = microtime( true ); while ( ( microtime( true ) - $t0 ) < $budget && 'done' !== $state['phase'] ) { if ( 'plugins' === $state['phase'] ) { if ( $state['pi'] >= count( $state['pq'] ) ) { $state['phase'] = 'files'; continue; } if ( self::check_plugin( $state['pq'][ $state['pi'] ], $state['findings'] ) ) { $state['plugins_checked']++; } $state['pi']++; } elseif ( 'audit' === $state['phase'] ) { if ( empty( $state['aq'] ) ) { $state['phase'] = 'done'; break; } $task = array_shift( $state['aq'] ); $state['aqd']++; ADT_Shield_Checks::run( $task, $state ); } else { if ( null === $files ) { $files = get_option( self::OPT_FILES, array() ); if ( ! is_array( $files ) ) { $files = array(); } } if ( 'web' === $state['phase'] ) { if ( $state['wi'] >= count( $state['sq'] ) ) { $state['phase'] = 'audit'; continue; } self::web_check( $state, $state['sq'][ $state['wi'] ] ); $state['wi']++; continue; } if ( $state['fi'] >= count( $files ) ) { $state['phase'] = $state['sq'] ? 'web' : 'audit'; continue; } $end = min( $state['fi'] + 40, count( $files ) ); for ( ; $state['fi'] < $end; $state['fi']++ ) { $path = $files[ $state['fi'] ]; $ext = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ); $nm = basename( $path ); if ( in_array( $ext, ADT_Shield_Engine::img_exts(), true ) ) { $state['st']['img']++; } elseif ( in_array( $ext, array( 'svg', 'html', 'htm' ), true ) ) { $state['st']['mk'] = ( isset( $state['st']['mk'] ) ? (int) $state['st']['mk'] : 0 ) + 1; } elseif ( 'js' === $ext ) { $state['st']['js']++; } elseif ( '.htaccess' === $nm || '.user.ini' === $nm ) { $state['st']['cfg']++; } elseif ( in_array( $ext, ADT_Shield_Engine::php_exts(), true ) ) { $state['st']['php']++; } else { $state['st']['sens']++; } foreach ( self::scan_file( $path, $uploads ) as $r ) { self::add_finding( $state['findings'], $path, $r['sev'], $r ); if ( 0 === strpos( $r['label'], 'Backup or' ) || 0 === strpos( $r['label'], 'Log or secret' ) || 0 === strpos( $r['label'], 'Copy of wp-config' ) || 0 === strpos( $r['label'], 'Zip archive' ) ) { if ( count( $state['sq'] ) < 40 ) { $state['sq'][] = $path; } } } $state['scanned']++; } } } update_option( self::OPT_STATE, $state, false ); if ( 'done' === $state['phase'] ) { self::finalize( $state ); } return self::progress( $state ); } /** * Asks the web server whether a sensitive file can be downloaded by anyone. */ private static function web_check( array &$state, $path ) { if ( ! isset( $state['findings'][ $path ] ) ) { return; } $uploads = wp_get_upload_dir(); $locations = array( array( $uploads['basedir'], $uploads['baseurl'] ), array( WP_PLUGIN_DIR, plugins_url() ), array( WPMU_PLUGIN_DIR, WPMU_PLUGIN_URL ), ); foreach ( (array) ( $GLOBALS['wp_theme_directories'] ?? array( get_theme_root() ) ) as $theme_root ) { $locations[] = array( $theme_root, get_theme_root_uri( '', $theme_root ) ); } $locations[] = array( WP_CONTENT_DIR, content_url() ); $locations[] = array( ABSPATH, site_url() ); $url = ''; foreach ( $locations as list( $directory, $base_url ) ) { $root = trailingslashit( wp_normalize_path( $directory ) ); if ( $directory && $base_url && 0 === strpos( $path, $root ) ) { $parts = array_map( 'rawurlencode', explode( '/', substr( $path, strlen( $root ) ) ) ); $url = trailingslashit( $base_url ) . implode( '/', $parts ); break; } } if ( '' === $url ) { return; } $res = wp_remote_head( $url, array( 'timeout' => 6, 'redirection' => 0 ) ); $code = is_wp_error( $res ) ? 0 : (int) wp_remote_retrieve_response_code( $res ); foreach ( $state['findings'][ $path ]['reasons'] as &$r ) { if ( 200 === $code ) { $r['label'] .= ' - publicly downloadable'; $r['sev'] = 'high'; $state['findings'][ $path ]['sev'] = 'high'; } elseif ( in_array( $code, array( 401, 403, 404 ), true ) ) { $r['label'] .= ' - not reachable from the web'; $r['sev'] = 'low'; $state['findings'][ $path ]['sev'] = 'low'; } else { $r['label'] .= ' - could not test whether it can be downloaded'; } break; } unset( $r ); } private static function progress( $state ) { if ( ! is_array( $state ) ) { return array( 'done' => true, 'pct' => 0, 'phase' => 'none', 'result' => null ); } $total = count( $state['pq'] ) + $state['ftotal'] + (int) $state['aqt']; $did = min( $state['pi'], count( $state['pq'] ) ) + min( $state['fi'], $state['ftotal'] ) + min( (int) $state['aqd'], (int) $state['aqt'] ); $done = ( 'done' === $state['phase'] ); $hi = 0; foreach ( $state['findings'] as $one ) { if ( 'high' === $one['sev'] ) { $hi++; } } $live = array( 'phase' => $state['phase'], 'did' => $did, 'total' => $total, 'files' => min( $state['fi'], $state['ftotal'] ), 'ftotal' => (int) $state['ftotal'], 'plugins' => min( $state['pi'], count( $state['pq'] ) ), 'ptotal' => count( $state['pq'] ), 'found' => count( $state['findings'] ), 'adv' => $hi, 'kinds' => $state['st'], ); return array( 'live' => $live, 'done' => $done, 'pct' => $done ? 100 : ( $total > 0 ? (int) floor( ( $did / $total ) * 100 ) : 100 ), 'phase' => $state['phase'], 'result' => $done ? self::view_result( get_option( self::OPT_RESULT ) ) : null, 'history' => $done ? ADT_Shield_History::summaries() : null, ); } /** * True when a plugin file is byte-for-byte the official wordpress.org file. Such a file cannot be malware, * so a content rule that matched it (for example a hidden iframe in a bundled library) is a false alarm. */ private static function is_official_plugin_file( $path, array $versions ) { $base = trailingslashit( wp_normalize_path( WP_PLUGIN_DIR ) ); if ( 0 !== strpos( $path, $base ) ) { return false; } $rel = substr( $path, strlen( $base ) ); $pos = strpos( $rel, '/' ); if ( false === $pos ) { return false; } $slug = substr( $rel, 0, $pos ); $file = substr( $rel, $pos + 1 ); if ( empty( $versions[ $slug ] ) || ! is_file( $path ) ) { return false; } $key = 'adt_shield_sum_' . md5( $slug . $versions[ $slug ] ); $json = get_transient( $key ); if ( ! is_array( $json ) ) { $res = wp_remote_get( 'https://downloads.wordpress.org/plugin-checksums/' . rawurlencode( $slug ) . '/' . rawurlencode( $versions[ $slug ] ) . '.json', array( 'timeout' => 15 ) ); if ( is_wp_error( $res ) || 200 !== wp_remote_retrieve_response_code( $res ) ) { return false; } $json = json_decode( wp_remote_retrieve_body( $res ), true ); if ( ! is_array( $json ) || empty( $json['files'] ) ) { return false; } set_transient( $key, $json, HOUR_IN_SECONDS ); } return isset( $json['files'][ $file ]['md5'] ) && in_array( md5_file( $path ), (array) $json['files'][ $file ]['md5'], true ); } private static function finalize( array $state ) { $versions = array(); foreach ( $state['pq'] as $q ) { $versions[ $q[0] ] = $q[1]; } $ign = get_option( self::OPT_IGNORE, array() ); if ( ! is_array( $ign ) ) { $ign = array(); } $list = array(); foreach ( $state['findings'] as $path => $f ) { // Retain missing official core files in reports. They have no bytes to // inspect or quarantine, but administrators must be told they are absent. if ( ! is_file( $path ) && ! in_array( 'WordPress core file missing from installation', wp_list_pluck( $f['reasons'], 'label' ), true ) ) { continue; } // A core file that differs from the release may also simply be damaged: say so. $labs = wp_list_pluck( $f['reasons'], 'label' ); if ( preg_grep( '/^WordPress core file differs/', $labs ) && ! preg_grep( '/^Broken file/', $labs ) ) { $extra = ADT_Shield_Engine::corruption_reasons( $path ); if ( $extra ) { $f['reasons'] = array_merge( $extra, $f['reasons'] ); $f['sev'] = ADT_Shield_Engine::top_sev( $f['reasons'] ); } } if ( isset( $ign[ $path ] ) && md5_file( $path ) === $ign[ $path ] ) { continue; } if ( ! preg_grep( '/^Broken file/', $labs ) && ! preg_grep( '/^Differs from the official/', $labs ) && self::is_official_plugin_file( $path, $versions ) ) { continue; } $list[] = $f; } usort( $list, function ( $a, $b ) { $d = ADT_Shield_Engine::sev_rank( $b['sev'] ) - ADT_Shield_Engine::sev_rank( $a['sev'] ); return $d ? $d : strcmp( $a['path'], $b['path'] ); } ); $alerts = array(); if ( ! empty( $state['truncated'] ) ) { $alerts[] = 'The folder has more files than one scan covers, so the scan stopped early. Narrow the scan area to cover the rest.'; } $ids = array_map( 'intval', get_users( array( 'role' => 'administrator', 'fields' => 'ID' ) ) ); $base = get_option( 'adt_shield_admin_ids', null ); if ( is_array( $base ) ) { foreach ( array_diff( $ids, $base ) as $id ) { $u = get_userdata( $id ); $alerts[] = sprintf( 'New administrator account since the last scan: %s', $u ? $u->user_login : '#' . $id ); } } update_option( 'adt_shield_admin_ids', $ids, false ); ADT_Shield_Updates::refresh_if_stale( 6 ); $upd = ADT_Shield_Updates::collect(); unset( $upd['checked'] ); $iign = get_option( ADT_Shield_Checks::OPT_IGNORE, array() ); $iign = is_array( $iign ) ? $iign : array(); $issues = array(); foreach ( isset( $state['issues'] ) ? $state['issues'] : array() as $iid => $iss ) { if ( ! isset( $iign[ $iid ] ) ) { $issues[] = $iss; } } usort( $issues, function ( $a, $b ) { return ADT_Shield_Engine::sev_rank( $b['sev'] ) - ADT_Shield_Engine::sev_rank( $a['sev'] ); } ); $stages = ADT_Shield_Checks::stages( $state, $list, $issues, $upd ); foreach ( array( 'plugins', 'themes', 'core' ) as $k ) { foreach ( $upd[ $k ] as &$ui ) { unset( $ui['url'] ); } unset( $ui ); } update_option( self::OPT_RESULT, array( 'time' => time(), 'scanned' => $state['scanned'], 'plugins_checked' => $state['plugins_checked'], 'core' => $state['core'], 'scope' => $state['scope'], 'root' => $state['root'], 'stats' => array_merge( $state['st'], array( 'core_verified' => (int) $state['core_verified'], 'core_unknown' => (int) $state['core_unknown'], 'plugins' => (int) $state['plugins_checked'], 'plugins_total' => count( $state['pq'] ), 'web' => count( $state['sq'] ), 'seconds' => max( 1, time() - (int) $state['started'] ), ) ), 'findings' => $list, 'alerts' => $alerts, 'updates' => $upd, 'issues' => $issues, 'stages' => $stages, ), false ); delete_option( self::OPT_FILES ); self::setup_schedule(); ADT_Shield_History::record( get_option( self::OPT_RESULT ), ( defined( 'DOING_CRON' ) && DOING_CRON ) ? 'scheduled' : 'manual' ); adt_shield_log( sprintf( 'Scan finished: %d files checked, %d file finding(s), %d site issue(s).', $state['scanned'], count( $list ), count( $issues ) ) ); } /** * Decorate stored results for the admin UI. */ public static function view_result( $res ) { if ( ! is_array( $res ) || ! isset( $res['findings'] ) ) { return null; } $abs = trailingslashit( wp_normalize_path( ABSPATH ) ); $root = ! empty( $res['root'] ) ? $res['root'] : ''; $base = ( ! empty( $res['scope'] ) && 'server' === $res['scope'] && $root ) ? $root : $abs; foreach ( $res['findings'] as &$f ) { $f['rel'] = ( 0 === strpos( $f['path'], $base ) ) ? substr( $f['path'], strlen( $base ) ) : $f['path']; $f['php'] = in_array( strtolower( pathinfo( $f['path'], PATHINFO_EXTENSION ) ), ADT_Shield_Engine::php_exts(), true ); $top = $f['reasons'][0]; foreach ( $f['reasons'] as $r ) { if ( ADT_Shield_Engine::sev_rank( $r['sev'] ) > ADT_Shield_Engine::sev_rank( $top['sev'] ) ) { $top = $r; } } $f['advice'] = ADT_Shield_Engine::advice( $top['label'] ); if ( 'high' === $f['sev'] ) { $f['advice']['rec'] = 'review'; $f['advice']['do'] = 'Investigate promptly and recover from a verified clean source if needed.'; } $f['area'] = ADT_Shield_Engine::area( $f['path'] ); $f['size_h'] = is_file( $f['path'] ) ? size_format( (int) filesize( $f['path'] ) ) : ''; $f['mtime'] = is_file( $f['path'] ) ? wp_date( 'Y-m-d H:i', (int) filemtime( $f['path'] ) ) : ''; $f['triage'] = ADT_Shield_Triage::decide( $f ); } unset( $f ); // Always show every severity. High-severity findings must remain visible, // even though Lite deliberately does not offer one-click repair for them. usort( $res['findings'], function ( $a, $b ) { if ( $a['triage']['rank'] !== $b['triage']['rank'] ) { return $a['triage']['rank'] - $b['triage']['rank']; } $sa = ADT_Shield_Engine::sev_rank( $a['sev'] ); $sb = ADT_Shield_Engine::sev_rank( $b['sev'] ); return $sa !== $sb ? $sb - $sa : strcmp( $a['path'], $b['path'] ); } ); $res['scope'] = isset( $res['scope'] ) ? $res['scope'] : 'content'; $res['time_h'] = wp_date( 'Y-m-d H:i', (int) $res['time'] ); return $res; } /* --------------------------------------------------------------------- * AJAX * ------------------------------------------------------------------ */ private static function guard() { check_ajax_referer( 'adt_shield', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 ); } } private static function post_path() { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in guard(). return isset( $_POST['path'] ) && is_string( $_POST['path'] ) ? wp_normalize_path( sanitize_text_field( wp_unslash( $_POST['path'] ) ) ) : ''; } public static function ajax_start() { self::guard(); @set_time_limit( 120 ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,Squiz.PHP.DiscouragedFunctions.Discouraged -- Raises the limit for one short scan step where the host allows it. // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in guard(). $scope = isset( $_POST['scope'] ) && is_string( $_POST['scope'] ) ? sanitize_key( wp_unslash( $_POST['scope'] ) ) : 'site'; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- verified in guard(). $root = isset( $_POST['root'] ) && is_string( $_POST['root'] ) ? wp_normalize_path( sanitize_text_field( wp_unslash( $_POST['root'] ) ) ) : ''; $state = self::start( $scope, $root ); if ( is_wp_error( $state ) ) { wp_send_json_error( array( 'message' => $state->get_error_message() ) ); } update_option( self::OPT_SCOPE, $state['scope'], false ); if ( 'server' === $state['scope'] ) { update_option( self::OPT_SROOT, untrailingslashit( $state['root'] ), false ); } wp_send_json_success( self::progress( $state ) ); } public static function ajax_step() { self::guard(); wp_send_json_success( self::process( 2 ) ); } }