.genlock child symlink is rejected/replaced and never followed (no zero-byte file outside the store). $fp = method_exists( 'GuardPress_File_Storage', 'safe_open_lock_file' ) ? GuardPress_File_Storage::safe_open_lock_file( $dir, $safe . '.genlock' ) : @fopen( $dir . '/' . $safe . '.genlock', 'c' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- fallback per-key advisory lock when the safe primitive is unavailable if ( ! $fp ) { return null; } if ( ! @flock( $fp, LOCK_EX ) ) { @fclose( $fp ); return null; } return $fp; } private static function gen_unlock( $fp ) { if ( $fp ) { @flock( $fp, LOCK_UN ); @fclose( $fp ); } } /** * Write a shared scan record, atomically bound to the authoritative scan lease (ACG-053-001). * * Under an exclusive per-key flock, the decision is: WHOEVER CURRENTLY HOLDS THE GLOBAL SCAN LOCK wins. * - If we can consult the lock and it shows we LOST it (owns()===false) → refuse. * - If a DIFFERENT generation already stamped the record and we cannot PROVE we currently own the global lock * (owns() !== true) → refuse, whether this is a claim or a continuation. A legitimate takeover proves * ownership (owns()===true) and is allowed to supersede an abandoned generation. * When no atomic lock primitive is available the write FAILS CLOSED — a shared owner-bound record is never * written unlocked (so a sub-millisecond takeover window cannot be lost). The previous fail-OPEN/unconditional- * claim paths could overwrite a successor; this closes both. * * @param string $key * @param mixed $data * @param string|null $owner Generation token; null/'' = legacy/tokenless unconditional write. * @param bool $claim True for init/takeover; false for a continuation. (Both now CAS against ownership.) * @param string $scan_type 'integrity'|'baseline' so the global lock owner can be consulted; '' = skip. * @return bool */ private static function save_scan_data( $key, $data, $owner = null, $claim = false, $scan_type = '' ) { if ( ! class_exists( 'GuardPress_File_Storage' ) ) { return false; } if ( null === $owner || '' === (string) $owner ) { return GuardPress_File_Storage::save( $key, $data, 'scan' ); // tokenless/legacy write } $wrapped = array( self::GEN_MARK => (string) $owner, 'd' => $data ); $lock = self::gen_lock( $key ); // Read the current record. (In a concurrent takeover this read is also where a successor may commit.) $raw = GuardPress_File_Storage::load( $key, null, 'scan' ); if ( null === $lock ) { return false; // no atomic lock primitive → FAIL CLOSED: never write shared owner-bound state unlocked } // The global scan lock is authoritative for "who owns this scan right now". true = we own it; false = we // demonstrably lost it; null = no lock subsystem to consult (e.g. a unit harness). $owns = ( '' !== (string) $scan_type && class_exists( 'GuardPress_Scan_Lock' ) ) ? (bool) GuardPress_Scan_Lock::owns( $scan_type, $owner ) : null; if ( false === $owns ) { self::gen_unlock( $lock ); return false; // lost the global lease } $diff_gen = ( is_array( $raw ) && array_key_exists( self::GEN_MARK, $raw ) && (string) $raw[ self::GEN_MARK ] !== (string) $owner ); if ( $diff_gen && true !== $owns ) { self::gen_unlock( $lock ); return false; // a different generation holds it and we cannot prove current ownership → refuse } $ok = GuardPress_File_Storage::save( $key, $wrapped, 'scan' ); self::gen_unlock( $lock ); return $ok; } private static function load_scan_data( $key, $default = null, $owner = null ) { if ( ! class_exists( 'GuardPress_File_Storage' ) ) { return $default; } $raw = GuardPress_File_Storage::load( $key, null, 'scan' ); if ( is_array( $raw ) && array_key_exists( self::GEN_MARK, $raw ) ) { if ( null !== $owner && '' !== (string) $owner && (string) $raw[ self::GEN_MARK ] !== (string) $owner ) { return $default; // belongs to a different generation — not ours } return array_key_exists( 'd', $raw ) ? $raw['d'] : $default; } return ( null === $raw ) ? $default : $raw; // legacy un-stamped record (back-compat) } private static function delete_scan_data( $key, $owner = null, $scan_type = '' ) { if ( ! class_exists( 'GuardPress_File_Storage' ) ) { return; } // ACG-051-001 / ACG-052-001 / ACG-053-001: owner-bound delete under the SAME per-key lock, bound to the // authoritative scan lock exactly like save_scan_data() — a stale generation can never delete a successor's // record, and with no lock primitive we FAIL CLOSED (a leftover key is harmless; the next claim supersedes // it once a lock is available). if ( null !== $owner && '' !== (string) $owner ) { $lock = self::gen_lock( $key ); $raw = GuardPress_File_Storage::load( $key, null, 'scan' ); if ( null === $lock ) { return; // no atomic lock → do not delete shared owner-bound state unlocked } $owns = ( '' !== (string) $scan_type && class_exists( 'GuardPress_Scan_Lock' ) ) ? (bool) GuardPress_Scan_Lock::owns( $scan_type, $owner ) : null; if ( false === $owns ) { self::gen_unlock( $lock ); return; // lost the global lease — leave it } $diff_gen = ( is_array( $raw ) && array_key_exists( self::GEN_MARK, $raw ) && (string) $raw[ self::GEN_MARK ] !== (string) $owner ); if ( $diff_gen && true !== $owns ) { self::gen_unlock( $lock ); return; // a successor generation owns this record — leave it intact } GuardPress_File_Storage::delete( $key, 'scan' ); self::gen_unlock( $lock ); return; } GuardPress_File_Storage::delete( $key, 'scan' ); } private static function cleanup_batch_data( $owner = null ) { // ACG-051-001: owner-bound — a stale generation's cleanup leaves a successor's stamped record intact. self::delete_scan_data( 'batch_files', $owner, 'integrity' ); self::delete_scan_data( 'batch_state', $owner, 'integrity' ); self::delete_scan_data( 'batch_current_keys', $owner, 'integrity' ); // Legacy DB cleanup (upgrading from old version that used transients) delete_transient( self::STATE_KEY ); } private static function cleanup_baseline_data( $owner = null ) { self::delete_scan_data( 'baseline_files', $owner, 'baseline' ); self::delete_scan_data( 'baseline_state', $owner, 'baseline' ); // Legacy DB cleanup delete_transient( self::BASELINE_STATE_KEY ); } // ========================================================================= // BATCH SCAN // ========================================================================= /** * ACG-049-001 (audit 2026-06-23): true when an owner token was supplied AND it no longer holds the named lock * (a successor stale-took-over). Used to TERMINATE before committing shared scan/baseline state so a stale * generation can never overwrite the successor's data. Returns false when no owner is supplied (back-compat: * direct/legacy callers keep the prior behavior). * * @param string $scan_type * @param string|null $owner * @return bool */ private static function owner_lost( $scan_type, $owner ) { return ( null !== $owner && '' !== (string) $owner && class_exists( 'GuardPress_Scan_Lock' ) && ! GuardPress_Scan_Lock::owns( $scan_type, $owner ) ); } /** * ACG-050-001 (audit 2026-06-23): the standard "lease lost to a successor" result. Returned WITHOUT any * cleanup_*_data() — the shared scan/baseline state keys now belong to the successor generation, so a stale * generation must never delete them. * * @return array */ private static function not_owner_result() { return array( 'success' => false, 'not_owner' => true, 'error' => __( 'This scan was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ), ); } /** * Initialize a new scan * * @param bool $is_full Whether this is a full scan * @param string|null $owner Scan-lock owner token (ACG-049-001); when set, init aborts if ownership is lost. * @return array Initial state with total file count */ public static function init_scan( $is_full = false, $owner = null ) { // ACG-051-001 (audit 2026-06-23): verify ownership BEFORE the leftover-data cleanup. If the caller already // lost the lease (a successor took over before this init even started), the shared keys now belong to the // successor — a stale generation must NOT delete them. Return not_owner without touching shared state. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // Clean up any leftover data from previous scans self::cleanup_batch_data( $owner ); // Set scan mode if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( $is_full ); } $paths = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::paths_to_scan() : array( ABSPATH ); // Collect all file paths (fast - no hashing) $all_files = array(); // ACG-031-005 (audit 2026-06-20): COVERAGE HONESTY at DISCOVERY time. The // SELF_FIRST + CATCH_GET_CHILD iterator silently SKIPS an unreadable // subdirectory (getChildren() failure is swallowed) and the is_readable // filter silently drops an unreadable file — neither entered $all_files, // so the per-file 'skipped' counter in process_batch() could never see // them and the scan reported 100%/complete despite never walking part of // the site. COUNT every such discovery skip and seed it into // report['skipped'] below so the EXISTING incomplete/amber chain reflects // the gap. Mirrors the malware scanner's RC-121-02 pattern. $discovery_skipped = 0; foreach ( $paths as $p ) { if ( @is_link( $p ) ) continue; if ( is_file( $p ) ) { $all_files[] = $p; } elseif ( is_dir( $p ) ) { try { // FIX (audit 2026-06-10): CATCH_GET_CHILD makes the iterator // SKIP an unreadable subdirectory instead of throwing and // aborting the ENTIRE file enumeration (which silently // truncated the scan to whatever was walked before the bad // dir). $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $p, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $iterator as $file ) { // ACG-031-005: a directory entry that is a symlink (not // descended) or unreadable (children swallowed by // CATCH_GET_CHILD) means its whole subtree was NOT walked. if ( $file->isDir() ) { $dp = $file->getPathname(); // ACG-082-H3 (audit 2026-06-27, MED): an EXCLUDED/ignored directory is out of scope — // exclude BEFORE counting a symlinked/unreadable EXCLUDED dir as a coverage gap. if ( class_exists( 'GuardPress_FS_Helpers' ) && ( GuardPress_FS_Helpers::should_exclude_path( $dp ) || GuardPress_FS_Helpers::is_ignored( $dp ) ) ) { continue; } if ( $file->isLink() || ! @is_readable( $dp ) ) { $discovery_skipped++; } continue; } if ( ! $file->isFile() ) continue; $fp = $file->getPathname(); // ACG-081-H2 (audit 2026-06-27, MED): exclusions BEFORE the symlink coverage-gap logic — a // symlink inside an internal-artifact or user-excluded directory is out of scope, not a gap. if ( class_exists( 'GuardPress_FS_Helpers' ) ) { if ( GuardPress_FS_Helpers::should_exclude_path( $fp ) ) continue; if ( GuardPress_FS_Helpers::is_ignored( $fp ) ) continue; } // ACG-032-007 (audit 2026-06-20): a SYMLINKED FILE is NOT // followed (a malicious .php reachable via an in-install // symlink must not be hashed through the link), but skipping // it silently left it OUTSIDE coverage while the report said // "complete". Count it as a discovery skip so the EXISTING // incomplete/RC-116-07 chain marks the scan incomplete. if ( @is_link( $fp ) ) { $discovery_skipped++; continue; } // ACG-031-005: an unreadable file is a discovery gap, not a silent drop. if ( ! @is_readable( $fp ) ) { $discovery_skipped++; continue; } $all_files[] = $fp; } } catch ( Exception $e ) { // ACG-032-007: a swallowed root-iterator failure means part of // this path's subtree was never walked. Count it so coverage is // marked incomplete instead of silently reporting "complete". $discovery_skipped++; continue; } } } $total = count( $all_files ); if ( $total > self::MAX_FILES ) { return array( 'success' => false, 'error' => sprintf( /* translators: %1$s is the number of files on the site, %2$s is the maximum allowed file count */ __( 'Site has %1$s files which exceeds the %2$s file limit. This prevents memory issues. Please use Directory Exclusions in Settings to exclude large folders like cache, backups, or node_modules.', 'ai-cyberguard' ), number_format( $total ), number_format( self::MAX_FILES ) ), ); } // ACG-050-001 (audit 2026-06-23, HIGH-COND): verify ownership IMMEDIATELY BEFORE the FIRST shared write // after enumeration. If a successor stale-took-over the lease during the (slow) discovery above, this stale // generation must NOT write into the shared scan namespace and must return WITHOUT cleanup — cleanup_batch_data( $owner ) // deletes the SHARED keys, which now belong to the successor. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // FIX: Store file list in JSON file (written ONCE, read-only during scan) // ACG-052-001: init is a CLAIM (true) — it may supersede a previous, abandoned generation. if ( ! self::save_scan_data( 'batch_files', $all_files, $owner, true, 'integrity' ) ) { if ( ! self::owner_lost( 'integrity', $owner ) ) { self::cleanup_batch_data( $owner ); } // own-generation failure only return array( 'success' => false, // ACG-121 C5: name BOTH real causes. This write fails when wp-content/ is not writable OR when // the filesystem provides no working flock() (some NFS/OpenVZ mounts) — the record is then // refused rather than written unlocked, where a stale generation could clobber a successor. // The old text blamed permissions only, sending admins to chase a non-existent chmod problem. 'error' => __( 'Could not save scan data. Either wp-content/ is not writable, or this server\'s filesystem does not support file locking (some NFS/OpenVZ mounts) — the scan will not run unlocked. Check the folder permissions first; if they are correct, ask your host about flock() support.', 'ai-cyberguard' ), ); } // Create initial state (lightweight — files[] stored separately above) $state = array( 'status' => 'scanning', 'is_full' => $is_full, 'total' => $total, 'processed' => 0, 'offset' => 0, 'started_at' => time(), 'report' => array( 'time' => current_time( 'mysql' ), 'total' => 0, 'unchanged' => 0, 'changed' => 0, 'new' => 0, 'deleted' => 0, // RC-116-07: files discovered but missing/unreadable/unhashable at batch time. // ACG-031-005: seeded with DISCOVERY-time skips (unreadable/symlinked dirs + // unreadable files) so a subtree never walked also marks the scan incomplete. 'skipped' => $discovery_skipped, 'details' => array(), // ACG-149-R37-X: findings this scan had to drop at MAX_DETAILS. Always present so a // consumer can read it without isset() and can never mistake "absent" for "none". 'details_dropped' => 0, 'no_baseline' => false, ), ); // ACG-050-001: re-verify ownership before EVERY subsequent shared write (the takeover can land between writes). if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // Initialize current_keys in its own file (grows large on big sites) if ( ! self::save_scan_data( 'batch_current_keys', array(), $owner, true, 'integrity' ) ) { if ( ! self::owner_lost( 'integrity', $owner ) ) { self::cleanup_batch_data( $owner ); } // own-generation failure only return array( 'success' => false, 'error' => __( 'Failed to initialize scan tracking. Check file permissions.', 'ai-cyberguard' ), ); } // ACG-049-001 / ACG-050-001: do not commit init state if a successor stale-took-over; never cleanup on loss. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // ACG-052-001: init state is a CLAIM (true). if ( ! self::save_scan_data( 'batch_state', $state, $owner, true, 'integrity' ) ) { if ( ! self::owner_lost( 'integrity', $owner ) ) { self::cleanup_batch_data( $owner ); } // own-generation failure only return array( 'success' => false, 'error' => __( 'Failed to save scan state. Check file permissions on wp-content/.', 'ai-cyberguard' ), ); } return array( 'success' => true, 'status' => 'scanning', 'total' => $total, 'processed' => 0, 'percent' => 0, /* translators: %s is the number of files found to scan */ 'message' => sprintf( __( 'Found %s files to scan', 'ai-cyberguard' ), number_format( $total ) ), ); } /** * ACG-083-003 (audit 2026-06-27): the no-follow contract for hashing an attacker-controllable site file. Prefers * the shared GuardPress_FS_Helpers primitive (ACG-083-H1); falls back to a self-contained, trusted-root-aware copy * when FS_Helpers lacks it. True ONLY for a REGULAR file with NO symlink component below the deepest trusted root * (ABSPATH / WP_CONTENT_DIR / uploads basedir — host may symlink those, not a deeper one) and a contained realpath. * Without this, a path discovered as a normal file but whose PARENT was swapped to a symlink after discovery would * realpath()/hash_file() an EXTERNAL target and record an outside key (is_link($fp) tested only the basename). * * @param string $path Absolute filesystem path. * @return bool */ private static function is_safe_regular_file( $path ) { if ( class_exists( 'GuardPress_FS_Helpers' ) && method_exists( 'GuardPress_FS_Helpers', 'regular_file_in_abspath_no_symlink_components' ) ) { return GuardPress_FS_Helpers::regular_file_in_abspath_no_symlink_components( $path ); } $path = (string) $path; if ( '' === $path || ! defined( 'ABSPATH' ) ) { return false; } clearstatcache( false, $path ); if ( @is_link( $path ) || ! @is_file( $path ) ) { return false; } $norm = static function ( $p ) { return str_replace( '\\', '/', (string) $p ); }; $full = $norm( $path ); $roots = array(); if ( function_exists( 'wp_upload_dir' ) ) { $u = @wp_upload_dir( null, false ); if ( is_array( $u ) && ! empty( $u['basedir'] ) ) { $roots[] = $u['basedir']; } } if ( defined( 'WP_CONTENT_DIR' ) ) { $roots[] = WP_CONTENT_DIR; } $roots[] = ABSPATH; $base = null; foreach ( $roots as $r ) { $rn = rtrim( $norm( $r ), '/' ); if ( '' !== $rn && 0 === strpos( $full, $rn . '/' ) ) { $base = $rn; break; } } if ( null === $base ) { $ra = @realpath( ABSPATH ); $rp = @realpath( $path ); return ( false !== $ra && false !== $rp && 0 === strpos( $norm( $rp ), rtrim( $norm( $ra ), '/' ) . '/' ) ); } $rel = substr( $full, strlen( $base ) + 1 ); $cur = $base; foreach ( explode( '/', $rel ) as $p ) { if ( '' === $p || '.' === $p ) { continue; } if ( '..' === $p ) { return false; } $cur .= '/' . $p; clearstatcache( false, $cur ); if ( @is_link( $cur ) ) { return false; } } $rp = @realpath( $path ); $rb = @realpath( $base ); if ( false === $rp || false === $rb ) { return false; } return ( 0 === strpos( $norm( $rp ), rtrim( $norm( $rb ), '/' ) . '/' ) ); } /** * Process one batch of files * * @return array Progress update or completion status */ public static function process_batch( $owner = null ) { $state = self::load_scan_data( 'batch_state', null, $owner ); if ( ! $state || $state['status'] !== 'scanning' ) { return array( 'success' => false, 'error' => __( 'No scan in progress', 'ai-cyberguard' ), ); } // GP-REL-002 (audit 2026-06-19): the Full/Regular scan mode is a per-request // static (GuardPress_FS_Helpers::$full_scan). It is set once in init_scan(), // but every process_batch() is a SEPARATE admin-ajax request where that // static defaults back to false. The deleted-file loop below calls // should_exclude_path(), which in Regular mode excludes all non-risky files // (e.g. a deleted .txt) — so a FULL scan's deleted-file detection was // silently running in Regular mode and MISSING deletions of non-code files. // Restore the mode from the persisted $state['is_full'] before any // should_exclude_path() use. The hashing loop iterates the frozen $all_files // and never consulted this static, so changed/new/malware detection is // unaffected — this only fixes the deleted-file loop. if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( ! empty( $state['is_full'] ) ); } $all_files = self::load_scan_data( 'batch_files', array(), $owner ); if ( empty( $all_files ) ) { self::cleanup_batch_data( $owner ); return array( 'success' => false, 'error' => __( 'Scan file list not found. Please restart the scan.', 'ai-cyberguard' ), ); } $baseline = class_exists( 'GuardPress_Baseline' ) ? GuardPress_Baseline::get() : array(); // FIX (false-positive logic, 2026-06-15): when NO baseline exists yet (fresh // install, or it was never created), EVERY file is "not in baseline" and the // diff below would mark them all 'new' — thousands of false positives on // legitimate WordPress core files (e.g. wp-admin/about.php). Detect the // no-baseline case so the diff suppresses new-file findings and flags the // report; the UI then prompts the user to create a baseline (the explicit, // correct way to record the site's clean state). The Malware Scan is // independent and still finds real threats by content. $has_baseline = ! empty( $baseline ); // FIX: current_keys stored in own file (prevents state bloat on large sites) $current_keys = self::load_scan_data( 'batch_current_keys', array(), $owner ); $start_time = microtime( true ); $offset = $state['offset']; $batch_end = min( $offset + self::BATCH_SIZE, $state['total'] ); $processed_in_batch = 0; for ( $i = $offset; $i < $batch_end; $i++ ) { if ( microtime( true ) - $start_time > self::MAX_BATCH_TIME ) { break; } if ( ! isset( $all_files[ $i ] ) ) { $processed_in_batch++; continue; } $fp = $all_files[ $i ]; // ACG-081-003 / ACG-083-003 (audit 2026-06-27, HIGH): apply the full no-follow contract IMMEDIATELY before // realpath()/hash_file(). A path discovered as a normal in-install file can be swapped to a symlink — or // have its PARENT directory swapped to a symlink (ACG-083-003) — before process_batch() runs (TOCTOU). // is_link($fp) tested only the basename, so a symlinked ANCESTOR let realpath()/hash_file() resolve and hash // the link's EXTERNAL target and record a current_keys entry OUTSIDE the install. is_safe_regular_file() // rejects any symlink path component + non-regular file; at processing time that is a coverage gap. if ( ! self::is_safe_regular_file( $fp ) || ! @is_readable( $fp ) ) { // RC-116-07: a file discovered at scan start but missing/unreadable/unsafe now is a // coverage gap, not a silent skip — count it so the report shows incomplete. $state['report']['skipped']++; $processed_in_batch++; continue; } $real = function_exists( 'realpath' ) ? realpath( $fp ) : $fp; $key = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::normalize_path( $real ? $real : $fp ) : strtolower( str_replace( '\\', '/', $fp ) ); $current_keys[ $key ] = true; $state['report']['total']++; // ACG-121 A4: cap size BEFORE hashing (see MAX_HASH_BYTES) — an un-interruptible hash_file() // on a multi-GB file kills the request mid-hash and the client retries the same offset forever. // Advance the offset so the scan progresses, and record the skip in its own reported bucket. // // ACG-137-B5: the cap decides whether we HASH — it must NOT decide whether the file is // INTERESTING. Those are different questions, and conflating them is what made a baselined file // padded past the cap vanish from the report entirely. What makes a skip a KNOWN BOUNDARY versus // a REAL EVENT is whether the file was previously baselined (see the 'oversize' marker written in // process_baseline_batch). $fsize = @filesize( $fp ); $in_baseline = isset( $baseline[ $key ] ); $was_oversize = $in_baseline && ! empty( $baseline[ $key ]['oversize'] ); if ( false !== $fsize && $fsize > self::MAX_HASH_BYTES ) { $state['report']['skipped_large'] = ( isset( $state['report']['skipped_large'] ) ? (int) $state['report']['skipped_large'] : 0 ) + 1; if ( $in_baseline && ! $was_oversize ) { // A KNOWN CODE FILE HAS CROSSED THE CAP. This is a real, PROVEN change: a baseline entry // without the marker was necessarily <= cap when it was indexed, so its size changed. We // cannot say HOW the content changed (we refuse to hash it), but staying silent is what // let an attacker pad a monitored file out of monitoring. Report it. $state['report']['changed']++; $gp_norm_big = wp_normalize_path( $fp ); if ( self::detail_room( $state['report'] ) ) { $state['report']['details'][ $gp_norm_big ] = array( 'status' => 'changed', 'note' => __( 'This file grew past the 50 MB integrity limit, so its contents are no longer checked. A code file that suddenly becomes this large is worth a look.', 'ai-cyberguard' ), 'baseline_hash' => isset( $baseline[ $key ]['hash'] ) ? $baseline[ $key ]['hash'] : '', 'current_hash' => '', 'mtime' => ( $gp_mt_big = @filemtime( $fp ) ) ? (int) $gp_mt_big : 0, ); } } // Otherwise: never indexed, or indexed AS oversize and still oversize — a known boundary. // It stays a coverage fact (skipped_large) and makes no change claim. $processed_in_batch++; continue; } $hash = @hash_file( 'sha256', $fp ); if ( ! $hash ) { $state['report']['skipped']++; // RC-116-07: unhashable file is a coverage gap $processed_in_batch++; continue; } $normalized_fp = wp_normalize_path( $fp ); if ( $in_baseline ) { if ( $was_oversize ) { // ACG-137-B5: it was over the cap when indexed and is now under it — the file demonstrably // changed (it shrank across the boundary). It is NOT new: it existed at baseline time. The // old code had no record of it, so it fell to the 'new' branch below and raised a false // alarm (and burned the email-alert budget) on a file that had always been there. $state['report']['changed']++; if ( self::detail_room( $state['report'] ) ) { $state['report']['details'][ $normalized_fp ] = array( 'status' => 'changed', 'note' => __( 'This file used to be too large to check and is now small enough — so it has changed. Its contents are being checked again from now on.', 'ai-cyberguard' ), 'baseline_hash' => '', 'current_hash' => $hash, 'mtime' => ( $gp_mt_sh = @filemtime( $fp ) ) ? (int) $gp_mt_sh : 0, ); } } elseif ( $baseline[ $key ]['hash'] === $hash ) { $state['report']['unchanged']++; } else { $mtime = @filemtime( $fp ); $state['report']['changed']++; if ( self::detail_room( $state['report'] ) ) { $state['report']['details'][ $normalized_fp ] = array( 'status' => 'changed', 'note' => self::status_hint( $fp, 'changed' ), 'baseline_hash' => $baseline[ $key ]['hash'], 'current_hash' => $hash, 'mtime' => $mtime ? (int) $mtime : 0, ); } } } elseif ( ! $has_baseline ) { // No baseline at all — "not in baseline" is meaningless (it's true for // EVERY file). Count the file as seen but emit NO new-file finding, // and flag the report so the UI prompts the user to create a baseline. $state['report']['unchanged']++; $state['report']['no_baseline'] = true; } else { $state['report']['new']++; if ( self::detail_room( $state['report'] ) ) { $state['report']['details'][ $normalized_fp ] = array( 'status' => 'new', 'note' => self::status_hint( $fp, 'new' ), ); } } $processed_in_batch++; } $state['offset'] = $offset + $processed_in_batch; $state['processed'] = $state['offset']; // ACG-050-001 (audit 2026-06-23): a stale process_batch must not write current_keys/state over a successor. // Verify ownership immediately before this shared write; on loss return WITHOUT writing or cleaning up. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // Save current_keys separately (can be 15-20MB on large sites) if ( ! self::save_scan_data( 'batch_current_keys', $current_keys, $owner, false, 'integrity' ) ) { // ACG-052-001: a false return can mean the CAS REFUSED the write because a successor took over (not a // disk error). If we no longer own the scan, report that — never the misleading disk-full message — and // never touch the successor's state. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } // CRITICAL: If current_keys write fails, subsequent batches would lose // all previously-seen keys, causing false "deleted" results. Stop scan. // ACG-050-001: the error-state commit must also prove ownership (don't overwrite a successor's state). $state['status'] = 'error'; if ( ! self::owner_lost( 'integrity', $owner ) ) { self::save_scan_data( 'batch_state', $state, $owner, false, 'integrity' ); } return array( 'success' => false, 'error' => __( 'Failed to save scan tracking data (disk full?). Scan aborted to prevent incorrect results.', 'ai-cyberguard' ), ); } $percent = $state['total'] > 0 ? round( ( $state['processed'] / $state['total'] ) * 100, 1 ) : 0; // Check if we've processed all files if ( $state['offset'] >= $state['total'] ) { foreach ( $baseline as $bkey => $bdata ) { $display = isset( $bdata['path'] ) ? $bdata['path'] : $bkey; if ( class_exists( 'GuardPress_FS_Helpers' ) && GuardPress_FS_Helpers::should_exclude_path( $display ) ) { continue; } if ( ! isset( $current_keys[ $bkey ] ) ) { $state['report']['deleted']++; if ( self::detail_room( $state['report'] ) ) { $normalized_display = wp_normalize_path( $display ); $state['report']['details'][ $normalized_display ] = array( 'status' => 'deleted' ); } } } $state['status'] = 'complete'; // ACG-049-001: verify ownership immediately before the authoritative 'complete' commit. if ( self::owner_lost( 'integrity', $owner ) ) { return array( 'success' => false, 'not_owner' => true, 'error' => __( 'This scan was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ) ); } // GP-REL-021 (audit 2026-06-19): this is the ONE write that carries the // deleted-file results plus the 'complete' status that finalize_scan() // requires before it will persist the report. If this save silently // fails (disk full / permissions), the next finalize would either // refuse (status not 'complete') or — worse on a stale read — report a // phantom "complete" with the deleted-file findings lost. Verify the // commit; on failure surface the same disk-full error already used for // current_keys instead of claiming success. if ( ! self::save_scan_data( 'batch_state', $state, $owner, false, 'integrity' ) ) { // ACG-052-001: CAS refusal (successor took over) reports not_owner, not disk-full. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } return array( 'success' => false, 'error' => __( 'Failed to save final scan results (disk full?). Scan aborted to prevent incorrect results.', 'ai-cyberguard' ), ); } return array( 'success' => true, 'status' => 'complete', 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => 100, 'message' => __( 'Scan complete!', 'ai-cyberguard' ), ); } // ACG-049-001: verify ownership immediately before the mid-scan progress commit. if ( self::owner_lost( 'integrity', $owner ) ) { return array( 'success' => false, 'not_owner' => true, 'error' => __( 'This scan was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ) ); } // GP-REL-021: a failed mid-scan progress write means the next batch would // resume from a stale offset and re-process / mis-attribute files. Surface // it rather than silently continuing on a state that was never committed. if ( ! self::save_scan_data( 'batch_state', $state, $owner, false, 'integrity' ) ) { // ACG-052-001: CAS refusal (successor took over) reports not_owner, not disk-full. if ( self::owner_lost( 'integrity', $owner ) ) { return self::not_owner_result(); } return array( 'success' => false, 'error' => __( 'Failed to save scan progress (disk full?). Scan aborted to prevent incorrect results.', 'ai-cyberguard' ), ); } $elapsed = time() - ( isset( $state['started_at'] ) ? $state['started_at'] : time() ); $rate = $state['processed'] > 0 ? $elapsed / $state['processed'] : 0; $remaining_files = $state['total'] - $state['processed']; $eta_seconds = $rate > 0 ? round( $rate * $remaining_files ) : 0; return array( 'success' => true, 'status' => 'scanning', 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => $percent, 'eta' => $eta_seconds, 'message' => sprintf( /* translators: %1$s is the number of files processed, %2$s is the total file count, %3$s is the percent complete */ __( 'Scanning... %1$s of %2$s files (%3$s%%)', 'ai-cyberguard' ), number_format( $state['processed'] ), number_format( $state['total'] ), $percent ), ); } /** * Finalize the scan and save results * * @return array Final report */ public static function finalize_scan( $owner = null ) { $state = self::load_scan_data( 'batch_state', null, $owner ); if ( ! $state || ! isset( $state['report'] ) ) { self::cleanup_batch_data( $owner ); return array( 'success' => false, 'error' => __( 'No scan data found', 'ai-cyberguard' ), ); } // FIX F-1 (audit 2026-05-25 round 2): refuse to persist a scan // result when the scan was NOT actually completed. Previously, // init_scan → finalize_scan (skipping every process_batch) would // persist a fake "all clear" report — wiping any real findings // from a previous scan and silently disabling email alerts. // // ACG-032-005 (audit 2026-06-20): a scan is "complete" ONLY when // process_batch promoted state['status'] to 'complete' after hashing // every file AND durably committing the final batch_state. The old // counter-fallback (processed >= total) WRONGLY upgraded a FAILED // last batch to success: a last-batch persistence failure leaves // state['status'] === 'error' with processed === total, and that OR // branch published a phantom "all clear", wiping real findings. // NEVER infer success from counters — require the explicit 'complete' // status (and, when the state carries a scan_id, a matching stored id). // An 'error' or 'cancelled' state is TERMINAL and NON-finalizable: // return an error WITHOUT publishing and WITHOUT deleting the // resumable state (so the prior good report survives). $status = isset( $state['status'] ) ? $state['status'] : ''; if ( 'error' === $status || 'cancelled' === $status ) { // Terminal failure/cancel — do NOT publish, do NOT cleanup. The // last good report stays intact; the user restarts or cancels. return array( 'success' => false, 'error' => __( 'Cannot finalize: the scan ended in an error or was cancelled. No results were saved — your previous scan report is unchanged. Please run the scan again.', 'ai-cyberguard' ), 'processed' => isset( $state['processed'] ) ? (int) $state['processed'] : 0, 'total' => isset( $state['total'] ) ? (int) $state['total'] : 0, ); } $is_complete = ( 'complete' === $status ); // If a scan_id was stamped into the state, the persisted state must // carry the SAME id we expect to finalize — guards against finalizing // a stale/mismatched state. if ( $is_complete && isset( $state['scan_id'], $state['finalize_scan_id'] ) ) { $is_complete = ( (string) $state['scan_id'] === (string) $state['finalize_scan_id'] ); } if ( ! $is_complete ) { // Do NOT cleanup_batch_data here — the user might want to resume // by calling process_batch. We only refuse the finalize. return array( 'success' => false, 'error' => __( 'Cannot finalize: scan is still in progress or has not run. Continue processing batches first, or use Cancel to start over.', 'ai-cyberguard' ), 'processed' => isset( $state['processed'] ) ? (int) $state['processed'] : 0, 'total' => isset( $state['total'] ) ? (int) $state['total'] : 0, ); } // ACG-032-006 (audit 2026-06-20): the final report write AND the // scan-meta write are the durable record of this scan. The old code // ignored BOTH return values and ran cleanup_batch_data( $owner ) + returned // success regardless — so a silent commit failure (disk full / // permissions) deleted the resumable state, overwrote (or failed to // write) the report, and still claimed "Scan complete". Now: attempt // both writes, VERIFY by read-back (the meta especially), and only // cleanup once BOTH commits verify. If either fails, KEEP the // resumable state, do NOT overwrite the prior report, and return a // retryable error so the user can re-finalize. // Build the report payload but do NOT clobber the prior report unless // we can verify the write landed. update_option returns false both on // failure AND when the value is unchanged, so we read back to confirm. $report_payload = $state['report']; update_option( 'guardpress_last_report_v1', $report_payload, false ); $report_saved = ( get_option( 'guardpress_last_report_v1' ) === $report_payload ); // FIX H-10 (audit 2026-05-25): autoload=false. Same scan-meta option as // class-cron.php — kept consistent in autoload flag so a manual scan // followed by a scheduled scan doesn't flip the autoload setting. // RC-118-05 (audit 2026-06-18): persist the coverage state so the dashboard banner, // widget and weekly digest can show AMBER ("scan incomplete") instead of a green // "All clear" when a file was skipped (missing/unreadable/unhashable mid-scan). The // return value already carried this, but the SAVED meta did not, so every UI that // reads the option showed green regardless. // ACG-137-B2: ask the ONE definition (GuardPress_FS_Helpers::coverage_gap_count) so this path and // class-cron.php can never disagree about the same file again. 'incomplete' means a FAILURE to // inspect (unreadable/unhashable) — NOT an over-cap file, which is a known boundary carried in its // own key. See coverage_gap_count() for why folding the two together was the wrong fix. $reg_skipped = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::coverage_gap_count( $state['report'] ) : (int) ( $state['report']['skipped'] ?? 0 ); $reg_oversize = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::oversize_count( $state['report'] ) : (int) ( $state['report']['skipped_large'] ?? 0 ); $meta_payload = array( 'time' => time(), 'type' => ! empty( $state['is_full'] ) ? 'Full' : 'Regular', 'skipped' => $reg_skipped, 'incomplete' => ( $reg_skipped > 0 ), // ACG-137-B2: the boundary travels as its own durable fact so the UI can state it plainly // instead of either hiding it or mislabelling it as "could not be read". 'skipped_large' => $reg_oversize, ); update_option( 'guardpress_last_scan_meta', $meta_payload, false ); // Verify the meta especially: read it back and confirm the durable // fields match what we intended to commit. $meta_back = get_option( 'guardpress_last_scan_meta' ); $meta_saved = ( is_array( $meta_back ) && isset( $meta_back['time'], $meta_back['type'], $meta_back['skipped'], $meta_back['incomplete'] ) && (int) $meta_back['time'] === (int) $meta_payload['time'] && (string) $meta_back['type'] === (string) $meta_payload['type'] && (int) $meta_back['skipped'] === (int) $meta_payload['skipped'] && (bool) $meta_back['incomplete'] === (bool) $meta_payload['incomplete'] ); if ( ! $report_saved || ! $meta_saved ) { // A commit did not verify. KEEP the resumable state (no cleanup), // do NOT trust the half-written report/meta, and ask the user to // retry the finalize. if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [finalize_scan]: commit verify failed (report=' . ( $report_saved ? '1' : '0' ) . ', meta=' . ( $meta_saved ? '1' : '0' ) . ') — keeping resumable state' ); } return array( 'success' => false, 'error' => __( 'Failed to save scan results (disk full or permissions?). Your previous report was not changed. Please try finalizing again.', 'ai-cyberguard' ), ); } delete_option( 'guardpress_ai_last_analysis' ); delete_transient( 'guardpress_db_scan_results' ); delete_transient( 'guardpress_core_verify_results' ); if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( false ); } $duration = time() - ( isset( $state['started_at'] ) ? $state['started_at'] : time() ); // Both commits verified — now it is safe to drop the resumable state. self::cleanup_batch_data( $owner ); return array( 'success' => true, 'status' => 'finalized', 'report' => array( 'total' => $state['report']['total'], 'unchanged' => $state['report']['unchanged'], 'changed' => $state['report']['changed'], 'new' => $state['report']['new'], 'deleted' => $state['report']['deleted'], 'skipped' => isset( $state['report']['skipped'] ) ? (int) $state['report']['skipped'] : 0, // RC-116-07 // ACG-137-B2: skipped_large was PRODUCED by process_batch() and then dropped right here — // this literal enumerates the keys, so the count never reached the caller at all. // It has a real reader: the durable meta written above -> the status banner // (class-view-scanner.php, $reg_oversize). // NOTE (self-review round 2): a 'coverage_gap' key was here too and I removed it — it had // ZERO readers. Adding a key nobody reads, inside the very round whose subject is "a fact // that never reaches the user", is the same defect wearing my name. If a consumer ever needs // it, it is one call to GuardPress_FS_Helpers::coverage_gap_count(). 'skipped_large' => isset( $state['report']['skipped_large'] ) ? (int) $state['report']['skipped_large'] : 0, ), 'incomplete' => ( $reg_skipped > 0 ), 'duration' => $duration, 'message' => sprintf( /* translators: %1$s is the number of files scanned, %2$s is the scan duration in seconds */ __( 'Scan complete! Scanned %1$s files in %2$s seconds.', 'ai-cyberguard' ), number_format( $state['report']['total'] ), $duration ), ); } /** * Cancel an ongoing scan */ public static function cancel_scan() { $has_scan = self::load_scan_data( 'batch_state' ); self::cleanup_batch_data(); if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( false ); } if ( $has_scan ) { return array( 'success' => true, 'message' => __( 'Scan cancelled', 'ai-cyberguard' ) ); } return array( 'success' => true, 'message' => __( 'No scan in progress', 'ai-cyberguard' ) ); } /** * Get current scan progress */ public static function get_progress() { $state = self::load_scan_data( 'batch_state' ); if ( ! $state ) { return null; } $percent = $state['total'] > 0 ? round( ( $state['processed'] / $state['total'] ) * 100, 1 ) : 0; return array( 'status' => $state['status'], 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => $percent, ); } /** * Check if a scan is in progress */ public static function is_scanning() { $state = self::load_scan_data( 'batch_state' ); return $state && isset( $state['status'] ) && $state['status'] === 'scanning'; } /** * Generate status hint for a file */ private static function status_hint( $path, $status ) { $l = strtolower( str_replace( '\\', '/', $path ) ); if ( strpos( $l, '/wp-content/plugins/' ) !== false || strpos( $l, '/wp-content/themes/' ) !== false || strpos( $l, '/wp-includes/' ) !== false ) { return __( 'Likely a legitimate WordPress/plugin/theme update', 'ai-cyberguard' ); } return ''; } // ========================================================================= // BATCHED BASELINE CREATION // ========================================================================= /** * Initialize baseline creation */ public static function init_baseline( $owner = null ) { // ACG-051-001 (audit 2026-06-23): verify ownership BEFORE the leftover-data cleanup (a successor that // already took over owns the shared baseline keys — a stale generation must not delete them). if ( self::owner_lost( 'baseline', $owner ) ) { return self::not_owner_result(); } self::cleanup_baseline_data( $owner ); // GP-REL-020 (audit 2026-06-19): a baseline is a FULL index, so enumerate // in Full-scan mode and apply the SAME should_exclude_path/is_ignored // filter the scan uses. In Full mode should_exclude_path() only strips the // GuardPress self-artifact dirs (baseline/reports/guardpress-data) and the // admin's user-excluded dirs — it returns false for every real code/config // file, so no risky file is ever dropped. Without this, the baseline // indexes its own state JSON (which the scan enumeration excludes), and // every later scan reports those self-artifacts as spuriously "deleted". // GuardPress_Scan_Runner already applies should_exclude_path; this aligns // the batched baseline with it. The mode static is per-request, so we set // it here for enumeration and reset it in a finally block. $has_helpers = class_exists( 'GuardPress_FS_Helpers' ); $had_full = false; if ( $has_helpers ) { $had_full = GuardPress_FS_Helpers::is_full_scan(); GuardPress_FS_Helpers::set_full_scan( true ); } $root = rtrim( ABSPATH, "/\\" ) . DIRECTORY_SEPARATOR; $all_files = array(); // ACG-031-006 (audit 2026-06-20): a baseline is the TRUST SOURCE for every // future scan. The SELF_FIRST + CATCH_GET_CHILD iterator silently skips an // unreadable subdirectory (children swallowed) and an unreadable file, so a // partial baseline could be PUBLISHED with skipped=0 — bypassing the // RC-116-07 guard in finalize_baseline() and replacing a prior good // baseline (the records for the unreadable area vanish from the trust set). // Count every discovery skip and seed it into state['skipped'] so the // EXISTING guard refuses to publish and keeps the last-good baseline. $discovery_skipped = 0; try { // FIX (audit 2026-06-10): CATCH_GET_CHILD — skip unreadable subdirs // instead of aborting the whole baseline build (same omission as the // scan enumeration above). $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD ); foreach ( $iterator as $file ) { // ACG-031-006: an unreadable/symlinked directory was not walked — // its whole subtree is missing from the index. if ( $file->isDir() ) { $dp = $file->getPathname(); // ACG-082-H3 (audit 2026-06-27, MED): exclude an out-of-scope dir BEFORE counting a symlinked/ // unreadable EXCLUDED dir as a coverage gap (would falsely block baseline finalization). if ( $has_helpers && ( GuardPress_FS_Helpers::should_exclude_path( $dp ) || GuardPress_FS_Helpers::is_ignored( $dp ) ) ) { continue; } if ( $file->isLink() || ! @is_readable( $dp ) ) { $discovery_skipped++; } continue; } if ( ! $file->isFile() ) continue; $fp = $file->getPathname(); // ACG-081-H2 (audit 2026-06-27, MED): GP-REL-020 exclusions BEFORE the symlink coverage-gap logic so // an excluded/internal symlink does not count as a discovery skip and block baseline finalization. if ( $has_helpers ) { if ( GuardPress_FS_Helpers::should_exclude_path( $fp ) ) continue; if ( GuardPress_FS_Helpers::is_ignored( $fp ) ) continue; } // ACG-032-007 (audit 2026-06-20): an IN-SCOPE SYMLINKED FILE is not followed // into the baseline (we never hash through an in-install symlink), // but skipping it silently would publish a baseline that omits it // with skipped=0 — bypassing the RC-116-07 publish guard. Count it // as a discovery skip so finalize_baseline() refuses to overwrite // the prior trusted baseline. if ( @is_link( $fp ) ) { $discovery_skipped++; continue; } // ACG-031-006: an unreadable file is a discovery gap, not a silent drop. if ( ! @is_readable( $fp ) ) { $discovery_skipped++; continue; } $all_files[] = $fp; } } catch ( Exception $e ) { if ( $has_helpers ) { GuardPress_FS_Helpers::set_full_scan( $had_full ); } // ACG-032-007: a swallowed traversal failure means part of the install // was never walked. A baseline is a TRUST SOURCE — refuse to build one // from a partial walk rather than returning an error that the caller // might treat as "try later". Keeping the prior baseline intact is the // safe outcome; surfacing the error here already aborts the build. return array( 'success' => false, 'error' => $e->getMessage() ); } // GP-REL-020: enumeration done; restore the prior mode. (process_*_batch // and finalize do not call should_exclude_path, so the file-list captured // here is the single source of truth for what gets indexed.) if ( $has_helpers ) { GuardPress_FS_Helpers::set_full_scan( $had_full ); } $total = count( $all_files ); if ( $total > self::MAX_FILES ) { return array( 'success' => false, 'error' => sprintf( /* translators: %1$s is the number of files on the site, %2$s is the maximum allowed file count */ __( 'Site has %1$s files which exceeds the %2$s file limit. This prevents memory issues. Please use Directory Exclusions in Settings to exclude large folders like cache, backups, or node_modules.', 'ai-cyberguard' ), number_format( $total ), number_format( self::MAX_FILES ) ), ); } // ACG-050-001 (audit 2026-06-23): verify ownership IMMEDIATELY BEFORE the FIRST shared write after // enumeration; a stale generation must not write into the shared baseline namespace, and on loss returns // WITHOUT cleanup (cleanup_baseline_data deletes the SHARED keys, now the successor's). if ( self::owner_lost( 'baseline', $owner ) ) { return self::not_owner_result(); } // FIX: Store file list in JSON file (written ONCE) // ACG-052-001: init is a CLAIM (true). if ( ! self::save_scan_data( 'baseline_files', $all_files, $owner, true, 'baseline' ) ) { if ( ! self::owner_lost( 'baseline', $owner ) ) { self::cleanup_baseline_data( $owner ); } // own-generation failure only return array( 'success' => false, 'error' => __( 'Failed to save baseline data. Check file permissions on wp-content/.', 'ai-cyberguard' ), ); } $state = array( 'status' => 'creating', 'total' => $total, 'processed' => 0, 'offset' => 0, 'started_at' => time(), 'baseline' => array(), // RC-116-07: files that became missing/unreadable during the build. // ACG-031-006: seeded with DISCOVERY-time skips so finalize_baseline()'s // RC-116-07 guard refuses to publish a baseline that never walked part // of the site, keeping the prior trusted baseline intact. 'skipped' => $discovery_skipped, ); // ACG-049-001 / ACG-050-001: do not commit baseline-init state if a successor stale-took-over; never cleanup on loss. if ( self::owner_lost( 'baseline', $owner ) ) { return self::not_owner_result(); } // ACG-052-001: init state is a CLAIM (true). if ( ! self::save_scan_data( 'baseline_state', $state, $owner, true, 'baseline' ) ) { if ( ! self::owner_lost( 'baseline', $owner ) ) { self::cleanup_baseline_data( $owner ); } // own-generation failure only return array( 'success' => false, 'error' => __( 'Failed to save baseline state. Check file permissions on wp-content/.', 'ai-cyberguard' ), ); } return array( 'success' => true, 'status' => 'creating', 'total' => $total, 'processed' => 0, 'percent' => 0, /* translators: %s is the number of files found to index */ 'message' => sprintf( __( 'Found %s files to index', 'ai-cyberguard' ), number_format( $total ) ), ); } /** * Process one batch of files for baseline */ public static function process_baseline_batch( $owner = null ) { $state = self::load_scan_data( 'baseline_state', null, $owner ); if ( ! $state || $state['status'] !== 'creating' ) { return array( 'success' => false, 'error' => __( 'No baseline creation in progress', 'ai-cyberguard' ) ); } $all_files = self::load_scan_data( 'baseline_files', array(), $owner ); if ( empty( $all_files ) ) { self::cleanup_baseline_data( $owner ); return array( 'success' => false, 'error' => __( 'Baseline file list not found. Please restart.', 'ai-cyberguard' ) ); } $start_time = microtime( true ); $offset = $state['offset']; $batch_end = min( $offset + self::BATCH_SIZE, $state['total'] ); $processed_in_batch = 0; for ( $i = $offset; $i < $batch_end; $i++ ) { if ( microtime( true ) - $start_time > self::MAX_BATCH_TIME ) { break; } if ( ! isset( $all_files[ $i ] ) ) { $processed_in_batch++; continue; } $fp = $all_files[ $i ]; // ACG-081-003 / ACG-083-003 (audit 2026-06-27, HIGH): apply the full no-follow contract before realpath()/ // hash_file() — a TOCTOU swap of a discovered real file to a symlink, OR of its PARENT directory to a // symlink (ACG-083-003), would otherwise hash the external target and index a baseline key OUTSIDE the // install (is_link($fp) tested only the basename). is_safe_regular_file() rejects any symlink component. if ( ! self::is_safe_regular_file( $fp ) || ! @is_readable( $fp ) ) { $state['skipped'] = ( isset( $state['skipped'] ) ? $state['skipped'] : 0 ) + 1; $processed_in_batch++; continue; } // RC-116-07 / ACG-081-003 / ACG-083-003 $real = function_exists( 'realpath' ) ? realpath( $fp ) : $fp; $key = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::normalize_path( $real ? $real : $fp ) : strtolower( str_replace( '\\', '/', $fp ) ); // ACG-121 A4: cap size BEFORE hashing (see MAX_HASH_BYTES). Baseline creation walks ALL of // ABSPATH, so one large media/backup file used to wedge baseline building forever — and with // no baseline the whole integrity feature is unusable. $fsize_pre = @filesize( $fp ); if ( false !== $fsize_pre && $fsize_pre > self::MAX_HASH_BYTES ) { $state['skipped_large'] = ( isset( $state['skipped_large'] ) ? (int) $state['skipped_large'] : 0 ) + 1; // ACG-137-B5 (self-review of the v1.0.137 diff, 2026-07-17): RECORD the oversize file in the // baseline with an 'oversize' marker instead of OMITTING it. This one modelling change is the // root fix for three separate defects that all came from "the baseline has no idea this file // exists": // 1. A baselined code file PADDED PAST THE CAP became INVISIBLE: process_batch() set // current_keys (so never 'deleted') and continue'd before the hash compare (so never // 'changed'). An attacker could pad a monitored file past 50 MB to drop it out of // integrity monitoring with ZERO UI signal. // 2. An oversize file that later SHRANK below the cap was reported as a spurious 'new' // file — it had been there all along; it just was not indexed. // 3. DELETING an oversize file was invisible (it was in no baseline to be missed from). // With the marker present, process_batch() can tell the four states apart, and — crucially — // an entry that is in the baseline is PROVABLY <= cap at baseline time (this branch is the // only thing that excludes files), so "in baseline without the marker, now over the cap" is a // PROVEN size change, not a guess. // No hash is stored: we deliberately never hashed it. 'oversize' is the load-bearing key; the // empty hash must never be compared against a real one. $state['baseline'][ $key ] = array( 'hash' => '', 'oversize' => true, 'mtime' => ( $mt = @filemtime( $fp ) ) ? (int) $mt : 0, 'size' => (int) $fsize_pre, 'path' => $fp, ); $processed_in_batch++; continue; } $hash = @hash_file( 'sha256', $fp ); if ( ! $hash ) { $state['skipped'] = ( isset( $state['skipped'] ) ? $state['skipped'] : 0 ) + 1; $processed_in_batch++; continue; } // RC-116-07 $mtime = @filemtime( $fp ); $size = @filesize( $fp ); $state['baseline'][ $key ] = array( 'hash' => $hash, 'mtime' => $mtime ? (int) $mtime : 0, 'size' => $size ? (int) $size : 0, 'path' => $fp, ); $processed_in_batch++; } $state['offset'] = $offset + $processed_in_batch; $state['processed'] = $state['offset']; $percent = $state['total'] > 0 ? round( ( $state['processed'] / $state['total'] ) * 100, 1 ) : 0; if ( $state['offset'] >= $state['total'] ) { $state['status'] = 'complete'; // GP-REL-021 (audit 2026-06-19): this write carries the accumulated // $state['baseline'] map AND the 'complete' status that // finalize_baseline() requires. A silent failure here would leave the // build looking incomplete (finalize refuses) or, on a stale read, // let a partial index be finalized. Verify the commit. // ACG-049-001: verify ownership immediately before the authoritative 'complete' baseline commit. if ( self::owner_lost( 'baseline', $owner ) ) { return array( 'success' => false, 'not_owner' => true, 'error' => __( 'This baseline build was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ) ); } if ( ! self::save_scan_data( 'baseline_state', $state, $owner, false, 'baseline' ) ) { // ACG-052-001: CAS refusal (successor took over) reports not_owner, not disk-full. if ( self::owner_lost( 'baseline', $owner ) ) { return self::not_owner_result(); } return array( 'success' => false, 'error' => __( 'Failed to save baseline progress (disk full?). Build aborted to keep your previous baseline intact.', 'ai-cyberguard' ), ); } return array( 'success' => true, 'status' => 'complete', 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => 100, 'message' => __( 'Baseline creation complete!', 'ai-cyberguard' ), ); } // ACG-049-001: verify ownership immediately before the mid-build progress commit. if ( self::owner_lost( 'baseline', $owner ) ) { return array( 'success' => false, 'not_owner' => true, 'error' => __( 'This baseline build was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ) ); } // GP-REL-021: a failed mid-build progress write would lose accumulated // hashes / resume from a stale offset. Surface it instead of pretending // the batch succeeded. if ( ! self::save_scan_data( 'baseline_state', $state, $owner, false, 'baseline' ) ) { // ACG-052-001: CAS refusal (successor took over) reports not_owner, not disk-full. if ( self::owner_lost( 'baseline', $owner ) ) { return self::not_owner_result(); } return array( 'success' => false, 'error' => __( 'Failed to save baseline progress (disk full?). Build aborted to keep your previous baseline intact.', 'ai-cyberguard' ), ); } $elapsed = time() - ( isset( $state['started_at'] ) ? $state['started_at'] : time() ); $rate = $state['processed'] > 0 ? $elapsed / $state['processed'] : 0; $remaining_files = $state['total'] - $state['processed']; $eta_seconds = $rate > 0 ? round( $rate * $remaining_files ) : 0; return array( 'success' => true, 'status' => 'creating', 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => $percent, 'eta' => $eta_seconds, 'message' => sprintf( /* translators: %1$s is the number of files processed, %2$s is the total file count, %3$s is the percent complete */ __( 'Creating baseline... %1$s of %2$s files (%3$s%%)', 'ai-cyberguard' ), number_format( $state['processed'] ), number_format( $state['total'] ), $percent ), ); } /** * Finalize baseline creation and save */ public static function finalize_baseline( $owner = null ) { $state = self::load_scan_data( 'baseline_state', null, $owner ); if ( ! $state || ! isset( $state['baseline'] ) || ! is_array( $state['baseline'] ) ) { self::cleanup_baseline_data( $owner ); return array( 'success' => false, 'error' => __( 'No baseline data found', 'ai-cyberguard' ) ); } // FIX F-1 (audit 2026-05-25 round 2): refuse to overwrite the // baseline if the build was not actually completed. Previously, // init_baseline → finalize_baseline (skipping every // process_baseline_batch) would overwrite baseline.json with an // empty/partial array AND delete the legacy DB fallback. The // next real scan then flooded the report with "new" entries for // every file on disk, burning the email alert budget. // ACG-033-004 (audit 2026-06-20): require the EXPLICIT 'complete' status — the // old counter fallback (processed >= total) wrongly promoted a non-complete // state (e.g. status 'creating'/'error' with matching counters from a failed // last batch) into a published baseline that then becomes the trusted integrity // reference. Counters are progress data only and must never infer commit // eligibility. An 'error'/'cancelled' state is terminal and non-finalizable. $status = isset( $state['status'] ) ? $state['status'] : ''; if ( 'error' === $status || 'cancelled' === $status ) { return array( 'success' => false, 'error' => __( 'Cannot finalize: the baseline build ended in an error or was cancelled. Your previous baseline is unchanged. Please run it again.', 'ai-cyberguard' ), 'processed' => isset( $state['processed'] ) ? (int) $state['processed'] : 0, 'total' => isset( $state['total'] ) ? (int) $state['total'] : 0, ); } $is_complete = ( 'complete' === $status ); if ( $is_complete && isset( $state['scan_id'], $state['finalize_scan_id'] ) ) { $is_complete = ( (string) $state['scan_id'] === (string) $state['finalize_scan_id'] ); } if ( ! $is_complete ) { return array( 'success' => false, 'error' => __( 'Cannot finalize: baseline build is still in progress. Continue processing batches first, or use Cancel to start over.', 'ai-cyberguard' ), 'processed' => isset( $state['processed'] ) ? (int) $state['processed'] : 0, 'total' => isset( $state['total'] ) ? (int) $state['total'] : 0, ); } // RC-116-07 (audit 2026-06-18): a baseline is a TRUST SOURCE for every future scan. // If any discovered file could not be read/hashed during the build, the acceptance // set is INCOMPLETE — saving it would silently drop those files from all future // change detection. Refuse to overwrite the existing trusted baseline; the admin // re-runs once the files are readable. (init_baseline already excludes files that // were unreadable at discovery, so a non-zero count here is a genuine TOCTOU gap.) $skipped = isset( $state['skipped'] ) ? (int) $state['skipped'] : 0; if ( $skipped > 0 ) { self::cleanup_baseline_data( $owner ); // discard the partial build; keep the previous baseline intact return array( 'success' => false, 'error' => sprintf( /* translators: %s: number of files that could not be read */ _n( 'Baseline not saved: %s file could not be read during indexing, so the baseline would be incomplete. Your previous baseline is unchanged — re-run once the file is accessible.', 'Baseline not saved: %s files could not be read during indexing, so the baseline would be incomplete. Your previous baseline is unchanged — re-run once the files are accessible.', $skipped, 'ai-cyberguard' ), number_format_i18n( $skipped ) ), 'skipped' => $skipped, ); } // ACG-137-B5: count the INDEXED entries only — a regression I introduced in this same round and // caught reviewing my own diff. The baseline now ALSO holds 'oversize' markers for files this // version deliberately did NOT hash (so that a baselined file padded past the cap can be reported // as changed). count() over the whole array therefore counts files that were never indexed, and // this number is the one the user reads: "Baseline created! Indexed %s files", the durable // guardpress_baseline_info_v1['count'], the admin bar and the dashboard widget. It would have sat // directly beside my own new "N files were larger than the 50 MB limit" line and contradicted it — // the exact coverage lie this round exists to remove, re-introduced by the fix for it. // Entries are marked at the single point that skips hashing (process_baseline_batch), so // "no 'oversize' key" == "we hashed it". $count = 0; foreach ( $state['baseline'] as $gp_bl_entry ) { if ( empty( $gp_bl_entry['oversize'] ) ) { $count++; } } // FIX: Write baseline to JSON file ONLY (no wp_options!) // ACG-071-002 (audit 2026-06-26, HIGH): the full-scan baseline writer had the SAME direct-path symlink // exposure as GuardPress_Baseline::baseline_dir() — it built uploads/guardpress-baseline directly + wp_mkdir_p, // so a symlinked baseline root redirected baseline.php (file paths + hashes — recon data) outside uploads. // Create the directory SYMLINK-SAFELY through the centralized helper instead; refuse (and fail the finalize // without writing) when it cannot be created safely. $upload_dir = wp_upload_dir(); $baseline_dir = false; if ( class_exists( 'GuardPress_File_Storage' ) && method_exists( 'GuardPress_File_Storage', 'safe_subdir' ) ) { $baseline_dir = GuardPress_File_Storage::safe_subdir( isset( $upload_dir['basedir'] ) ? $upload_dir['basedir'] : '', 'guardpress-baseline' ); } if ( false === $baseline_dir || '' === (string) $baseline_dir ) { // DO NOT delete the legacy baseline — that would cause data loss. self::cleanup_baseline_data( $owner ); return array( 'success' => false, 'error' => __( 'Could not create a safe baseline directory. Ensure wp-content/uploads/guardpress-baseline is a real directory and not a symbolic link.', 'ai-cyberguard' ), ); } // ACG-031-009 (audit 2026-06-20): write to the GUARDED .php store so a direct // HTTP fetch is inert on Nginx (write_atomic() prepends the exit guard for a // .php path). The no-class fallback writes the guarded bytes itself. $baseline_file = trailingslashit( $baseline_dir ) . 'baseline.php'; $json = wp_json_encode( $state['baseline'], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE ); // GP-REL-006 / ADD-5 (audit 2026-06-19): use the SHARED transactional // writer (temp -> verify -> rename, Windows fallback backs up + rolls back // on a short write) instead of a bare in-place file_put_contents. The old // direct write could leave a TRUNCATED baseline on a short write while // still about to delete the legacy DB fallback below — destroying the only // trusted reference set. write_atomic() never truncates last-good and // returns true only when the full file is durably on disk. $write_ok = false; if ( $json !== false ) { if ( class_exists( 'GuardPress_Baseline' ) ) { $write_ok = GuardPress_Baseline::write_atomic( $baseline_file, $json ); } else { $guarded = "\n" . $json; $write_ok = ( @file_put_contents( $baseline_file, $guarded, LOCK_EX ) === strlen( $guarded ) ); } } unset( $json ); if ( ! $write_ok ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [finalize_baseline]: JSON write failed' ); } // DO NOT delete legacy baseline — that would cause data loss! self::cleanup_baseline_data( $owner ); return array( 'success' => false, 'error' => __( 'Failed to save baseline file. Check file permissions on wp-content/uploads/.', 'ai-cyberguard' ), ); } // JSON write succeeded — safe to clean up legacy DB baseline delete_option( 'guardpress_baseline_v1' ); // ACG-031-009: a verified guarded .php store now exists — remove the legacy // plaintext baseline.json so the exposed copy does not linger on Nginx. $legacy_json = trailingslashit( $baseline_dir ) . 'baseline.json'; if ( file_exists( $legacy_json ) ) { @unlink( $legacy_json ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- remove the now-redundant exposed plaintext baseline } // Save only small metadata to DB // ACG-137-B2 (self-review of the v1.0.137 diff, 2026-07-17): PERSIST the over-size skip count HERE, // next to the count it qualifies. This is the third round of the same bug and the first fix at the // right layer: // round 1 — the counter was not returned by finalize_baseline(); // round 2 — returned, but the JS never read it; // round 3 (this) — the JS CANNOT usefully read it: on success it REDIRECTS to // ?gp_notice=baseline_created, and the reload destroys the AJAX payload. Any fix // that only teaches the JS to print response.data.message dies on the next line. // A fact that must outlive a redirect has to be DURABLE. guardpress_baseline_info_v1 is the // baseline's own durable record and is already read by the UI, so the boundary now travels with the // thing it describes and the notice can render it after the reload (see class-view-scanner.php). $gp_skipped_large = isset( $state['skipped_large'] ) ? (int) $state['skipped_large'] : 0; update_option( 'guardpress_baseline_info_v1', array( 'count' => $count, 'time' => time(), 'storage' => 'json', 'skipped_large' => $gp_skipped_large, ), false ); // ACG-138-R2-04: this is the LIVE build path the admin UI uses. Its entries carry the // ACG-137-B5 over-size markers, so record that the stored baseline is current-schema — that // is what dismisses the "rebuild your baseline" notice (GuardPress_Baseline::needs_rebuild_for_oversize). if ( class_exists( 'GuardPress_Baseline' ) ) { GuardPress_Baseline::mark_schema_current(); } // Clear related data delete_option( 'guardpress_last_report_v1' ); delete_option( 'guardpress_last_alert_signature_v1' ); // ACG-149-R36-B: the two alert markers are a PAIR — the combined signature and the // "malware we already emailed about" fingerprint. Retiring one and keeping the other is // exactly how the re-infection defect was born, so they are cleared together. Erring here // costs at most one duplicate malware email; the other direction costs a missed backdoor. delete_option( 'guardpress_last_malware_sig_v1' ); delete_option( 'guardpress_ai_last_analysis' ); delete_transient( 'guardpress_db_scan_results' ); delete_transient( 'guardpress_core_verify_results' ); // ACG-149-144 (owner report, 2026-07-27): KEEP THE MALWARE VERDICT. // // v145 cleared it here, reasoning that "the files they flagged as threats are now part of the // accepted baseline". That conflates the two engines. A baseline accepts the current file state as // the reference for CHANGE detection; malware detection is signature-based and does not depend on // it. Accepting a file as the change-reference is not the user accepting malware inside it — and // the owner confirmed the behaviour empirically: the same threats reappear on the next scan, so // deleting them here only hid them temporarily. // // What it actually caused: run a malware scan → see threats → create a baseline (which this // product's own onboarding tells you to do) → the threat list vanishes and the banner says // "Run your first malware scan". A user can lose sight of a real backdoor by following the // product's advice. // // The v145 finding was really about BASELINE-RELATIVE data, and that is still cleared — see the // delete_option() calls immediately above (guardpress_last_report_v1 = the Regular-scan Scan // Details, which genuinely are pre-baseline state). Working scan data is still cleaned too; only // the verdict survives. if ( class_exists( 'GuardPress_Malware_Scanner' ) ) { GuardPress_Malware_Scanner::clear_results( true ); // true = keep the malware verdict } if ( class_exists( 'GuardPress_Update_Detector' ) ) { GuardPress_Update_Detector::clear(); } $duration = time() - ( isset( $state['started_at'] ) ? $state['started_at'] : time() ); self::cleanup_baseline_data( $owner ); // ACG-122 (review round 2): SURFACE the over-size skips. ACG-121 added the skipped_large counter in // process_baseline_batch() and promised those files would be "reported separately", but this // finalize — the path the admin UI actually uses — neither returned nor displayed it, so a file that // was silently left OUT of the baseline (and therefore goes unmonitored for changes) was invisible. // A boundary the user cannot see is indistinguishable from a boundary that does not exist. $gp_large = isset( $state['skipped_large'] ) ? (int) $state['skipped_large'] : 0; $gp_msg = sprintf( /* translators: %1$s is the number of files indexed, %2$s is the duration in seconds */ __( 'Baseline created! Indexed %1$s files in %2$s seconds.', 'ai-cyberguard' ), number_format( $count ), $duration ); if ( $gp_large > 0 ) { $gp_msg .= ' ' . sprintf( /* translators: %s is the number of files that were larger than the 50 MB hashing limit */ _n( '%s file was larger than the 50 MB limit and is not covered by change monitoring.', '%s files were larger than the 50 MB limit and are not covered by change monitoring.', $gp_large, 'ai-cyberguard' ), number_format_i18n( $gp_large ) ); } return array( 'success' => true, 'status' => 'finalized', 'count' => $count, 'duration' => $duration, 'skipped_large' => $gp_large, 'message' => $gp_msg, ); } /** * Cancel ongoing baseline creation */ public static function cancel_baseline() { $has_baseline = self::load_scan_data( 'baseline_state' ); self::cleanup_baseline_data(); if ( $has_baseline ) { return array( 'success' => true, 'message' => __( 'Baseline creation cancelled', 'ai-cyberguard' ) ); } return array( 'success' => true, 'message' => __( 'No baseline creation in progress', 'ai-cyberguard' ) ); } /** * Get current baseline creation progress */ public static function get_baseline_progress() { $state = self::load_scan_data( 'baseline_state' ); if ( ! $state ) return null; $percent = $state['total'] > 0 ? round( ( $state['processed'] / $state['total'] ) * 100, 1 ) : 0; return array( 'status' => $state['status'], 'total' => $state['total'], 'processed' => $state['processed'], 'percent' => $percent, ); } /** * Check if baseline creation is in progress */ public static function is_creating_baseline() { $state = self::load_scan_data( 'baseline_state' ); return $state && isset( $state['status'] ) && $state['status'] === 'creating'; } }