=== Guardian Shield — Advanced WordPress Security ===
Contributors:      guardianshield
Tags:              security, firewall, malware scanner, login security, brute force, bot protection, file integrity, XSS, SQL injection, two-factor
Requires at least: 6.0
Tested up to:      6.7
Requires PHP:      8.0
Stable tag:        1.0.0
License:           GPLv2 or later
License URI:       https://www.gnu.org/licenses/gpl-2.0.html

Enterprise-grade WordPress security: firewall, malware scanner, brute-force protection, file integrity monitoring, rate limiting, and a modern admin dashboard — all in one lightweight plugin.

== Description ==

Guardian Shield is a production-ready, OOP-architected security plugin that protects WordPress websites against the most common and dangerous attacks without sacrificing performance.

= Core Protection Modules =

**🔒 Login Security**
* Configurable failed-login limit with automatic temporary IP lockout
* User-enumeration blocking (hides wp-login.php, disables ?author= queries)
* Generic error messages to prevent credential fishing
* Session IP-binding (optionally invalidates session on IP change)
* 2FA-ready hook architecture (`gs_post_login_2fa`, `gs_2fa_verify`)
* Optional custom login URL (hides `/wp-login.php`)
* Full login attempt log with IP, username, result, and timestamp

**🛡 Firewall Engine**
* Scoring-based rule system — blocks requests only when cumulative threat score ≥ threshold
* 15 SQL-injection pattern rules (UNION SELECT, DROP TABLE, `xp_cmdshell`, time-based blind, etc.)
* 10 XSS pattern rules (script tags, `javascript:`, inline event handlers, `<iframe>`, `data:text/html`, hex encoding)
* 12 path-traversal / RCE pattern rules (`../`, null bytes, `eval(`, `base64_decode`, `/etc/passwd`, `/proc/self`)
* Inspects GET/POST params, REQUEST_URI (double-decoded), User-Agent, and Referer
* IPv4 + IPv6 blacklist / whitelist / temporary-block system with expiry
* 60-second transient caching of IP rules for high-traffic safety

**🤖 Bot Detection & Rate Limiting**
* 22 bad-bot signature matches (sqlmap, nikto, masscan, Selenium, scrapers, etc.)
* Safe-listed good bots (Googlebot, Bingbot, etc.) never blocked
* Heuristic bot-score 0-100 combining UA analysis, header anomalies, and request patterns
* Per-IP rate limiting with Redis/Memcached support for object-cache-backed environments
* Configurable request windows and thresholds per context (frontend, login, REST, XML-RPC)

**📁 File Integrity Monitor**
* SHA-256 hashes stored for all PHP/JS/CSS/HTML/.htaccess/ini files across WordPress core, active plugins, and active themes
* Detects modified, newly added, and deleted files
* Auto-rebuilds baseline after legitimate plugin/theme updates (`upgrader_process_complete` hook)
* Admin-triggered baseline rebuild available
* Skips uploads, cache, and plugin-owned log/quarantine directories

**🦠 Malware Scanner**
* 25 malware-signature patterns covering: `eval(base64_decode(`, `preg_replace /e`, web-shell callbacks (`shell_exec`, `passthru`, `proc_open`), FilesMan/r57/c99/WSO shells, remote file inclusion, `str_rot13`/`gzinflate` obfuscation, hex/chr encoding chains, rogue WP hook injections
* Severity scoring 1–4; auto-quarantine when score ≥ threshold
* Quarantine: file renamed under `wp-content/gs-quarantine/`, JSON manifest written, harmless stub left in-place so the application does not crash
* Cron-scheduled scans (hourly / twice-daily / daily, configurable)

**🌐 XML-RPC & REST API Protection**
* One-click XML-RPC disable
* `system.multicall` method removal (prevents brute-force amplification)
* Per-IP rate limiting on XML-RPC calls
* Unauthenticated REST API access restriction (optionally removes `/wp/v2/users` endpoint)

**🔐 Security Headers**
* `X-Content-Type-Options: nosniff`
* `X-Frame-Options: SAMEORIGIN`
* `X-XSS-Protection: 1; mode=block`
* `Referrer-Policy: strict-origin-when-cross-origin`
* `Permissions-Policy` (camera, microphone, geolocation off by default)
* `Strict-Transport-Security` (HTTPS only, configurable max-age)
* `Content-Security-Policy` (configurable per-site policy string)

**📊 Modern Admin Dashboard**
* Security score gauge (0-100) with colour-coded risk level
* Live stat cards: attacks (24 h), blocked (24 h), login events, active threats
* Chart.js attack-type breakdown bar chart (last 7 days)
* Tabbed settings with AJAX save — no page reloads
* Attack log table with severity badges, threat scores, and block indicators
* Login attempt log with colour-coded result badges
* Firewall page: add/remove IP rules inline, recent firewall events
* Scanner page: animated progress bar during scan, results table with quarantine status
* File monitor page: last check timestamp, per-file change type with colour-coded rows
* System health overview: module status table + quick-action buttons

**📧 Email Alerts**
* Configurable alert email address
* Per-event toggles: brute-force detected, malware found, file changes detected, critical attack
* 1-per-hour rate-limiting per alert type prevents alert storms
* HTML email templates with event details

= Performance =

* All hot-path IP-rule lookups cached in 60-second transients
* No frontend JS or CSS loaded on non-admin pages
* Database queries use `$wpdb->prepare()` with indexed columns
* Stats queries cached for 5 minutes
* Uses WordPress cron for scheduled work (no blocking real-time scans)

= Developer Hooks =

**Actions**
* `gs_brute_force_detected` — fires when brute force threshold is hit
* `gs_malware_detected` — fires when a file is quarantined
* `gs_file_changes_detected` — fires after an integrity check that found changes
* `gs_critical_attack_detected` — fires when a high-score attack is blocked
* `gs_post_login_2fa` — fires after password auth passes; return `false` to block login

**Filters**
* `gs_2fa_verify` — second-factor verification result; use to plug in any 2FA provider
* `gs_firewall_block_score_threshold` — override the blocking threshold (default: 10)
* `gs_malware_patterns` — add custom malware detection patterns
* `gs_scanner_extensions` — add or remove file extensions scanned for malware
* `gs_allowed_ip_check` — add custom IP whitelist logic
* `gs_security_score_deductions` — add custom score deductions to the dashboard gauge

= Requirements =

* WordPress 6.0 or later
* PHP 8.0 or later
* MySQL 5.7+ / MariaDB 10.3+
* Write access to `wp-content/` (for logs and quarantine)

== Installation ==

1. Upload the `guardian-shield` folder to `/wp-content/plugins/`.
2. Activate the plugin through the **Plugins** screen in WordPress.
3. Navigate to **Guardian Shield → Overview** in the admin menu.
4. Review the security score and enable/configure modules under **Settings**.
5. Click **Rebuild Baseline** on the File Monitor page to record your initial file hashes.
6. Click **Run Scan** on the Scanner page to perform your first malware scan.

= Upgrading =

The plugin runs `dbDelta()` on every activation, so database schema upgrades are handled automatically.

== Frequently Asked Questions ==

= Will this slow down my website? =

No. All protection logic runs at `init` priority 1 and uses transient-cached IP rules. No scripts or styles are loaded on the frontend. Expensive operations (file scanning, integrity checks) run via WP-Cron, not in response to visitor requests.

= Can I use my own 2FA provider? =

Yes. Add a callback on the `gs_post_login_2fa` action and use the `gs_2fa_verify` filter to validate the second factor. Return `false` from the action to prevent login.

= What happens to quarantined files? =

Quarantined files are moved to `wp-content/gs-quarantine/` and renamed with a `.quarantine` extension. A JSON manifest is written alongside each file recording the original path, hash, detection details, and timestamp. A harmless stub PHP file is left in the original location so the application continues to function. You can review and restore files from the Scanner page.

= Does it work with Cloudflare? =

Yes. Enable **Cloudflare Mode** in Settings → Advanced. Guardian Shield will then trust the `CF-Connecting-IP` header for real visitor IP detection. Leave this OFF if you are not behind Cloudflare to prevent IP-spoofing attacks.

= Does it support IPv6? =

Yes. All IP storage, matching, and rate-limiting logic handles both IPv4 and IPv6 addresses including CIDR range matching.

= What is the security score? =

The score starts at 100 and deductions are applied for each disabled security module and for active threats (locked-out IPs, detected malware, modified files). It is a quick at-a-glance risk indicator, not a penetration-test result.

= How do I completely remove the plugin data? =

Go to **Guardian Shield → Settings → Advanced** and enable **Remove all data on uninstall**, then delete the plugin from the Plugins screen. All database tables, options, transients, logs, and the quarantine directory will be removed.

== Screenshots ==

1. **Overview dashboard** — security score gauge, stat cards, attack-type chart, and module status.
2. **Firewall page** — IP rule management and recent firewall events.
3. **Attack logs** — colour-coded severity badges with threat scores and block indicators.
4. **Malware scanner** — animated progress bar during scan and results with quarantine badges.
5. **File integrity monitor** — change summary with per-file type colour coding.
6. **Settings** — tabbed panel with AJAX save across all modules.

== Changelog ==

= 1.0.0 =
* Initial release.
* Firewall engine with SQL-injection, XSS, and path-traversal detection.
* Scoring-based block system with IP blacklist/whitelist/temp-block.
* Login security: attempt limiting, lockout, user-enumeration blocking, custom login URL.
* Bot detection: 22 bad-bot signatures, heuristic scoring.
* Rate limiter: transient-based with Redis/Memcached support.
* Security headers: CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy.
* XML-RPC guard: disable, multicall removal, rate limiting.
* REST API guard: guest access restriction, rate limiting.
* File integrity monitor: SHA-256 baseline, cron-scheduled checks, post-update rebaseline.
* Malware scanner: 25 patterns, severity scoring, auto-quarantine, scheduled scans.
* Email alerts: per-event toggles, 1-per-hour rate limiting, HTML templates.
* Admin dashboard: Chart.js attack chart, security gauge, AJAX-powered settings.
* Full uninstall cleanup script.

== Upgrade Notice ==

= 1.0.0 =
First release. No upgrade path needed.

== License ==

Guardian Shield is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.

Guardian Shield is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
