CoreFiles by mySites.guru
httpheaders.php665 lines, 17,859 bytes, from Joomla_4.0.0-beta6-Beta-Full_Package.zip
Raw History Compare with 4.0.0-beta5
md5
af415c0f2c9f929cdfa04d452ad859cf
sha1
aa69a9358475671592f64816e99a6bd9b67cd2c2
sha256
3510251456127b4734989182c0035abd3f53af5cf09b826c7f68cd8ac8927111
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  System.HttpHeaders
 *
 * @copyright   (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

use Joomla\CMS\Application\CMSApplication;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Uri\Uri;
use Joomla\Database\DatabaseDriver;
use Joomla\Event\SubscriberInterface;

/**
 * Plugin class for HTTP Headers
 *
 * @since  4.0.0
 */
class PlgSystemHttpHeaders extends CMSPlugin implements SubscriberInterface
{
	/**
	 * If true, language files will be loaded automatically.
	 *
	 * @var    boolean
	 * @since  4.0.0
	 */
	protected $autoloadLanguage = true;

	/**
	 * Application object.
	 *
	 * @var    CMSApplication
	 * @since  4.0.0
	 */
	protected $app;

	/**
	 * Database object.
	 *
	 * @var    DatabaseDriver
	 * @since  4.0.0
	 */
	protected $db;

	/**
	 * The generated csp nonce value
	 *
	 * @var    string
	 * @since  4.0.0
	 */
	private $cspNonce;

	/**
	 * The params of the com_csp component
	 *
	 * @var    \Joomla\Registry\Registry
	 * @since  4.0.0
	 */
	private $comCspParams;

	/**
	 * The list of the supported HTTP headers
	 *
	 * @var    array
	 * @since  4.0.0
	 */
	private $supportedHttpHeaders = [
		'strict-transport-security',
		'content-security-policy',
		'content-security-policy-report-only',
		'x-frame-options',
		'referrer-policy',
		'expect-ct',
		'feature-policy',
		'cross-origin-opener-policy',
		'report-to',
		'permissions-policy',
	];

	/**
	 * The list of valid directives based on: https://www.w3.org/TR/CSP3/#csp-directives
	 *
	 * @var    array
	 * @since  4.0.0
	 */
	private $validDirectives = [
		'child-src',
		'connect-src',
		'default-src',
		'font-src',
		'frame-src',
		'img-src',
		'manifest-src',
		'media-src',
		'prefetch-src',
		'object-src',
		'script-src',
		'script-src-elem',
		'script-src-attr',
		'style-src',
		'style-src-elem',
		'style-src-attr',
		'worker-src',
		'base-uri',
		'plugin-types',
		'sandbox',
		'form-action',
		'frame-ancestors',
		'navigate-to',
		'report-uri',
		'report-to',
		'block-all-mixed-content',
		'upgrade-insecure-requests',
		'require-sri-for',
	];

	/**
	 * The list of directives without a value
	 *
	 * @var    array
	 * @since  4.0.0
	 */
	private $noValueDirectives = [
		'block-all-mixed-content',
		'upgrade-insecure-requests',
	];

	/**
	 * The list of directives supporting nonce
	 *
	 * @var    array
	 * @since  4.0.0
	 */
	private $nonceDirectives = [
		'script-src',
		'style-src',
	];

	/**
	 * Constructor.
	 *
	 * @param   object  &$subject  The object to observe.
	 * @param   array   $config    An optional associative array of configuration settings.
	 *
	 * @since   4.0.0
	 */
	public function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config);

		// Get the com_csp params that include the content-security-policy configuration
		$this->comCspParams = ComponentHelper::getParams('com_csp');

		// Nonce generation
		$this->cspNonce = base64_encode(bin2hex(random_bytes(64)));
		$this->app->set('csp_nonce', $this->cspNonce);
	}

	/**
	 * Returns an array of events this subscriber will listen to.
	 *
	 * @return  array
	 *
	 * @since   4.0.0
	 */
	public static function getSubscribedEvents(): array
	{
		return [
			'onAfterInitialise' => 'setHttpHeaders',
			'onAfterRender'     => 'applyHashesToCspRule',
		];
	}

	/**
	 * The `applyHashesToCspRule` method makes sure the csp hashes are added to the csp header when enabled
	 *
	 * @return  void
	 *
	 * @since   4.0.0
	 */
	public function applyHashesToCspRule(): void
	{
		// CSP is only relevant on html pages. Let's early exit here.
		if ($this->app->getDocument()->getType() !== 'html')
		{
			return;
		}

		$scriptHashesEnabled = (int) $this->comCspParams->get('script_hashes_enabled', 0);
		$styleHashesEnabled  = (int) $this->comCspParams->get('style_hashes_enabled', 0);

		// Early exit when both options are disabled
		if (!$scriptHashesEnabled && !$styleHashesEnabled)
		{
			return;
		}

		$headData     = $this->app->getDocument()->getHeadData();
		$scriptHashes = [];
		$styleHashes  = [];

		if ($scriptHashesEnabled)
		{
			// Generate the hashes for the script-src
			$inlineScripts = is_array($headData['script']) ? $headData['script'] : [];

			foreach ($inlineScripts as $type => $scripts)
			{
				foreach ($scripts as $hash => $scriptContent)
				{
					$scriptHashes[] = "'sha256-" . base64_encode(hash('sha256', $scriptContent, true)) . "'";
				}
			}
		}

		if ($styleHashesEnabled)
		{
			// Generate the hashes for the style-src
			$inlineStyles = is_array($headData['style']) ? $headData['style'] : [];

			foreach ($inlineStyles as $type => $styles)
			{
				foreach ($styles as $hash => $styleContent)
				{
					$styleHashes[] = "'sha256-" . base64_encode(hash('sha256', $styleContent, true)) . "'";
				}
			}
		}

		// Replace the hashes in the csp header when set.
		$headers = $this->app->getHeaders();

		foreach ($headers as $id => $headerConfiguration)
		{
			if (strtolower($headerConfiguration['name']) === 'content-security-policy'
				|| strtolower($headerConfiguration['name']) === 'content-security-policy-report-only')
			{
				$newHeaderValue = $headerConfiguration['value'];

				if (!empty($scriptHashes))
				{
					$newHeaderValue = str_replace('{script-hashes}', implode(' ', $scriptHashes), $newHeaderValue);
				}
				else
				{
					$newHeaderValue = str_replace('{script-hashes}', '', $newHeaderValue);
				}

				if (!empty($styleHashes))
				{
					$newHeaderValue = str_replace('{style-hashes}', implode(' ', $styleHashes), $newHeaderValue);
				}
				else
				{
					$newHeaderValue = str_replace('{style-hashes}', '', $newHeaderValue);
				}

				$this->app->setHeader($headerConfiguration['name'], $newHeaderValue, true);
			}
		}
	}

	/**
	 * The `setHttpHeaders` method handle the setting of the configured HTTP Headers
	 *
	 * @return  void
	 *
	 * @since   4.0.0
	 */
	public function setHttpHeaders(): void
	{
		// Set the default header when they are enabled
		$this->setStaticHeaders();

		// Handle CSP Header configuration
		$cspEnabled = (int) $this->comCspParams->get('contentsecuritypolicy', 0);
		$cspClient  = (string) $this->comCspParams->get('contentsecuritypolicy_client', 'site');

		// Check whether CSP is enabled and enabled by the current client
		if ($cspEnabled && ($this->app->isClient($cspClient) || $cspClient === 'both'))
		{
			$this->setCspHeader();
		}
	}

	/**
	 * Set the CSP header when enabled
	 *
	 * @return  void
	 *
	 * @since   4.0.0
	 */
	private function setCspHeader(): void
	{
		// Mode Selector
		$cspMode = $this->comCspParams->get('contentsecuritypolicy_mode', 'detect');

		// In detecting mode we set this default rule so any report gets collected by com_csp
		if ($cspMode === 'detect')
		{
			$this->app->setHeader(
				'content-security-policy-report-only',
				"default-src 'self'; report-uri " . Uri::root() . "index.php?option=com_csp&task=report.log&client=" . $this->app->getName()
			);

			return;
		}

		$cspReadOnly = (int) $this->comCspParams->get('contentsecuritypolicy_report_only', 1);
		$cspHeader   = $cspReadOnly === 0 ? 'content-security-policy' : 'content-security-policy-report-only';

		// In automatic mode we compile the automatic header values and append it to the header
		if ($cspMode === 'auto')
		{
			$automaticRules = trim(
				implode(
					'; ',
					$this->compileAutomaticCspHeaderRules()
				)
			);

			// Set the header
			$this->app->setHeader($cspHeader, $automaticRules);

			return;
		}

		// In custom mode we compile the header from the values configured
		$cspValues                 = $this->comCspParams->get('contentsecuritypolicy_values', []);
		$nonceEnabled              = (int) $this->comCspParams->get('nonce_enabled', 0);
		$scriptHashesEnabled       = (int) $this->comCspParams->get('script_hashes_enabled', 0);
		$strictDynamicEnabled      = (int) $this->comCspParams->get('strict_dynamic_enabled', 0);
		$styleHashesEnabled        = (int) $this->comCspParams->get('style_hashes_enabled', 0);
		$frameAncestorsSelfEnabled = (int) $this->comCspParams->get('frame_ancestors_self_enabled', 1);
		$frameAncestorsSet         = false;

		foreach ($cspValues as $cspValue)
		{
			// Handle the client settings foreach header
			if (!$this->app->isClient($cspValue->client) && $cspValue->client != 'both')
			{
				continue;
			}

			// Handle non value directives
			if (in_array($cspValue->directive, $this->noValueDirectives))
			{
				$newCspValues[] = trim($cspValue->directive);

				continue;
			}

			// We can only use this if this is a valid entry
			if (in_array($cspValue->directive, $this->validDirectives)
				&& !empty($cspValue->value))
			{
				if (in_array($cspValue->directive, $this->nonceDirectives) && $nonceEnabled)
				{
					// Append the nonce
					$cspValue->value = str_replace('{nonce}', "'nonce-" . $this->cspNonce . "'", $cspValue->value);
				}

				// Append the script hashes placeholder
				if ($scriptHashesEnabled && strpos($cspValue->directive, 'script-src') === 0)
				{
					$cspValue->value = '{script-hashes} ' . $cspValue->value;
				}

				// Append the style hashes placeholder
				if ($styleHashesEnabled && strpos($cspValue->directive, 'style-src') === 0)
				{
					$cspValue->value = '{style-hashes} ' . $cspValue->value;
				}

				if ($cspValue->directive === 'frame-ancestors')
				{
					$frameAncestorsSet = true;
				}

				// Add strict-dynamic to the script-src directive when enabled
				if ($strictDynamicEnabled
					&& $cspValue->directive === 'script-src'
					&& strpos($cspValue->value, 'strict-dynamic') === false)
				{
					$cspValue->value .= " 'strict-dynamic' ";
				}

				$newCspValues[] = trim($cspValue->directive) . ' ' . trim($cspValue->value);
			}
		}

		if ($frameAncestorsSelfEnabled && !$frameAncestorsSet)
		{
			$newCspValues[] = "frame-ancestors 'self'";
		}

		if (empty($newCspValues))
		{
			return;
		}

		$this->app->setHeader($cspHeader, trim(implode('; ', $newCspValues)));
	}

	/**
	 * Compile the automatic csp header rules based on com_csp / #__csp
	 *
	 * @return  array  An array containing the csp rules found in com_csp
	 *
	 * @since   4.0.0
	 */
	private function compileAutomaticCspHeaderRules(): array
	{
		// Get the published infos from the database
		$query = $this->db->getQuery(true)
			->select($this->db->quoteName(['client', 'directive', 'blocked_uri']))
			->from($this->db->quoteName('#__csp'))
			->where($this->db->quoteName('published') . ' = 1');

		$this->db->setQuery($query);

		try
		{
			$rows = (array) $this->db->loadObjectList();
		}
		catch (\RuntimeException $e)
		{
			$this->app->enqueueMessage(Text::_('JERROR_AN_ERROR_HAS_OCCURRED'), 'error');

			return [];
		}

		$automaticCspHeader        = [];
		$cspHeaderCollection       = [];
		$nonceEnabled              = (int) $this->comCspParams->get('nonce_enabled', 0);
		$scriptHashesEnabled       = (int) $this->comCspParams->get('script_hashes_enabled', 0);
		$strictDynamicEnabled      = (int) $this->comCspParams->get('strict_dynamic_enabled', 0);
		$styleHashesEnabled        = (int) $this->comCspParams->get('style_hashes_enabled', 0);
		$frameAncestorsSelfEnabled = (int) $this->comCspParams->get('frame_ancestors_self_enabled', 1);

		foreach ($rows as $row)
		{
			// Handle the client information for each rule
			if (!$this->app->isClient($row->client))
			{
				continue;
			}

			// Make sure the directive exists as a key
			if (!isset($cspHeaderCollection[$row->directive]))
			{
				$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys([$row->directive], ''));
			}

			// Eval or inline lets us make sure they still work by adding ' before and after
			if (in_array($row->blocked_uri, ['unsafe-eval', 'unsafe-inline']))
			{
				$row->blocked_uri = "'$row->blocked_uri'";
			}

			// Whitelist the blocked_uri for the given directive
			$cspHeaderCollection[$row->directive] .= ' ' . $row->blocked_uri;
		}

		// Add the frame-ancestors when not done already
		if (!isset($cspHeaderCollection['frame-ancestors']) && $frameAncestorsSelfEnabled)
		{
			$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys(['frame-ancestors'], ''));
		}

		// We should have a default-src, script-src and style-src rule
		if (!empty($cspHeaderCollection))
		{
			if (!isset($cspHeaderCollection['default-src']))
			{
				$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys(['default-src'], ''));
			}

			if (!isset($cspHeaderCollection['script-src']) && ($scriptHashesEnabled || $nonceEnabled))
			{
				$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys(['script-src'], ''));
			}

			if (!isset($cspHeaderCollection['style-src']) && ($scriptHashesEnabled || $nonceEnabled))
			{
				$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys(['style-src'], ''));
			}
		}

		foreach ($cspHeaderCollection as $cspHeaderkey => $cspHeaderValue)
		{
			// Handle non value directives
			if (in_array($cspHeaderkey, $this->noValueDirectives))
			{
				$automaticCspHeader[] = $cspHeaderkey;

				continue;
			}

			// Make sure this is a valid directive
			if (!in_array($cspHeaderkey, $this->validDirectives))
			{
				continue;
			}

			// Append the random $nonce for the script and style tags if enabled
			if (in_array($cspHeaderkey, $this->nonceDirectives) && $nonceEnabled)
			{
				// Append nonce
				$cspHeaderValue = "'nonce-" . $this->cspNonce . "'" . $cspHeaderValue;
			}

			// Append the script hashes placeholder
			if ($scriptHashesEnabled && strpos($cspHeaderkey, 'script-src') === 0)
			{
				$cspHeaderValue = '{script-hashes} ' . $cspHeaderValue;
			}

			// Append the style hashes placeholder
			if ($styleHashesEnabled && strpos($cspHeaderkey, 'style-src') === 0)
			{
				$cspHeaderValue = '{style-hashes} ' . $cspHeaderValue;
			}

			// Add strict-dynamic to the script-src directive when enabled
			if ($strictDynamicEnabled
				&& $cspHeaderkey === 'script-src'
				&& strpos($cspHeaderValue, 'strict-dynamic') === false)
			{
				$cspHeaderValue .= " 'strict-dynamic' ";
			}

			// By default we should whitelist 'self' on any directive
			$automaticCspHeader[] = $cspHeaderkey . " 'self' " . trim($cspHeaderValue);
		}

		return $automaticCspHeader;
	}

	/**

	 * Get the configured static headers.
	 *
	 * @return  array  We return the array of static headers with its values.
	 *
	 * @since   4.0.0
	 */
	private function getStaticHeaderConfiguration(): array
	{
		$staticHeaderConfiguration = [];

		// X-frame-options
		if ($this->params->get('xframeoptions', 1) === 1)
		{
			$staticHeaderConfiguration['x-frame-options#both'] = 'SAMEORIGIN';
		}

		// Referrer-policy
		$referrerPolicy = (string) $this->params->get('referrerpolicy', 'strict-origin-when-cross-origin');

		if ($referrerPolicy !== 'disabled')
		{
			$staticHeaderConfiguration['referrer-policy#both'] = $referrerPolicy;
		}

		// Cross-Origin-Opener-Policy
		$coop = (string) $this->params->get('coop', 'same-origin');

		if ($coop !== 'disabled')
		{
			$staticHeaderConfiguration['cross-origin-opener-policy#both'] = $coop;
		}

		// Generate the strict-transport-security header and make sure the site is SSL
		if ($this->params->get('hsts', 0) === 1 && Uri::getInstance()->isSsl() === true)
		{
			$hstsOptions   = [];
			$hstsOptions[] = 'max-age=' . (int) $this->params->get('hsts_maxage', 31536000);

			if ($this->params->get('hsts_subdomains', 0) === 1)
			{
				$hstsOptions[] = 'includeSubDomains';
			}

			if ($this->params->get('hsts_preload', 0) === 1)
			{
				$hstsOptions[] = 'preload';
			}

			$staticHeaderConfiguration['strict-transport-security#both'] = implode('; ', $hstsOptions);
		}

		// Generate the additional headers
		$additionalHttpHeaders = $this->params->get('additional_httpheader', []);

		foreach ($additionalHttpHeaders as $additionalHttpHeader)
		{
			// Make sure we have a key and a value
			if (empty($additionalHttpHeader->key) || empty($additionalHttpHeader->value))
			{
				continue;
			}

			// Make sure the header is a valid and supported header
			if (!in_array(strtolower($additionalHttpHeader->key), $this->supportedHttpHeaders))
			{
				continue;
			}

			// Make sure we do not add one header twice but we support to set a different header per client.
			if (isset($staticHeaderConfiguration[$additionalHttpHeader->key . '#' . $additionalHttpHeader->client])
				|| isset($staticHeaderConfiguration[$additionalHttpHeader->key . '#both']))
			{
				continue;
			}

			// Allow the custom csp headers to use the random $cspNonce in the rules
			if (in_array(strtolower($additionalHttpHeader->key), ['content-security-policy', 'content-security-policy-report-only']))
			{
				$additionalHttpHeader->value = str_replace('{nonce}', "'nonce-" . $this->cspNonce . "'", $additionalHttpHeader->value);
			}

			$staticHeaderConfiguration[$additionalHttpHeader->key . '#' . $additionalHttpHeader->client] = $additionalHttpHeader->value;
		}

		return $staticHeaderConfiguration;
	}

	/**
	 * Set the static headers when enabled
	 *
	 * @return  void
	 *
	 * @since   4.0.0
	 */
	private function setStaticHeaders(): void
	{
		$staticHeaderConfiguration = $this->getStaticHeaderConfiguration();

		if (empty($staticHeaderConfiguration))
		{
			return;
		}

		foreach ($staticHeaderConfiguration as $headerAndClient => $value)
		{
			$headerAndClient = explode('#', $headerAndClient);
			$header = $headerAndClient[0];
			$client = isset($headerAndClient[1]) ? $headerAndClient[1] : 'both';

			if (!$this->app->isClient($client) && $client != 'both')
			{
				continue;
			}

			$this->app->setHeader($header, $value, true);
		}
	}
}

The same content is in 2 releases, Joomla 4.0.0-beta6 to 4.0.0-beta7. See them all, or every version of this file.