Block Malicious Request Patterns
A tiny firewall that returns 403 Forbidden for URLs containing typical attack strings, such as directory traversal, SQL injection and PHP stream wrappers.
Opens WPIDE on
Code
// Patterns checked against the decoded URL (path and query string).
$wpide_firewall_patterns = array(
'#\.\./#',
'#(?:/|%2f)etc/passwd#i',
'#(?:php|phar|zip|data|expect)://#i',
'#union(?:\s|\+|/\*.*\*/)+(?:all(?:\s|\+)+)?select#i',
'#\b(?:base64_decode|eval|assert|shell_exec|passthru|system)\s*\(#i',
'#<\s*script#i',
'#(?:GLOBALS|_REQUEST|_SERVER)\s*\[#',
'#wp-config\.php#i',
);
add_action( 'init', function () use ( $wpide_firewall_patterns ) {
if ( empty( $_SERVER['REQUEST_URI'] ) || ( is_user_logged_in() && current_user_can( 'unfiltered_html' ) ) ) {
return;
}
$uri = rawurldecode( rawurldecode( (string) wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
foreach ( $wpide_firewall_patterns as $pattern ) {
if ( preg_match( $pattern, $uri ) ) {
status_header( 403 );
nocache_headers();
exit( 'Forbidden' );
}
}
}, 0 );
Notes
Form submissions are not inspected, so editors keep working, and it complements rather than replaces a real web application firewall.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.