3 * Handle sending Content-Security-Policy headers
5 * @see https://www.w3.org/TR/CSP2/
7 * Copyright © 2015–2018 Brian Wolff
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 class ContentSecurityPolicy
{
28 const REPORT_ONLY_MODE
= 1;
30 /** Used for meta tag. Does not include report urls or nonce sources */
31 const FULL_MODE_RESTRICTED
= 3;
33 /** @var string The nonce to use for inline scripts (from OutputPage) */
35 /** @var Config The site configuration object */
37 /** @var WebResponse */
41 * @param string $nonce
42 * @param WebResponse $response
43 * @param Config $mwConfig
45 public function __construct( $nonce, WebResponse
$response, Config
$mwConfig ) {
46 $this->nonce
= $nonce;
47 $this->response
= $response;
48 $this->mwConfig
= $mwConfig;
52 * Send a single CSP header based on a given policy config.
54 * @note Most callers will probably want ContentSecurityPolicy::sendHeaders() instead.
55 * @param array $csp ContentSecurityPolicy configuration
56 * @param int $reportOnly self::*_MODE constant
58 public function sendCSPHeader( $csp, $reportOnly ) {
59 $policy = $this->makeCSPDirectives( $csp, $reportOnly );
60 $headerName = $this->getHeaderName( $reportOnly );
62 $this->response
->header(
63 "$headerName: $policy"
69 * Return the meta header to use for after load restricted mode
71 * This should restrict browsers that don't support nonce-sources.
73 * https://blogs.dropbox.com/tech/2015/09/unsafe-inline-and-nonce-deployment/
75 * @param array $csp CSP configuration
76 * @return string Content for meta tag
78 public function getMetaHeader( $csp ) {
79 return $this->makeCSPDirectives( $csp, self
::FULL_MODE_RESTRICTED
);
83 * Send CSP headers based on wiki config
85 * Main method that callers are expected to use
86 * @param IContextSource $context A context object, the associated OutputPage
87 * object must be the one that the page in question was generated with.
89 public static function sendHeaders( IContextSource
$context ) {
90 $out = $context->getOutput();
91 $csp = new ContentSecurityPolicy(
93 $context->getRequest()->response(),
97 $cspConfig = $context->getConfig()->get( 'CSPHeader' );
98 $cspConfigReportOnly = $context->getConfig()->get( 'CSPReportOnlyHeader' );
100 $csp->sendCSPHeader( $cspConfig, self
::FULL_MODE
);
101 $csp->sendCSPHeader( $cspConfigReportOnly, self
::REPORT_ONLY_MODE
);
103 // Include <meta> header which increases security level after initial load.
104 // This helps mitigate attacks on browsers not supporting CSP2. It also
105 // helps mitigate attacks due to the shared nonce that non-logged in users
106 // get due to varnish cache.
107 // Unclear if this is the best place to insert the meta tag, or if
108 // it should be in a RL module. I figure its best to do this as early
110 // FIXME: Needs testing to see if this actually works properly
111 $metaHeader = $csp->getMetaHeader( $cspConfig );
113 $context->getOutput()->addScript(
114 ResourceLoader
::makeInlineScript(
115 $csp->makeMetaInsertScript(
125 * Makes javascript to insert a meta CSP header after page load
127 * @see https://blogs.dropbox.com/tech/2015/09/unsafe-inline-and-nonce-deployment/
128 * @param string $metaContents content of meta tag
129 * @return string JS for including in page
131 private function makeMetaInsertScript( $metaContents ) {
132 return "$('\\x3Cmeta http-equiv=\"Content-Security-Policy\"\\x3E')" .
134 Xml
::encodeJsVar( $metaContents ) .
135 ').prependTo($("head"))';
139 * Get the name of the HTTP header to use.
141 * @param int $reportOnly Either self::REPORT_ONLY_MODE or self::FULL_MODE
142 * @return string Name of http header
143 * @throws UnexpectedValueException if you feed it self::FULL_MODE_RESTRICTED.
145 private function getHeaderName( $reportOnly ) {
146 if ( $reportOnly === self
::REPORT_ONLY_MODE
) {
147 return 'Content-Security-Policy-Report-Only';
148 } elseif ( $reportOnly === self
::FULL_MODE
) {
149 return 'Content-Security-Policy';
151 throw new UnexpectedValueException( $reportOnly );
155 * Determine what CSP policies to set for this page
157 * @param array|bool $config Policy configuration (Either $wgCSPHeader or $wgCSPReportOnlyHeader)
158 * @param int $mode self::REPORT_ONLY_MODE, self::FULL_MODE or Self::FULL_MODE_RESTRICTED
159 * @return string Policy directives, or empty string for no policy.
161 private function makeCSPDirectives( $policyConfig, $mode ) {
162 if ( $policyConfig === false ) {
166 if ( $policyConfig === true ) {
170 $mwConfig = $this->mwConfig
;
172 $additionalSelfUrls = $this->getAdditionalSelfUrls();
173 $additionalSelfUrlsScript = $this->getAdditionalSelfUrlsScript();
174 $nonceSrc = "'nonce-" . $this->nonce
. "'";
176 // If no default-src is sent at all, it
177 // seems browsers (or at least some), interpret
178 // that as allow anything, but the spec seems
179 // to imply that data: and blob: should be
181 $defaultSrc = [ '*', 'data:', 'blob:' ];
185 $scriptSrc = [ "'unsafe-eval'", "'self'" ];
186 if ( $mode !== self
::FULL_MODE_RESTRICTED
) {
187 $scriptSrc[] = $nonceSrc;
189 $scriptSrc = array_merge( $scriptSrc, $additionalSelfUrlsScript );
190 if ( isset( $policyConfig['script-src'] )
191 && is_array( $policyConfig['script-src'] )
193 foreach ( $policyConfig['script-src'] as $src ) {
194 $scriptSrc[] = $this->escapeUrlForCSP( $src );
197 // Note: default on if unspecified.
198 if ( ( !isset( $policyConfig['unsafeFallback'] )
199 ||
$policyConfig['unsafeFallback'] )
200 && $mode !== self
::FULL_MODE_RESTRICTED
202 // unsafe-inline should be ignored on browsers
203 // that support 'nonce-foo' sources.
204 // Some older versions of firefox don't follow this
205 // rule, but new browsers do. (Should be for at least
207 $scriptSrc[] = "'unsafe-inline'";
209 // If default source option set to true or
210 // an array of urls, set a restrictive default-src.
211 // If set to false, we send a lenient default-src,
212 // see the code above where $defaultSrc is set initially.
213 if ( isset( $policyConfig['default-src'] )
214 && $policyConfig['default-src'] !== false
216 $defaultSrc = array_merge(
217 [ "'self'", 'data:', 'blob:' ],
220 if ( is_array( $policyConfig['default-src'] ) ) {
221 foreach ( $policyConfig['default-src'] as $src ) {
222 $defaultSrc[] = $this->escapeUrlForCSP( $src );
227 if ( !isset( $policyConfig['includeCORS'] ) ||
$policyConfig['includeCORS'] ) {
228 $CORSUrls = $this->getCORSSources();
229 if ( !in_array( '*', $defaultSrc ) ) {
230 $defaultSrc = array_merge( $defaultSrc, $CORSUrls );
232 // Unlikely to have * in scriptSrc, but doesn't
234 if ( !in_array( '*', $scriptSrc ) ) {
235 $scriptSrc = array_merge( $scriptSrc, $CORSUrls );
239 Hooks
::run( 'ContentSecurityPolicyDefaultSource', [ &$defaultSrc, $policyConfig, $mode ] );
240 Hooks
::run( 'ContentSecurityPolicyScriptSource', [ &$scriptSrc, $policyConfig, $mode ] );
242 // Check if array just in case the hook made it false
243 if ( is_array( $defaultSrc ) ) {
244 $cssSrc = array_merge( $defaultSrc, [ "'unsafe-inline'" ] );
247 if ( $mode === self
::FULL_MODE_RESTRICTED
) {
248 // report-uri disallowed in <meta> tags.
250 } elseif ( isset( $policyConfig['report-uri'] ) && $policyConfig['report-uri'] !== true ) {
251 if ( $policyConfig['report-uri'] === false ) {
254 $reportUri = $this->escapeUrlForCSP( $policyConfig['report-uri'] );
257 $reportUri = $this->getReportUri( $mode );
260 // Only send an img-src, if we're sending a restricitve default.
261 if ( !is_array( $defaultSrc )
262 ||
!in_array( '*', $defaultSrc )
263 ||
!in_array( 'data:', $defaultSrc )
264 ||
!in_array( 'blob:', $defaultSrc )
266 // A future todo might be to make the whitelist options only
267 // add all the whitelisted sites to the header, instead of
268 // allowing all (Assuming there is a small number of sites).
269 // For now, the external image feature disables the limits
270 // CSP puts on external images.
271 if ( $mwConfig->get( 'AllowExternalImages' )
272 ||
$mwConfig->get( 'AllowExternalImagesFrom' )
273 ||
$mwConfig->get( 'AllowImageTag' )
275 $imgSrc = [ '*', 'data:', 'blob:' ];
276 } elseif ( $mwConfig->get( 'EnableImageWhitelist' ) ) {
277 $whitelist = wfMessage( 'external_image_whitelist' )
278 ->inContentLanguage()
280 if ( preg_match( '/^\s*[^\s#]/m', $whitelist ) ) {
281 $imgSrc = [ '*', 'data:', 'blob:' ];
288 $directives[] = 'script-src ' . implode( ' ', $scriptSrc );
291 $directives[] = 'default-src ' . implode( ' ', $defaultSrc );
294 $directives[] = 'style-src ' . implode( ' ', $cssSrc );
297 $directives[] = 'img-src ' . implode( ' ', $imgSrc );
300 $directives[] = 'report-uri ' . $reportUri;
303 Hooks
::run( 'ContentSecurityPolicyDirectives', [ &$directives, $policyConfig, $mode ] );
305 return implode( '; ', $directives );
309 * Get the default report uri.
311 * @param int $mode self::*_MODE constant. Do not use with self::FULL_MODE_RESTRICTED
312 * @return string The URI to send reports to.
313 * @throws UnexpectedValueException if given invalid mode.
315 private function getReportUri( $mode ) {
316 if ( $mode === self
::FULL_MODE_RESTRICTED
) {
317 throw new UnexpectedValueException( $mode );
320 'action' => 'cspreport',
323 if ( $mode === self
::REPORT_ONLY_MODE
) {
324 $apiArguments['reportonly'] = '1';
326 $reportUri = wfAppendQuery( wfScript( 'api' ), $apiArguments );
328 // Per spec, ';' and ',' must be hex-escaped in report uri
329 $reportUri = $this->escapeUrlForCSP( $reportUri );
334 * Given a url, convert to form needed for CSP.
336 * Currently this does either scheme + host, or
337 * if protocol relative, just the host. Future versions
338 * could potentially preserve some of the path, if its determined
339 * that that would be a good idea.
341 * @note This does the extra escaping for CSP, but assumes the url
342 * has already had normal url escaping applied.
343 * @note This discards urls same as server name, as 'self' directive
344 * takes care of that.
346 * @return string|bool Converted url or false on failure
348 private function prepareUrlForCSP( $url ) {
350 if ( preg_match( '/^[a-z][a-z0-9+.-]*:$/i', $url ) ) {
351 // A schema source (e.g. blob: or data:)
354 $bits = wfParseUrl( $url );
355 if ( !$bits && strpos( $url, '/' ) === false ) {
356 // probably something like example.com.
357 // try again protocol-relative.
359 $bits = wfParseUrl( $url );
361 if ( $bits && isset( $bits['host'] )
362 && $bits['host'] !== $this->mwConfig
->get( 'ServerName' )
364 $result = $bits['host'];
365 if ( $bits['scheme'] !== '' ) {
366 $result = $bits['scheme'] . $bits['delimiter'] . $result;
368 if ( isset( $bits['port'] ) ) {
369 $result .= ':' . $bits['port'];
371 $result = $this->escapeUrlForCSP( $result );
377 * Get additional script sources
379 * @return array Additional sources for loading scripts from
381 private function getAdditionalSelfUrlsScript() {
382 $additionalUrls = [];
383 // wgExtensionAssetsPath for ?debug=true mode
384 $pathVars = [ 'LoadScript', 'ExtensionAssetsPath', 'ResourceBasePath' ];
386 foreach ( $pathVars as $path ) {
387 $url = $this->mwConfig
->get( $path );
388 $preparedUrl = $this->prepareUrlForCSP( $url );
389 if ( $preparedUrl ) {
390 $additionalUrls[] = $preparedUrl;
393 $RLSources = $this->mwConfig
->get( 'ResourceLoaderSources' );
394 foreach ( $RLSources as $wiki => $sources ) {
395 foreach ( $sources as $id => $value ) {
396 $url = $this->prepareUrlForCSP( $value );
398 $additionalUrls[] = $url;
403 return array_unique( $additionalUrls );
407 * Get additional host names for the wiki (e.g. if static content loaded elsewhere)
409 * @note These are general load sources, not script sources
410 * @return array Array of other urls for wiki (for use in default-src)
412 private function getAdditionalSelfUrls() {
413 // XXX on a foreign repo, the included description page can have anything on it,
414 // including inline scripts. But nobody sane does that.
416 // In principle, you can have even more complex configs... (e.g. The urlsByExt option)
418 $additionalSelfUrls = [];
420 // Future todo: The zone urls should never go into
421 // style-src. They should either be only in img-src, or if
422 // img-src unspecified they should be in default-src. Similarly,
423 // the DescriptionStylesheetUrl only needs to be in style-src
424 // (or default-src if style-src unspecified).
425 $callback = function ( $repo, &$urls ) {
426 $urls[] = $repo->getZoneUrl( 'public' );
427 $urls[] = $repo->getZoneUrl( 'transcoded' );
428 $urls[] = $repo->getZoneUrl( 'thumb' );
429 $urls[] = $repo->getDescriptionStylesheetUrl();
431 $localRepo = RepoGroup
::singleton()->getRepo( 'local' );
432 $callback( $localRepo, $pathUrls );
433 RepoGroup
::singleton()->forEachForeignRepo( $callback, [ &$pathUrls ] );
435 // Globals that might point to a different domain
436 $pathGlobals = [ 'LoadScript', 'ExtensionAssetsPath', 'StylePath', 'ResourceBasePath' ];
437 foreach ( $pathGlobals as $path ) {
438 $pathUrls[] = $this->mwConfig
->get( $path );
440 foreach ( $pathUrls as $path ) {
441 $preparedUrl = $this->prepareUrlForCSP( $path );
442 if ( $preparedUrl !== false ) {
443 $additionalSelfUrls[] = $preparedUrl;
446 $RLSources = $this->mwConfig
->get( 'ResourceLoaderSources' );
448 foreach ( $RLSources as $wiki => $sources ) {
449 foreach ( $sources as $id => $value ) {
450 $url = $this->prepareUrlForCSP( $value );
452 $additionalSelfUrls[] = $url;
457 return array_unique( $additionalSelfUrls );
461 * include domains that are allowed to send us CORS requests.
463 * Technically, $wgCrossSiteAJAXdomains lists things that are allowed to talk to us
464 * not things that we are allowed to talk to - but if something is allowed to talk to us,
465 * then there is a good chance that we should probably be allowed to talk to it.
467 * This is configurable with the 'includeCORS' key in the CSP config, and enabled
469 * @note CORS domains with single character ('?') wildcards, are not included.
470 * @return array Additional hosts
472 private function getCORSSources() {
473 $additionalUrls = [];
474 $CORSSources = $this->mwConfig
->get( 'CrossSiteAJAXdomains' );
475 foreach ( $CORSSources as $source ) {
476 if ( strpos( $source, '?' ) !== false ) {
477 // CSP doesn't support single char wildcard
480 $url = $this->prepareUrlForCSP( $source );
482 $additionalUrls[] = $url;
485 return $additionalUrls;
489 * CSP spec says ',' and ';' are not allowed to appear in urls.
491 * @note This assumes that normal escaping has been applied to the url
492 * @param string $url URL (or possibly just part of one)
495 private function escapeUrlForCSP( $url ) {
504 * Does this browser give false positive reports?
506 * Some versions of firefox (40-42) incorrectly report a csp
507 * violation for nonce sources, despite allowing them.
509 * @see https://bugzilla.mozilla.org/show_bug.cgi?id=1026520
510 * @param string $ua User-agent header
513 public static function falsePositiveBrowser( $ua ) {
514 return (bool)preg_match( '!Firefox/4[0-2]\.!', $ua );
518 * Is CSP currently enabled (i.e. Should we set nonce attribute)
520 * @param Config $config Configuration object
523 public static function isEnabled( Config
$config ) {
524 return $config->get( 'CSPHeader' ) !== false
525 ||
$config->get( 'CSPReportOnlyHeader' ) !== false;