__( 'AI CyberGuard — Login Security', 'ai-cyberguard' ), 'callback' => array( __CLASS__, 'privacy_export' ), ); return $exporters; } public static function register_privacy_eraser( $erasers ) { $erasers['ai-cyberguard-login-security'] = array( 'eraser_friendly_name' => __( 'AI CyberGuard — Login Security', 'ai-cyberguard' ), 'callback' => array( __CLASS__, 'privacy_erase' ), ); return $erasers; } /** * Export login-security personal data for the user with this email (paginated). * ACG-050-003 (audit 2026-06-23): matches the verified account (user_id / user_login) AND the literal email — * WordPress permits login by email, so login_log.username and the attempts usernames JSON can store the email * itself. Supports UNREGISTERED/DELETED identities (no WP_User) by matching the email alone. On ANY database * error it reports done=FALSE (data retained, not exhausted) so WordPress retries. The plugin-wide Security * Event Log is NOT exported and need not be — its only direct-username carrier was removed (see block_ip_temp). */ public static function privacy_export( $email, $page = 1 ) { $email = (string) $email; // Defense-in-depth: an empty subject must match NOTHING (an empty username predicate would otherwise match // already-anonymized rows whose username is ''). WordPress core always supplies a validated email. if ( '' === $email ) { return array( 'data' => array(), 'done' => true ); } global $wpdb; $log = self::table( self::TABLE_LOG ); $attempts = self::table( self::TABLE_ATTEMPTS ); $batch = 2000; // ACG-062-001: BOUNDED work per callback — safe even on a high-volume (uncapped) attempts table. $data = array(); // ACG-062-001 (audit 2026-06-25): BOUNDED keyset pagination with a durable, request-scoped PER-PAGE-SLOT // cursor. v1.0.62's single-pass design avoided the multi-page replay race but accumulated every matching row // in one PHP array, which can exhaust memory/time on a large attempts table. We restore WordPress' bounded- // per-callback contract: each callback reads ONE bounded batch per source by keyset (id>last_id, ip>last_ip) // and persists the boundary in slot[page]; page N reads slot[N-1], so a replayed or lost page re-reads the // SAME batch (resumable + idempotent) rather than skipping or duplicating. A moderate data set still reaches // done=true on the first page (one callback). Item data arrays are STRING-keyed so a re-delivered item merges // idempotently in the WordPress accumulator (no duplicate fields). This plugin's exporter is NOT the first // registered exporter, so core's accumulator reset (exporter-index 1, page 1 only) never fires for our pages. $reqid = self::priv_request_id(); $state_key = 'export|' . $reqid . '|' . md5( $email ); // ACG-063-001 (audit 2026-06-25): the IMMUTABLE request identity AND a request-start HIGH-WATER bound are // captured ONCE at the cursor TOP LEVEL (not a per-page slot) and reused for EVERY page — including a page-1 // retry, which must NOT re-resolve get_user_by() (a rename/deletion between pages would otherwise drift the // identity and falsely complete with records omitted). ACG-063-002: the high-water (the max id / max ip that // matched at request start) bounds the export to a fixed snapshot so it TERMINATES even while new attempts // keep arriving. priv_export_identity returns null only if the identity/high-water could not be persisted. $idrec = self::priv_export_identity( $state_key, $email ); if ( null === $idrec ) { return self::export_failure(); // could not establish/persist the request identity → retry, never drift } $id_bind = (int) $idrec['id_bind']; $login_bind = (string) $idrec['login_bind']; $has_user = ( $id_bind >= 0 ); $high_id = (int) $idrec['high_id']; $high_ip = (string) $idrec['high_ip']; $log_empty = ! empty( $idrec['log_empty'] ); $att_empty = ! empty( $idrec['att_empty'] ); $cur = self::priv_state_get( $state_key, (int) $page, array( 'last_id' => 0, 'last_ip' => '', 'd_log' => false, 'd_att' => false ) ); if ( self::$priv_io_error ) { return self::export_failure(); // ACG-066-002: cursor read errored → fail the page, never re-export from defaults } // ACG-064-002 (audit 2026-06-25): a source that matched NOTHING at request start is done immediately — it must // not absorb rows that arrive mid-export. An empty request-start snapshot is NOT an open-ended upper bound. if ( $log_empty ) { $cur['d_log'] = true; } if ( $att_empty ) { $cur['d_att'] = true; } // 1) Per-event login log — verified account OR the literal email. ONE bounded keyset batch (id > last_id), // CAPPED at the request-start high-water (id <= high_id) so new arrivals never keep the export running. if ( empty( $cur['d_log'] ) ) { $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own personal-data table; privacy export must read live rows // ACG-149-157 (adversarial audit, MySQL-only — invisible on SQLite): the username column // collates utf8mb4_unicode_520_ci, which is case- AND accent-insensitive. `username = %s` // therefore matched OTHER PEOPLE. Measured: privacy_export('bob@example.com') returned 3 // rows including 'BOB@example.com' and 'bob@example.com' with an accented o — i.e. the // GDPR export LEAKED another user's login history, and privacy_erase ANONYMISED their // records too. BINARY forces an exact byte comparison, which is what an identity match // must be; it also restores the compare-and-swap below, which this file documents as // matching "the EXACT usernames value we read". "SELECT id, time, ip, username, status FROM {$log} WHERE ( user_id = %d OR BINARY username = %s OR BINARY username = %s ) AND id > %d AND id <= %d ORDER BY id ASC LIMIT %d", $id_bind, $login_bind, $email, (int) $cur['last_id'], $high_id, $batch ) ); if ( null === $rows || ! empty( $wpdb->last_error ) ) { return self::export_failure(); // DB error → core retries this page; never a silently partial archive } foreach ( (array) $rows as $r ) { $data[] = array( 'group_id' => 'gp-login-activity', 'group_label' => __( 'Login activity (AI CyberGuard)', 'ai-cyberguard' ), 'item_id' => 'gp-login-' . (int) $r->id, 'data' => array( 'date' => array( 'name' => __( 'Date', 'ai-cyberguard' ), 'value' => gmdate( 'Y-m-d H:i:s', (int) $r->time ) . ' UTC' ), 'ip' => array( 'name' => __( 'IP address', 'ai-cyberguard' ), 'value' => (string) $r->ip ), 'user' => array( 'name' => __( 'Username', 'ai-cyberguard' ), 'value' => (string) $r->username ), 'result' => array( 'name' => __( 'Result', 'ai-cyberguard' ), 'value' => (string) $r->status ), ), ); if ( (int) $r->id > (int) $cur['last_id'] ) { $cur['last_id'] = (int) $r->id; } // advance keyset } if ( count( (array) $rows ) < $batch ) { $cur['d_log'] = true; } // short page → this source is exhausted } // 2) IP-keyed failed-attempt records. ONE bounded keyset batch (ip > last_ip). ACG-062-003: attempt_count and // last_attempt are IP-WIDE AGGREGATES shared by EVERY identity on that row, so they are exported ONLY for a // SINGLE-identity row (attributable to the subject). For a shared row we export only the attributable fact // (the IP), never another occupant's aggregate count/timestamp. if ( empty( $cur['d_att'] ) ) { $like_email = '%' . $wpdb->esc_like( '"' . $email . '"' ) . '%'; $like_login = $has_user ? '%' . $wpdb->esc_like( '"' . $login_bind . '"' ) . '%' : ''; // ACG-063-002 / ACG-064-002: cap at the request-start high-water (ip <= high_ip). We only reach here when // the attempts source was NON-EMPTY at request start (an empty source set d_att above), so $high_ip is a // concrete MAX(ip) bound — never an open sentinel. New attempts arriving mid-export are excluded. $ip_cap = $high_ip; if ( $has_user ) { $arows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own personal-data table "SELECT ip, attempt_count, last_attempt FROM {$attempts} WHERE ( usernames LIKE %s OR usernames LIKE %s ) AND ip > %s AND ip <= %s ORDER BY ip ASC LIMIT %d", $like_login, $like_email, (string) $cur['last_ip'], $ip_cap, $batch ) ); } else { $arows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own personal-data table "SELECT ip, attempt_count, last_attempt FROM {$attempts} WHERE usernames LIKE %s AND ip > %s AND ip <= %s ORDER BY ip ASC LIMIT %d", $like_email, (string) $cur['last_ip'], $ip_cap, $batch ) ); } if ( null === $arows || ! empty( $wpdb->last_error ) ) { return self::export_failure(); } foreach ( (array) $arows as $ar ) { $data[] = array( 'group_id' => 'gp-login-attempts', 'group_label' => __( 'Failed login attempts (AI CyberGuard)', 'ai-cyberguard' ), 'item_id' => 'gp-attempt-' . md5( (string) $ar->ip ), // ACG-062-003: export ONLY the attributable IP. The row's attempt_count / last_attempt are IP-WIDE // aggregates shared by every identity on the row, so they are NOT exported as this subject's data. 'data' => array( 'ip' => array( 'name' => __( 'IP address', 'ai-cyberguard' ), 'value' => (string) $ar->ip ), ), ); if ( strcmp( (string) $ar->ip, (string) $cur['last_ip'] ) > 0 ) { $cur['last_ip'] = (string) $ar->ip; } // advance keyset } if ( count( (array) $arows ) < $batch ) { $cur['d_att'] = true; } } $done = ( ! empty( $cur['d_log'] ) && ! empty( $cur['d_att'] ) ); if ( $done ) { if ( ! self::priv_state_finalize( $state_key ) ) { // ACG-068-002: the terminal transition did not durably commit → do NOT report completion. Persist the // boundary so a retry resumes (no rows are re-emitted: both sources are already marked done), and tell // WordPress the request is not yet complete so it calls again to finalize. $persisted = self::priv_state_put( $state_key, $cur, (int) $page ); if ( ! $persisted ) { return self::export_failure(); } $done = false; } } else { $persisted = self::priv_state_put( $state_key, $cur, (int) $page ); // store this page's boundary slot if ( ! $persisted ) { return self::export_failure(); // cursor could not be persisted (incl. a fail-closed lock miss) → retry } } return array( 'data' => $data, 'done' => $done ); } /** * ACG-056-001/002 (audit 2026-06-24): a privacy EXPORT page that cannot make safe, complete progress (the * durable cursor write genuinely failed, or a source DB error persisted past the retry budget) must FAIL the * page — never report done=true with a source silently omitted, and never accept a partial page. On real * WordPress we return WP_Error so core rejects the page and surfaces a failed export to the admin (a later * retry resumes once the fault clears). In an isolated unit harness where WP_Error is unavailable we return a * not-done page carrying no data, so no partial/zero-row archive is ever treated as a completed export. * * @return WP_Error|array */ private static function export_failure() { if ( class_exists( 'WP_Error' ) ) { return new WP_Error( 'gp_export_incomplete', __( 'The Login Security personal-data export could not be completed safely and was stopped to avoid producing a silently incomplete archive. Please try again.', 'ai-cyberguard' ) ); } return array( 'data' => array(), 'done' => false ); } /** * ACG-061-001/002 (audit 2026-06-25): companion to export_failure() for the single-page eraser. A TRANSIENT * database/mutation error during erasure means the erase could not complete; on real WordPress we return * WP_Error so core aborts and the admin retries (re-anonymizing already-erased rows is idempotent), rather than * reporting a (silently incomplete) completion. In an isolated unit harness without WP_Error we return a * not-done page marked retained, so no partial erasure is ever treated as complete. * * @param int $removed rows anonymized before the error (for the harness-fallback shape only) * @return WP_Error|array */ private static function erase_failure( $removed ) { $msg = __( 'Some login-security data could not be erased due to a database error and was retained. Please resolve the database issue and run the erasure again.', 'ai-cyberguard' ); if ( class_exists( 'WP_Error' ) ) { return new WP_Error( 'gp_erase_incomplete', $msg ); } return array( 'items_removed' => $removed > 0, 'items_retained' => true, 'messages' => array( $msg ), 'done' => false ); } /** * Erase (anonymize) login-security personal data for the user with this email — SINGLE-PAGE, stateless. * ACG-050-003 (audit 2026-06-23): same identity set as the exporter (the literal email ALWAYS, plus the verified * user_id / user_login when an account exists) — supports unregistered/deleted identities (no early return). * ACG-061-001/002 (audit 2026-06-25): anonymizes EVERY matching record in one callback (no cross-page cursor, * so no shared mutable state to race and no unlocked terminal-marker write). A transient DB/mutation error * returns WP_Error (retry the whole erase, idempotent); a permanently unreadable matching row is reported * retained with an actionable message and does NOT block completion. */ public static function privacy_erase( $email, $page = 1 ) { $email = (string) $email; $removed = 0; $retained = false; $messages = array(); $malformed_msg = __( 'Some failed-login records could not be erased (unreadable data) and were retained. Please retry.', 'ai-cyberguard' ); $contend_msg = __( 'Some failed-login records could not be erased due to concurrent activity and were retained. Please retry.', 'ai-cyberguard' ); // Defense-in-depth: an empty subject must match NOTHING (an empty username predicate would otherwise touch // already-anonymized rows). WordPress core always supplies a validated email. if ( '' === $email ) { return array( 'items_removed' => false, 'items_retained' => false, 'messages' => array(), 'done' => true ); } global $wpdb; $log = self::table( self::TABLE_LOG ); $attempts = self::table( self::TABLE_ATTEMPTS ); $batch = 1000; // ACG-062-001: BOUNDED mutations per callback (never tens of thousands of deletes in one request) // ACG-062-001 / ACG-063-001/002: bounded multi-request erasure. The identity is IMMUTABLE (ACG-063-001: // resolved once and reused across page-1 retries, so an account rename/deletion between pages cannot drift it // and leave rows). The attempts source uses a SHRINK-THE-SET scan with NO forward cursor (ACG-063-002): each // page reads a bounded batch of CURRENTLY-matching rows excluding a small "permanently-retained" set, so a // matching row inserted at ANY key (including behind a previous position) is still found and erased. $reqid = self::priv_request_id(); $state_key = 'erase|' . $reqid . '|' . md5( $email ); $idrec = self::priv_export_identity( $state_key, $email ); if ( null === $idrec ) { return self::erase_failure( $removed ); // could not establish/persist the request identity → retry } $id_bind = (int) $idrec['id_bind']; $login_bind = (string) $idrec['login_bind']; $has_user = ( $id_bind >= 0 ); // ACG-051-004b: case-insensitive comparison keys for the in-PHP JSON strip. $email_key = self::privacy_norm( $email ); $login_key = $has_user ? self::privacy_norm( $login_bind ) : ''; $st = self::priv_state_get( $state_key, (int) $page, array( 'log_done' => false, 'last_ip' => '', 'phase' => 'drain', 'sweep_erased' => 0, 'pass_no' => 0, 'ret_flag' => false, 'ret_msgs' => array() ) ); if ( self::$priv_io_error ) { return self::erase_failure( $removed ); // ACG-066-002: cursor read errored → fail the page (never restart from defaults) } // ACG-064-003: retained status + messages are CUMULATIVE across callbacks (carried in the durable cursor), so // the FINAL page still reports them. ACG-065-001: they are O(1) (a flag + at most two distinct messages) — the // un-erasable rows are NOT accumulated as a list (that grew the cursor quadratically and tripped the validator). $retained = ! empty( $st['ret_flag'] ); $messages = ( isset( $st['ret_msgs'] ) && is_array( $st['ret_msgs'] ) ) ? array_values( $st['ret_msgs'] ) : array(); // 1) Per-event login log: ONE bounded UPDATE ... LIMIT batch (shrink-the-set — an anonymized row no longer // matches). On ANY error → WP_Error (retry; idempotent). if ( empty( $st['log_done'] ) ) { $log_affected = $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own personal-data table; privacy erase must mutate live rows "UPDATE {$log} SET ip = '', username = '', user_id = 0 WHERE user_id = %d OR BINARY username = %s OR BINARY username = %s LIMIT %d", $id_bind, $login_bind, $email, $batch ) ); if ( false === $log_affected || ! empty( $wpdb->last_error ) ) { return self::erase_failure( $removed ); } $removed += (int) $log_affected; if ( (int) $log_affected < $batch ) { $st['log_done'] = true; } // short batch → log source drained } // 2) ACG-065-001 / ACG-066-001 (audit 2026-06-25): BOUNDED attempts erasure with a DRAIN + VERIFY model. The // durable cursor is O(1) (a forward keyset position + a phase + an O(1) retained summary) — there is NO // retained-IP list and NO unbounded NOT IN. Two phases: // DRAIN — a forward keyset scan (ip > last_ip) erases matching rows across bounded callbacks until it // reaches the end; then it switches to VERIFY. // VERIFY — a from-start scan whose keyset cursor PERSISTS across callbacks (ACG-067-001): it is NOT reset // every callback (that discarded progress and could never reach the tail above the per-callback // scan cap), so verification advances monotonically to the end. Completion requires a verify that // reaches the end having erased nothing — independent of whether the previous pass erased a row. // Behind-insert handling (ACG-066-001/ACG-063-002): when a DRAIN reaches the end having erased NOTHING this // request, the verify is DEFERRED to the next callback starting from ip 0, so a row inserted between the // drain and the verify is seen from the beginning; when the drain erased rows, the verify runs in-callback // from ip 0 to catch a row a strip may have exposed. A verify that finds an erasable row erases it and // returns to DRAIN. Un-erasable rows (malformed/contended) are reported via the O(1) cumulative retained // flag, never accumulated. Each strip is a co-tenant-preserving CAS. $att_done = false; $phase = ( isset( $st['phase'] ) && 'verify' === $st['phase'] ) ? 'verify' : 'drain'; $last_ip = (string) ( isset( $st['last_ip'] ) ? $st['last_ip'] : '' ); $sweep_erased = isset( $st['sweep_erased'] ) ? (int) $st['sweep_erased'] : 0; $pass_no = isset( $st['pass_no'] ) ? (int) $st['pass_no'] : 0; $contend_retries = isset( $st['contend_retries'] ) ? (int) $st['contend_retries'] : 0; $drain_erased = ! empty( $st['drain_erased'] ); // ACG-066-001: did the CURRENT drain strip any row? // ACG-068-001: a mutation epoch (count of currently-matching rows) snapshotted when a verify generation begins, // plus a count of consecutive clean from-start verify generations. A verify completes ONLY after a from-start // generation reaches the end having erased nothing AND the matching-set FINGERPRINT is unchanged AND a SECOND // consecutive clean generation confirms it - so a matching row inserted behind the persisted verify cursor // while the request is still active (it sorts before last_ip and the forward scan would never revisit it) is // caught by the next from-zero generation. ACG-069-001: the epoch is a CONTENT FINGERPRINT (count + max-ip + // two CRC32 aggregates over the matching rows), not a bare count, so a NET-ZERO mutation (one row inserted // behind the cursor while another ahead is deleted) is still detected; a DB error computing it fails closed. $verify_fp = isset( $st['verify_fp'] ) ? (string) $st['verify_fp'] : ''; // ACG-069-001: matching-set fingerprint (string), not a count $clean_streak = isset( $st['clean_streak'] ) ? (int) $st['clean_streak'] : 0; $saw_contended = false; // ACG-066-001: a still-erasable row we could not strip THIS callback (sustained CAS contention) $like_email = '%' . $wpdb->esc_like( '"' . $email . '"' ) . '%'; $like_login = $has_user ? '%' . $wpdb->esc_like( '"' . $login_bind . '"' ) . '%' : ''; $erased_here = 0; // erased in THIS callback — used only to bound per-callback mutation work $scans = 0; do { $scans++; if ( $has_user ) { $arows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; bounded keyset scan "SELECT ip, usernames FROM {$attempts} WHERE ( usernames LIKE %s OR usernames LIKE %s ) AND ip > %s ORDER BY ip ASC LIMIT %d", $like_login, $like_email, $last_ip, $batch ) ); } else { $arows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; bounded keyset scan "SELECT ip, usernames FROM {$attempts} WHERE usernames LIKE %s AND ip > %s ORDER BY ip ASC LIMIT %d", $like_email, $last_ip, $batch ) ); } if ( null === $arows || ! empty( $wpdb->last_error ) ) { return self::erase_failure( $removed ); } $arows = array_values( (array) $arows ); $acount = count( $arows ); foreach ( $arows as $ar ) { $row_ip = (string) $ar->ip; if ( strcmp( $row_ip, $last_ip ) > 0 ) { $last_ip = $row_ip; } // advance the keyset past EVERY examined row $res = self::privacy_strip_attempt_row( $attempts, $row_ip, (string) $ar->usernames, $email_key, $login_key ); if ( 'error' === $res ) { return self::erase_failure( $removed ); } if ( 'erased' === $res ) { $removed++; $sweep_erased++; $erased_here++; if ( 'drain' === $phase ) { $drain_erased = true; } // a drain that strips → verify in-callback later } elseif ( 'malformed' === $res ) { $retained = true; if ( ! in_array( $malformed_msg, $messages, true ) ) { $messages[] = $malformed_msg; } } elseif ( 'contended' === $res ) { // ACG-066-001 / ACG-068-004: TRANSIENT CAS contention. The row IS erasable, so it drives a bounded // retry (the request stays done=false) — but it is NOT permanent retention, so it does NOT set the // sticky retained flag/message here. If the row succeeds on a later callback nothing sticks; ONLY if // it is STILL contended at the retry cap is it reported as retained (below). $saw_contended = true; } // 'skip' (false LIKE match) → nothing to retain; the keyset already advanced past it. } if ( $acount >= $batch ) { // more rows ahead in this forward segment: if we did mutation work this callback, hand back to keep the // callback bounded; otherwise (pure reads — verifying or a non-matching drain) keep scanning in-callback. if ( $erased_here > 0 ) { break; } continue; } // short batch → reached the END of the current forward segment. if ( 'drain' === $phase ) { $phase = 'verify'; // drain exhausted → begin a from-start verification generation (ip 0) $last_ip = ''; $sweep_erased = 0; $clean_streak = 0; $verify_fp = self::attempts_match_epoch( $attempts, $has_user, $like_login, $like_email ); // ACG-069-001 epoch continue; } // phase === 'verify', reached the end: if ( $sweep_erased > 0 && $pass_no < self::ERASE_MAX_PASSES ) { $phase = 'drain'; // the verify found+erased rows → a behind/late row existed → re-drain $last_ip = ''; $sweep_erased = 0; $drain_erased = false; // fresh drain generation $clean_streak = 0; $pass_no++; break; // bounded: hand back after a verify that did mutation work } // ACG-068-001 / ACG-069-001: a from-start verify generation reached the end having erased nothing. // Complete ONLY if the matching-set FINGERPRINT (count + max-ip + two CRC32 content aggregates) is // unchanged since this generation began AND a second consecutive clean generation confirms it. The // fingerprint detects a NET-ZERO mutation (one matching row inserted behind the cursor + one deleted // ahead) that a bare count would miss, so a row inserted behind the persisted verify cursor during this // active request cannot slip through. A fresh from-zero generation rescans the front, where a // behind-cursor insert sorts. $now_fp = self::attempts_match_epoch( $attempts, $has_user, $like_login, $like_email ); if ( false === $now_fp ) { // ACG-069-001: the epoch query itself errored — we cannot PROVE the set is stable, so FAIL CLOSED: // do not complete. Hand back with the verify cursor reset so the next callback re-reads cleanly and // WP retries; the request never reports done while it could not be verified. $last_ip = ''; $sweep_erased = 0; $clean_streak = 0; break; } if ( $now_fp !== $verify_fp ) { $last_ip = ''; // the matching set changed mid-generation → restart verification from ip 0 $sweep_erased = 0; $clean_streak = 0; $verify_fp = $now_fp; if ( $pass_no < self::ERASE_MAX_PASSES ) { $pass_no++; } continue; } $clean_streak++; if ( $clean_streak >= 2 ) { $att_done = true; // two consecutive clean, unchanged from-zero generations → no erasable row remains → DONE break; } $last_ip = ''; // one clean generation; run a second confirming from-zero generation $sweep_erased = 0; $verify_fp = $now_fp; continue; } while ( $scans < self::ERASE_MAX_SCANS_PER_PAGE ); // ACG-066-001: a still-erasable row we could not strip this callback (contention) must NOT let the request // complete — re-drain and retry on the next page, bounded so a genuinely stuck row eventually completes-with- // retained instead of looping forever. if ( $att_done && $saw_contended ) { if ( $contend_retries < self::ERASE_MAX_CONTEND_RETRIES ) { $att_done = false; $phase = 'drain'; $last_ip = ''; $sweep_erased = 0; $drain_erased = false; $clean_streak = 0; $contend_retries++; } else { // ACG-068-004: a row STILL contended at the retry cap genuinely remains un-erasable now → report it as // retained at completion (this is the ONLY place transient contention becomes a sticky retained result). $retained = true; if ( ! in_array( $contend_msg, $messages, true ) ) { $messages[] = $contend_msg; } } } $st['phase'] = $phase; $st['last_ip'] = $last_ip; $st['sweep_erased'] = $sweep_erased; $st['drain_erased'] = $drain_erased; $st['verify_fp'] = $verify_fp; $st['clean_streak'] = $clean_streak; $st['pass_no'] = $pass_no; $st['contend_retries'] = $contend_retries; $st['ret_flag'] = $retained; // ACG-064-003: persist cumulative retained status $st['ret_msgs'] = $messages; // ACG-064-003: persist cumulative messages (bounded set) $done = ( ! empty( $st['log_done'] ) && $att_done ); if ( $done ) { if ( ! self::priv_state_finalize( $state_key, $retained ) ) { // ACG-068-002: the terminal transition (PII-dropping marker) did not durably commit → NEVER report // done=true while the PII-bearing cursor may remain. Persist the state so a retry resumes, keep the // request open, and surface an actionable retry notice. $persisted = self::priv_state_put( $state_key, $st, (int) $page ); if ( ! $persisted ) { return self::erase_failure( $removed ); } $done = false; $retained = true; if ( ! in_array( $contend_msg, $messages, true ) ) { $messages[] = $contend_msg; } } } else { $persisted = self::priv_state_put( $state_key, $st, (int) $page ); if ( ! $persisted ) { return self::erase_failure( $removed ); // cursor could not be persisted (incl. fail-closed lock miss) → retry } } return array( 'items_removed' => $removed > 0, 'items_retained' => $retained, 'messages' => $messages, 'done' => $done, ); } /** * ACG-069-001 (audit 2026-06-25): the verify-generation mutation epoch — a FINGERPRINT of the rows currently * matching the subject, snapshotted when a verify generation begins and re-read when it reaches the end. If the * fingerprint changed, the attempts table mutated during the active request (e.g. a failed-login row inserted * behind the persisted verify cursor), so a fresh from-zero verification generation must run. * * A bare COUNT(*) (ACG-068-001) is NOT sufficient: a NET-ZERO change — one matching row inserted behind the * cursor while another matching row ahead is deleted — leaves the count identical and would let a behind-cursor * erasable row slip through. The fingerprint therefore combines the row count, the highest matching ip, and TWO * independent content aggregates over CONCAT(ip, usernames) of the matching set (SUM and BIT_XOR of CRC32). Any * insert/delete/update of a matching row changes at least one component; an attacker cannot read the co-tenant * rows, so a simultaneous blind collision across both CRC aggregates is not achievable. * * Returns the fingerprint string, or '' when there is no query-capable DB layer (a unit double) — in which case * the second confirming generation provides the guarantee. Returns FALSE (fail closed) on a genuine DB error, so * the caller never completes an erasure it could not verify. * * @param string $attempts * @param bool $has_user * @param string $like_login * @param string $like_email * @return string|false */ private static function attempts_match_epoch( $attempts, $has_user, $like_login, $like_email ) { global $wpdb; if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) ) { return ''; // no query-capable DB double → empty epoch; the confirming generation covers it } $where = $has_user ? '( usernames LIKE %s OR usernames LIKE %s )' : 'usernames LIKE %s'; $params = $has_user ? array( $like_login, $like_email ) : array( $like_email ); // ACG-070-H1 (audit 2026-06-26): prefer ONE atomic aggregate SELECT so all four components are computed // under a SINGLE statement snapshot (no smear across separate round trips) and there is one DB round trip // instead of four. Fall back to the per-aggregate path only for a get_var-only test double that lacks // get_row. if ( method_exists( $wpdb, 'get_row' ) ) { $wpdb->last_error = ''; $row = $wpdb->get_row( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin's own attempts table; $where is a fixed literal; one-shot verify-generation epoch "SELECT COUNT(*) AS c, MAX(ip) AS m, SUM(CRC32(CONCAT(ip, 0x1f, usernames))) AS s, BIT_XOR(CRC32(CONCAT(ip, 0x1f, usernames))) AS x FROM {$attempts} WHERE {$where}", ...$params ) ); if ( null === $row && '' !== (string) $wpdb->last_error ) { return false; // ACG-069-001: genuine DB error → fail closed (caller must not complete) } if ( is_object( $row ) && property_exists( $row, 'c' ) ) { return (string) $row->c . '|' . (string) $row->m . '|' . (string) $row->s . '|' . (string) $row->x; } // get_row exists but did not return the expected shape (an unusual double) → fall through to get_var. } $parts = array(); // Four aggregates: row count, highest matching ip, and two content fingerprints over the matching set. $aggregates = array( 'COUNT(*)', 'MAX(ip)', 'SUM(CRC32(CONCAT(ip, 0x1f, usernames)))', 'BIT_XOR(CRC32(CONCAT(ip, 0x1f, usernames)))', ); foreach ( $aggregates as $agg ) { $wpdb->last_error = ''; $val = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- plugin's own attempts table; $agg is a fixed literal from the list above, $where is a fixed literal; verify-generation epoch "SELECT {$agg} FROM {$attempts} WHERE {$where}", ...$params ) ); if ( null === $val && '' !== (string) $wpdb->last_error ) { return false; // ACG-069-001: genuine DB error → fail closed (caller must not complete) } $parts[] = (string) $val; // null (aggregate unsupported by a unit double) → '' component } return implode( '|', $parts ); } /** * ACG-062-002 (audit 2026-06-25): strip the target identity from ONE shared-IP attempts row using a COMPARE-AND- * SWAP on the EXACT usernames value we read, so a concurrent co-tenant write committed between our SELECT and our * mutation is never clobbered. The conditional DELETE/UPDATE carries `WHERE ip = ? AND usernames = ?` (the * snapshot); 0 affected rows means the row changed under us, so we RE-READ the current value, recompute the kept * list (preserving the co-tenant) and retry, bounded. Never deletes/overwrites a row whose value no longer * matches the snapshot. Returns one of: 'erased', 'skip' (nothing attributable), 'malformed' (unreadable JSON, * permanently unerasable), 'contended' (could not safely mutate under sustained contention → retained), 'error'. * * @param string $attempts * @param string $ip * @param string $usernames_json * @param string $email_key * @param string $login_key * @return string */ private static function privacy_strip_attempt_row( $attempts, $ip, $usernames_json, $email_key, $login_key ) { global $wpdb; $snapshot = (string) $usernames_json; for ( $try = 0; $try < 4; $try++ ) { $list = json_decode( $snapshot, true ); if ( ! is_array( $list ) ) { return 'malformed'; } $kept = array_values( array_filter( $list, function ( $u ) use ( $email_key, $login_key ) { $k = self::privacy_norm( (string) $u ); if ( $k === $email_key ) { return false; } if ( '' !== $login_key && $k === $login_key ) { return false; } return true; } ) ); if ( count( $kept ) === count( $list ) ) { return 'skip'; // nothing attributable to the target in the CURRENT value } // COMPARE-AND-SWAP on the exact snapshot. An emptied row was the target's alone → DELETE it (the table is // keyed by ip, so blanking the PK could collide); otherwise UPDATE only the usernames list, preserving // every co-tenant field (counters, timestamps, block state) untouched. if ( empty( $kept ) ) { $affected = $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; conditional compare-and-swap on the value read "DELETE FROM {$attempts} WHERE ip = %s AND usernames = %s", $ip, $snapshot ) ); } else { $affected = $wpdb->query( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; conditional compare-and-swap on the value read "UPDATE {$attempts} SET usernames = %s WHERE ip = %s AND usernames = %s", wp_json_encode( $kept ), $ip, $snapshot ) ); } if ( false === $affected || ! empty( $wpdb->last_error ) ) { return 'error'; } if ( (int) $affected >= 1 ) { return 'erased'; // CAS succeeded: only the row whose value still matched our snapshot was mutated } // 0 affected → the row's usernames changed under us (a co-tenant committed). Re-read the CURRENT value and // retry the CAS against it (recomputing kept preserves the new co-tenant). Same query shape so a value- // versioned store returns the live row. $fresh = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; re-read for the next CAS attempt "SELECT ip, usernames FROM {$attempts} WHERE ip = %s LIMIT 1", $ip ) ); if ( ! empty( $wpdb->last_error ) ) { return 'error'; } if ( empty( $fresh ) || ! isset( $fresh[0]->usernames ) ) { return 'erased'; // row vanished (deleted concurrently) → the target is no longer present here } $snapshot = (string) $fresh[0]->usernames; } return 'contended'; // sustained contention → leave the row intact (never clobber a co-tenant) and report retained } /** * ACG-051-004b: normalize an identifier for case-insensitive privacy comparison. Lowercases via mb_strtolower * when available (correct for Unicode local-parts), with a strtolower fallback. Used ONLY for comparison — the * stored value's exact form is preserved for entries that do not match. * * @param string $s * @return string */ private static function privacy_norm( $s ) { $s = (string) $s; return function_exists( 'mb_strtolower' ) ? mb_strtolower( $s, 'UTF-8' ) : strtolower( $s ); } /** * ACG-053-002 / ACG-054-001 / ACG-054-004 (audit 2026-06-23): load the privacy callback's pagination state. * - page 1: RESET (the start of a fresh export/erase request) and return $default. * - page>1: return the carried state. If it is MISSING (the durable option was evicted, or its write failed), * RESTART from $default rather than reporting completion — re-reading from the start may duplicate rows but * NEVER omits any (no row is silently skipped, and the callback never falsely reports done=true with rows * remaining). A stale cursor (older than PRIV_STATE_TTL) is garbage-collected and treated as a restart, so an * abandoned erasure leaves no long-lived IP-bearing option. The cursor lives in a durable OPTION * (autoload=false) mirrored in a per-request static; a unit harness with no option API uses the static alone. * * @param string $key * @param int $page * @param array $default * @return array $default on page 1 or when state is missing/stale; the carried state otherwise. */ /** * ACG-057-002 (audit 2026-06-24): the WordPress privacy export/erase AJAX handlers carry the user-request post * ID in $_REQUEST['id'] during the callback. Folding it into the cursor key keeps two CONCURRENT requests for * the same email isolated (each gets its own cursor option). Read-only and integer-cast; absent (e.g. a unit * harness or direct call) → 0, in which case the per-page slot model still prevents a replayed page from * clobbering an in-flight cursor. * * @return int */ private static function priv_request_id() { if ( ! isset( $_REQUEST['id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only: only namespaces the plugin's own cursor option; not a state-changing action and never used for authorization return 0; } $raw = $_REQUEST['id']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- integer-cast on the next line; read-only namespacing only if ( function_exists( 'wp_unslash' ) ) { $raw = wp_unslash( $raw ); } return function_exists( 'absint' ) ? absint( $raw ) : abs( (int) $raw ); } private static function priv_state_get( $key, $page, $default ) { $all = self::priv_state_load( $key ); if ( $page <= 1 ) { // A fresh page-1 start returns the default. ACG-057-002: we no longer DELETE the option here — its // per-page slots stay intact, so a concurrent or replayed page-1 for the same email/request cannot wipe // the slot an in-flight later page will read. The slot this page produces overwrites only p[1]. return $default; } // ACG-057-002: page N reads the slot the IMMEDIATELY-PRECEDING page (N-1) wrote in this sequential drive. // A replayed page-1 of another worker rewrites only p[1], so p[N-1] for N>2 is untouched. A missing // predecessor (option evicted, or its write failed) RESTARTS from $default — re-reading may duplicate but // never omits, and never falsely reports done. $slot = ( isset( $all['p'][ $page - 1 ] ) && is_array( $all['p'][ $page - 1 ] ) ) ? $all['p'][ $page - 1 ] : null; return null !== $slot ? $slot : $default; } /** * ACG-057-002: load the full per-request cursor option (a map { 'p' => { pageNum: slotState }, '_ts' => int }) * from the per-request static or the durable option, garbage-collecting it if older than PRIV_STATE_TTL. * * @param string $key * @return array */ private static function priv_state_load( $key ) { $opt = 'gp_priv_' . md5( $key ); // ACG-063-005 (audit 2026-06-25): read the cursor from the in-request static first, else from the durable // store via priv_reread_raw() — which reads the RAW option_value and decodes it with allowed_classes=false — // NEVER through get_option(), whose maybe_unserialize() would instantiate a serialized object planted in the // option (firing __wakeup) before the value could be rejected as a non-cursor. $all = ( isset( self::$priv_state[ $key ] ) && is_array( self::$priv_state[ $key ] ) ) ? self::$priv_state[ $key ] : null; if ( null === $all ) { $raw = self::priv_reread_raw( $opt ); // raw + safe_decode_cursor (scalar-only), or null $all = is_array( $raw ) ? $raw : array(); } if ( ! is_array( $all ) ) { $all = array(); } // ACG-063-004 (audit 2026-06-25): do NOT delete an expired cursor here. An access-time delete is unlocked and // unconditional, so it can clobber a cursor another callback refreshed between our stale read and the delete. // Expiry is handled ONLY by the scheduled garbage collector, which holds the advisory lock and uses a raw // compare-and-delete (gc_stale_privacy_cursors). We still ignore an obviously-expired stale value in-memory. $ts = isset( $all['_ts'] ) ? (int) $all['_ts'] : 0; if ( $ts > 0 && ( time() - $ts ) > self::PRIV_STATE_TTL ) { return array(); } self::$priv_state[ $key ] = $all; return $all; } /** * ACG-058-002: has this export/erase request already COMPLETED? The terminal marker is stored at the OPTION * level (not in a page slot) so any replayed page — including page 1 — observes completion and returns the * committed terminal state idempotently instead of restarting and re-emitting rows. * * @param string $key * @return bool */ private static function priv_state_done( $key ) { $all = self::priv_state_load( $key ); return ! empty( $all['done'] ); } /** * ACG-059-001: return the COMMITTED slot for a given page (if this page already ran and persisted), else null. * A callback uses this to make an INTERMEDIATE-page replay idempotent: page N writes slot[N] only after it * emits, so on a replay slot[N] already exists and the callback returns no new rows. * * @param string $key * @param int $page * @return array|null */ private static function priv_state_page( $key, $page ) { $all = self::priv_state_load( $key ); return ( isset( $all['p'][ (int) $page ] ) && is_array( $all['p'][ (int) $page ] ) ) ? $all['p'][ (int) $page ] : null; } /** * Persist the cursor (static + durable option). Returns whether the DURABLE store accepted the write — false * means the option could not be written (ACG-055-001: the caller must then STOP rather than loop). When no * option API exists (a unit harness) the static alone is authoritative, so this returns true. * * ACG-057-002: with a $page, the state is stored in that page's SLOT (read-modify-write of the option's 'p' * map) so concurrent pages do not clobber one another. Called WITHOUT $page (legacy 2-arg) it stores $state as * the whole option (used by direct callers / the unit same-value harness). * * @param string $key * @param array $state * @param int|null $page * @return bool */ private static function priv_state_put( $key, $state, $page = null, $mark_done = false ) { $opt = 'gp_priv_' . md5( $key ); // ACG-061-002 (audit 2026-06-25): serialize EVERY cursor write under the named advisory lock — page-scoped // writes AND the whole-option terminal marker (page === null), which previously bypassed the lock entirely — // and FAIL CLOSED. 'acquired' → proceed and release in finally; 'failed' (GET_LOCK timeout/error) → do NOT // write, return false so the caller fails the page rather than running an unserialized read-modify-write that // could clobber a concurrent newer write; 'unsupported' (unit double / no DB) → proceed (no real concurrency). $lock = self::priv_lock( $opt ); if ( 'failed' === $lock ) { return false; } try { if ( null === $page ) { $all = $state; // legacy whole-option store } else { // ACG-058-002 + ACG-063-005: merge into the CURRENT DURABLE cursor — read RAW + safe-decoded (never // get_option, which could instantiate a planted object) — NOT the possibly stale in-request static, so // a late/stale writer cannot overwrite a newer page's slot (lost update). Fall back to the static when // there is no durable value yet (e.g. an in-process unit run). $base = self::priv_reread_raw( $opt ); if ( self::$priv_io_error ) { return false; // ACG-067-002: an uncertain durable read must NOT fall back to the stale static and // merge/write over it — that can overwrite a newer completion marker / later-page slot. } $all = is_array( $base ) ? $base : ( ( isset( self::$priv_state[ $key ] ) && is_array( self::$priv_state[ $key ] ) ) ? self::$priv_state[ $key ] : array() ); if ( ! isset( $all['p'] ) || ! is_array( $all['p'] ) ) { $all['p'] = array(); } $all['p'][ (int) $page ] = $state; // ACG-065-001 (audit 2026-06-25): COMPACT obsolete page slots. The sequential privacy driver only ever // reads slot[page-1] (the predecessor) and slot[page] (an idempotent replay of the current page); older // slots are dead weight that would otherwise grow the option linearly with the page count. Drop every // slot below page-1 so the slot map — and therefore the whole cursor — stays bounded (O(1)). $keep_from = (int) $page - 1; foreach ( array_keys( $all['p'] ) as $pk ) { if ( (int) $pk < $keep_from ) { unset( $all['p'][ $pk ] ); } } // ACG-060-001: track the HIGHEST page reached and the option-level completion marker. $all['max_page'] = max( isset( $all['max_page'] ) ? (int) $all['max_page'] : 0, (int) $page ); if ( $mark_done ) { $all['done'] = true; } // ACG-059-001: optimistic compare-and-swap. After merging, RE-READ the durable cursor (raw + safe); if // it changed under us (a newer worker committed) ABORT rather than clobber the newer value. $check = self::priv_reread_raw( $opt ); if ( self::$priv_io_error ) { return false; // ACG-067-002: the CAS re-read errored → abort rather than risk clobbering a newer value } if ( null !== $check && $check != $base ) { self::$priv_state[ $key ] = is_array( $check ) ? $check : $all; return true; // the newer durable value stands; our slot write is intentionally a no-op } } $all['_ts'] = time(); // ACG-054-004: stamp so an abandoned cursor can be garbage-collected self::$priv_state[ $key ] = $all; return self::priv_write_verified( $opt, $all ); } finally { if ( 'acquired' === $lock ) { self::priv_unlock( $opt ); } } } /** * ACG-064-001 (audit 2026-06-25): write a cursor to the durable option and VERIFY it persisted by reading it * back. update_option() returns false BOTH on a genuine write failure AND when the stored value is unchanged; * an empty $wpdb->last_error does NOT prove the expected value now exists in the store (the previous code * trusted it and could accept a page whose cursor/identity was never stored, letting a later callback restart * from the head and duplicate rows). So on a false return we RAW-read the durable option (object-safe, never * get_option) and require it to EQUAL exactly what we intended to store. Only a true equality match is an * acceptable unchanged-success; an absent or different value means the write did not land → return false so the * caller fails the page (fail closed). With no option API (a unit double) the static is authoritative → true. * * @param string $opt * @param array $all * @return bool */ private static function priv_write_verified( $opt, $all ) { if ( ! function_exists( 'update_option' ) ) { return true; } $ok = update_option( $opt, $all, false ); // autoload=false if ( $ok ) { return true; // WordPress wrote the new value } $durable = self::priv_reread_raw( $opt ); // raw + safe-decoded (scalar-only), or null return is_array( $durable ) && ( $durable == $all ); // loose, order-independent array equality } /** * ACG-063-001/002 (audit 2026-06-25): establish (once) and return the IMMUTABLE request identity plus the * request-start HIGH-WATER bound for an export request, stored at the cursor TOP LEVEL (not a per-page slot) and * reused for every page including a page-1 retry. The first page that runs resolves get_user_by() and the max * id / max ip that match at request start; every later page (and any page-1 retry) reuses that record verbatim, * so an account rename/deletion between pages can never drift the identity, and new rows arriving during the * export never extend it. Returns the record, or NULL if it could not be persisted (so the caller fails closed). * * @param string $key * @param string $email * @return array|null */ private static function priv_export_identity( $key, $email ) { $all = self::priv_state_load( $key ); if ( self::$priv_io_error ) { return null; // ACG-066-002: the cursor read hit a DB error → fail the page (never rebuild from defaults) } if ( isset( $all['id_bind'] ) ) { return self::priv_identity_record( $all ); } global $wpdb; $log = self::table( self::TABLE_LOG ); $attempts = self::table( self::TABLE_ATTEMPTS ); $user = get_user_by( 'email', $email ); $id_bind = $user ? (int) $user->ID : -1; $login_bind = $user ? (string) $user->user_login : $email; $like_email = '%' . $wpdb->esc_like( '"' . $email . '"' ) . '%'; $like_login = ( $id_bind >= 0 ) ? '%' . $wpdb->esc_like( '"' . $login_bind . '"' ) . '%' : ''; // ACG-064-002 (audit 2026-06-25): capture an EXPLICIT request-start snapshot for EACH source — empty (no row // matched at the start), finite (a concrete MAX bound), or query-error (fail closed). The previous code turned // a NULL MAX into an open upper bound (PHP_INT_MAX / a lexical sentinel), which meant a source that was empty // at the start would absorb rows arriving mid-export and could never terminate. We now record empty as EMPTY. $max_id = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table; request-start snapshot bound "SELECT MAX(id) FROM {$log} WHERE user_id = %d OR username = %s OR username = %s", $id_bind, $login_bind, $email ) ); if ( ! empty( $wpdb->last_error ) ) { return null; // a high-water query error is a visible failure, never an open bound → caller returns WP_Error } $log_empty = ( null === $max_id ); $high_id = $log_empty ? 0 : (int) $max_id; if ( $id_bind >= 0 ) { $max_ip = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table "SELECT MAX(ip) FROM {$attempts} WHERE usernames LIKE %s OR usernames LIKE %s", $like_login, $like_email ) ); } else { $max_ip = $wpdb->get_var( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- plugin's own table "SELECT MAX(ip) FROM {$attempts} WHERE usernames LIKE %s", $like_email ) ); } if ( ! empty( $wpdb->last_error ) ) { return null; } $att_empty = ( null === $max_ip ); $high_ip = $att_empty ? '' : (string) $max_ip; $rec = array( 'id_bind' => $id_bind, 'login_bind' => $login_bind, 'log_empty' => $log_empty, 'high_id' => $high_id, 'att_empty' => $att_empty, 'high_ip' => $high_ip, ); if ( ! self::priv_state_set_top( $key, $rec ) ) { return null; // could not persist the immutable identity/snapshot → fail closed (caller returns WP_Error) } // Re-load so a concurrent page-1 that committed FIRST wins (its identity/snapshot is the authoritative one). $all = self::priv_state_load( $key ); return self::priv_identity_record( isset( $all['id_bind'] ) ? $all : $rec ); } /** * ACG-064-002: normalize a stored cursor's immutable identity + request-start snapshot into the record the * export/erase callbacks consume. * * @param array $all * @return array */ private static function priv_identity_record( $all ) { return array( 'id_bind' => isset( $all['id_bind'] ) ? (int) $all['id_bind'] : -1, 'login_bind' => isset( $all['login_bind'] ) ? (string) $all['login_bind'] : '', 'log_empty' => ! empty( $all['log_empty'] ), 'high_id' => isset( $all['high_id'] ) ? (int) $all['high_id'] : 0, 'att_empty' => ! empty( $all['att_empty'] ), 'high_ip' => isset( $all['high_ip'] ) ? (string) $all['high_ip'] : '', ); } /** * ACG-063-001: merge IMMUTABLE top-level fields into the cursor (only set a field if absent), under the advisory * lock, reading the durable value RAW + safe-decoded (never get_option). Returns false only on a genuine write * failure (fail closed). * * @param string $key * @param array $fields * @return bool */ private static function priv_state_set_top( $key, $fields ) { $opt = 'gp_priv_' . md5( $key ); $lock = self::priv_lock( $opt ); if ( 'failed' === $lock ) { return false; } try { $base = self::priv_reread_raw( $opt ); if ( self::$priv_io_error ) { return false; // ACG-067-002: uncertain durable read → do not seed top-level fields from a stale static } $all = is_array( $base ) ? $base : ( ( isset( self::$priv_state[ $key ] ) && is_array( self::$priv_state[ $key ] ) ) ? self::$priv_state[ $key ] : array() ); foreach ( $fields as $k => $v ) { if ( ! isset( $all[ $k ] ) ) { $all[ $k ] = $v; } // immutable: first writer wins } $all['_ts'] = time(); self::$priv_state[ $key ] = $all; return self::priv_write_verified( $opt, $all ); // ACG-064-001: read-back-verified durable write (fail closed) } finally { if ( 'acquired' === $lock ) { self::priv_unlock( $opt ); } } } /** * ACG-061-002 (audit 2026-06-25): the advisory-lock name. MySQL GET_LOCK names are SERVER-global, so two sites * on the same database server must not share a name — we namespace by DB_NAME + table prefix. Bounded to <= 64. * * @param string $opt * @return string */ private static function priv_lock_name( $opt ) { global $wpdb; $ns = ( defined( 'DB_NAME' ) ? (string) DB_NAME : '' ) . '|' . ( ( isset( $wpdb ) && isset( $wpdb->prefix ) ) ? (string) $wpdb->prefix : '' ); return substr( 'gpl_' . substr( md5( $ns ), 0, 12 ) . '_' . md5( (string) $opt ), 0, 60 ); } /** * ACG-061-002 (audit 2026-06-25): acquire the named advisory lock serializing a cursor read-modify-write across * concurrent callbacks on a real database. Returns a TRI-STATE so callers can FAIL CLOSED: * 'acquired' — GET_LOCK returned 1; the caller holds the lock and MUST release it. * 'failed' — GET_LOCK returned 0 (timeout) or NULL (error); the lock is supported but NOT held, so the * caller must NOT perform the correctness-sensitive write/delete (fail closed). * 'unsupported' — no $wpdb advisory-lock capability (a unit double / no DB); the caller proceeds unserialized * because there is no real concurrency to lose to. * * @param string $opt * @return string */ private static function priv_lock( $opt ) { global $wpdb; if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) || ! method_exists( $wpdb, 'prepare' ) ) { return 'unsupported'; } $got = $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, %d)', self::priv_lock_name( $opt ), 2 ) ); // bounded 2s wait return ( '1' === (string) $got ) ? 'acquired' : 'failed'; } private static function priv_unlock( $opt ) { global $wpdb; if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_var' ) || ! method_exists( $wpdb, 'prepare' ) ) { return; } $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', self::priv_lock_name( $opt ) ) ); } private static function priv_state_clear( $key ) { unset( self::$priv_state[ $key ] ); if ( function_exists( 'delete_option' ) ) { delete_option( 'gp_priv_' . md5( $key ) ); } } /** * ACG-067-005 / ACG-068-002 (audit 2026-06-25): on a truthful completion, replace the cursor with a MINIMAL non-PII * terminal marker ({done:true}) under the advisory lock, through READ-BACK VERIFICATION, and RETURN whether the * transition durably committed. The caller must NOT report done=true unless this returns true — a lock miss or an * unverified write means the PII-bearing cursor may remain, and reporting completion while plugin-held personal data * lingers would be a false completion (ACG-068-002). On failure the caller keeps the request not-done so WordPress * retries the finalization; the scheduled TTL collector remains a backstop for genuinely abandoned requests. * * @param string $key * @param bool $retained * @return bool true iff the minimal marker durably replaced the cursor */ private static function priv_state_finalize( $key, $retained = false ) { $opt = 'gp_priv_' . md5( $key ); $lock = self::priv_lock( $opt ); if ( 'failed' === $lock ) { return false; // ACG-068-002: could not lock → terminal transition NOT durable → caller must not report done } try { $marker = $retained ? array( 'done' => true, 'retained_final' => true, '_ts' => time() ) : array( 'done' => true, '_ts' => time() ); self::$priv_state[ $key ] = $marker; return self::priv_write_verified( $opt, $marker ); // ACG-068-002: read-back-verified durable write } finally { if ( 'acquired' === $lock ) { self::priv_unlock( $opt ); } } } /** * ACG-054-004: bulk garbage-collect the dynamic gp_priv_* cursor option family (abandoned exports/erasures). * Called from reset/uninstall so no IP-bearing cursor option lingers beyond the plugin's data lifecycle. */ public static function purge_privacy_cursor_options() { global $wpdb; if ( isset( $wpdb ) && method_exists( $wpdb, 'query' ) && method_exists( $wpdb, 'esc_like' ) ) { // ACG-055-006: escape the LIKE wildcards (_) so only the exact gp_priv_ prefix matches. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( 'gp_priv_' ) . '%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own privacy-cursor options; live data must not be cached } } // ========================================================================= // Table Management // ========================================================================= private static function table( $suffix ) { global $wpdb; return $wpdb->prefix . $suffix; } /** * Ensure both DB tables exist. * * GP-REL-011: once the schema is confirmed for this site we store a numeric * schema_version option and skip the per-request information_schema probe * entirely (a cheap autoloaded option read instead of a metadata query on * every page load). The expensive probe runs ONLY when the version marker is * absent/stale, and `$tables_verified` is set true ONLY after both tables are * confirmed present (so a failed dbDelta is retried on the next request). * * @return bool True iff both tables are confirmed to exist. */ public static function maybe_create_tables() { if ( self::$tables_verified ) { return true; } global $wpdb; $charset = $wpdb->get_charset_collate(); $attempts_table = self::table( self::TABLE_ATTEMPTS ); $log_table = self::table( self::TABLE_LOG ); // ACG-048-006 (audit 2026-06-23, MEDIUM): HOT PATH — trust the autoloaded version marker WITHOUT an // information_schema query on every request (the v1.0.48 self-heal probe added a metadata query to every // page load). The marker can only mislead if the tables were dropped WITHOUT clearing it: // - our own Uninstall/Reset clears it — GuardPress_Cleanup::option_keys() lists it and purge_state() // deletes it, so a reinstall sees NO marker and (re)creates the tables on the create path below; // - (re)activation clears it too — see the activation hook in ai-cyberguard.php (ACG-048-006), which // deletes the marker so the next request re-verifies once via the create path. // So schema verification lives at activation/version-migration, not on the request hot path. if ( (int) get_option( self::OPTION_SCHEMA_VERSION, 0 ) === self::SCHEMA_VERSION ) { self::$tables_verified = true; return true; } // ACG-148-010 (pre-sale siege): we reach here only when the version marker is ABSENT or STALE, // i.e. this is a fresh install OR a schema MIGRATION. The previous code took a shortcut here: if // both tables already existed it stamped the CURRENT SCHEMA_VERSION and returned WITHOUT running // dbDelta. That silently defeats every future migration — the day SCHEMA_VERSION is bumped to add // a column, an existing site (whose tables "exist") would get the new marker written while the new // column was never created, and the first query that used it would error. "Table exists" is not // "table is at this schema". So on the stale-marker path dbDelta ALWAYS runs. dbDelta is idempotent // by design — it diffs against information_schema and issues only the ALTERs actually needed — so // when the tables are already current this costs one comparison and changes nothing; when a column // was added it applies it. The marker is written only AFTER the post-dbDelta existence re-check // below, so a failed migration is retried next request instead of being marked done. require_once ABSPATH . 'wp-admin/includes/upgrade.php'; // One row per IP — tracks failed attempt count and block status. dbDelta( "CREATE TABLE {$attempts_table} ( ip VARCHAR(45) NOT NULL, attempt_count INT UNSIGNED NOT NULL DEFAULT 0, first_attempt INT UNSIGNED NOT NULL DEFAULT 0, last_attempt INT UNSIGNED NOT NULL DEFAULT 0, usernames TEXT, blocked_until INT UNSIGNED NOT NULL DEFAULT 0, lockout_count INT UNSIGNED NOT NULL DEFAULT 0, block_reason VARCHAR(20) NOT NULL DEFAULT '', PRIMARY KEY (ip) ) {$charset};" ); // Append-only event log — INSERT only, never updated. dbDelta( "CREATE TABLE {$log_table} ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, time INT UNSIGNED NOT NULL DEFAULT 0, ip VARCHAR(45) NOT NULL DEFAULT '', username VARCHAR(100) NOT NULL DEFAULT '', status VARCHAR(10) NOT NULL DEFAULT '', user_id BIGINT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (id), KEY time_idx (time), KEY ip_idx (ip) ) {$charset};" ); // GP-REL-011: gate the "verified" flag on a POST-dbDelta re-check that // BOTH tables now actually exist. If creation failed (permissions, etc.) // we leave $tables_verified false and DO NOT write the version marker, so // the next request retries instead of trusting an unbuilt schema. $confirmed = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (%s, %s)", $attempts_table, $log_table ) ); if ( $confirmed >= 2 ) { update_option( self::OPTION_SCHEMA_VERSION, self::SCHEMA_VERSION, false ); self::$tables_verified = true; return true; } return false; } /** * One-time migration from legacy wp_options to DB tables. * * GP-REL-011: the migrated flag is set and the legacy options are deleted * ONLY after the destination tables are confirmed to exist AND their row * counts cover the rows we expected to migrate. On any shortfall/DB error we * leave both the legacy data and the un-set flag in place so the next request * retries idempotently — last-good data is never deleted before a verified * commit (record-then-delete). */ private static function maybe_migrate_legacy_data() { if ( get_option( 'guardpress_login_db_migrated_v1' ) ) { return; } // Never migrate into an unbuilt schema — confirm tables first. if ( ! self::maybe_create_tables() ) { return; // tables not ready; retry next request, legacy data intact } global $wpdb; $attempts_table = self::table( self::TABLE_ATTEMPTS ); $log_table = self::table( self::TABLE_LOG ); // Expected counts let us VERIFY the migration before we delete anything. $expected_attempt_ips = array(); // unique valid IPs across both attempt sources $expected_log_rows = 0; // ACG-031-011 (audit 2026-06-20): track per-write success. The old code only // compared TOTAL destination row counts, which pre-existing unrelated rows can // satisfy even when every INSERT failed — so it would commit + delete the // legacy source with nothing migrated (data loss). $wpdb->query/insert return // literal false on a DB error (0 affected rows from INSERT IGNORE on an // existing row is NOT a failure); any false aborts the commit. $write_failed = false; // -- Migrate failed logins -- $failed_legacy = get_option( self::OPTION_FAILED_LOGINS, array() ); if ( is_array( $failed_legacy ) ) { foreach ( $failed_legacy as $ip => $data ) { if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { continue; } $expected_attempt_ips[ $ip ] = true; $res = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$attempts_table} (ip, attempt_count, first_attempt, last_attempt, usernames) VALUES (%s, %d, %d, %d, %s)", $ip, (int) ( $data['count'] ?? 0 ), (int) ( $data['first_time'] ?? time() ), (int) ( $data['last_time'] ?? time() ), wp_json_encode( array_slice( (array) ( $data['usernames'] ?? array() ), -10 ) ) ) ); if ( false === $res ) { $write_failed = true; } } } // -- Migrate blocked IPs -- $blocked_legacy = get_option( self::OPTION_BLOCKED_IPS, array() ); if ( is_array( $blocked_legacy ) ) { foreach ( $blocked_legacy as $ip => $data ) { if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { continue; } $expected_attempt_ips[ $ip ] = true; $expires = (int) ( $data['expires_at'] ?? 0 ); $locks = (int) ( $data['lockout_count'] ?? 1 ); $reason = sanitize_text_field( $data['reason'] ?? 'auto' ); $res = $wpdb->query( $wpdb->prepare( "INSERT INTO {$attempts_table} (ip, attempt_count, first_attempt, last_attempt, usernames, blocked_until, lockout_count, block_reason) VALUES (%s, %d, %d, %d, %s, %d, %d, %s) ON DUPLICATE KEY UPDATE blocked_until = %d, lockout_count = %d, block_reason = %s", $ip, (int) ( $data['attempts'] ?? 0 ), (int) ( $data['blocked_at'] ?? time() ), (int) ( $data['blocked_at'] ?? time() ), wp_json_encode( array_slice( (array) ( $data['usernames'] ?? array() ), -10 ) ), $expires, $locks, $reason, $expires, $locks, $reason ) ); if ( false === $res ) { $write_failed = true; } } } // -- Migrate login log (in reverse so oldest ids are inserted first) -- $log_legacy = get_option( self::OPTION_LOGIN_LOG, array() ); if ( is_array( $log_legacy ) && ! empty( $log_legacy ) ) { foreach ( array_reverse( $log_legacy ) as $entry ) { if ( empty( $entry['time'] ) ) { continue; } $expected_log_rows++; // ACG-149-R36-A: routed through insert_log_row() so ONE over-long legacy username // cannot wedge the migration permanently. The return was already checked here, and // that was the problem: a rejected row set $write_failed, which keeps the legacy // option and returns early — so the whole migration would be retried, and fail // again, on every single request, forever. if ( ! self::insert_log_row( $log_table, array( 'time' => (int) $entry['time'], 'ip' => sanitize_text_field( $entry['ip'] ?? '' ), 'username' => sanitize_text_field( $entry['username'] ?? '' ), 'status' => sanitize_text_field( $entry['status'] ?? '' ), 'user_id' => (int) ( $entry['user_id'] ?? 0 ), ) ) ) { $write_failed = true; } } } // ACG-031-011: VERIFY before deleting last-good legacy data. // (1) Every write must have succeeded (no $wpdb error returned false). This // alone defeats the count-mask: if any INSERT errored, we keep legacy. if ( $write_failed ) { return; // a write errored — keep the intact legacy source, retry next request } // (2) Read back the EXACT keys we migrated (not a blanket COUNT(*), which // pre-existing unrelated rows could satisfy on total failure). Every // expected attempt IP must now be present. foreach ( array_keys( $expected_attempt_ips ) as $exp_ip ) { $found = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$attempts_table} WHERE ip = %s", $exp_ip ) ); if ( $found < 1 ) { return; // a required IP is missing — abort, keep legacy intact } } // (3) The log table must hold at least the rows we just inserted. if ( $expected_log_rows > 0 ) { $dest_log = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$log_table}" ); if ( $dest_log < $expected_log_rows ) { return; // log rows short — abort, keep legacy intact } } // Verified — commit: mark migrated, then delete the legacy options. update_option( 'guardpress_login_db_migrated_v1', 1, false ); delete_option( self::OPTION_FAILED_LOGINS ); delete_option( self::OPTION_BLOCKED_IPS ); delete_option( self::OPTION_LOGIN_LOG ); } // ========================================================================= // Settings (stays in wp_options — written only by admin) // ========================================================================= public static function get_settings() { $defaults = array( 'enabled' => 1, 'max_attempts' => 5, 'lockout_duration' => 30, 'lockout_increase' => 1, 'log_logins' => 1, 'notify_lockout' => 0, ); return wp_parse_args( get_option( self::OPTION_SETTINGS, array() ), $defaults ); } public static function save_settings( $data ) { $settings = array( 'enabled' => ! empty( $data['gp_login_enabled'] ) ? 1 : 0, 'max_attempts' => isset( $data['gp_max_attempts'] ) ? max( 1, min( 20, absint( $data['gp_max_attempts'] ) ) ) : 5, 'lockout_duration' => isset( $data['gp_lockout_duration'] ) ? max( 5, min( 1440, absint( $data['gp_lockout_duration'] ) ) ) : 30, 'lockout_increase' => ! empty( $data['gp_lockout_increase'] ) ? 1 : 0, 'log_logins' => ! empty( $data['gp_log_logins'] ) ? 1 : 0, 'notify_lockout' => ! empty( $data['gp_notify_lockout'] ) ? 1 : 0, ); update_option( self::OPTION_SETTINGS, $settings, false ); return $settings; } // ========================================================================= // Login Check & Blocking // ========================================================================= public static function check_login( $user, $username, $password ) { if ( empty( $username ) ) { return $user; } // HIGH-3 (proactive hardening 2026-06-18): XML-RPC `system.multicall` // packs many authentication calls into ONE HTTP request. This gate runs // on the `authenticate` filter for every inner call and our counter is // incremented on `wp_login_failed` for every inner call, so credentials // CANNOT be brute-forced past the configured threshold via multicall — // the (max+1)th inner call is rejected here. To also stop a giant // multicall from hammering the DB on every call once an IP is blocked, // we memoise a HARD verdict (blacklist/lockout) for the rest of this // request and short-circuit subsequent calls with no further DB reads. // We deliberately do NOT memoise the "clear" verdict: a multicall can // push the IP over the threshold mid-request, and that fresh block must // be seen on the very next inner call. system.multicall itself is left // enabled so Jetpack and other legitimate clients keep working. static $blocked_verdict = null; if ( $blocked_verdict instanceof WP_Error ) { return $blocked_verdict; } $ip = self::get_client_ip(); if ( self::is_whitelisted( $ip ) ) { return $user; } if ( self::is_blacklisted( $ip ) ) { $blocked_verdict = new WP_Error( 'guardpress_blacklisted', __( 'Access Denied. Your IP address has been permanently blocked.', 'ai-cyberguard' ) ); return $blocked_verdict; } if ( self::is_ip_blocked( $ip ) ) { $remaining = self::get_lockout_remaining( $ip ); $blocked_verdict = new WP_Error( 'guardpress_lockout', /* translators: %d is the number of minutes until login is allowed again */ sprintf( __( 'Too many failed attempts. Please try again in %d minutes.', 'ai-cyberguard' ), ceil( $remaining / 60 ) ) ); return $blocked_verdict; } return $user; } public static function check_lockout() { $ip = self::get_client_ip(); if ( self::is_whitelisted( $ip ) ) { return; } if ( self::is_blacklisted( $ip ) ) { /* translators: %s is the site homepage URL */ wp_die( wp_kses_post( sprintf( __( '

Access Permanently Blocked

Your IP address has been blocked.

Go to homepage

', 'ai-cyberguard' ), esc_url( home_url() ) ) ), esc_html__( 'Access Blocked', 'ai-cyberguard' ), array( 'response' => 403 ) ); } if ( self::is_ip_blocked( $ip ) ) { $remaining = self::get_lockout_remaining( $ip ); /* translators: 1: number of minutes until login is allowed again, 2: site homepage URL */ wp_die( wp_kses_post( sprintf( __( '

Access Temporarily Blocked

Too many failed login attempts.

Try again in %1$d minutes.

Go to homepage

', 'ai-cyberguard' ), ceil( $remaining / 60 ), esc_url( home_url() ) ) ), esc_html__( 'Login Blocked', 'ai-cyberguard' ), array( 'response' => 403 ) ); } } /** * Record a failed login attempt. * * BINLOG FIX: Single INSERT … ON DUPLICATE KEY UPDATE — one tiny row * in the binlog instead of the entire serialised options array. */ public static function log_failed_attempt( $username, $error = null ) { // ACG-121 A1 (audit 2026-07-16): the 2FA step returns a WP_Error even when the PASSWORD WAS CORRECT // (gp_2fa_required = "now enter your code"), and again for each wrong code. WP fires wp_login_failed // for ANY authenticate WP_Error, so every legitimate 2FA login burned a brute-force strike and a few // mistyped codes locked the admin out of their OWN IP — with check_lockout() then wp_die()ing before // authenticate, so even the correct code no longer helped. These are second-factor states, not // password guessing: code guessing is throttled by the 2FA layer itself (FAIL_MAX -> FAIL_LOCK). // This counter defends the PASSWORD, so only the 2FA-step codes are exempt — a wrong password (and // gp_captcha, which is bot defence) still counts. $error defaults to null so a 1-arg do_action() // caller (pre-5.4 shape / third-party) keeps working. if ( is_wp_error( $error ) && in_array( $error->get_error_code(), array( 'gp_2fa_required', 'gp_2fa_invalid', 'gp_2fa_locked' ), true ) ) { return; } $ip_full = self::get_client_ip(); if ( self::is_whitelisted( $ip_full ) ) { return; } // HIGH-2: count against the /64 network for IPv6, exact for IPv4. $ip = self::lockout_key( $ip_full ); global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); $now = time(); // Read current attempt_count + usernames (single indexed SELECT). $existing = $wpdb->get_row( $wpdb->prepare( "SELECT attempt_count, usernames FROM {$table} WHERE ip = %s", $ip ) ); // ACG-033-015 (audit 2026-06-20, HIGH): an EXPIRED block must be normalized // BEFORE this failure is counted. Access checks already treat a row whose // blocked_until <= now as expired (the user can reach the login form again), // but log_failed_attempt() used to increment the STALE attempt_count — still // sitting at the old threshold (e.g. 5) — so the FIRST mistyped password // after a block expired jumped straight to 6 (>= max_attempts) and the IP // was immediately RE-LOCKED with lockout_count bumped and a LONGER duration. // One mistype after expiry trapped a user/network in escalating lockouts. // // Read the block marker from the row (separate read keeps the usernames read // above unchanged). A block has EXPIRED when blocked_until is non-zero and in // the past; blocked_until == 0 means "never blocked / already normalized" and // blocked_until > now means an ACTIVE block — left fully intact (the user is // currently locked out and won't even reach this code path via the form). $marker = $wpdb->get_row( $wpdb->prepare( "SELECT lockout_count, blocked_until FROM {$table} WHERE ip = %s", $ip ) ); $prev_blocked_until = $marker ? (int) $marker->blocked_until : 0; $expired_block = ( $prev_blocked_until > 0 && $prev_blocked_until <= $now ); $usernames = array(); if ( $existing ) { // Drop the stale username list when normalizing an expired block. $usernames = $expired_block ? array() : ( json_decode( $existing->usernames, true ) ?: array() ); } if ( ! in_array( $username, $usernames, true ) ) { $usernames[] = $username; } $usernames = array_slice( $usernames, -10 ); $usernames_json = wp_json_encode( $usernames ); if ( $expired_block ) { // NORMALIZE-AND-COUNT in ONE guarded write: this failure starts a fresh // window as attempt #1. We gate the UPDATE on the row STILL being expired // (blocked_until <> 0 AND blocked_until <= now) so a concurrent request // that already re-blocked or re-counted can't be clobbered — only the // first post-expiry writer wins the reset; a racing second one falls // through to the increment path below on its own re-read. Column order // deliberately starts with `attempt_count` so this is an attempt-counter // reset, NOT a (re)block. lockout_count is left UNCHANGED — escalation // happens only on a genuine NEW threshold breach inside block_ip_temp(). $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET attempt_count = 1, first_attempt = %d, last_attempt = %d, usernames = %s, blocked_until = 0, block_reason = '' WHERE ip = %s AND blocked_until <> 0 AND blocked_until <= %d", $now, $now, $usernames_json, $ip, $now ) ); // Post-expiry: a single mistype is attempt #1 of a brand-new budget — it // can NEVER reach the lockout threshold on its own, so do not even consult // block_ip_temp(). (Documented cooldown policy: an expired block grants a // full fresh attempt budget; lockouts re-escalate only after a new breach.) if ( self::get_settings()['log_logins'] ) { self::add_log_entry( array( 'ip' => $ip_full, 'username' => $username, 'status' => 'failed', 'user_id' => 0 ) ); } return; } // Normal path (no expired block): single UPSERT — primary-key lookup, one // small binlog row. $wpdb->query( $wpdb->prepare( "INSERT INTO {$table} (ip, attempt_count, first_attempt, last_attempt, usernames) VALUES (%s, 1, %d, %d, %s) ON DUPLICATE KEY UPDATE attempt_count = attempt_count + 1, last_attempt = %d, usernames = %s", $ip, $now, $now, $usernames_json, $now, $usernames_json ) ); // Read new count (single indexed SELECT). $new_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT attempt_count FROM {$table} WHERE ip = %s", $ip ) ); $settings = self::get_settings(); if ( $new_count >= $settings['max_attempts'] ) { self::block_ip_temp( $ip, array( 'count' => $new_count, 'usernames' => $usernames ) ); } if ( $settings['log_logins'] ) { self::add_log_entry( array( 'ip' => $ip_full, 'username' => $username, 'status' => 'failed', 'user_id' => 0 ) ); } } /** * Record a successful login and reset the IP's failed-attempt counter. */ public static function log_successful_login( $user_login, $user ) { $ip_full = self::get_client_ip(); $ip = self::lockout_key( $ip_full ); $settings = self::get_settings(); global $wpdb; $attempts_table = self::table( self::TABLE_ATTEMPTS ); // GP-REL-009: reset the counter for THIS IP/lockout-key unconditionally // and normalize any STALE (expired) block markers in the same statement, // so an already-expired block can't immediately re-block on the next fail. // The `blocked_until <= now` predicate clears the row whenever the IP is // NOT currently blocked (covers the old blocked_until=0 case AND the // previously-broken expired-but-nonzero case) while leaving an ACTIVE // block intact — a success from another host sharing the same /64 key // must not lift a live lockout. $wpdb->query( $wpdb->prepare( "UPDATE {$attempts_table} SET attempt_count = 0, usernames = '[]', blocked_until = 0, block_reason = '' WHERE ip = %s AND blocked_until <= %d", $ip, time() ) ); if ( $settings['log_logins'] ) { self::add_log_entry( array( 'ip' => $ip_full, 'username' => $user_login, 'status' => 'success', 'user_id' => $user->ID ) ); } } // ========================================================================= // Temporary Blocking // ========================================================================= /** * Auto-block an IP when attempt_count hits the threshold. * * BINLOG FIX: Single UPDATE by primary key — one tiny binlog row. */ private static function block_ip_temp( $ip, $attempt_data ) { $ip = self::lockout_key( $ip ); // idempotent — already a key from log_failed_attempt $settings = self::get_settings(); global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); // FIX L-7 (audit 2026-05-25): Short-circuit if the IP is already // currently blocked. Previously, every failed attempt during a // lockout window re-incremented lockout_count and re-applied the // multiplier — a single rapid burst would balloon the duration to // many hours, locking out the LEGITIMATE user behind a CGNAT // alongside the attacker. Now we only escalate on a NEW lockout // event (transition from "not blocked" to "blocked"), not on // every attempt during an existing one. $current = $wpdb->get_row( $wpdb->prepare( "SELECT lockout_count, blocked_until FROM {$table} WHERE ip = %s", $ip ) ); $now = time(); if ( $current && (int) $current->blocked_until > $now ) { // Already in an active lockout — refresh notification at most once // per call, but do NOT re-increment lockout_count or extend // blocked_until. The attacker can't make their own lockout worse // for the legitimate user. if ( $settings['notify_lockout'] ) { // (We intentionally allow re-notification — the operator may // want to see continued attempts on a blocked IP. Notification // dedup happens in send_lockout_notification's own throttle.) self::send_lockout_notification( $ip, $attempt_data ); } return; } $current_lockouts = $current ? (int) $current->lockout_count : 0; $lockout_minutes = $settings['lockout_duration']; if ( $settings['lockout_increase'] && $current_lockouts > 0 ) { $lockout_minutes *= ( $current_lockouts + 1 ); } $expires_at = $now + ( $lockout_minutes * 60 ); $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET blocked_until = %d, lockout_count = lockout_count + 1, block_reason = 'auto' WHERE ip = %s", $expires_at, $ip ) ); if ( $settings['notify_lockout'] ) { self::send_lockout_notification( $ip, $attempt_data ); } // FIX (audit 2026-06-10) / programmer review #3: feed the FREE-Plus Event // Log (TYPE_LOGIN was defined but nothing wrote it). // ACG-050-003 (audit 2026-06-23): do NOT store the tried usernames in the event meta — that was a DIRECT // personal identifier in a plugin-wide log with no per-user index, which the GDPR exporter/eraser could not // cleanly cover. The event message carries only the IP + attempt count; the per-user identity already lives // in login_log / login_attempts, which the privacy callbacks export and erase. self::log_event( sprintf( /* translators: 1: IP address, 2: failed-attempt count */ __( 'IP %1$s locked out after %2$d failed login attempts', 'ai-cyberguard' ), $ip, (int) ( $attempt_data['count'] ?? 0 ) ), array( 'ip' => $ip, 'reason' => 'auto' ) ); } public static function block_ip_manual( $ip, $duration_minutes = 60 ) { $ip = sanitize_text_field( $ip ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } $ip = self::lockout_key( $ip ); // group an IPv6 manual block to its /64, matching the auto path global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); $wpdb->query( $wpdb->prepare( "INSERT INTO {$table} (ip, attempt_count, first_attempt, last_attempt, usernames, blocked_until, lockout_count, block_reason) VALUES (%s, 0, %d, %d, '[]', %d, 1, 'manual') ON DUPLICATE KEY UPDATE blocked_until = %d, lockout_count = lockout_count + 1, block_reason = 'manual'", $ip, time(), time(), time() + ( $duration_minutes * 60 ), time() + ( $duration_minutes * 60 ) ) ); // FIX (audit 2026-06-10) / programmer review #3: log manual blocks too. self::log_event( sprintf( /* translators: %s: IP address */ __( 'IP %s blocked manually', 'ai-cyberguard' ), $ip ), array( 'ip' => $ip, 'reason' => 'manual' ) ); return true; } /** * FIX (audit 2026-06-10): thin, never-fatal bridge to the FREE-Plus Event * Log so login security actually populates TYPE_LOGIN. No-op if the event * log module is not loaded. */ private static function log_event( $message, $meta = array() ) { if ( class_exists( 'GuardPress_FreePlus_Event_Log' ) ) { try { GuardPress_FreePlus_Event_Log::log( 'login', $message, $meta ); } catch ( \Throwable $e ) { // never let logging break authentication } } } /** Single indexed SELECT — microseconds. */ public static function is_ip_blocked( $ip ) { $ip = self::lockout_key( $ip ); global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM {$table} WHERE ip = %s AND blocked_until > %d LIMIT 1", $ip, time() ) ); } public static function get_lockout_remaining( $ip ) { $ip = self::lockout_key( $ip ); global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); $exp = (int) $wpdb->get_var( $wpdb->prepare( "SELECT blocked_until FROM {$table} WHERE ip = %s", $ip ) ); return max( 0, $exp - time() ); } public static function unblock_ip( $ip ) { $ip = self::lockout_key( $ip ); global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); // FIX (2026-06-13): the attempts table only exists once login protection has // run its installer. Login Rescue can call this before brute-force protection // was ever enabled, so skip silently if the table isn't there (avoids a DB // warning in debug.log). Cached per-request to avoid a repeated SHOW TABLES. static $exists = null; if ( null === $exists ) { $exists = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table ); } if ( ! $exists ) { return; } $wpdb->update( $table, array( 'blocked_until' => 0, 'attempt_count' => 0 ), array( 'ip' => $ip ), array( '%d', '%d' ), array( '%s' ) ); } public static function get_blocked_ips() { global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); // FIX (April 2026): previously this SELECT aliased // `blocked_until - 1800 AS blocked_at` // which produced a fake timestamp assuming every lockout lasted // exactly 30 minutes. For any lockout duration other than 30 min // the displayed "Blocked At" time was wrong (often hours off). // `last_attempt` is the unix timestamp of the login attempt that // triggered the block, which is the actual moment the IP was // locked out — exactly what the UI should display. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT ip, attempt_count AS attempts, blocked_until AS expires_at, last_attempt AS blocked_at, lockout_count, block_reason AS reason FROM {$table} WHERE blocked_until > %d", time() ), ARRAY_A ); $result = array(); foreach ( (array) $rows as $row ) { $result[ $row['ip'] ] = array( 'blocked_at' => (int) $row['blocked_at'], 'expires_at' => (int) $row['expires_at'], 'attempts' => (int) $row['attempts'], 'lockout_count' => (int) $row['lockout_count'], 'reason' => $row['reason'], 'usernames' => array(), ); } return $result; } // ========================================================================= // Blacklist (wp_options — small, admin-written only) // ========================================================================= public static function add_to_blacklist( $ip, $reason = 'manual' ) { $ip = sanitize_text_field( trim( $ip ) ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } $bl = get_option( self::OPTION_BLACKLIST, array() ); $bl[ $ip ] = array( 'added_at' => time(), 'reason' => $reason, 'added_by' => get_current_user_id() ); update_option( self::OPTION_BLACKLIST, $bl, false ); self::unblock_ip( $ip ); self::clear_failed_attempts( $ip ); return true; } public static function remove_from_blacklist( $ip ) { $bl = get_option( self::OPTION_BLACKLIST, array() ); if ( ! isset( $bl[ $ip ] ) ) { return false; } unset( $bl[ $ip ] ); update_option( self::OPTION_BLACKLIST, $bl, false ); return true; } public static function is_blacklisted( $ip ) { return isset( get_option( self::OPTION_BLACKLIST, array() )[ $ip ] ); } public static function get_blacklist() { return get_option( self::OPTION_BLACKLIST, array() ); } // ========================================================================= // Whitelist (wp_options — small, admin-written only) // ========================================================================= public static function add_to_whitelist( $ip, $label = '' ) { $ip = sanitize_text_field( trim( $ip ) ); if ( ! filter_var( $ip, FILTER_VALIDATE_IP ) ) { return false; } $wl = get_option( self::OPTION_WHITELIST, array() ); $wl[ $ip ] = array( 'added_at' => time(), 'label' => sanitize_text_field( $label ), 'added_by' => get_current_user_id() ); update_option( self::OPTION_WHITELIST, $wl, false ); self::unblock_ip( $ip ); self::remove_from_blacklist( $ip ); self::clear_failed_attempts( $ip ); return true; } public static function remove_from_whitelist( $ip ) { $wl = get_option( self::OPTION_WHITELIST, array() ); if ( ! isset( $wl[ $ip ] ) ) { return false; } unset( $wl[ $ip ] ); update_option( self::OPTION_WHITELIST, $wl, false ); return true; } public static function is_whitelisted( $ip ) { return isset( get_option( self::OPTION_WHITELIST, array() )[ $ip ] ); } public static function get_whitelist() { return get_option( self::OPTION_WHITELIST, array() ); } // ========================================================================= // Suspicious IPs // ========================================================================= public static function get_suspicious_ips() { global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); $settings = self::get_settings(); $rows = $wpdb->get_results( "SELECT ip, attempt_count AS count, first_attempt AS first_time, last_attempt AS last_time, usernames FROM {$table} WHERE blocked_until = 0 AND attempt_count > 0 ORDER BY last_attempt DESC", ARRAY_A ); $result = array(); foreach ( (array) $rows as $row ) { $result[ $row['ip'] ] = array( 'count' => (int) $row['count'], 'first_time' => (int) $row['first_time'], 'last_time' => (int) $row['last_time'], 'usernames' => json_decode( $row['usernames'], true ) ?: array(), 'max_attempts' => $settings['max_attempts'], ); } return $result; } public static function clear_failed_attempts( $ip ) { $ip = self::lockout_key( $ip ); global $wpdb; $wpdb->update( self::table( self::TABLE_ATTEMPTS ), array( 'attempt_count' => 0, 'usernames' => '[]' ), array( 'ip' => $ip ), array( '%d', '%s' ), array( '%s' ) ); } public static function clear_all_failed_attempts() { global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); // GP-REL-009: clear every row that is NOT currently in an ACTIVE block, // and normalize stale (expired) block markers at the same time. Gating on // `blocked_until = 0` left expired-but-nonzero rows untouched, so an // admin "clear suspicious" left a stale block that re-engaged on the next // failed attempt. `blocked_until <= now` clears those too while preserving // live lockouts. $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET attempt_count = 0, usernames = '[]', blocked_until = 0, block_reason = '' WHERE blocked_until <= %d", time() ) ); } public static function block_ip_temporarily( $ip, $duration_minutes = 60 ) { return self::block_ip_manual( $ip, $duration_minutes ); } // ========================================================================= // Login Log // ========================================================================= /** * Append a log entry. * * BINLOG FIX: Single INSERT of one small row — no read-modify-write, * no full-array serialisation. */ /** * Append a log entry. * * BINLOG FIX: Single INSERT of one small row — no read-modify-write, * no full-array serialisation. * * RATE LIMIT: During a bot attack the same IP can attempt thousands of * logins per minute. Without limiting, each attempt creates an INSERT. * With rate limiting we log at most one 'failed' entry per IP per 60 s, * regardless of burst size. This keeps the log meaningful while cutting * writes by >99% during attacks. * 'success' and 'blocked' events are always logged (no rate limit). * * @param array $entry { ip, username, status, user_id } */ private static function add_log_entry( $entry ) { global $wpdb; $table = self::table( self::TABLE_LOG ); $status = sanitize_text_field( $entry['status'] ?? '' ); // Rate limit: skip if we already logged a 'failed' event from this // IP within the last 60 seconds (one cheap indexed SELECT). if ( $status === 'failed' ) { $already = $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM {$table} WHERE ip = %s AND status = 'failed' AND time > %d LIMIT 1", sanitize_text_field( $entry['ip'] ?? '' ), time() - 60 ) ); if ( $already ) { return; // Already recorded this IP recently — skip. } } self::insert_log_row( $table, array( 'time' => time(), 'ip' => sanitize_text_field( $entry['ip'] ?? '' ), 'username' => sanitize_text_field( $entry['username'] ?? '' ), 'status' => $status, 'user_id' => (int) ( $entry['user_id'] ?? 0 ), ) ); } /** * ACG-149-R36-A (pre-release audit 2026-07-27) — AUDIT-LOG EVASION: an over-long username * wrote NO row at all. * * wpdb::insert() does not truncate. process_fields() runs strip_invalid_text() and then * compares the result against what it was handed; the moment they differ it records * "The supplied value may be too long…" and returns FALSE, so _insert_replace_helper() * returns before issuing any query and NOTHING is written (wp-includes/class-wpdb.php: * process_fields() 2826-2854, strip_invalid_text() 3593-3632 — read, not assumed). * * login_log.username is VARCHAR(100). A failed login whose login field is padded past 100 * characters therefore left no audit row, while the lockout counter still climbed — that * path is a raw query(), and WordPress strips STRICT_TRANS_TABLES from sql_mode * (class-wpdb.php:644-651), so MySQL truncates there instead of erroring. So this is log * EVASION, not a lockout bypass: the brute force is still throttled, it is just invisible in * the Security Log. An attacker picks their own username, so they picked whether we saw them. * * Fix shape: leave the happy path byte-identical (no extra query, no behaviour change for a * normal login) and REPAIR ONLY ON REJECTION. The retry row is rebuilt as printable ASCII cut * to each column's own width, which provably survives strip_invalid_text(): ASCII takes the * check_ascii() branch, so the only transform available to wpdb is a byte cut at the column * length, and the value is already inside it — the equality check cannot trip. The username * tail is lost; the security fact (which IP, when, what outcome) never is. * * @param string $table Fully-qualified log table name. * @param array $row time / ip / username / status / user_id. * @return bool True when a row exists after this call. */ private static function insert_log_row( $table, $row ) { global $wpdb; $formats = array( '%d', '%s', '%s', '%s', '%d' ); if ( false !== $wpdb->insert( $table, $row, $formats ) ) { return true; } // Column widths from the CREATE TABLE in maybe_create_tables(): ip VARCHAR(45), // username VARCHAR(100), status VARCHAR(10). $row['ip'] = self::ascii_fit( $row['ip'] ?? '', 45 ); $row['username'] = self::ascii_fit( $row['username'] ?? '', 100 ); $row['status'] = self::ascii_fit( $row['status'] ?? '', 10 ); return false !== $wpdb->insert( $table, $row, $formats ); } /** * Reduce a value to printable ASCII, hard-cut to $max BYTES. * * ASCII is one byte per character, so the result is within $max under a byte-limited AND a * character-limited column, whatever the table charset turns out to be. See insert_log_row(). */ private static function ascii_fit( $value, $max ) { return substr( preg_replace( '/[^\x20-\x7E]/', '', (string) $value ), 0, $max ); } public static function get_log( $limit = 50 ) { global $wpdb; $table = self::table( self::TABLE_LOG ); return $wpdb->get_results( $wpdb->prepare( "SELECT time, ip, username, status, user_id FROM {$table} ORDER BY id DESC LIMIT %d", max( 1, (int) $limit ) ), ARRAY_A ) ?: array(); } // ========================================================================= // Statistics (pure SQL — no PHP array iteration on large sets) // ========================================================================= public static function get_stats() { global $wpdb; $lt = self::table( self::TABLE_LOG ); $at = self::table( self::TABLE_ATTEMPTS ); $now = time(); $td = strtotime( 'today midnight' ); $wa = strtotime( '-7 days midnight' ); return array( 'blocked_ips' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$at} WHERE blocked_until > %d", $now ) ), 'blacklisted_ips' => count( self::get_blacklist() ), 'suspicious_ips' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$at} WHERE blocked_until = 0 AND attempt_count > 0" ), 'failed_today' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$lt} WHERE status = 'failed' AND time >= %d", $td ) ), 'failed_week' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$lt} WHERE status = 'failed' AND time >= %d", $wa ) ), 'successful_today' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$lt} WHERE status = 'success' AND time >= %d", $td ) ), 'successful_week' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$lt} WHERE status = 'success' AND time >= %d", $wa ) ), 'total_failed' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$lt} WHERE status = 'failed'" ), 'total_successful' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$lt} WHERE status = 'success'" ), ); } // ========================================================================= // Cleanup (daily CRON — pure SQL DELETE, no read-modify-write cycle) // ========================================================================= public static function cleanup_old_records() { global $wpdb; $lt = self::table( self::TABLE_LOG ); $at = self::table( self::TABLE_ATTEMPTS ); // Delete log entries older than 30 days. $wpdb->query( $wpdb->prepare( "DELETE FROM {$lt} WHERE time < %d", strtotime( '-30 days' ) ) ); // Remove expired attempt records older than 7 days. $wpdb->query( $wpdb->prepare( "DELETE FROM {$at} WHERE last_attempt < %d AND blocked_until < %d", strtotime( '-7 days' ), time() ) ); // GP-REL-009: normalize EXPIRED blocks that are too recent to delete — // zero the stale block markers so an expired block can never silently // re-engage, while leaving ACTIVE blocks (blocked_until > now) intact. $wpdb->query( $wpdb->prepare( "UPDATE {$at} SET blocked_until = 0, block_reason = '' WHERE blocked_until > 0 AND blocked_until <= %d", time() ) ); // Hard cap: keep only the newest 5 000 log rows. $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$lt}" ); if ( $count > 5000 ) { $wpdb->query( $wpdb->prepare( "DELETE FROM {$lt} ORDER BY id ASC LIMIT %d", $count - 5000 ) ); } // ACG-055-006 (audit 2026-06-24): scheduled garbage-collection of abandoned privacy-cursor options so a // stale gp_priv_* cursor (with its last processed IP) cannot linger indefinitely even if no later privacy // request occurs to trigger the access-time TTL check. self::gc_stale_privacy_cursors(); } /** * ACG-055-006: bounded sweep of stale/abandoned gp_priv_* cursor options. Deletes any whose stored timestamp is * older than PRIV_STATE_TTL (or that carry no timestamp), leaving only the cursor of a genuinely in-flight * export/erase. Bounded by LIMIT so a daily cron pass is cheap. */ public static function gc_stale_privacy_cursors() { global $wpdb; if ( ! isset( $wpdb ) || ! method_exists( $wpdb, 'get_results' ) ) { return; } $cutoff = time() - self::PRIV_STATE_TTL; $like = method_exists( $wpdb, 'esc_like' ) ? $wpdb->esc_like( 'gp_priv_' ) . '%' : 'gp_priv_%'; $last_id = 0; // ACG-056-005 (audit 2026-06-24): page DETERMINISTICALLY through the WHOLE gp_priv_* family by the // option_id keyset (option_id > last_id, ascending), so a stale cursor sitting behind a screenful of // fresh ones is still reached — the old unordered head-only LIMIT could hide it forever. The loop is // bounded so a single cron pass always terminates and stays cheap; it stops on the last (short) page or // when the keyset cannot advance. for ( $guard = 0; $guard < 200; $guard++ ) { $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own privacy-cursor options "SELECT option_id, option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s AND option_id > %d ORDER BY option_id ASC LIMIT %d", $like, (int) $last_id, 500 ) ); if ( empty( $rows ) ) { return; } $advanced = false; foreach ( $rows as $row ) { if ( isset( $row->option_id ) && (int) $row->option_id > $last_id ) { $last_id = (int) $row->option_id; $advanced = true; } // ACG-056-006 (audit 2026-06-24): NEVER instantiate objects from option content during an // unattended cron — decode with allowed_classes=false (no __wakeup gadget) and accept only a // scalar cursor array. A malformed/non-scalar/objectful value is treated as garbage and removed. $val = self::safe_decode_cursor( $row->option_value ); $ts = ( is_array( $val ) && isset( $val['_ts'] ) ) ? (int) $val['_ts'] : 0; if ( null === $val ) { // ACG-065-002 (audit 2026-06-25): a malformed/objectful candidate is garbage, BUT a concurrent // callback can REFRESH this option into a VALID fresh cursor between our SELECT and this delete. // Use the SAME advisory lock + raw compare-and-delete as the stale branch below: re-read the LIVE // value (priv_reread_raw → safe-decoded, never get_option's object-instantiating unserialize) and // delete ONLY if it is STILL not a valid cursor (re-read is null). A fresh valid cursor committed // after our SELECT is preserved. Fail closed on a lock miss (skip; the daily cron retries). $mlock = self::priv_lock( $row->option_name ); if ( 'failed' === $mlock ) { continue; } try { // ACG-066-002: a NULL re-read that is a DATABASE ERROR (self::$priv_io_error) is NOT proof the // value is still malformed — skip rather than delete a possibly-valid cursor on a transient error. $mlive = self::priv_reread_raw( $row->option_name ); if ( ! self::$priv_io_error && null === $mlive ) { delete_option( $row->option_name ); // still malformed/absent → remove } } finally { if ( 'acquired' === $mlock ) { self::priv_unlock( $row->option_name ); } } } elseif ( $ts <= 0 || $ts < $cutoff ) { // ACG-059-002 / ACG-060-006 (audit 2026-06-24): COMPARE-AND-DELETE. The SELECTed value is stale, // but a concurrent callback can REFRESH the live option between the SELECT and this delete. Re-read // the LIVE value and only delete if it is STILL stale. The re-read goes through priv_reread_raw(), // which reads the RAW serialized option_value and decodes it with allowed_classes=false — NOT // get_option(), whose maybe_unserialize() would INSTANTIATE a concurrently-injected object // (firing __wakeup) in the unattended cron. ACG-061-002: hold the SAME advisory lock the cursor // writer uses so the re-read+delete is atomic against a concurrent refresh, and FAIL CLOSED — if // the lock could not be acquired ('failed': GET_LOCK timeout/error) SKIP this candidate rather // than deleting it unserialized. 'unsupported' (unit double) proceeds; the daily cron retries. $glock = self::priv_lock( $row->option_name ); if ( 'failed' === $glock ) { continue; } try { $live = self::priv_reread_raw( $row->option_name ); // ACG-066-002: a live re-read DB error is NOT proof of staleness/absence — skip, never delete. if ( self::$priv_io_error ) { continue; } $live_ts = ( is_array( $live ) && isset( $live['_ts'] ) ) ? (int) $live['_ts'] : 0; if ( null === $live || $live_ts <= 0 || $live_ts < $cutoff ) { delete_option( $row->option_name ); // still stale/abandoned (or no longer a valid cursor) → remove } } finally { if ( 'acquired' === $glock ) { self::priv_unlock( $row->option_name ); } } } } if ( count( $rows ) < 500 || ! $advanced ) { return; // last page, or a store that cannot advance the keyset (unit mock) → stop } } } /** * ACG-056-006 / ACG-058-001 (audit 2026-06-24): safely decode a stored gp_priv_* cursor value WITHOUT * instantiating any object (allowed_classes=false), then RECURSIVELY validate it against the cursor schema — * a bounded-depth array whose leaves are all scalar (or null). This accepts the v1.0.58 NESTED cursor * ({ 'p' => { pageNum => { scalar slot fields } }, '_ts' => int, 'done' => bool }) as well as the earlier flat * shape, while still rejecting anything carrying an object/resource. Returns the cursor array, or NULL for * anything unparseable / non-array / object-bearing / over-large — the caller then deletes such a row. * IMPORTANT: a fresh, valid NESTED cursor must SURVIVE here (only the GC's timestamp check may remove it). * * @param mixed $raw * @return array|null */ private static function safe_decode_cursor( $raw ) { if ( ! is_string( $raw ) || '' === $raw ) { return null; } if ( function_exists( 'guardpress_safe_unserialize' ) ) { $val = guardpress_safe_unserialize( $raw ); } else { $val = @unserialize( $raw, array( 'allowed_classes' => false ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_unserialize -- allowed_classes=false: scalars only, no object instantiation } if ( ! is_array( $val ) ) { return null; } $nodes = 0; if ( ! self::cursor_is_scalar_tree( $val, 0, $nodes ) ) { return null; // object/resource value, too deep, or too large → treat as garbage and remove } return $val; } /** * ACG-058-001 / ACG-059-002: recursive validation of the cursor schema — every value must be a scalar/null OR a * nested array of the same, bounded by depth (<= 4) and total node count so a hostile blob cannot cause runaway * work. No object/resource is ever accepted. The node cap is generous (200,000) so a LEGITIMATE high-volume * request — a per-page slot map for a multi-hundred-page export/erase — is NOT mistaken for an attack and * deleted; only a genuinely pathological structure is rejected. (Writers also compact the page map to a small * recent window, so an honest cursor never approaches this bound.) * * @param array $val * @param int $depth * @param int $nodes passed by reference, accumulates the visited element count * @return bool */ /** * ACG-060-006: re-read the LIVE raw serialized value of a gp_priv_* option and decode it SAFELY * (allowed_classes=false), WITHOUT going through get_option()/maybe_unserialize() — which would instantiate a * concurrently-injected serialized object and fire its magic methods in the unattended GC cron. Returns the * safe-decoded cursor array, or NULL when the row is gone / no longer a valid scalar cursor. * * @param string $name * @return array|null */ private static function priv_reread_raw( $name ) { global $wpdb; self::$priv_io_error = false; // ACG-066-002: reset; set below ONLY on a genuine DB error if ( ! isset( $wpdb ) ) { return null; } // Preferred: a single raw value read. if ( method_exists( $wpdb, 'get_var' ) ) { $raw = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- raw re-read of the plugin's own cursor option; must NOT round-trip through get_option's object-instantiating unserialize // ACG-066-002: a NULL result with a non-empty $wpdb->last_error is a DATABASE ERROR, NOT absence. Flag it so // callers fail the page / skip the GC candidate instead of treating it as a missing or corrupt cursor. if ( null === $raw && isset( $wpdb->last_error ) && '' !== (string) $wpdb->last_error ) { self::$priv_io_error = true; return null; } return ( null === $raw ) ? null : self::safe_decode_cursor( (string) $raw ); } // Fallback for a $wpdb double exposing only get_results. if ( method_exists( $wpdb, 'get_results' ) ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1", $name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- raw re-read of the plugin's own cursor option if ( isset( $wpdb->last_error ) && '' !== (string) $wpdb->last_error ) { self::$priv_io_error = true; return null; } if ( ! empty( $rows ) ) { foreach ( $rows as $r ) { if ( isset( $r->option_name ) && $r->option_name === $name && isset( $r->option_value ) ) { return self::safe_decode_cursor( (string) $r->option_value ); } } } } return null; } private static function cursor_is_scalar_tree( $val, $depth, &$nodes ) { if ( $depth > 4 ) { return false; } foreach ( $val as $v ) { if ( ++$nodes > 200000 ) { return false; } if ( is_array( $v ) ) { if ( ! self::cursor_is_scalar_tree( $v, $depth + 1, $nodes ) ) { return false; } } elseif ( null !== $v && ! is_scalar( $v ) ) { return false; // object / resource → reject the whole cursor } } return true; } // ========================================================================= // Utilities // ========================================================================= /** Delegates to GuardPress_Network::get_client_ip() — trusted-proxy-aware. */ public static function get_client_ip() { return GuardPress_Network::get_client_ip(); } /** * HIGH-2 (proactive hardening 2026-06-18): brute-force lockout key. * * An IPv6 attacker is normally handed a routed /64 and can mint a fresh * source address per request, walking straight past a per-exact-address * counter. We therefore key the AUTOMATIC failed-attempt counter on the * /64 network for IPv6 (the smallest block a single subscriber typically * gets) and on the exact address for IPv4. IPv4-mapped IPv6 is treated as * its embedded IPv4. The function is IDEMPOTENT — feeding it a value that * is already a /64 base returns the same string — so it is safe to apply * again anywhere downstream. Anything that is not a valid IP is returned * verbatim. * * NOTE: the admin blacklist/whitelist deliberately stay EXACT (operator * intent to allow/deny one specific address); only the automatic * attempts-table counter is grouped to a network. */ private static function lockout_key( $ip ) { if ( ! is_string( $ip ) || '' === $ip ) { return (string) $ip; } // Plain IPv4 — exact. if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { return $ip; } if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) && function_exists( 'inet_pton' ) ) { $packed = @inet_pton( $ip ); if ( false === $packed || 16 !== strlen( $packed ) ) { return $ip; } // IPv4-mapped (::ffff:a.b.c.d) — keep the embedded IPv4 exact, but // canonicalise the textual spelling so the four equivalent forms // (::ffff:1.2.3.4 / ::FFFF:1.2.3.4 / ::ffff:0102:0304 / long form) // all collapse to ONE key, matching how the pure-IPv6 branch below // canonicalises. (Unreachable via attacker-controlled headers — the // network layer rejects mapped forms — but belt-and-suspenders.) if ( "\0\0\0\0\0\0\0\0\0\0\xff\xff" === substr( $packed, 0, 12 ) ) { $canon = @inet_ntop( $packed ); return $canon ? $canon : $ip; } // Zero the low 64 bits → /64 network base, re-expand to canonical text. $network = substr( $packed, 0, 8 ) . str_repeat( "\0", 8 ); $base = @inet_ntop( $network ); return $base ? $base : $ip; } return $ip; } public static function get_admin_ip() { return self::get_client_ip(); } public static function login_message( $message ) { $ip = self::get_client_ip(); if ( self::is_whitelisted( $ip ) ) { return $message; } $ip = self::lockout_key( $ip ); // read the counter under the same key the writer used global $wpdb; $table = self::table( self::TABLE_ATTEMPTS ); $settings = self::get_settings(); $count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT attempt_count FROM {$table} WHERE ip = %s AND blocked_until = 0", $ip ) ); if ( $count > 0 ) { $remaining = $settings['max_attempts'] - $count; if ( $remaining <= 3 && $remaining > 0 ) { $message .= '
'; $message .= '' . esc_html__( 'Warning:', 'ai-cyberguard' ) . ' '; /* translators: %d is the number of login attempts remaining before lockout */ $message .= sprintf( esc_html__( '%d login attempts remaining before lockout.', 'ai-cyberguard' ), $remaining ); $message .= '
'; } } return $message; } private static function send_lockout_notification( $ip, $attempt_data ) { // FIX (audit 2026-06-10): block_ip_temp() claimed "Notification dedup // happens in send_lockout_notification's own throttle" — but there was NO // throttle, so every failed attempt during an active lockout fired another // admin email (an unauthenticated attacker could flood the inbox / mail // spool). Add a real throttle: (1) at most one email per IP per lockout // window, and (2) a global hourly cap so a distributed attack can't flood. $per_ip_key = 'gp_lockout_notified_' . md5( (string) $ip ); if ( false !== get_transient( $per_ip_key ) ) { return; // already notified for this IP's current lockout } $cap = (int) apply_filters( 'guardpress_max_lockout_emails_per_hour', 10 ); $global_key = 'gp_lockout_notify_count'; $global_count = (int) get_transient( $global_key ); if ( $cap > 0 && $global_count >= $cap ) { return; // global hourly cap reached — suppress the flood } $admin_email = get_option( 'admin_email' ); $site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $subject = sprintf( '[%s] IP Locked Out: %s', $site_name, $ip ); $message = "An IP address has been locked out due to too many failed login attempts.\n\n"; $message .= sprintf( "IP Address: %s\n", $ip ); $message .= sprintf( "Failed Attempts: %d\n", $attempt_data['count'] ); $message .= sprintf( "Usernames Tried: %s\n", implode( ', ', $attempt_data['usernames'] ) ); $message .= sprintf( "Time: %s\n", wp_date( 'Y-m-d H:i:s' ) ); $message .= sprintf( "\nManage blocked IPs: %s\n", admin_url( 'admin.php?page=guardpress_settings' ) ); wp_mail( $admin_email, $subject, $message ); // Record the throttle markers (see top of method). $settings = self::get_settings(); $window = max( 300, (int) ( $settings['lockout_duration'] ?? 15 ) * 60 ); set_transient( $per_ip_key, 1, $window ); set_transient( $global_key, $global_count + 1, HOUR_IN_SECONDS ); } // ========================================================================= // Uninstall helper // ========================================================================= public static function drop_tables() { global $wpdb; $wpdb->query( 'DROP TABLE IF EXISTS ' . self::table( self::TABLE_ATTEMPTS ) ); $wpdb->query( 'DROP TABLE IF EXISTS ' . self::table( self::TABLE_LOG ) ); delete_option( 'guardpress_login_db_migrated_v1' ); // GP-REL-011: clear the schema-version marker so a fresh install re-probes // and recreates the tables instead of trusting a stale "verified" flag. delete_option( self::OPTION_SCHEMA_VERSION ); } /** * FIX (audit 2026-06-10): clear the daily login-records cleanup cron. * The plugin's deactivation hook used to leave 'guardpress_cleanup_login_records' * scheduled forever (orphaned cron). Called from the main deactivation hook. */ public static function unschedule() { $next = wp_next_scheduled( 'guardpress_cleanup_login_records' ); while ( $next ) { wp_unschedule_event( $next, 'guardpress_cleanup_login_records' ); $next = wp_next_scheduled( 'guardpress_cleanup_login_records' ); } wp_clear_scheduled_hook( 'guardpress_cleanup_login_records' ); } // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter }