', '', 'Require all denied', '', '', 'Order Deny,Allow', 'Deny from all', '', '', ); } /** * The XML-RPC rule written by version 2.0 (Apache 2.2 only) */ public static function legacy_xmlrpc_lines() { return array('', 'Order Deny,Allow', 'Deny from all', ''); } /** * Whether an "XMLRPC Restriction" block was written by this plugin (any version). * The marker name is generic, so blocks written by people or other plugins are left alone. */ public static function is_own_xmlrpc_block($body) { $body = self::normalize($body); return $body === self::normalize(implode("\n", self::xmlrpc_lines())) || $body === self::normalize(implode("\n", self::legacy_xmlrpc_lines())); } public static function is_legacy_xmlrpc_block($body) { return self::normalize($body) === self::normalize(implode("\n", self::legacy_xmlrpc_lines())); } /** * Rules that deny direct execution of PHP files (Apache 2.4 syntax with a 2.2 fallback) */ public static function uploads_lines() { return array( '', '', 'Require all denied', '', '', 'Order Deny,Allow', 'Deny from all', '', '', ); } public static function write_block($file, $marker, $lines, $create = false, $reason = '') { return self::rewrite($file, function ($content) use ($marker, $lines) { $eol = (strpos($content, "\r\n") !== false) ? "\r\n" : "\n"; $block = '# BEGIN ' . $marker . $eol . implode($eol, $lines) . $eol . '# END ' . $marker . $eol; $pattern = AOWPCS_Htaccess::pattern($marker); if (preg_match($pattern, $content)) { return preg_replace_callback($pattern, function ($m) use ($block) { return (isset($m[1]) ? $m[1] : '') . $block; }, $content, 1); } if ($content !== '' && substr($content, -1) !== "\n") { $content .= $eol; } return $content . ($content !== '' ? $eol : '') . $block; }, $create, $reason !== '' ? $reason : sprintf('write %s', $marker)); } public static function remove_block($file, $marker, $reason = '') { if (!file_exists($file) || self::read_block($file, $marker) === null) { return true; } return self::rewrite($file, function ($content) use ($marker) { return AOWPCS_Htaccess::without_block($content, $marker); }, false, $reason !== '' ? $reason : sprintf('remove %s', $marker)); } /** * Content without a marker block (and without the blank separator line added when it was * appended), so writing then removing a block restores the original file exactly */ public static function without_block($content, $marker) { $quoted = preg_quote($marker, '/'); while (preg_match('/^[ \t]*# BEGIN ' . $quoted . '[ \t]*\R.*?^[ \t]*# END ' . $quoted . '[^\r\n]*(?:\R|\z)/ms', $content, $m, PREG_OFFSET_CAPTURE)) { $eol = (strpos($content, "\r\n") !== false) ? "\r\n" : "\n"; $before = substr($content, 0, $m[0][1]); $after = substr($content, $m[0][1] + strlen($m[0][0])); if (trim($after) === '') { // Block at the end: drop only the blank separator line write_block() added if (substr($before, -2 * strlen($eol)) === $eol . $eol) { $before = substr($before, 0, -strlen($eol)); } $content = $before; } elseif (preg_match('/\R\R$/', $before) && preg_match('/^\R/', $after)) { $content = $before . preg_replace('/^\R/', '', $after); } else { $content = $before . $after; } } return $content; } /** * Read, change and write a file while holding an exclusive lock */ private static function rewrite($file, $callback, $create, $reason) { if (!file_exists($file)) { if (!$create) { /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_missing', sprintf(__('The file %s does not exist.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } if (!is_writable(dirname($file))) { /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_dir', sprintf(__('The directory of %s is not writable by WordPress.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } if (@file_put_contents($file, '', LOCK_EX) === false) { /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_create', sprintf(__('The file %s could not be created.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } } if (!is_readable($file) || !is_writable($file)) { /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_not_writable', sprintf(__('The file %s is not writable by WordPress. Change it manually (instructions are shown below) or make it writable for the web server user.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } $fp = @fopen($file, 'r+'); if (!$fp) { /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_open', sprintf(__('The file %s could not be opened.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } if (!flock($fp, LOCK_EX)) { fclose($fp); /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_lock', sprintf(__('The file %s could not be locked for writing.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } $content = stream_get_contents($fp); if ($content === false) { flock($fp, LOCK_UN); fclose($fp); /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_read', sprintf(__('The file %s could not be read, so it was left unchanged.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } $new_content = call_user_func($callback, $content); if (!is_string($new_content) || $new_content === $content) { flock($fp, LOCK_UN); fclose($fp); return true; } self::backup($file, $content, $reason); ftruncate($fp, 0); rewind($fp); $bytes = fwrite($fp, $new_content); fflush($fp); if ($bytes !== strlen($new_content)) { ftruncate($fp, 0); rewind($fp); fwrite($fp, $content); fflush($fp); flock($fp, LOCK_UN); fclose($fp); /* translators: %s: path */ return new WP_Error('aowpcs_htaccess_write', sprintf(__('Writing to %s failed; the original content was restored.', 'all-in-one-wp-content-security'), AOWPCS_Plugin::relative_path($file))); } flock($fp, LOCK_UN); fclose($fp); return true; } /** * Store the previous content of a file (newest first, limited count and size) */ public static function backup($file, $content, $reason) { $backups = get_site_option(self::BACKUP_OPTION, array()); if (!is_array($backups)) { $backups = array(); } $id = AOWPCS_Plugin::token(6); array_unshift($backups, array( 'id' => $id, 'time' => AOWPCS_Plugin::now(), 'file' => wp_normalize_path($file), 'reason' => substr((string) $reason, 0, 200), 'user' => get_current_user_id(), 'size' => strlen($content), 'content' => strlen($content) > 262144 ? '' : $content, )); update_site_option(self::BACKUP_OPTION, array_slice($backups, 0, self::MAX_BACKUPS)); return $id; } public static function backups() { $backups = get_site_option(self::BACKUP_OPTION, array()); return is_array($backups) ? $backups : array(); } public static function latest_backup_id($file) { foreach (self::backups() as $backup) { if ($backup['file'] === wp_normalize_path($file)) { return $backup['id']; } } return ''; } /** * Put a backup back in place (the current content is itself backed up first) */ public static function restore($backup_id) { foreach (self::backups() as $backup) { if ($backup['id'] !== $backup_id) { continue; } if ($backup['content'] === '' && $backup['size'] > 0) { return new WP_Error('aowpcs_backup_too_large', __('This backup was too large to store and cannot be restored automatically.', 'all-in-one-wp-content-security')); } $content = $backup['content']; return self::rewrite($backup['file'], function () use ($content) { return $content; }, true, sprintf('restore backup %s', $backup_id)); } return new WP_Error('aowpcs_backup_missing', __('The backup no longer exists.', 'all-in-one-wp-content-security')); } /** * Check that the site and the login page still respond without a server error */ public static function validate_site() { foreach (array(home_url('/'), wp_login_url()) as $url) { $response = AOWPCS_Loopback::request($url, array('cache' => false)); if ($response['error'] !== '') { /* translators: %s: response error */ return new WP_Error('aowpcs_validation_unavailable', sprintf(__('The change could not be verified because the site could not request itself (%s).', 'all-in-one-wp-content-security'), $response['error'])); } if ($response['status'] >= 500) { /* translators: 1: url, 2: response status */ return new WP_Error('aowpcs_validation_failed', sprintf(__('%1$s returned HTTP %2$d after the change.', 'all-in-one-wp-content-security'), $url, $response['status'])); } } return true; } /** * Write a block, then roll back automatically when the site returns a server error. * Returns true, or WP_Error (with data 'rolled_back' => bool). */ public static function write_validated($file, $marker, $lines, $create = false, $reason = '') { $before = file_exists($file) ? file_get_contents($file) : null; $result = self::write_block($file, $marker, $lines, $create, $reason); if (is_wp_error($result)) { return $result; } return self::validate_or_revert($file, $before, true); } /** * Restore a backup, then put the previous content back when the site returns a server error. * Returns true, WP_Error 'aowpcs_rolled_back', or the validation warning when the site could * not be checked. */ public static function restore_validated($backup_id) { $file = ''; foreach (self::backups() as $backup) { if ($backup['id'] === $backup_id) { $file = $backup['file']; break; } } if ($file === '') { return new WP_Error('aowpcs_backup_missing', __('The backup no longer exists.', 'all-in-one-wp-content-security')); } $before = file_exists($file) ? file_get_contents($file) : null; $result = self::restore($backup_id); if (is_wp_error($result)) { return $result; } return self::validate_or_revert($file, $before, false); } /** * After a change: request the site and revert the file to $before on a server error */ private static function validate_or_revert($file, $before, $ignore_unavailable) { $check = self::validate_site(); if (is_wp_error($check) && $check->get_error_code() === 'aowpcs_validation_failed') { if ($before === null || $before === false) { @unlink($file); } else { self::rewrite($file, function () use ($before) { return $before; }, false, 'automatic rollback'); } return new WP_Error('aowpcs_rolled_back', $check->get_error_message() . ' ' . __('The change was rolled back automatically.', 'all-in-one-wp-content-security'), array('rolled_back' => true)); } return ($ignore_unavailable && is_wp_error($check)) ? true : $check; } /** * Lines of a block body as returned by read_block() */ public static function body_lines($body) { return preg_split('/\R/', rtrim((string) $body, "\r\n")); } /** * Blocks this plugin may have written: array of array(file, marker) */ private static function own_blocks() { $blocks = array(); foreach (self::root_files() as $file) { $blocks[] = array($file, self::LEGACY_HEADERS); $blocks[] = array($file, self::XMLRPC); } $blocks[] = array(self::root_file(), self::HEADERS); $blocks[] = array(self::uploads_file(), self::UPLOADS); return $blocks; } public static function remove_blocks_for_deactivation() { $removed = array(); foreach (self::own_blocks() as $block) { list($file, $marker) = $block; $body = self::read_block($file, $marker); if ($body === null || ($marker === self::XMLRPC && !self::is_own_xmlrpc_block($body))) { continue; } if (!is_wp_error(self::remove_block($file, $marker, 'plugin deactivated'))) { $removed[] = array('file' => $file, 'marker' => $marker, 'body' => $body); } } AOWPCS_Settings::set_state('deactivated_blocks', $removed ? $removed : null); } public static function restore_deactivated_blocks() { $blocks = AOWPCS_Settings::state('deactivated_blocks'); if (empty($blocks) || !is_array($blocks)) { return; } foreach ($blocks as $block) { if (self::read_block($block['file'], $block['marker']) === null) { $lines = preg_split('/\R/', rtrim($block['body'])); self::write_block($block['file'], $block['marker'], $lines, $block['marker'] === self::UPLOADS, 'plugin activated'); } } AOWPCS_Settings::set_state('deactivated_blocks', null); } }