Search by

helsingborg-stad / wpmu-security

sebastianthulin

A WordPress MU Plugin for security enhancements

Package info

github.com/helsingborg-stad/wpmu-security

Type:wordpress-muplugin

pkg:composer/helsingborg-stad/wpmu-security

Statistics

Installs: 4 720

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 7

1.12.13 2026-12-01 14:23 UTC

README

A lightweight WordPress plugin focused on modern security hardening best practices without unnecessary bloat.

🚀 Features

  • ✅ Generic login error messages (prevent user enumeration)
  • ✅ Generic password reset responses
  • ✅ HTTP Strict Transport Security (HSTS)
  • ✅ CORS configuration
  • ✅ Subresource Integrity (SRI) for scripts and styles
  • ✅ XML-RPC disabling
  • ✅ Comment sanitization (anti-XSS)
  • ✅ Content Security Policy (CSP)
  • ✅ Custom port number support (development environments, custom setups)
  • ✅ Api Rate Limiter

⚙️ Configuration

This plugin is designed to be hassle free, however if you like to add domains that are not detected in the content security policy. Please use the following filter:

add_filter(
    'WpSecurity/Csp',
    function ($domains) {
        if(!isset($domains['connect-src'])) {
            $domains['connect-src'] = [];
        }
        $domains['connect-src'][] = 'https://*.domain.com';
        $domains['connect-src'][] = 'https://*.domain.net';
        return $domains;
    }
);

🔧 Custom Port Support

The plugin fully supports WordPress installations running on custom ports (e.g., localhost:8080 for development). All security features work correctly with custom ports:

  • ✅ CSP headers include port numbers in domain policies
  • ✅ CORS headers respect the full URL with port
  • ✅ SRI verification works with local assets on custom ports
  • ✅ All URL parsing and domain matching handles ports correctly

No additional configuration is needed - the plugin automatically detects and handles custom ports from your WordPress site URL.

For detailed information about custom port support, see CUSTOM_PORTS.md.

HTTP Strict Transport Security

HSTS is sent only when WordPress is_ssl() identifies the current request as HTTPS. Behind a trusted reverse proxy, configure WordPress and the proxy together so that is_ssl() sees HTTPS; never accept forwarded protocol headers directly from untrusted clients. Configure the edge as well for redirects, static files, errors, and cache hits that bypass PHP. Avoid conflicting edge and PHP headers.

The existing WPSecurity/GetHstsMaxAge filter remains available (default 31536000 seconds). includeSubDomains is now opt-in using WPSecurity/GetHstsIncludeSubDomains; enable it only when every subdomain supports HTTPS. Preload is not enabled. Previously HSTS could be sent on HTTP because the site URL was used instead of the request; installations behind proxies should verify their HTTPS detection when upgrading.

Cross-Origin-Opener-Policy

COOP is disabled by default to preserve existing popup authentication and other integrations. Choose a policy under Settings → Security, or filter WPMUSecurity/Headers/CrossOriginOpenerPolicy to same-origin, same-origin-allow-popups, or unsafe-none. The plugin preserves an existing PHP response header. same-origin isolates cross-origin windows but may break communication with authentication or payment popups; same-origin-allow-popups offers compatibility for some integrations, but does not restrict popup compatibility to selected domains. Test actual popup flows before enabling it. Configure the web server or proxy consistently, since it can overwrite or add headers after PHP, and configure cache-served and static responses at the edge.

Referrer-Policy

The default remains origin for compatibility. Use Settings → Security or filter WPMUSecurity/Headers/ReferrerPolicy to a valid policy, for example strict-origin-when-cross-origin; invalid values fall back to origin. origin sends only the origin on same- and cross-origin requests, including HTTPS-to-HTTP requests. strict-origin-when-cross-origin sends the full URL same-origin, only the origin cross-origin, and nothing on an HTTPS downgrade. Choose after reviewing analytics and privacy requirements. An existing PHP header is respected; a web server, CDN or cache may replace it or add another header after PHP. Configure the same policy at the edge for redirects, static files, errors and cache hits, and check actual HTTPS responses for duplicates.

Frame ancestors

frame-src controls what this site embeds, not who may embed it. To opt in to embedding restrictions, use Settings → Security or filter WpSecurity/FrameAncestors to an array such as ["'self'", 'https://partner.example'] or ["'none'"]. The default is empty for compatibility. The ACF repeater accepts exact HTTP(S) origin URLs, optionally with a port, and validates each row. The programmatic filter also accepts wildcard subdomains, 'self', and 'none'; invalid configurations are ignored. This directive is sent only when the plugin's CSP is generated. The plugin does not change X-Frame-Options: remove any conflicting SAMEORIGIN or DENY header at the server or other plugins if external embeds are authorized. Multiple CSP headers are all enforced, so another policy can still block an allowed embed. Configure and test redirects and cached responses at the edge.

REST API rate limits

Settings → Security provides optional GET and POST/PUT request limits and time windows. Blank fields keep the current default or existing PHP filter value. GET defaults to 600 requests per 300 seconds per route; POST/PUT defaults to 50 per 300 seconds. OPTIONS is checked by both. Users who can edit posts are exempt. A persistent object cache is required to count across requests, and upstream caching or rate limiting can change the effective behavior. Very low limits can block legitimate clients; test integrations after a change.

The existing WPSecurity/RateLimit/Api/GET/MaxRequests, WPSecurity/RateLimit/Api/GET/TimeWindow, WPSecurity/RateLimit/Api/POST/MaxRequests, and WPSecurity/RateLimit/Api/POST/TimeWindow filters remain available. A saved setting runs at priority 10; use a later filter priority to override it in code.

Trusted Types

Settings → Security → Trusted Types is disabled by default. Report-only emits an additional Content-Security-Policy-Report-Only header and does not block violations. Enable Collect violation reports to store reports in the built-in WordPress collector. Enforcement emits an additional CSP header with require-trusted-types-for 'script'. Browsers enforce all CSP headers together; this does not replace an existing policy. Other server or CDN policies, headers and cache hits may change the result and must be configured and tested at the edge. Browser support varies; unsupported browsers do not gain Trusted Types protection.

Optionally add allowed Trusted Types policy names one per row. An empty list does not restrict names. This plugin does not create a JavaScript Trusted Types policy or a permissive default policy: application code must create appropriate policies and safely convert values at protected DOM sinks. A permissive default policy can undermine enforcement. Start in report-only, inventory violations, then test frontend, login, Gutenberg, admin, Modularity and third-party integrations before opting in to enforcement. Existing installations remain disabled on upgrade.

The WpSecurity/TrustedTypes filter can supply an array with mode (report-only or enforce), optional policies (names), and optional reporting (boolean). Invalid configuration is ignored. The ACF setting runs at priority 10; a later filter can override it.

Staged CSP hardening

Settings → Security → Strict CSP rollout is disabled by default. On themes that invoke Website/HTML/output, report-only emits a candidate alongside the current policy; enforce replaces this plugin's generated policy with that candidate. An existing enforced CSP set by another PHP component is left in place. Strict CSP and its nonce option are off by default; existing CSP behavior continues until an administrator opts in. Report collection is a separate, optional setting.

The candidate removes 'unsafe-eval' and 'unsafe-inline' from script-src. Reviewed, stable inline scripts can be allowed with individual SHA-256 hashes in the repeater (enter sha256- and the base64 digest, without quotes). Hashes must cover the exact script bytes and be updated when the script changes. Inline event handlers cannot be approved with these hashes; migrate them to external scripts and event listeners. Replace eval and dynamic function construction. With Nonce-based strict CSP enabled, the candidate instead uses a fresh, cryptographically random nonce and 'strict-dynamic', with any approved hashes; it does not trust script hosts parsed from markup. WordPress-generated script tags and inline scripts receive the nonce through WordPress script attribute filters. Trusting those scripts also trusts scripts they load dynamically; audit WordPress plugins and any user-controlled data supplied to these APIs. Raw HTML script tags do not automatically receive a nonce. Move them to WordPress's script APIs or add a reviewed stable hash. Inline event handlers and eval still need migration. Styles may still use style-src 'unsafe-inline'. When nonce mode is off, the existing host-based candidate is retained.

Nonce mode defines DONOTCACHEPAGE and sends Cache-Control: private, no-store and no-cache headers for dynamically generated frontend responses. These are requests to caches, not proof that all caches obey them. Explicitly bypass page, reverse-proxy and CDN caches for these responses; test cache hits, misses and redirects through the real edge, and do not enforce nonce mode until headers and HTML are paired and nonces differ across requests. A previously cached response may bypass WordPress entirely. This implementation covers frontend pages whose theme invokes Website/HTML/output; it does not promise coverage on login, admin, REST, static, cached or proxy-served responses. On one local Municipio frontend, 17 of 21 script tags received a nonce; three of the other four were JSON-LD. Inventory and test the remaining script and real frontend, Gutenberg, admin, Modularity and third-party workflows in report-only before enforcement. The local site cannot establish production CDN/cache or integration compatibility.

Developers can supply WpSecurity/StrictCsp with mode (report-only or enforce), optional nonce_strict and reporting (booleans), and hashes (an array). Invalid configuration is ignored; a later filter can override the ACF settings. See the WordPress Interactivity API CSP guidance and CSP Level 3 strict CSP guidance.

Built-in CSP reports

Report collection is disabled by default and can be enabled separately for Trusted Types and strict CSP. Reports are sent to this site's built-in HTTPS WordPress REST endpoint and shown in Settings → CSP Reports; no reporting URL is needed. On HTTP installations no collector URL is emitted. Previously configured external reporting URLs are no longer used; explicitly enable collection to use the native collector. Report-only still logs violations in browser developer tools when collection is off.

Administrators can inspect and clear reports under Settings → CSP Reports. The collector keeps at most 100 recent entries, accepts at most 100 requests per minute per site, and rejects request bodies over 16 KiB. It stores only the directive, blocked origin or type, and receipt time: page URLs, paths, queries, script samples, IP addresses and user agents are not retained by the plugin. Reports older than seven days are hidden and are purged on the next report or daily WordPress cron run (cron may be delayed on inactive sites). The quota is global, so an abusive client can temporarily crowd out legitimate reports; web-server or edge rate limits are recommended for public deployments. Reports are untrusted and may be lost under concurrent updates, so this is a diagnostic sample, not an audit log. The web server and infrastructure may maintain their own request logs.