value. $context: front or admin (the dashboard and * the login page never receive the CSP or Permissions-Policy, so they always stay reachable) */ public static function headers($context = 'front', $settings = null) { $s = $settings ? $settings : AOWPCS_Settings::all(); $headers = array(); if (!empty($s['header_nosniff'])) { $headers['X-Content-Type-Options'] = 'nosniff'; } if ($s['header_frame'] === 'sameorigin') { $headers['X-Frame-Options'] = 'SAMEORIGIN'; } if ($s['header_referrer'] !== 'off') { $headers['Referrer-Policy'] = $s['header_referrer']; } $hsts = array('test' => 'max-age=300', 'year' => 'max-age=31536000', 'year_subdomains' => 'max-age=31536000; includeSubDomains'); if (isset($hsts[$s['header_hsts']])) { $headers['Strict-Transport-Security'] = $hsts[$s['header_hsts']]; } if ($context === 'front') { if (!empty($s['header_permissions']) && self::valid_permissions_policy($s['header_permissions_value'])) { $headers['Permissions-Policy'] = $s['header_permissions_value']; } $policy = self::clean_policy($s['header_csp_policy']); if ($policy !== '' && $s['header_csp_mode'] === 'enforce') { $headers['Content-Security-Policy'] = $policy; } elseif ($policy !== '' && $s['header_csp_mode'] === 'report-only') { $headers['Content-Security-Policy-Report-Only'] = $policy; } } return $headers; } public static function clean_policy($policy) { $policy = trim(preg_replace('/[\r\n]+/', ' ', (string) $policy)); return preg_match('/^[a-zA-Z0-9\-\s\'";:\/\.\*\+=_\(\)\[\]%@,#]*$/', $policy) ? $policy : ''; } public static function valid_permissions_policy($value) { return AOWPCS_Check_Server_Headers::header_problem('permissions-policy', (string) $value) === ''; } public static function send_front() { $headers = self::headers('front'); if (AOWPCS_Settings::get('headers_delivery') === 'htaccess') { // The basic headers come from .htaccess; only the page policies are added here $headers = array_diff_key($headers, self::headers('admin')); } self::send($headers); } public static function send_admin() { self::send(self::headers('admin')); } private static function send($headers) { if (headers_sent()) { return; } foreach ($headers as $name => $value) { if ($name === 'Strict-Transport-Security' && !is_ssl()) { continue; } header($name . ': ' . $value); } } /** * Lines of the .htaccess block for the current settings. Only headers that are safe for every * response (including the dashboard and static files); page policies stay in PHP. */ public static function htaccess_lines($settings = null) { $lines = array(''); foreach (self::headers('admin', $settings) as $name => $value) { $value = str_replace('"', '\"', $value); if ($name === 'Strict-Transport-Security') { $lines[] = 'Header always set Strict-Transport-Security "' . $value . '" env=HTTPS'; } else { $lines[] = 'Header always set ' . $name . ' "' . $value . '"'; } } $lines[] = ''; return $lines; } /** * Bring .htaccess in line with the settings (called after the settings are saved). * Returns true or WP_Error. */ public static function sync_htaccess() { $file = AOWPCS_Htaccess::root_file(); $wanted = AOWPCS_Settings::get('headers_enabled') && AOWPCS_Settings::get('headers_delivery') === 'htaccess'; if (!$wanted) { $result = AOWPCS_Htaccess::remove_block($file, AOWPCS_Htaccess::HEADERS, 'security headers moved to PHP or disabled'); } elseif (!AOWPCS_Environment::uses_htaccess()) { return new WP_Error('aowpcs_no_htaccess', __('This server does not read .htaccess files; choose PHP delivery instead.', 'all-in-one-wp-content-security')); } else { $result = AOWPCS_Htaccess::write_validated($file, AOWPCS_Htaccess::HEADERS, self::htaccess_lines(), false, 'security headers'); } if (!is_wp_error($result)) { AOWPCS_Check_Fs_Walk::note_own_write($file); } return $result; } /** * Nginx configuration equivalent, for administrators to copy */ public static function nginx_snippet() { $lines = array(); foreach (self::headers('front') as $name => $value) { $lines[] = 'add_header ' . $name . ' "' . str_replace('"', '\"', $value) . '" always;'; } return implode("\n", $lines); } } /** * Heuristic compatibility check for a Content-Security-Policy: lists the external resources the * home page loads and which of them the policy would block. Resources added by JavaScript at * runtime cannot be seen, so the result is a guide, not a guarantee. */ class AOWPCS_Csp_Analyzer { public static function parse_policy($policy) { $directives = array(); foreach (explode(';', (string) $policy) as $part) { $tokens = preg_split('/\s+/', trim($part)); if (empty($tokens[0])) { continue; } $directives[strtolower(array_shift($tokens))] = $tokens; } return $directives; } /** * Sources that apply to a fetch directive (with default-src fallback), or null when unrestricted */ private static function sources($directives, $directive) { if (isset($directives[$directive])) { return $directives[$directive]; } $fallbacks = array('script-src-elem' => 'script-src', 'style-src-elem' => 'style-src', 'frame-src' => 'child-src'); if (isset($fallbacks[$directive]) && isset($directives[$fallbacks[$directive]])) { return $directives[$fallbacks[$directive]]; } return isset($directives['default-src']) ? $directives['default-src'] : null; } private static function allowed($url, $sources, $site_origin) { if ($sources === null) { return true; } $lower = array_map('strtolower', $sources); if (in_array("'none'", $lower, true)) { return false; } $scheme = strtolower((string) wp_parse_url($url, PHP_URL_SCHEME)); $host = strtolower((string) wp_parse_url($url, PHP_URL_HOST)); $origin = $scheme . '://' . $host; if ($origin === $site_origin && in_array("'self'", $lower, true)) { return true; } foreach ($lower as $source) { if ($source === '*' && !in_array($scheme, array('data', 'blob'), true)) { return true; } if ($source === $scheme . ':') { return true; } $source_host = preg_replace('#^[a-z]+://#', '', rtrim($source, '/')); $source_host = preg_replace('#/.*$#', '', $source_host); if ($source_host === $host) { return true; } if (strpos($source_host, '*.') === 0 && substr($host, -strlen(substr($source_host, 1))) === substr($source_host, 1)) { return true; } } return false; } /** * Analyse the home page against a policy. Returns array(blocked => list, inline => counts, checked => URL) */ public static function analyze($policy) { $response = AOWPCS_Loopback::request(home_url('/'), array('cache' => false, 'redirects' => 3)); if ($response['error'] !== '') { return new WP_Error('aowpcs_csp', $response['error']); } $html = $response['body']; $directives = self::parse_policy($policy); $site = strtolower(wp_parse_url(home_url(), PHP_URL_SCHEME) . '://' . wp_parse_url(home_url(), PHP_URL_HOST)); $resources = array(); $patterns = array( 'script-src' => '/]+src=["\']([^"\']+)["\']/i', 'style-src' => '/]+rel=["\'](?:stylesheet|preload)["\'][^>]+href=["\']([^"\']+)["\']|]+href=["\']([^"\']+)["\'][^>]+rel=["\']stylesheet["\']/i', 'img-src' => '/]+src=["\']([^"\']+)["\']/i', 'frame-src' => '/]+src=["\']([^"\']+)["\']/i', 'media-src' => '/<(?:video|audio|source)[^>]+src=["\']([^"\']+)["\']/i', 'font-src' => '/url\(["\']?([^"\')]+\.(?:woff2?|ttf|otf|eot)[^"\')]*)["\']?\)/i', ); foreach ($patterns as $directive => $pattern) { if (!preg_match_all($pattern, $html, $m, PREG_SET_ORDER)) { continue; } foreach ($m as $match) { $url = html_entity_decode(isset($match[2]) && $match[2] !== '' ? $match[2] : $match[1]); if (strpos($url, '//') === 0) { $url = 'https:' . $url; } elseif (!preg_match('#^[a-z]+:#i', $url)) { $url = home_url($url); } $scheme = strtolower((string) wp_parse_url($url, PHP_URL_SCHEME)); $host = $scheme === 'data' ? 'data:' : strtolower((string) wp_parse_url($url, PHP_URL_HOST)); $key = $directive . '|' . $host; if (!isset($resources[$key])) { $resources[$key] = array('directive' => $directive, 'origin' => $scheme === 'data' ? 'data:' : $scheme . '://' . $host, 'example' => substr($url, 0, 200), 'allowed' => self::allowed($url, self::sources($directives, $directive), $site)); } } } $inline_scripts = preg_match_all('/]*\bsrc=)[^>]*>\s*\S/i', $html); $inline_handlers = preg_match_all('/\son[a-z]+\s*=\s*["\']/i', $html); $inline_styles = preg_match_all('/\sstyle\s*=\s*["\']/i', $html) + preg_match_all('/]*>/i', $html); $script_sources = self::sources($directives, 'script-src'); $style_sources = self::sources($directives, 'style-src'); $inline_script_ok = $script_sources === null || in_array("'unsafe-inline'", array_map('strtolower', $script_sources), true); $inline_style_ok = $style_sources === null || in_array("'unsafe-inline'", array_map('strtolower', $style_sources), true); $blocked = array_values(array_filter($resources, function ($r) { return !$r['allowed']; })); return array( 'checked' => home_url('/'), 'resources' => array_values($resources), 'blocked' => $blocked, 'inline' => array( 'scripts' => (int) $inline_scripts, 'handlers' => (int) $inline_handlers, 'styles' => (int) $inline_styles, 'scripts_blocked' => !$inline_script_ok && ($inline_scripts + $inline_handlers) > 0, 'styles_blocked' => !$inline_style_ok && $inline_styles > 0, ), ); } }