=== PB4Host Security ===
Contributors: pb4host, pbkrishnagmailcom
Tags: security, firewall, malware scanner, 2fa, turnstile
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 1.0.5
License: GPL-2.0-or-later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Enterprise Security Suite for WordPress: Web Application Firewall (WAF), Active Malware Scanner, Brute-Force Defense, 2FA, and System Hardening.

== Description ==

**PB4Host Security** is an enterprise-grade, all-in-one Security & Protection suite engineered specifically for WordPress. Built to safeguard your website from cyber threats, brute force attacks, malicious payloads, and backdoors with minimal performance impact.

Featuring an early Web Application Firewall (WAF), active heuristic malware scanner, native Two-Factor Authentication (2FA/TOTP), intelligent brute-force lockout defense, system hardening, and zero-day virtual patching.

Key Highlights:
* High-Performance Web Application Firewall (WAF) running at early priority before plugins execute.
* Active Malware & Heuristic Scanner with quarantined vault isolation and 1-click restoration.
* Native Two-Factor Authentication (2FA / TOTP) compatible with Google Authenticator, Authy, and Microsoft Authenticator.
* Intelligent Brute-Force Login Defense with honeypot traps and custom login slugs.
* Comprehensive System Hardening (XML-RPC disabler, user enumeration guard, uploads PHP execution blocker).
* Privacy-first architecture: Threat intelligence feeds, disposable email lists, and trackback verification run 100% offline with zero external tracking.

== Features ==

### 🛡️ Complete Enterprise Security Engines:

1. **Web Application Firewall (WAF)**:
   * **Early Packet Inspection**: Runs before theme and plugin execution to intercept malicious requests.
   * **Deep Threat Detection**: Protects against SQL Injection (SQLi), Cross-Site Scripting (XSS), Local File Inclusion (LFI), and Remote Code Execution (RCE).
   * **Scanner & Bot Defense**: Blocks automated vulnerability scanners (sqlmap, nikto, wpscan, nmap).
   * **Rate Limiting & IP Set**: Protects against velocity surges and supports full CIDR IP white/blacklisting.

2. **Active Malware & File Integrity Scanner**:
   * **Heuristic Signature Engine**: Detects webshells, obfuscated base64 execution, and dynamic backdoors.
   * **Uploads Directory Guard**: Flags and prevents executable scripts inside uploads directories.
   * **Quarantine Vault**: Safely isolates infected files with 1-click restore and permanent delete options.

3. **Login Security & Brute-Force Defense**:
   * **Intelligent IP Lockout**: Automatically locks out IP addresses exceeding maximum failed login attempts.
   * **Honeypot Traps**: Immediate lockout upon login attempts with reserved usernames (`admin`, `root`).
   * **Custom Login Slug**: Conceals `wp-login.php` behind a custom URL with 403 Forbidden on direct requests.
   * **Masked Errors**: Neutralizes login hints to prevent username enumeration.

4. **Native Two-Factor Authentication (2FA / TOTP)**:
   * **RFC 6238 Standard**: Fully compatible with Google Authenticator, Authy, Microsoft Authenticator, and 1Password.
   * **Offline & Privacy-First**: Zero external tracking or third-party API dependencies.
   * **Role Enforcement & Backup Codes**: Enforce mandatory 2FA on admin/editor roles, with emergency recovery codes.

5. **WordPress & System Hardening**:
   * **Surface Reduction**: Disables XML-RPC and unauthenticated REST API user enumeration.
   * **File Protection**: Disables administrative file editing and secures uploads folder via `.htaccess`.
   * **HTTP Security Headers**: Enforces `X-Frame-Options`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy`.

6. **Live Security Audit Log**:
   * Real-time stream of security events: WAF blocks, failed logins, lockouts, 2FA, and file changes.
   * Filterable by severity with automated 30-day log rotation and 1-click CSV export.

7. **Frictionless Bot Defense (Turnstile & reCAPTCHA)**:
   * Protects login, registration, lost password, and comment forms against automated abuse.
   * Fail-open network resilience prevents user lockouts during upstream API hiccups.

8. **Known CVE Vulnerability Scanner**:
   * Audits core, plugins, and themes against known CVE vulnerabilities and CVSS scores.
   * 1-click direct update links to patch vulnerable extensions quickly.

9. **Compromised Password Checking & Password Policy**:
   * Optional HaveIBeenPwned check using privacy-preserving k-anonymity (5-char SHA-1 prefix only).
   * Enforces configurable password strength, mixed case, and personal data restrictions.

10. **GeoIP & Country Access Control**:
    * Granular country allowlisting and denylisting for the whole site or login screens.
    * Uses fast edge server headers (Cloudflare `CF-IPCountry`) or cached fallback lookups.

11. **User Session Manager**:
    * Real-time visibility into all active user sessions and device fingerprints.
    * Enforces idle auto-logout and concurrent session caps with 1-click remote session revocation.

12. **Curated Threat Intelligence & IP Set**:
    * Bundled local threat intelligence and suspicious IP rules block bad actors before execution.
    * 100% offline local processing ensures zero external latency or privacy leaks.

13. **Official WordPress.org Checksum Verifier**:
    * Verifies core and plugin files against official WordPress.org cryptographic hashes.
    * Detects rogue or extraneous files within core directories.

14. **File Integrity Monitoring (FIM)**:
    * Takes cryptographic SHA-256 baselines of site files and detects additions, alterations, or deletions.
    * Smart exclusion filters ignore cache files and media uploads.

15. **Targeted Virtual Patching (vPatch)**:
    * Intercepts critical exploit vectors for known high-impact WordPress vulnerabilities before plugin code runs.
    * Proactive micro-rules protect sites even before vendor security updates are installed.

16. **Real-Time Multi-Channel Security Alerts**:
    * Dispatches instant security incident notifications via Slack, Discord, Email, or SIEM webhooks.
    * Anti-flood rate limiting prevents alert fatigue while ensuring critical alerts pass through.

17. **Security Fleet Profile Export & Import**:
    * Standardize security policies across client and staging sites using portable JSON profiles.
    * Automatic pre-import rollback snapshots protect against configuration errors.

18. **Database Security Hardening & Hygiene**:
    * Audits user accounts for rogue administrators and disposable email domains.
    * Scans database tables for obfuscated payloads, script injections, and unhygienic transient overhead.

== Shortcodes ==

* `[pb4host_security_2fa_status]` - Optional shortcode to display current 2FA activation status to logged-in users.

== WP-CLI Commands ==

* `wp pb4host-security scan [--scope=<all|core|plugins|themes|uploads>]` - Run automated malware scan.
* `wp pb4host-security waf-status [--mode=<protect|monitor>]` - View or update WAF settings.
* `wp pb4host-security block-ip <ip>` - Add IP to WAF blacklist.
* `wp pb4host-security unblock-ip <ip>` - Remove IP from blacklist and release active lockouts.
* `wp pb4host-security lockouts [--clear]` - List or clear active login lockouts.
* `wp pb4host-security audit-log [--limit=20] [--event=<event>]` - View recent audit logs.
* `wp pb4host-security vuln-scan [--format=<table|json|csv>]` - Inspect core, plugins, and themes for known CVE vulnerabilities.
* `wp pb4host-security sessions <list|revoke|force-logout-all> [--user=<user>]` - Inspect or remotely terminate user sessions.
* `wp pb4host-security checksums <core|plugins|rogue> [<plugin>]` - Verify core & plugin files against official WordPress.org checksums.
* `wp pb4host-security fim <status|check|accept>` - Manage File Integrity Monitoring baseline snapshots and differential audits.
* `wp pb4host-security vpatch <status|list|toggle> [<patch_id>] [--enable|--disable]` - Manage Targeted Virtual Patching (vPatch) micro-rules and exploit shields.
* `wp pb4host-security alerts <status|test|configure> [--channel=<all|email|slack|discord|webhook>]` - Manage multi-channel security alerts, test notification channels, and configure SIEM webhooks.
* `wp pb4host-security config <presets|apply-preset|export|import|backups> [...]` - Export/import fleet configurations, deploy preset profiles, and manage rollback snapshots.
* `wp pb4host-security db <posture|check-admins|trust-admin|demote-admin|scan|clean-threat> [...]` - Database security hardening, rogue administrator auditing, and payload disinfection.

== Installation ==

1. Upload the `pb4host-security` folder to the `/wp-content/plugins/` directory, or install via the WordPress Plugins screen.
2. Activate the plugin through the 'Plugins' menu in WordPress.
3. Navigate to **PB4Host Security** in the WordPress admin menu to review your security score and configure your firewall rules.

== Frequently Asked Questions ==

= Does PB4Host Security slow down my website? =
No. PB4Host Security is designed to be lightweight, utilizing compiled regex patterns, transient caching, and memory-safe chunked scanning to minimize performance impact on your website.

= What happens if I get locked out? =
If your IP is locked out due to failed attempts, you can wait for the lockout duration (default 30 mins) or run `wp pb4host-security lockouts --clear` via SSH / WP-CLI.

= Does the Two-Factor Authentication require internet connectivity? =
No. The TOTP algorithm runs completely offline on your server using standard math and time calculations.

== External Services ==

PB4Host Security may optionally connect to third-party external services only when explicitly enabled and configured by the website administrator. Under WordPress.org Privacy Guidelines 7 & 9, all remote service calls are strictly optional, turned OFF by default, and never phone home without explicit administrator opt-in consent:

* **Offline Privacy Notice**:
  * The Community Threat Intelligence IP list, Disposable Email Domain blocker, and Pingback/Trackback verification operate 100% offline using locally bundled curated databases. They make zero external HTTP requests, phone home to no remote servers, and transmit no data whatsoever.

* **WPVulnerability API**
  * Service URL: https://www.wpvulnerability.net
  * Purpose: Checks installed WordPress core, plugins, and themes against known CVE security advisories and CVSS vulnerability scores.
  * What Data is Sent and When: Transmits only plugin and theme directory slugs and installed version numbers (e.g. `plugin/woocommerce`, `9.0.0`). No site URLs, visitor data, IP addresses, or personal information are ever transmitted.
  * Opt-In Requirement: 100% optional and disabled by default (`vuln_scanner_remote_api = 0`). Only executes when an administrator explicitly opts in via settings or manually triggers a vulnerability scan.
  * Terms of Service: https://www.wpvulnerability.com/license/
  * Legal Notice: https://www.robotstxt.es/legal/
  * Privacy Policy: https://www.wpvulnerability.com/privacy/

* **Country.is Geolocation API**
  * Service URL: https://api.country.is
  * Purpose: Resolves client IP addresses to 2-letter ISO country codes for GeoIP and country-based firewall blocking when native web server / reverse-proxy headers (such as Cloudflare `CF-IPCountry`, Cloudfront, or Fastly) are unavailable.
  * What Data is Sent and When: Transmits the client IP address to resolve country code. Results are cached locally in WordPress transients for 7 days to eliminate redundant lookups.
  * Opt-In Requirement: 100% optional and disabled by default (`geoip_enabled = 0`). Only queries Country.is if the administrator enables GeoIP blocking in settings.
  * Terms of Service & Privacy Policy: https://country.is/

* **Cloudflare Turnstile**
  * Service URL: https://challenges.cloudflare.com
  * Purpose: Frictionless bot mitigation and human verification for login, registration, lost password, and comment forms.
  * What Data is Sent and When: Client IP address, browser User-Agent, and the client-side challenge token are sent to Cloudflare during form submission for cryptographic token verification.
  * Opt-In Requirement: 100% optional and disabled by default. Requires the site administrator to obtain and configure Turnstile API Site Key and Secret Key.
  * Terms of Service: https://www.cloudflare.com/terms/
  * Privacy Policy: https://www.cloudflare.com/privacypolicy/

* **Google reCAPTCHA (v2 / v3)**
  * Service URL: https://www.google.com/recaptcha/api/siteverify
  * Purpose: Bot defense and human verification on public forms.
  * What Data is Sent and When: Client IP address, browser User-Agent, and response token are transmitted to Google upon form submission for verification.
  * Opt-In Requirement: 100% optional and disabled by default. Requires the site administrator to configure reCAPTCHA Site Key and Secret Key.
  * Terms of Service: https://policies.google.com/terms
  * Privacy Policy: https://policies.google.com/privacy

* **HaveIBeenPwned API (Troy Hunt)**
  * Service URL: https://haveibeenpwned.com
  * Purpose: Checking candidate passwords during user registration or password reset against known breached credential dumps.
  * What Data is Sent and When: Utilizes a privacy-preserving k-Anonymity mathematical model. Transmits ONLY the first 5 characters of the SHA-1 hash of the candidate password. Raw passwords, usernames, site URLs, and user accounts are never sent over the network.
  * Opt-In Requirement: 100% optional and disabled by default (`pw_check_hibp = 0`). Only executed if an administrator explicitly enables "Check candidate passwords against HaveIBeenPwned" in Login Security settings.
  * Terms of Service: https://haveibeenpwned.com/API/v3#AcceptableUse
  * Privacy Policy: https://haveibeenpwned.com/Privacy

* **WordPress.org Checksums & SVN API**
  * Service URL: https://api.wordpress.org/core/checksums/1.0/
  * Purpose: Compares local WordPress core and repository plugin files against official cryptographic hashes published by WordPress.org to detect altered files or backdoors.
  * What Data is Sent and When: WordPress core version and installed plugin slugs/versions. Runs only when an administrator manually triggers core or plugin checksum verification.
  * Privacy Policy: https://wordpress.org/about/privacy/

* **External Notification Webhooks (Slack, Discord, Custom SIEM)**
  * Service URL: Configured by administrator (e.g., https://hooks.slack.com, https://discord.com, or custom SIEM HTTPS endpoint).
  * Purpose: Dispatches real-time security incident alerts to the administrator's chosen notification channel.
  * What Data is Sent and When: Incident event title, severity level, timestamp, site URL, and incident description. Runs only when configured and enabled by the site administrator.

== Changelog ==

= 1.0.5 =
* Feature: Added Live Threat IP Activity & Real-Time Intelligence Stream to Security Analytics dashboard.
* Performance: Zero-CPU Server Conservation Mode automatically halts background polling when tabs are inactive or when polling is disabled.
* Improvement: Resilient in-place Settings & CPU panel toggle with instant inline script fallback, active chevron feedback, and direct Hardening settings link.
* Fix: Add default variable initialization in Scheduled WP-Cron Tasks & Backdoor Hunter.
* Fix: Removed inline scripts and ensured all assets adhere to standard wp_enqueue_script and wp_enqueue_style APIs.
* Fix: Harmonized all internal symbols, REST routes, CLI commands, and hooks to canonical 'pb4host_' prefixes (>= 4 characters) to resolve WordPress.org review requirements.
* Fix: Updated Author URI and License URI to ensure robust availability during automated checks.

= 1.0.4 =
* Release: Standardized plugin directory naming and text domain across all components to 'pb4host-security'.
* Performance: Enhanced WAF fast-drop Nginx compilation and pre-bootstrap early cache sync.
* Packaging: Resolved WordPress.org Plugin Check validations and cleaned production archive structures.

= 1.0.3 =
* Fix: Ensure all external third-party calls (WPVulnerability API, HaveIBeenPwned) are disabled by default and require explicit administrator opt-in consent per Guidelines 7 & 9.
* Fix: Converted Community Threat Intelligence Feed, Disposable Email Domain blocking, and Pingback/Trackback verification to 100% local offline processing, removing all undocumented network requests.
* Fix: Standardize text domain to 'pb4host-security' matching the approved WordPress.org plugin directory slug.
* Fix: Removed waf-bootstrap.php to eliminate inline CSS styles and ensure proper script/style enqueuing.
* Fix: Resolve filesystem locations strictly using WordPress directory API helpers (get_home_path(), plugin_dir_path(), wp_upload_dir()) avoiding hardcoded paths.
* Fix: Restrict WP-CLI configuration exports strictly to the plugin's uploads directory.
* Fix: Enforce nonce verification on WAF self-unblock actions.
* Fix: Ensure all function, class, transient, option, and hook prefixes meet or exceed the 4-character requirement (pb4host_ / pb4host_security_).
* Fix: Add explicit direct-access checks (defined('ABSPATH') || exit) across all PHP files.

= 1.0.2 =
* Fix: Standardize all internal translation text domains to 'pb4host-security' in compliance with WordPress Plugin Guidelines.
* Fix: Add missing translator context comments for localized strings containing format placeholders.
* Fix: Ensure strict output escaping on dynamic parameters in two-factor administrative screens and database audit logs.
* Fix: Sanitize and unslash administrative navigation input variables.
* Improvement: Modernize translation loading in accordance with WordPress 4.6+ automatic core language pack standard.
* Hardening: Strengthen input sanitization and unslashing on trusted device cookies.

= 1.0.1 =
* Security and performance hardening patch.
* Added multi-tier GeoIP resolution and country-level filtering.
* Enhanced WAF pre-execution packet gating.

= 1.0.0 =
* Initial release of PB4Host Security.
* Web Application Firewall (WAF) with SQLi, XSS, LFI, RCE, and bad bot threat inspection.
* Active heuristic malware scanner with uploads folder enforcement and quarantine vault.
* Brute force defense with IP lockouts and honeypot username traps.
* RFC 6238 Two-Factor Authentication (2FA / TOTP) with role enforcement.
* System hardening: XML-RPC disabler, REST API user enumeration lock, uploads execution guard, and security HTTP headers.
* Real-time security audit log with 30-day auto-prune and CSV export.
* Frictionless Bot Defense Engine supporting Cloudflare Turnstile & Google reCAPTCHA v3/v2 with fail-open network resilience.
* Known Plugin, Theme & Core CVE Vulnerability Scanner with dual-layer offline/online intelligence.
* Compromised Passwords (HaveIBeenPwned k-Anonymity API) & Password Policy Engine.
* GeoIP & Country Blocking Extension with multi-tier resolution, whitelist/blacklist modes, and fail-safe private IP immunity.
* User Session Manager & Remote Device Termination with idle auto-logout, concurrent session caps, and emergency containment.
* Automated Community Threat Intelligence IP Feed with dynamic WP-Cron sync, offline seed defense, and fast O(1) pre-execution packet gating.
* Official WordPress.org Core & Plugin Checksum Integrity Verification engine.
* File Integrity Monitoring (FIM) & Filesystem Snapshot Engine with SHA-256 differential auditing.
* Targeted Virtual Patching (vPatch) Engine with early WAF interception (priority 4), curated high-impact CVE micro-rules, and dual auto/proactive modes.
* Multi-Channel Real-Time Security Alerts & Webhook Notifications Engine (Slack Block Kit, Discord Embeds, HTML Email, and SIEM HMAC-SHA256 Webhooks).
* Security Fleet Profile Export/Import & Hosting Standardization Engine with SHA-256 integrity verification, secret scrubbing, automatic rollback snapshots, and curated profiles (High Security, WooCommerce, VPS).
* Database Security Hardening & Rogue Admin Audit Engine with covert administrator account detection, disposable email flagging, options/posts malware payload scanning, MySQL privilege audit, and 1-click remediation.
* Complete WP-CLI CLI command suite.
