'absent', 'key' => '' ); } $target = trailingslashit( $u['basedir'] ) . 'guardpress-baseline'; clearstatcache( false, $target ); if ( @is_link( $target ) ) { return array( 'state' => 'unsafe', 'key' => '' ); } if ( @file_exists( $target ) ) { if ( ! @is_dir( $target ) ) { return array( 'state' => 'unsafe', 'key' => '' ); } $rb = realpath( $u['basedir'] ); $rt = realpath( $target ); if ( false === $rb || false === $rt || $rt !== rtrim( $rb, '/\\' ) . DIRECTORY_SEPARATOR . 'guardpress-baseline' ) { return array( 'state' => 'unsafe', 'key' => '' ); } $st = @lstat( $target ); $key = ( is_array( $st ) && isset( $st['dev'], $st['ino'] ) ) ? $st['dev'] . ':' . $st['ino'] : ''; return array( 'state' => 'ok', 'key' => $key ); } return array( 'state' => 'absent', 'key' => '' ); } protected static function baseline_dir() { $u = wp_upload_dir(); if ( empty( $u['basedir'] ) ) { return false; } // ACG-071-002 (audit 2026-06-26, HIGH): create the baseline directory SYMLINK-SAFELY. Previously this built // uploads/guardpress-baseline directly + wp_mkdir_p, so a symlinked baseline root redirected baseline.php (and // its protection files) outside uploads. Prefer the centralized File_Storage helper; fall back to an // equivalent inline guard when that class is not loaded. Returns false (refused) on a symlinked root — every // caller already treats a non-string/empty path as "do not write". if ( class_exists( 'GuardPress_File_Storage' ) && method_exists( 'GuardPress_File_Storage', 'safe_subdir' ) ) { return GuardPress_File_Storage::safe_subdir( $u['basedir'], 'guardpress-baseline' ); } return self::safe_baseline_dir_fallback( $u['basedir'] ); } /** * ACG-071-002: self-contained symlink-safe creation of uploads/guardpress-baseline, used only when * GuardPress_File_Storage is not loaded. Mirrors File_Storage::safe_subdir(). * * @param string $base uploads basedir. * @return string|false */ private static function safe_baseline_dir_fallback( $base ) { if ( ! is_dir( $base ) ) { return false; } $dir = trailingslashit( $base ) . 'guardpress-baseline'; if ( is_link( $dir ) ) { return false; // a planted symlink at the baseline root → refuse } if ( ! is_dir( $dir ) ) { if ( ! wp_mkdir_p( $dir ) ) { return false; } // Protect directory from direct access (Apache/LiteSpeed). ACG-073-001 / audit follow-up (2026-06-26): // write each protection file SYMLINK-SAFELY (unlink a planted child symlink, then temp + atomic rename), // mirroring GuardPress_File_Storage::safe_write_protection_file(). This fallback only runs when File_Storage // is not loaded (dead in a normal install — the primary safe_subdir() path is used), so this is // defense-in-depth so the two write paths never diverge. $htaccess = "# GuardPress Security - Deny All Access\n" . "\n" . " Require all denied\n" . "\n" . "\n" . " Order allow,deny\n" . " Deny from all\n" . "\n"; $web_config = "\n" . "\n \n \n" . " \n true\n" . " \n \n \n\n"; self::bl_safe_write_protection( $dir, '.htaccess', $htaccess ); self::bl_safe_write_protection( $dir, 'index.php', "\n"; } /** * ACG-084-H1 (audit 2026-06-27): the shared no-follow contract for the legacy baseline builder's hashing. Prefers * the canonical GuardPress_FS_Helpers primitive; falls back to a self-contained, trusted-root-aware copy for an * isolated harness. True ONLY for a REGULAR file (no symlink/FIFO/dir/socket/device) with NO symlink path * component below the deepest trusted root (ABSPATH / WP_CONTENT_DIR / uploads basedir) and a contained realpath. * * @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 ), '/' ) . '/' ) ); } /** * Create FULL baseline with normalized keys. * * ⚠️ ACG-137 (self-review of the v1.0.137 diff, 2026-07-17): DEAD CODE — THIS METHOD HAS NO CALLERS. * Verified by grepping the entire tree (includes/, admin/, cli/, cron/, tools/): the only occurrence of * "Baseline::create" is this definition. Every live path builds the baseline through * GuardPress_Batch_Scanner::process_baseline_batch() + ::finalize_baseline() — the admin AJAX batch flow * (class-admin-menu.php), WP-CLI (class-cli.php) and cron (class-cron.php) all go via * GuardPress_Scan_Runner / the batch scanner, never here. * * Consequences, recorded so the next reviewer does not spend a round on it as I did: * - The ACG-121 A4 over-size accounting inside this method NEVER EXECUTES. * - The claim further down this file that the logic is shared "so there is ONE implementation" is * STALE with respect to create(). * - The ACG-137-B5 'oversize' baseline marker is deliberately NOT mirrored here: adding it would be * writing new behaviour into code that cannot run, and would make this look live again. * Retained (not deleted) only because deleting a public method carries more risk than it removes. * DO NOT fix bugs "found" in here — fix them in class-batch-scanner.php, which is the live path. */ public static function create() { $root = rtrim( ABSPATH, "/\\" ) . DIRECTORY_SEPARATOR; $paths = array( $root ); $baseline = array(); $count = 0; $skipped = 0; // ACG-081-H1 (audit 2026-06-27, MED): in-scope symlink/unreadable files are a coverage gap. // ACG-121 A4 (audit 2026-07-16): files over MAX_HASH_BYTES are counted SEPARATELY — a documented size // limit is a known boundary, not a coverage failure, so it must not flip 'partial'/'success' (every site // with one ordinary backup/media file would otherwise report a failed baseline forever). $skipped_large = 0; // GP-REL-020 (audit 2026-06-19): a baseline is a FULL index of the site, // so set Full-scan mode while enumerating. In Full mode // should_exclude_path() ONLY strips the GuardPress self-artifact dirs and // the admin's user-excluded dirs (it returns false for every real // code/config file), so this can NEVER drop a risky/code file from the // baseline — it only prevents the baseline from indexing its own // state/report JSON (which the scan enumeration already excludes, causing // a coverage mismatch otherwise). Mode is restored in a finally block so // an exception cannot leave the global scan mode flipped to Full. $had_full = false; $has_helpers = class_exists( 'GuardPress_FS_Helpers' ); if ( $has_helpers ) { $had_full = GuardPress_FS_Helpers::is_full_scan(); GuardPress_FS_Helpers::set_full_scan( true ); } try { foreach ( $paths as $p ) { if ( is_file( $p ) ) { $files = array( new SplFileInfo( $p ) ); } elseif ( is_dir( $p ) ) { // FIX (audit 2026-06-10): CATCH_GET_CHILD so one unreadable // subdirectory is skipped rather than throwing and aborting the // entire baseline build. $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $p, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); } else { $files = array(); } foreach ( $files as $file ) { $fp = is_object( $file ) && method_exists( $file, 'getPathname' ) ? $file->getPathname() : (string) $file; // GP-REL-020 (audit 2026-06-19): mirror the SCAN enumeration's // exclusion logic so the baseline indexes exactly the same set // the scan walks — otherwise the baseline records its own // self-artifact JSON (excluded from the scan) and every scan // reports them as spuriously "deleted". In Full mode this only // strips self-artifacts + user-excluded dirs (never code files). // ACG-081-H2 (audit 2026-06-27, MED): exclusions run BEFORE the symlink coverage-gap check so an // excluded/internal symlink is NOT counted as a gap (it is out of scope). if ( $has_helpers ) { if ( GuardPress_FS_Helpers::should_exclude_path( $fp ) ) { continue; } if ( GuardPress_FS_Helpers::is_ignored( $fp ) ) { continue; } } // ACG-080-004 / ACG-084-003 (audit 2026-06-27, HIGH): never follow an IN-SCOPE symlinked FILE — or // a file whose PARENT directory was swapped to a symlink after discovery — into the baseline. // realpath()/hash_file() would record the link's EXTERNAL target as a TRUSTED baseline key OUTSIDE // the install. is_link($fp) tested only the basename; the shared no-symlink-component + regular-file // contract also rejects a symlinked ANCESTOR (and a FIFO). Count it a coverage gap (non-zero skipped) // so create() reports the baseline partial (not success) and no external key is ever indexed. if ( ! self::is_safe_regular_file( $fp ) ) { $skipped++; continue; } if ( ! @is_readable( $fp ) ) { $skipped++; continue; } // Normalized key (same logic used by Scan Runner) $real = function_exists('realpath') ? realpath($fp) : $fp; $key = $has_helpers ? GuardPress_FS_Helpers::normalize_path( $real ? $real : $fp ) : strtolower(str_replace('\\','/',$fp)); // ACG-121 A4: cap size BEFORE hashing — hash_file() on a multi-GB file cannot be // interrupted and wedges the build. Same value/semantics as the cron path // (GuardPress_Scan_Runner) and the batch path (GuardPress_Batch_Scanner); read from // Batch_Scanner when loaded, with an identical literal fallback so this legacy entry // point can never fatal on a context where that class was not required. $size_pre = @filesize( $fp ); $gp_cap = class_exists( 'GuardPress_Batch_Scanner' ) ? GuardPress_Batch_Scanner::MAX_HASH_BYTES : 52428800; if ( false !== $size_pre && $size_pre > $gp_cap ) { $skipped_large++; continue; } $hash = hash_file( 'sha256', $fp ); $mtime = @filemtime( $fp ); $size = @filesize( $fp ); $baseline[ $key ] = array( 'hash' => $hash, 'mtime' => $mtime ? (int)$mtime : 0, 'size' => $size ? (int)$size : 0, 'path' => $fp, // keep original for nicer display ); $count++; } } } finally { // GP-REL-020: always restore the prior scan mode. if ( $has_helpers ) { GuardPress_FS_Helpers::set_full_scan( $had_full ); } } // FIX: Write baseline to JSON file ONLY — no wp_options. // Writing ~18-35MB of baseline data to wp_options causes massive MySQL binlog bloat. $json = wp_json_encode( $baseline, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE ); // FIX (audit 2026-06-10): atomic write (temp + rename) so a concurrent // get() never reads a truncated baseline. Still verifies full persistence. $write_ok = self::write_baseline_atomic( $json ); unset( $json ); // Free memory if ( ! $write_ok ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [baseline_create]: JSON write failed' ); } // GP-REL-006 (audit 2026-06-19): DO NOT @unlink the prior baseline on // a failed build. The write_baseline_atomic() helper is transactional // (temp -> verify -> rename, and on the rename-replace fallback it // restores the prior file on a short write), so when it returns false // the LAST-GOOD baseline.json is still intact on disk. Deleting it here // would destroy the only trusted reference set and flood the next scan // with false "new file" findings for the entire site. Record the // failure in OPTION_INFO but leave the previous baseline untouched. update_option( self::OPTION_INFO, array( 'count' => 0, 'time' => time(), 'storage' => 'json_error', ), false ); return array( 'count' => 0, 'skipped' => $skipped, 'skipped_large' => $skipped_large, 'time' => time(), 'success' => false ); } // JSON succeeded — clean up any legacy DB baseline data delete_option( self::OPTION_BASELINE ); // Only save small metadata to DB (count + timestamp, ~50 bytes) update_option( self::OPTION_INFO, array( 'count' => $count, 'time' => time(), 'storage' => 'json', ), false ); // ACG-138-R2-04: a genuine (re)build re-stats the filesystem, so its entries carry the // ACG-137-B5 over-size markers — record that the stored baseline is now current-schema, so // the rebuild notice stops prompting. Only a real build does this; the reindex path must not. self::mark_schema_current(); // GP-REL-006 (audit 2026-06-19): return an explicit 'success' bool on the // success path too (previously only the failure path carried it), so the // admin/AJAX handlers can reliably branch on $res['success']. // ACG-081-H1 (audit 2026-06-27, MED): a file-integrity baseline that silently omitted symlinked/unreadable // files (which then go UNMONITORED) must not report a plain "complete success". The baseline IS written // ('written' => true), but 'success' now means COMPLETE — it is false when any in-scope file was skipped, and // 'partial'/'skipped' surface the coverage gap so a caller can warn. (No production caller uses this legacy // public method — the admin UI builds the baseline via the batch path — so tightening 'success' is safe.) return array( 'count' => $count, 'skipped' => $skipped, // ACG-121 A4: reported so a caller can surface "N files over the size limit were not hashed", // but deliberately NOT folded into 'skipped'/'partial'/'success' — see $skipped_large above. 'skipped_large' => $skipped_large, 'time' => time(), 'written' => true, 'partial' => ( $skipped > 0 ), 'success' => ( 0 === $skipped ), ); } /** * FIX (audit 2026-06-10): atomically persist the baseline JSON (temp file + * rename) so the unlocked reader in get() can never observe a truncated file * mid-write. Returns true only when the new file is fully on disk. * * @param string|false $json Encoded baseline JSON (false short-circuits). * @return bool */ private static function write_baseline_atomic( $json ) { return self::write_atomic( self::baseline_file(), $json ); } /** * GP-REL-006 / D2 (audit 2026-06-19): the single shared atomic-write helper * for the scan-orchestration subsystem. Reused by write_baseline_atomic() * here AND by GuardPress_Batch_Scanner::finalize_baseline() so there is ONE * implementation of the "never truncate last-good" invariant. * * Strategy: * 1. Write the full payload to a unique sibling temp file and VERIFY the * byte count. On any short write, unlink the temp and return false — * the destination is never touched. * 2. Atomically rename temp -> destination (all-or-nothing for readers on * POSIX). On success, return true. * 3. Windows fallback (rename can't replace an existing file): keep a * backup copy of the current destination FIRST, then write the temp * contents in place and verify the byte count. On a short/failed write, * ROLL BACK from the backup so the last-good file is restored, and * return false. NEVER leave a truncated destination, and NEVER delete * the destination before a verified replacement exists. * * @param string $file Absolute destination path. * @param string|false $json Encoded payload (false short-circuits to false). * @return bool True only when the new content is fully persisted. */ public static function write_atomic( $file, $json ) { if ( $json === false || ! is_string( $file ) || $file === '' ) { return false; } // ACG-031-009: when writing the canonical guarded .php store, prepend the // exit guard so the on-disk bytes are inert to a direct HTTP fetch. A legacy // .json path (back-compat) is written raw. get() strips the guard on read. if ( substr( $file, -4 ) === '.php' && substr( $json, 0, 5 ) !== 'rename path above already ran.) // B. CONDITIONAL ROLLBACK: a same-key committer can use the lock-free primary rename path, // so the lock alone does not serialize against it. Before the destructive in-place // write, RE-READ the live target and confirm it still equals THIS writer's snapshot // (the verified backup). If it differs, another writer committed — discard our backup // and return false WITHOUT touching the live file. On a short write, only roll the // backup back when the live target still equals this writer's own partial output. $dest_exists = @is_file( $file ); if ( ! $dest_exists ) { // No pre-existing baseline — nothing to lose; just write in place and verify. $written = @file_put_contents( $file, $json, LOCK_EX ); @unlink( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here return ( $written !== false && $written === $len ); } // ACG-035-012 (self-audit re-review 2026-06-20, HIGH-COND): the atomic temp->rename could not // replace an EXISTING baseline. A non-atomic in-place overwrite — even under a flock — can // CLOBBER a newer baseline another writer committed via the lock-free rename path between the // safety re-check and the destructive write (no atomic compare-and-swap exists for an in-place // overwrite). Rather than risk losing a newer trusted baseline, FAIL CLOSED: leave the // existing baseline untouched and report failure. On Linux and modern Windows the primary // atomic rename replaces in place, so this path is reached only on filesystems that cannot // atomically replace — where a safe overwrite is impossible anyway. @unlink( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- discard our temp; the live baseline is left untouched if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [baseline]: atomic replace unavailable; refusing a non-atomic in-place overwrite for: ' . $file ); } return false; } /** * ACG-033-008: run the fallback in-place write for a PRE-EXISTING baseline $file while the * caller holds the per-key write lock. Implements the single-writer guarantees (verified unique * backup, verified rollback, keep-backup-if-unverifiable) PLUS the two-writer interleave guard * (conditional rollback gated on the live target still being this writer's snapshot/partial). * * @param string $file Absolute destination path (already known to exist). * @param string $json Bytes to persist (guard already prepended for .php targets). * @param int $len Expected byte length of $json. * @param string $tmp The primary temp file to clean up. * @return bool True only when the new content is fully persisted. */ private static function inplace_write_locked( $file, $json, $len, $tmp ) { $bak = $file . '.bak.' . (string) @getmypid() . '.' . uniqid( '', true ); // ACG-032-009: a backup is only trustworthy if the copy succeeded AND // the backup byte count matches the original. A copy() that returns // true but produces a short/empty file (full disk, truncated write) // would otherwise be a useless rollback source. Verify before we ever // touch the live baseline. $orig_size = @filesize( $file ); $copied = @copy( $file, $bak ); $bak_size = $copied ? @filesize( $bak ) : false; $have_bak = ( $copied && $orig_size !== false && $bak_size === $orig_size ); if ( ! $have_bak ) { // Cannot safeguard the current file — refuse rather than risk it. // Remove any partial backup and leave the live baseline untouched. if ( file_exists( $bak ) ) { @unlink( $bak ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here } @unlink( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here return false; // live baseline untouched } // (B) Snapshot identity of what THIS writer believes the live target is (its backup). $snapshot_hash = @hash_file( 'sha256', $bak ); // (B) Before the DESTRUCTIVE in-place write, re-read the live target and confirm it still // equals this writer's snapshot. If another writer committed a different value (via the // lock-free primary rename path), abort: discard our backup and preserve their content. $current_hash = @hash_file( 'sha256', $file ); if ( false !== $snapshot_hash && false !== $current_hash && ! hash_equals( $snapshot_hash, $current_hash ) ) { @unlink( $bak ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here @unlink( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [baseline]: Another writer committed — abandoning in-place write for: ' . $file ); } return false; // newer committed content preserved (not overwritten) } $written = @file_put_contents( $file, $json, LOCK_EX ); $ok = ( $written !== false && $written === $len ); // ACG-032-009: the cleanup of scratch files must NOT run unconditionally — // the backup may be the only surviving copy of the last-good baseline if // the in-place write failed and the rollback could not be verified. $delete_bak = true; // default: drop the backup once the committed state is verified good if ( ! $ok ) { // The in-place write was short/failed. ACG-033-008: roll back ONLY if the live target // still equals THIS writer's partial/failed output — i.e. nobody committed over it // since. If a different writer committed in the meantime, do NOT restore OLD over their // newer content; discard our backup instead. $partial = ( false === $written ) ? '' : substr( $json, 0, (int) $written ); $live_hash = @hash_file( 'sha256', $file ); $partial_hash = hash( 'sha256', $partial ); if ( false !== $live_hash && hash_equals( $partial_hash, $live_hash ) ) { // It is our own partial write on disk — restore the verified backup and CONFIRM // the restore (byte count matches the original) BEFORE we delete the backup. If // the rollback cannot be verified, KEEP the backup so the trusted last-good // baseline is still recoverable from disk. $restored = @copy( $bak, $file ); $restore_size = $restored ? @filesize( $file ) : false; $restore_ok = ( $restored && $restore_size === $orig_size ); $delete_bak = $restore_ok; // only drop the backup once the live file is provably restored } else { // The live target is NOT our partial — another writer committed over it. Do NOT // restore OLD; preserve their content. Discard our (now-useless) backup. $delete_bak = true; if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [baseline]: Short write but newer commit detected — not rolling back: ' . $file ); } } } // Always remove the temp; remove the backup only when the committed state // is verified good (write succeeded, or rollback was confirmed, or the // backup is provably useless because a newer value is already committed). @unlink( $tmp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here if ( $delete_bak ) { @unlink( $bak ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- direct filesystem operation required by the scanner baseline store; WP_Filesystem is unsuitable here } return $ok; } /** * ACG-033-008: acquire an exclusive per-key write lock for the fallback in-place section. * Uses a sibling '.wlock' file opened 'c' (create-if-absent) and flock(LOCK_EX). Returns the * open handle on success, or false if the lock cannot be acquired — callers MUST treat false * as "cannot serialize" and refuse the unserialized in-place write (fail closed). * * @param string $file Absolute destination path. * @return resource|false */ private static function acquire_write_lock( $file ) { // ACG-074-H2 (audit 2026-06-26): open the per-file write lock through the symlink-safe primitive so a planted // .wlock child symlink is rejected/replaced and never followed (no zero-byte file outside the store). $dir = dirname( (string) $file ); $name = basename( (string) $file ) . '.wlock'; if ( class_exists( 'GuardPress_File_Storage' ) && method_exists( 'GuardPress_File_Storage', 'safe_open_lock_file' ) ) { $fh = GuardPress_File_Storage::safe_open_lock_file( $dir, $name ); } else { $fh = @fopen( $file . '.wlock', 'c' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- fallback advisory write lock when the safe primitive is unavailable } if ( ! $fh ) { return false; // flock unsupported / dir unwritable / unsafe — cannot serialize } if ( ! @flock( $fh, LOCK_EX ) ) { @fclose( $fh ); return false; } return $fh; } /** * ACG-033-008: release a write lock acquired by acquire_write_lock(). * * @param resource $lock The handle returned by acquire_write_lock(). */ private static function release_write_lock( $lock ) { if ( $lock ) { @flock( $lock, LOCK_UN ); @fclose( $lock ); } } /** * Load baseline. * JSON file is PRIMARY storage. * Legacy DB option is read-only migration input. */ /** * ACG-075-002: read a baseline file (.php / .json) symlink- and FIFO-safely. Delegates to the centralized * File_Storage primitive; an inline fallback (identical lstat-based check) covers the File_Storage-not-loaded * case. Returns the raw bytes, or false when the path is absent / a symlink / not a regular file / unreadable. * * @param string|false $path * @return string|false */ private static function safe_baseline_read( $path ) { $r = self::safe_baseline_read_ex( $path ); return ( 'ok' === $r['state'] ) ? $r['content'] : false; } /** * ACG-076-001 (audit 2026-06-26, HIGH): tri-state baseline read. Distinguishes an ABSENT baseline file from * an UNSAFE one (symlink/FIFO/special), so get() can fall back to the legacy .json ONLY when the primary is * authoritatively absent and FAIL CLOSED (load nothing) when the primary is unsafe/unreadable — never load a * legacy/poisoned baseline behind a symlinked primary. Delegates to the centralized File_Storage primitive; * an inline lstat fallback covers the File_Storage-not-loaded case. * * @param string|false $path * @return array{state:string,content:?string} */ private static function safe_baseline_read_ex( $path ) { if ( false === $path || '' === (string) $path ) { return array( 'state' => 'absent', 'content' => null ); } if ( class_exists( 'GuardPress_File_Storage' ) && method_exists( 'GuardPress_File_Storage', 'safe_read_file_ex' ) ) { return GuardPress_File_Storage::safe_read_file_ex( $path ); } clearstatcache( false, $path ); if ( is_link( $path ) ) { return array( 'state' => 'unsafe', 'content' => null ); } if ( ! @file_exists( $path ) ) { return array( 'state' => 'absent', 'content' => null ); } if ( ! @is_file( $path ) ) { return array( 'state' => 'unsafe', 'content' => null ); } $c = @file_get_contents( $path ); if ( false === $c ) { return array( 'state' => 'error', 'content' => null ); } return array( 'state' => 'ok', 'content' => $c ); } /** * ACG-077 (audit 2026-06-26): strip the optional PHP exit-guard line and JSON-decode a baseline blob to its * array, or array() when the content is empty / not a non-empty JSON object (a CORRUPT/truncated primary). The * single decode path keeps get() and exists() byte-for-byte consistent about what counts as a real baseline. * * @param string|null $raw * @return array */ private static function decode_baseline_blob( $raw ) { $raw = (string) $raw; if ( '' === $raw ) { return array(); } if ( ' $_ ) { if ( strpos($k, '\\') !== false || strpos($k, '//?/') === 0 || ( $gp_is_windows && $k !== strtolower($k) ) ) { $needs_reindex = true; break; } } if ( $needs_reindex ) { $normalized = array(); foreach ( $base as $k => $row ) { $key = class_exists('GuardPress_FS_Helpers') ? GuardPress_FS_Helpers::normalize_path( $k ) : strtolower(str_replace('\\','/',$k)); if ( isset($normalized[$key]) ) { $keep = ( strlen( isset($normalized[$key]['path']) ? $normalized[$key]['path'] : '' ) >= strlen( isset($row['path']) ? $row['path'] : '' ) ) ? $normalized[$key] : $row; $normalized[$key] = $keep; } else { $normalized[$key] = $row; } } // Save normalized version to JSON only (no DB writes!) // FIX (audit 2026-06-10): VERIFY the write before updating OPTION_INFO. // The old code ignored the file_put_contents return and then claimed // success in OPTION_INFO (with the new count), so a failed reindex // write left the option lying about what was persisted. The in-memory // $normalized is still returned (correct for this request), but // OPTION_INFO is only updated when the new file is actually on disk. $reindex_ok = self::write_baseline_atomic( wp_json_encode( $normalized, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE ) ); if ( $reindex_ok ) { // ACG-137-B2/B5 (self-review round 2): this whole-array write CLOBBERS keys it does not // know about. It silently dropped 'skipped_large' — the durable "N files were too large to // index" fact finalize_baseline() stores and class-view-scanner.php renders as an amber // notice — so a reindex quietly turned that amber back to green. A fact is only durable if // EVERY writer of its option preserves it; there are four writers and only one knew the key. // Also count only INDEXED entries: the baseline now carries 'oversize' markers for files we // deliberately did not hash (ACG-137-B5), and a raw count() would report them as indexed. $gp_prev_info = get_option( self::OPTION_INFO, array() ); $gp_indexed = 0; foreach ( $normalized as $gp_ni ) { if ( ! is_array( $gp_ni ) || empty( $gp_ni['oversize'] ) ) { $gp_indexed++; } } update_option( self::OPTION_INFO, array( 'count' => $gp_indexed, 'time' => time(), 'storage' => 'json', 'skipped_large' => ( is_array( $gp_prev_info ) && isset( $gp_prev_info['skipped_large'] ) ) ? (int) $gp_prev_info['skipped_large'] : 0, ), false ); } return $normalized; } return $base; } /** * Check if baseline exists (lightweight — no full data load) * * @return bool */ public static function exists() { // ACG-031-009: guarded .php store first (the guard line alone is ~60 bytes, // so require > guard length so a bare-guard empty file doesn't read as // "exists"), then the legacy plaintext .json, then the DB option. // ACG-076-H1 / ACG-077-H1 (audit 2026-06-26): exists() MUST mirror get()'s fail-closed state machine exactly // — same tri-state read, same decode, same fallback order. The old file_exists()/filesize() FOLLOWED a // symlink AND fell through to the legacy .json / DB even when the primary was unsafe or corrupt, so exists() // could report true while get() returned empty. Now: an unsafe/error/corrupt primary returns false WITHOUT // consulting the legacy file or the DB; the legacy file and the DB option are reached only when the higher // tiers are authoritatively absent. // ACG-079-001 / ACG-081-002 (audit 2026-06-27): capture the container probe ONCE at entry. An UNSAFE baseline // directory fails closed here, exactly as get() does, and the captured identity gates the DB tier below so a // mid-read delete/recreate or symlink-and-back cannot make exists() report true from the DB. $dir_probe = self::baseline_dir_probe(); if ( 'unsafe' === $dir_probe['state'] ) { return false; } // ACG-081-002 (audit 2026-06-27): latch $unsafe_seen if the container is refused (baseline_file()==='') at any // point during the reads — the inode-independent mid-read-swap signal (mirrors get()). $unsafe_seen = false; $bf = self::baseline_file(); if ( '' === (string) $bf ) { $unsafe_seen = true; } $pr = self::safe_baseline_read_ex( $bf ); if ( 'ok' === $pr['state'] ) { return ! empty( self::decode_baseline_blob( $pr['content'] ) ); } if ( 'absent' !== $pr['state'] ) { return false; // primary unsafe/error → fail closed, consistent with get() } $bfl = self::baseline_file_legacy(); if ( '' === (string) $bfl ) { $unsafe_seen = true; } $lr = self::safe_baseline_read_ex( $bfl ); if ( 'ok' === $lr['state'] ) { return ! empty( self::decode_baseline_blob( $lr['content'] ) ); } if ( 'absent' !== $lr['state'] ) { return false; // legacy unsafe/error → fail closed } // ACG-082-001 (audit 2026-06-27, HIGH): the DB tier may report a baseline ONLY for a TRUE // fresh install (container AUTHORITATIVELY ABSENT at entry) AND no unsafe container observed during the reads. // A container that existed at entry is authoritative — never report a baseline from the stale DB behind a // mid-read delete/recreate or symlink-and-back. Mirrors get(). if ( 'absent' !== $dir_probe['state'] || $unsafe_seen ) { return false; } // Both disk files authoritatively absent → DB option (legacy). ACG-PROACTIVE-78 (self-audit matrix // 2026-06-27): mirror get()'s DB-tier signal EXACTLY. get() serves a non-empty OPTION_BASELINE array, so // exists() must test the SAME option — the previous OPTION_INFO['count'] check could disagree with get() // (e.g. an orphaned info-count with the baseline data option deleted → exists()=true while get()=empty). $db = get_option( self::OPTION_BASELINE, array() ); return is_array( $db ) && ! empty( $db ); } public static function info() { $i = get_option( self::OPTION_INFO, array() ); return is_array($i) ? $i : array(); } }