initial_state( $max_entries, $traversal_mode ); $findings = array(); do { $batch = $this->run_batch( $state, 500 ); $state = $batch['state']; $findings = array_merge( $findings, $batch['findings'] ); } while ( ! $batch['done'] ); if ( ! empty( $state['budget_reached'] ) ) { $findings[] = $this->budget_finding( $state ); } return $findings; } public function initial_state( $max_entries, $traversal_mode = 'standard' ) { $budget = max( 500, min( 100000, absint( $max_entries ) ) ); $mode = $this->sanitize_traversal_mode( $traversal_mode ); $depths = $this->depths_for_mode( $mode ); $queue = array(); $uploads = wp_get_upload_dir(); if ( is_array( $uploads ) && empty( $uploads['error'] ) && ! empty( $uploads['basedir'] ) ) { $this->queue_root( $queue, (string) $uploads['basedir'], 'uploads', $depths['uploads'] ); } $includes = ACHWPA_Paths::wp_includes_dir(); if ( is_dir( $includes ) ) { $this->queue_root( $queue, $includes, 'wp-includes', $depths['wp-includes'] ); } $plugins_dir = ACHWPA_Paths::plugins_dir(); if ( '' !== $plugins_dir && is_dir( $plugins_dir ) ) { $this->queue_root( $queue, $plugins_dir, 'plugins', $depths['plugins'] ); } return array( 'budget' => $budget, 'traversal_mode' => $mode, 'candidates_inspected' => 0, 'directories_seen' => 0, 'files_seen' => 0, 'files_ignored' => 0, 'entries_traversed' => 0, 'budget_reached' => false, 'queue' => $queue, ); } public function run_batch( array $state, $batch_size = 0 ) { $state = $this->sanitize_state( $state ); $findings = array(); $started = microtime( true ); $time_budget = 0.45; $directories_this_batch = 0; /* * Alpha14 uses native glob filtering instead of stat'ing every asset. * We enumerate child directories and PHP-like filenames separately, so * large uploads trees full of images/PDFs do not trigger PHP-level file * checks one entry at a time. Each queued directory is consumed once. */ while ( ! empty( $state['queue'] ) && $state['candidates_inspected'] < $state['budget'] ) { if ( $directories_this_batch > 0 && ( microtime( true ) - $started ) >= $time_budget ) { break; } $job = array_pop( $state['queue'] ); $dir = $this->absolute_from_relative( $job['path'] ); if ( '' === $dir || ! is_dir( $dir ) || ! is_readable( $dir ) || is_link( $dir ) ) { continue; } $directories_this_batch++; $state['directories_seen']++; if ( (int) $job['depth'] < (int) $job['max_depth'] ) { foreach ( $this->child_directories( $dir ) as $child_dir ) { if ( ! $this->inside_installation( $child_dir ) || is_link( $child_dir ) ) { continue; } $name = basename( $child_dir ); if ( 'plugins' === $job['scope'] && 0 === strpos( $name, '.' ) ) { $this->finding_hidden_plugin_dir( $child_dir, $findings ); } if ( $this->should_skip_directory( $name, $job['scope'], $state['traversal_mode'] ) ) { continue; } $state['queue'][] = array( 'path' => $this->relative_path( $child_dir ), 'scope' => $job['scope'], 'depth' => (int) $job['depth'] + 1, 'max_depth' => (int) $job['max_depth'], ); } } foreach ( $this->php_like_files( $dir ) as $path ) { if ( ! $this->inside_installation( $path ) || is_link( $path ) || ! is_readable( $path ) ) { continue; } $state['entries_traversed']++; $state['files_seen']++; if ( ! $this->is_candidate_file( $path, $job['scope'] ) ) { $state['files_ignored']++; continue; } $state['candidates_inspected']++; $this->inspect_file( $path, $job['scope'], $findings ); if ( $state['candidates_inspected'] >= $state['budget'] ) { break 2; } } } if ( $state['candidates_inspected'] >= $state['budget'] && ! empty( $state['queue'] ) ) { $state['budget_reached'] = true; $state['queue'] = array(); } $done = empty( $state['queue'] ); return array( 'state' => $state, 'findings' => $findings, 'done' => $done, 'progress' => $done ? 100 : 0, ); } private function child_directories( $dir ) { $dirs = array(); $normal = glob( trailingslashit( $dir ) . '*', GLOB_ONLYDIR ); if ( is_array( $normal ) ) { $dirs = $normal; } $hidden = glob( trailingslashit( $dir ) . '.??*', GLOB_ONLYDIR ); if ( is_array( $hidden ) ) { $dirs = array_merge( $dirs, $hidden ); } return array_values( array_unique( array_map( 'wp_normalize_path', $dirs ) ) ); } private function php_like_files( $dir ) { $files = array(); $base = trailingslashit( $dir ); if ( defined( 'GLOB_BRACE' ) ) { foreach ( array( '*.{php,php3,php4,php5,php7,phtml,phar,obf}', '.??*.{php,php3,php4,php5,php7,phtml,phar,obf}' ) as $pattern ) { $matches = glob( $base . $pattern, GLOB_BRACE ); if ( is_array( $matches ) ) { $files = array_merge( $files, $matches ); } } } else { foreach ( array( 'php', 'php3', 'php4', 'php5', 'php7', 'phtml', 'phar', 'obf' ) as $ext ) { foreach ( array( '*.' . $ext, '.??*.' . $ext ) as $pattern ) { $matches = glob( $base . $pattern ); if ( is_array( $matches ) ) { $files = array_merge( $files, $matches ); } } } } return array_values( array_unique( array_map( 'wp_normalize_path', $files ) ) ); } public function budget_finding( array $state ) { return new ACHWPA_Finding( array( 'category' => 'Filesystem', 'level' => 'Info', 'location' => '', 'indicator' => 'filesystem scan incomplete - candidate budget reached', 'explanation' => __( 'The read-only filesystem scan stopped after reaching the candidate-file limit selected for this audit. Files excluded by scope rules do not consume the budget.', 'aiutocomputerhelp-persistence-audit' ), 'preview' => 'Traversal mode: ' . ( isset( $state['traversal_mode'] ) ? sanitize_text_field( $state['traversal_mode'] ) : 'standard' ) . "\nCandidate files inspected: " . (string) absint( $state['candidates_inspected'] ) . "\nConfigured candidate budget: " . (string) absint( $state['budget'] ) . "\nDirectories traversed: " . (string) absint( $state['directories_seen'] ) . "\nPHP-like files encountered: " . (string) absint( $state['files_seen'] ) . "\nPHP-like files skipped by metadata rules: " . (string) absint( $state['files_ignored'] ), ) ); } public function completion_summary( array $state ) { return 'Traversal mode: ' . ( isset( $state['traversal_mode'] ) ? sanitize_text_field( $state['traversal_mode'] ) : 'standard' ) . "\nCandidate files inspected: " . (string) absint( $state['candidates_inspected'] ) . "\nDirectories traversed: " . (string) absint( $state['directories_seen'] ) . "\nPHP-like files encountered: " . (string) absint( $state['files_seen'] ) . "\nPHP-like files skipped by metadata rules: " . (string) absint( $state['files_ignored'] ); } private function queue_root( array &$queue, $root, $scope, $max_depth ) { $root = wp_normalize_path( $root ); if ( ! $this->inside_installation( $root ) || ! is_dir( $root ) || ! is_readable( $root ) || is_link( $root ) ) { return; } $queue[] = array( 'path' => $this->relative_path( $root ), 'scope' => (string) $scope, 'depth' => 0, 'max_depth' => (int) $max_depth, ); } private function sanitize_state( array $state ) { $clean = array( 'budget' => max( 500, min( 100000, isset( $state['budget'] ) ? absint( $state['budget'] ) : 1500 ) ), 'traversal_mode' => $this->sanitize_traversal_mode( isset( $state['traversal_mode'] ) ? $state['traversal_mode'] : 'standard' ), 'candidates_inspected' => isset( $state['candidates_inspected'] ) ? absint( $state['candidates_inspected'] ) : 0, 'directories_seen' => isset( $state['directories_seen'] ) ? absint( $state['directories_seen'] ) : 0, 'files_seen' => isset( $state['files_seen'] ) ? absint( $state['files_seen'] ) : 0, 'files_ignored' => isset( $state['files_ignored'] ) ? absint( $state['files_ignored'] ) : 0, 'entries_traversed' => isset( $state['entries_traversed'] ) ? absint( $state['entries_traversed'] ) : 0, 'budget_reached' => ! empty( $state['budget_reached'] ), 'queue' => array(), ); $allowed_scopes = array( 'uploads', 'wp-includes', 'plugins' ); if ( isset( $state['queue'] ) && is_array( $state['queue'] ) ) { foreach ( array_slice( $state['queue'], 0, 5000 ) as $job ) { if ( ! is_array( $job ) || empty( $job['path'] ) || empty( $job['scope'] ) || ! in_array( $job['scope'], $allowed_scopes, true ) ) { continue; } $relative = ltrim( wp_normalize_path( sanitize_text_field( $job['path'] ) ), '/' ); $absolute = $this->absolute_from_relative( $relative ); if ( '' === $absolute || ! $this->inside_installation( $absolute ) ) { continue; } $clean['queue'][] = array( 'path' => $relative, 'scope' => $job['scope'], 'depth' => min( 12, isset( $job['depth'] ) ? absint( $job['depth'] ) : 0 ), 'max_depth' => min( 12, isset( $job['max_depth'] ) ? absint( $job['max_depth'] ) : 0 ), ); } } return $clean; } private function is_candidate_file( $path, $scope ) { $basename = basename( $path ); $extension = strtolower( pathinfo( $basename, PATHINFO_EXTENSION ) ); $php_exts = array( 'php', 'php3', 'php4', 'php5', 'php7', 'phtml', 'phar' ); $is_php = in_array( $extension, $php_exts, true ); $ioc_hits = ACHWPA_IOC::matches( $path . ' ' . $basename ); if ( ! empty( $ioc_hits ) ) { return true; } if ( 'uploads' === $scope ) { return $is_php; } if ( 'wp-includes' === $scope ) { if ( ! $is_php ) { return false; } /* * Recency is intentionally NOT a candidate selector. A WordPress core * update can legitimately touch hundreds of PHP files at once. We only * spend the content-analysis budget when the cheap metadata checks are * already unusual; mtime remains contextual evidence later. */ return $this->looks_random_or_hex_filename( $basename ) || ( $this->is_strong_core_impostor_name( $basename ) && $this->is_unusual_core_location( $path, $scope ) ); } if ( 'plugins' === $scope ) { if ( ! $is_php ) { return false; } return $this->looks_random_or_hex_filename( $basename ) || ( $this->is_strong_core_impostor_name( $basename ) && $this->is_unusual_core_location( $path, $scope ) ); } return false; } private function inspect_file( $path, $scope, array &$findings ) { $basename = basename( $path ); $extension = strtolower( pathinfo( $basename, PATHINFO_EXTENSION ) ); $is_php = in_array( $extension, array( 'php', 'php3', 'php4', 'php5', 'php7', 'phtml', 'phar' ), true ); $signals = array(); $level = 'Info'; if ( 'uploads' === $scope && $is_php ) { if ( $this->is_benign_index_placeholder( $path ) ) { return; } $signals[] = 'PHP-capable file inside uploads'; $level = 'Review'; } if ( $is_php && $this->looks_random_or_hex_filename( $basename ) ) { $signals[] = 'random-or-hex PHP filename'; $level = 'Review'; } if ( $is_php && $this->is_strong_core_impostor_name( $basename ) && $this->is_unusual_core_location( $path, $scope ) ) { $signals[] = 'core-imitating PHP filename in unusual path'; $level = 'Review'; } $ioc_hits = ACHWPA_IOC::matches( $path . ' ' . $basename ); if ( ! empty( $ioc_hits ) ) { $signals[] = 'known indicator'; $level = 'Review'; } $mtime = @filemtime( $path ); $recent = is_int( $mtime ) && $mtime > 0 && ( time() - $mtime ) >= 0 && ( time() - $mtime ) <= $this->recent_window; if ( $recent && ! empty( $signals ) ) { $signals[] = 'recently modified'; } if ( 'wp-includes' === $scope && $is_php && empty( $signals ) ) { return; } if ( 'plugins' === $scope && empty( $signals ) ) { return; } if ( empty( $signals ) ) { return; } $content = ''; $content_signals = array(); if ( $is_php && @filesize( $path ) <= 512 * 1024 ) { $content = ACHWPA_Preview::read_limited_file( $path, 256 * 1024 ); if ( '' !== $content ) { if ( preg_match( '/\b(?:base64_decode|gzinflate|gzuncompress|str_rot13|eval|assert)\s*\(/i', $content ) ) { $content_signals[] = 'code transformation/execution primitive'; } if ( preg_match( '/\b(?:file_put_contents|fopen|unlink|rename|copy)\s*\(/i', $content ) ) { $content_signals[] = 'filesystem write primitive'; } if ( preg_match( '/\b(?:get_option|get_site_option|wp_schedule_event|wp_schedule_single_event)\s*\(/i', $content ) ) { $content_signals[] = 'persistence-related WordPress API reference'; } if ( ! empty( $content_signals ) && 'Info' === $level ) { $level = 'Review'; } } } $signals = array_values( array_unique( array_merge( $signals, $content_signals, $ioc_hits ) ) ); $relative = $this->relative_path( $path ); $size = @filesize( $path ); $hash = @hash_file( 'sha256', $path ); $preview = 'File: ' . $relative . "\n"; $preview .= 'Size: ' . ( false !== $size ? (string) $size : 'unknown' ) . " bytes\n"; $preview .= 'Modified: ' . ( is_int( $mtime ) && $mtime > 0 ? gmdate( 'c', $mtime ) : 'unknown' ) . "\n"; $preview .= 'SHA-256: ' . ( is_string( $hash ) ? $hash : '[unavailable]' ); if ( '' !== $content ) { $preview .= "\n\n" . ACHWPA_Preview::sanitize( $content, 1200, false ); } $artifacts = array( 'FILE:' . $basename, 'PATH:' . $relative ); if ( '' !== $content ) { $artifacts = array_merge( $artifacts, $this->extract_artifacts( $content ) ); } $findings[] = new ACHWPA_Finding( array( 'category' => 'Filesystem', 'level' => $level, 'location' => $relative, 'indicator' => implode( ', ', $signals ), 'explanation' => __( 'The file has one or more contextual characteristics associated with persistence or unusual PHP placement. Location, naming, recency or sensitive functions are supporting indicators and are not treated as proof of compromise on their own.', 'aiutocomputerhelp-persistence-audit' ), 'preview' => $preview, 'artifacts' => array_values( array_unique( $artifacts ) ), 'identifiers' => $this->extract_identifiers( $basename . ' ' . $relative . ' ' . $content ), ) ); } private function finding_hidden_plugin_dir( $path, array &$findings ) { $findings[] = new ACHWPA_Finding( array( 'category' => 'Filesystem', 'level' => 'Info', 'location' => $this->relative_path( $path ), 'indicator' => 'hidden directory inside plugin tree', 'explanation' => __( 'A hidden directory was found inside the plugin tree. Hidden directories can be legitimate development or packaging artifacts, so this is contextual information unless correlated with stronger indicators.', 'aiutocomputerhelp-persistence-audit' ), 'preview' => 'Directory: ' . $this->relative_path( $path ), 'artifacts' => array( 'PATH:' . $this->relative_path( $path ) ), 'identifiers' => $this->extract_identifiers( basename( $path ) ), ) ); } private function is_benign_index_placeholder( $path ) { if ( 'index.php' !== strtolower( basename( $path ) ) ) { return false; } $size = @filesize( $path ); if ( false === $size || $size > 2048 ) { return false; } if ( 0 === (int) $size ) { return true; } $content = ACHWPA_Preview::read_limited_file( $path, 2048 ); if ( '' === $content ) { return true; } $normalized = strtolower( preg_replace( '/\s+/', ' ', $content ) ); return false !== strpos( $normalized, 'silence is golden' ) || preg_match( '/^\s*<\?php\s*(?:\/\/[^\n]*)?\s*(?:exit|die)?\s*\(?\s*\)?\s*;?\s*$/i', $content ); } private function looks_random_or_hex_filename( $basename ) { $stem = strtolower( pathinfo( (string) $basename, PATHINFO_FILENAME ) ); if ( $this->looks_structured_generated_filename( $basename ) ) { return false; } if ( preg_match( '/^[a-f0-9]{8,}$/i', $stem ) ) { return true; } /* * Mixed random-looking names are only interesting when there is little * linguistic structure. This avoids class/migration names with digits. */ if ( strlen( $stem ) >= 12 && preg_match( '/[a-z]/i', $stem ) && preg_match( '/\\d/', $stem ) && ! preg_match( '/[_-][a-z]{3,}/i', $stem ) && ! preg_match( '/[a-z]{4,}/i', $stem ) ) { return true; } return false; } private function looks_structured_generated_filename( $basename ) { $name = pathinfo( (string) $basename, PATHINFO_FILENAME ); /* * Common migration naming: * 20200428123747_BreadcrumbTitleAndHierarchyReset.php * 20171228151840_WpYoastIndexable.php * * The numeric prefix is a timestamp-like migration identifier and the * suffix is a readable class/migration name. It is structured, not random. */ if ( preg_match( '/^\\d{14}_[A-Za-z][A-Za-z0-9_]{3,}$/', $name ) ) { return true; } /* * Other frameworks use shorter numeric migration/version prefixes. */ if ( preg_match( '/^\\d{3,13}_[A-Za-z][A-Za-z0-9_]{3,}$/', $name ) ) { return true; } if ( preg_match( '/^\\d{3,14}-[A-Za-z][A-Za-z0-9_-]{3,}$/', $name ) ) { return true; } return false; } private function is_strong_core_impostor_name( $basename ) { /* * Only names that are strongly tied to WordPress bootstrap/admin entry * points are candidate selectors. Generic names such as functions.php or * plugin.php are common inside legitimate plugins and must not consume the * candidate budget by themselves. */ static $strong_core_like = array( 'wp-config.php', 'wp-settings.php', 'wp-load.php', 'wp-login.php', 'wp-cron.php', 'wp-blog-header.php', 'wp-links-opml.php', 'wp-trackback.php', 'xmlrpc.php', 'admin-ajax.php', ); return in_array( strtolower( $basename ), $strong_core_like, true ); } private function is_unusual_core_location( $path, $scope ) { $basename = strtolower( basename( $path ) ); if ( 'uploads' === $scope ) { return true; } if ( 'plugins' === $scope ) { $relative = wp_normalize_path( $this->relative_path( $path ) ); $plugin_relative = preg_replace( '#^wp-content/plugins/#', '', $relative ); $segments = array_values( array_filter( explode( '/', $plugin_relative ), 'strlen' ) ); $depth_inside_plugin = max( 0, count( $segments ) - 1 ); /* * xmlrpc.php is a common descriptive filename in legitimate plugin * integration classes. Treat it as core-imitating only when it sits * unusually close to the plugin root. Deep structured paths such as * plugin/src/integrations/xmlrpc.php are not suspicious by name alone. */ if ( 'xmlrpc.php' === $basename ) { return $depth_inside_plugin <= 1; } return true; } if ( 'wp-includes' === $scope ) { $relative = $this->relative_path( $path ); return in_array( $basename, array( 'wp-config.php', 'wp-settings.php', 'wp-load.php', 'wp-login.php', 'wp-cron.php', 'admin-ajax.php' ), true ) || false !== strpos( $relative, '/.' ); } return false; } private function sanitize_traversal_mode( $mode ) { $mode = strtolower( sanitize_key( (string) $mode ) ); return in_array( $mode, array( 'standard', 'deep', 'deep-plus' ), true ) ? $mode : 'standard'; } private function depths_for_mode( $mode ) { if ( 'deep-plus' === $mode ) { return array( 'uploads' => 12, 'wp-includes' => 10, 'plugins' => 8 ); } if ( 'deep' === $mode ) { return array( 'uploads' => 8, 'wp-includes' => 6, 'plugins' => 4 ); } return array( 'uploads' => 5, 'wp-includes' => 3, 'plugins' => 2 ); } private function should_skip_directory( $name, $scope, $mode ) { $name = strtolower( (string) $name ); // SCM metadata is outside the persistence-audit value proposition. if ( in_array( $name, array( '.git', '.svn', '.hg' ), true ) ) { return true; } if ( 'deep-plus' === $mode ) { return false; } if ( 'plugins' !== $scope ) { return false; } $standard_skip = array( 'node_modules', 'vendor', 'tests', 'test', 'docs', 'documentation', 'languages', 'assets', 'dist', 'build', 'coverage', 'examples', 'example', ); if ( 'standard' === $mode ) { return in_array( $name, $standard_skip, true ); } // Deep still avoids very large dependency/test trees, but traverses // source, assets, languages and other plugin internals. return in_array( $name, array( 'node_modules', 'vendor', 'tests', 'test', 'coverage' ), true ); } private function extract_artifacts( $content ) { $artifacts = array(); if ( preg_match_all( '/[A-Za-z0-9_.-]{3,}\.php\b/', (string) $content, $matches ) ) { foreach ( $matches[0] as $file ) { $artifacts[] = 'FILE:' . basename( $file ); } } if ( preg_match_all( '/(?:_site_transient_|_transient_|wp_cache_|wp_compat_|_wp_)[A-Za-z0-9_.-]{3,}/i', (string) $content, $matches ) ) { foreach ( $matches[0] as $name ) { $artifacts[] = 'OPTION:' . $name; } } return array_slice( array_values( array_unique( $artifacts ) ), 0, 50 ); } private function extract_identifiers( $text ) { $ids = array(); if ( preg_match_all( '/\b[a-f0-9]{6,32}\b/i', (string) $text, $matches ) ) { foreach ( $matches[0] as $candidate ) { if ( ! ctype_digit( $candidate ) ) { $ids[] = strtolower( $candidate ); } } } return array_slice( array_values( array_unique( $ids ) ), 0, 40 ); } private function inside_installation( $path ) { $normalized = wp_normalize_path( $path ); $root = untrailingslashit( ACHWPA_Paths::wordpress_root() ); return $normalized === $root || 0 === strpos( $normalized, $root . '/' ); } private function absolute_from_relative( $relative ) { $relative = ltrim( wp_normalize_path( (string) $relative ), '/' ); if ( false !== strpos( $relative, '..' ) ) { return ''; } $path = wp_normalize_path( trailingslashit( ACHWPA_Paths::wordpress_root() ) . $relative ); return $this->inside_installation( $path ) ? $path : ''; } private function relative_path( $path ) { $normalized = wp_normalize_path( $path ); $root = trailingslashit( ACHWPA_Paths::wordpress_root() ); return 0 === strpos( $normalized, $root ) ? ltrim( substr( $normalized, strlen( $root ) ), '/' ) : basename( $path ); } }