', 'Require all denied', '', '', 'Order allow,deny', 'Deny from all', '', ); } private static function rewrite_base() { $path = (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ); return '' === $path ? '/' : $path; } /** * Lines for the root .htaccess, from the enabled rules. */ public static function root_lines() { $on = array( 'Softvolt_Ai_Bodyguard_Settings', 'hardening_enabled' ); $lines = array(); if ( $on( 'disable_directory_indexes' ) ) { $lines[] = '# Disable directory browsing'; $lines[] = 'Options -Indexes'; } if ( $on( 'protect_sensitive_files' ) ) { $lines[] = '# Protect sensitive files'; $lines[] = ''; $lines = array_merge( $lines, self::deny_block() ); $lines[] = ''; $lines[] = ''; $lines = array_merge( $lines, self::deny_block() ); $lines[] = ''; } if ( $on( 'block_xmlrpc_htaccess' ) ) { $lines[] = '# Block XML-RPC'; $lines[] = ''; $lines = array_merge( $lines, self::deny_block() ); $lines[] = ''; } if ( $on( 'block_install_scripts' ) ) { $lines[] = '# Block the installer scripts'; $lines[] = ''; $lines = array_merge( $lines, self::deny_block() ); $lines[] = ''; } $rewrite = array(); if ( $on( 'block_php_includes' ) ) { $rewrite[] = '# Block direct access to PHP in wp-includes'; $rewrite[] = 'RewriteRule ^wp-admin/includes/ - [F,L]'; $rewrite[] = 'RewriteRule !^wp-includes/ - [S=3]'; $rewrite[] = 'RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]'; $rewrite[] = 'RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]'; $rewrite[] = 'RewriteRule ^wp-includes/theme-compat/ - [F,L]'; } if ( $on( 'block_bad_query_strings' ) ) { $rewrite[] = '# Block suspicious query strings'; $rewrite[] = 'RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]'; $rewrite[] = 'RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]'; $rewrite[] = 'RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) [OR]'; $rewrite[] = 'RewriteCond %{QUERY_STRING} (\.\./|\.\.%2f|%2e%2e%2f) [NC,OR]'; $rewrite[] = 'RewriteCond %{QUERY_STRING} base64_(en|de)code[^(]*\([^)]*\) [NC,OR]'; $rewrite[] = 'RewriteCond %{QUERY_STRING} (etc/passwd|proc/self/environ|php://input|php://filter) [NC]'; $rewrite[] = 'RewriteRule .* - [F,L]'; } if ( $on( 'block_author_scan_htaccess' ) ) { $rewrite[] = '# Block author scanning'; $rewrite[] = 'RewriteCond %{REQUEST_URI} !^' . preg_quote( rtrim( self::rewrite_base(), '/' ), '/' ) . '/wp-admin'; $rewrite[] = 'RewriteCond %{QUERY_STRING} ^author=\d+ [NC]'; $rewrite[] = 'RewriteRule ^ ' . self::rewrite_base() . '? [L,R=301]'; } if ( $rewrite ) { $lines[] = ''; $lines[] = 'RewriteEngine On'; $lines[] = 'RewriteBase ' . self::rewrite_base(); $lines = array_merge( $lines, $rewrite ); $lines[] = ''; } if ( $on( 'htaccess_basic' ) ) { $lines = array_merge( $lines, self::basic_lines() ); } if ( $on( 'htaccess_6g' ) ) { $lines = array_merge( $lines, self::six_g_lines() ); } if ( $on( 'hotlink_protection' ) ) { $lines = array_merge( $lines, self::hotlink_lines() ); } return $lines; } /** * Basic server firewall: no server signature, no TRACE/TRACK, a request body limit above the upload limit. */ private static function basic_lines() { $limit = max( 64 * MB_IN_BYTES, (int) wp_max_upload_size() + 8 * MB_IN_BYTES ); return array( '# Basic server firewall', 'ServerSignature Off', 'LimitRequestBody ' . $limit, '', 'RewriteEngine On', 'RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK) [NC]', 'RewriteRule .* - [F]', '', ); } /** * The 6G firewall (Jeff Starr, perishablepress.com), without the rules that most often block real URLs. */ private static function six_g_lines() { return array( '# 6G firewall: query strings', '', 'RewriteEngine On', 'RewriteCond %{QUERY_STRING} (eval\() [NC,OR]', 'RewriteCond %{QUERY_STRING} (127\.0\.0\.1) [NC,OR]', 'RewriteCond %{QUERY_STRING} ([a-z0-9]{2000,}) [NC,OR]', 'RewriteCond %{QUERY_STRING} (javascript:)(.*)(;) [NC,OR]', 'RewriteCond %{QUERY_STRING} (base64_encode)(.*)(\() [NC,OR]', 'RewriteCond %{QUERY_STRING} (GLOBALS|REQUEST)(=|\[|%) [NC,OR]', 'RewriteCond %{QUERY_STRING} (<|%3C)(.*)script(.*)(>|%3) [NC,OR]', 'RewriteCond %{QUERY_STRING} (\\\\|\.\.\.|\.\./|~|`|<|>|\|) [NC,OR]', 'RewriteCond %{QUERY_STRING} (boot\.ini|etc/passwd|self/environ) [NC,OR]', 'RewriteCond %{QUERY_STRING} (thumbs?(_editor|open)?|tim(thumb)?)\.php [NC,OR]', 'RewriteCond %{QUERY_STRING} (\'|\")(.*)(drop|insert|md5|select|union) [NC]', 'RewriteRule .* - [F]', '', '# 6G firewall: request methods', '', 'RewriteCond %{REQUEST_METHOD} ^(connect|debug|move|trace|track) [NC]', 'RewriteRule .* - [F]', '', '# 6G firewall: request strings', '', 'RedirectMatch 403 (?i)(,,,)', 'RedirectMatch 403 (?i)(-------)', 'RedirectMatch 403 (?i)([a-z0-9]{2000,})', 'RedirectMatch 403 (?i)(=?\\\\(\'|%27)/?)(\.)', 'RedirectMatch 403 (?i)(\{0\}|\(/\(|\.\.\.|\+\+\+|\\\\\"\\\\\")', 'RedirectMatch 403 (?i)/(=|\$&|_mm|cgi-|muieblack)', 'RedirectMatch 403 (?i)(&pws=0|_vti_|\(null\)|\{\$itemURL\}|echo(.*)kae|etc/passwd|eval\(|self/environ)', 'RedirectMatch 403 (?i)\.(aspx?|bash|bak?|cfg|cgi|dll|exe|git|hg|ini|jsp|log|mdb|out|sql|svn|swp|tar|rar|rdf)$', 'RedirectMatch 403 (?i)/((wp-)?config|mobiquo|phpinfo|shell|sqlpatch|thumb|thumb_editor|thumbopen|timthumb|webshell)\.php', '', '# 6G firewall: user agents and referrers', '', 'SetEnvIfNoCase User-Agent ([a-z0-9]{2000,}) svabg_bad', 'SetEnvIfNoCase User-Agent (binlar|casper|checkpriv|choppy|clshttp|cmsworld|diavol|extract|feedfinder|flicky|g00g1e|harvest|heritrix|httrack|kmccrew|loader|miner|nikto|nutch|planetwork|postrank|purebot|pycurl|seekerspider|siclab|skygrid|sqlmap|sucker|turnit|vikspider|winhttp|xxxyy|youda|zmeu|zune) svabg_bad', 'SetEnvIfNoCase Referer ([a-z0-9]{2000,}) svabg_bad', 'SetEnvIfNoCase Referer (semalt\.com|todaperfeita) svabg_bad', '', '', 'Require all granted', 'Require not env svabg_bad', '', '', '', 'Order Allow,Deny', 'Allow from all', 'Deny from env=svabg_bad', '', '', ); } /** * Images may only be embedded by this site, search engines and social networks. */ private static function hotlink_lines() { $host = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $host = preg_replace( '/^www\./i', '', $host ); return array( '# Stop image hotlinking', '', 'RewriteEngine On', 'RewriteCond %{HTTP_REFERER} !^$', 'RewriteCond %{HTTP_REFERER} !^https?://([a-z0-9-]+\.)*' . preg_quote( $host, '/' ) . '(/|:|$) [NC]', 'RewriteCond %{HTTP_REFERER} !(google|bing|yahoo|duckduckgo|yandex|baidu|facebook|twitter|t\.co|x\.com|linkedin|pinterest|instagram|whatsapp|telegram|slack)\. [NC]', 'RewriteRule \.(jpe?g|png|gif|webp|avif|bmp|svg)$ - [F,NC]', '', ); } public static function uploads_lines() { if ( ! Softvolt_Ai_Bodyguard_Settings::hardening_enabled( 'block_php_uploads' ) ) { return array(); } $lines = array( '# No PHP execution inside uploads' ); $lines[] = ''; $lines = array_merge( $lines, self::deny_block() ); $lines[] = ''; return $lines; } /** * Write both files from the enabled rules, check the site still answers, * roll back on a 500. * * @since 1.0.0 * @return true|WP_Error */ public static function sync() { if ( ! function_exists( 'insert_with_markers' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } $root_lines = self::root_lines(); $uploads_lines = self::uploads_lines(); $results = array(); foreach ( array( self::root_file() => $root_lines, self::uploads_file() => $uploads_lines ) as $file => $lines ) { $existing = file_exists( $file ) ? (string) file_get_contents( $file ) : ''; $current = self::current_lines( $existing ); if ( $current === $lines ) { continue; } if ( ! $lines && '' === $existing ) { continue; } if ( file_exists( $file ) && ! wp_is_writable( $file ) ) { $results[] = new WP_Error( 'svabg_htaccess_ro', sprintf( /* translators: %s: path path */ __( '%s is not writable, so the .htaccess rules were not applied. Make it writable or add the rules by hand.', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::rel_path( $file ) ) ); continue; } if ( ! file_exists( $file ) && ! wp_is_writable( dirname( $file ) ) ) { $results[] = new WP_Error( 'svabg_htaccess_ro', sprintf( /* translators: %s: path path */ __( '%s cannot be created (folder not writable).', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::rel_path( $file ) ) ); continue; } $written = insert_with_markers( $file, self::MARKER, $lines ); if ( ! $written ) { $results[] = new WP_Error( 'svabg_htaccess_write', sprintf( /* translators: %s: path path */ __( '%s could not be written.', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::rel_path( $file ) ) ); continue; } // A broken rule shows as a 500 straight away: undo it. if ( $lines && self::site_broken() ) { insert_with_markers( $file, self::MARKER, $current ); $results[] = new WP_Error( 'svabg_htaccess_500', sprintf( /* translators: %s: path path */ __( 'The new rules in %s made the server answer 500, so they were removed again. Your host may not allow "Options" or rewrite rules in .htaccess; switch those rules off.', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::rel_path( $file ) ) ); Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'hardening', __( '.htaccess rules rolled back after the server answered 500.', 'ai-guardwall' ) ); continue; } Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'hardening', sprintf( /* translators: %s: path path */ __( '.htaccess rules updated in %s.', 'ai-guardwall' ), Softvolt_Ai_Bodyguard_Helpers::rel_path( $file ) ) ); } if ( $results ) { $error = new WP_Error(); foreach ( $results as $r ) { $error->add( $r->get_error_code(), $r->get_error_message() ); } set_transient( 'svabg_htaccess_error', $error->get_error_messages(), HOUR_IN_SECONDS ); return $error; } delete_transient( 'svabg_htaccess_error' ); return true; } public static function remove_all() { if ( ! function_exists( 'insert_with_markers' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } foreach ( array( self::root_file(), self::uploads_file() ) as $file ) { if ( file_exists( $file ) && false !== strpos( (string) file_get_contents( $file ), '# BEGIN ' . self::MARKER ) ) { insert_with_markers( $file, self::MARKER, array() ); } } } private static function current_lines( $content ) { if ( ! preg_match( '/# BEGIN ' . preg_quote( self::MARKER, '/' ) . '\r?\n(.*?)# END ' . preg_quote( self::MARKER, '/' ) . '/s', $content, $m ) ) { return array(); } $lines = preg_split( '/\r?\n/', trim( $m[1] ) ); $out = array(); foreach ( $lines as $line ) { if ( '' !== trim( $line ) && ! preg_match( '/^# The directives \(lines\)/', $line ) && ! preg_match( '/^# Any changes to the directives/', $line ) && ! preg_match( '/^# dynamically generated/', $line ) ) { $out[] = $line; } } return $out; } private static function site_broken() { $res = wp_remote_get( home_url( '/?svabg_check=' . time() ), array( 'timeout' => 10, 'redirection' => 2, 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), 'user-agent' => Softvolt_Ai_Bodyguard_Providers::user_agent() . ' (self-check)', ) ); if ( is_wp_error( $res ) ) { return false; // Unreachable loopback: cannot judge, keep the rules. } return 500 === (int) wp_remote_retrieve_response_code( $res ); } public static function status() { $root = file_exists( self::root_file() ) ? (string) file_get_contents( self::root_file() ) : ''; $up = file_exists( self::uploads_file() ) ? (string) file_get_contents( self::uploads_file() ) : ''; return array( 'apache' => self::is_apache(), 'root_managed' => false !== strpos( $root, '# BEGIN ' . self::MARKER ), 'root_writable' => file_exists( self::root_file() ) ? wp_is_writable( self::root_file() ) : wp_is_writable( self::home_dir() ), 'uploads_managed' => false !== strpos( $up, '# BEGIN ' . self::MARKER ), 'error' => get_transient( 'svabg_htaccess_error' ), ); } }