CoreFiles by mySites.guru
httpheaders.php840 lines, 23,135 bytes, from Joomla_4.0.0-alpha11-Alpha-Full_Package.zip
Raw History Compare with 4.0.0-alpha10
md5
1e51fdf8262f1af8ac69087373ca2aee
sha1
6410f849f0ef168b3c7bd8f322d6edeccb13f786
sha256
eb387c3162ae193e347453ac032088b940413d7d60917c8960390266ff38fad8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  System.HttpHeaders
 *
 * @copyright   Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved.
 * @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\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Uri\Uri;
use Joomla\Database\DatabaseDriver;
use Joomla\Event\Event;
use Joomla\Event\SubscriberInterface;
use Joomla\Filesystem\File;
use Joomla\Registry\Registry;

/**
 * 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 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',
	];

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

	/**
	 * The static header configuration as array
	 *
	 * @var    array
	 * @since  4.0.0
	 */
	private $staticHeaderConfiguration = [];

	/**
	 * Defines the Server config file type none
	 *
	 * @var    string
	 * @since  4.0.0
	 */
	const SERVER_CONFIG_FILE_NONE = '';

	/**
	 * Defines the Server config file type htaccess
	 *
	 * @var    string
	 * @since  4.0.0
	 */
	const SERVER_CONFIG_FILE_HTACCESS = '.htaccess';

	/**
	 * Defines the Server config file type web.config
	 *
	 * @var    string
	 * @since  4.0.0
	 */
	const SERVER_CONFIG_FILE_WEBCONFIG = 'web.config';

	/**
	 * 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 application if not done by JPlugin.
		if (!$this->app)
		{
			$this->app = Factory::getApplication();
		}

		// Get the db if not done by JPlugin.
		if (!$this->db)
		{
			$this->db = Factory::getDbo();
		}

		// 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',
			'onExtensionAfterSave' => 'writeStaticHttpHeaders',
		];
	}

	/**
	 * 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
		$cspOptions = (int) $this->comCspParams->get('contentsecuritypolicy', 0);

		if ($cspOptions)
		{
			$this->setCspHeader();
		}
	}

	/**
	 * On saving this plugin we may want to generate the latest static headers
	 *
	 * @param   Event  $event  The Event Object with the passed arguments
	 *
	 * @return  void
	 *
	 * @since   4.0.0
	 */
	public function writeStaticHttpHeaders(Event $event): void
	{
		// Read the arguments from the event object
		$context = $event->getArgument('0');
		$table   = $event->getArgument('1');
		$isNew   = $event->getArgument('2');

		// When the updated extension is not PLG_SYSTEM_HTTPHEADERS we don't do anything
		if ($context !== 'com_plugins.plugin' || $table->element !== $this->_name || $table->folder !== $this->_type)
		{
			return;
		}

		// Get the new params saved by the plugin
		$pluginParams = new Registry($table->get('params'));

		// When the option is disabled we don't do anything here.
		if (!$pluginParams->get('write_static_headers', 0))
		{
			return;
		}

		$serverConfigFile = $this->getServerConfigFile();

		if (!$serverConfigFile)
		{
			$this->app->enqueueMessage(
				Text::_('PLG_SYSTEM_HTTPHEADERS_MESSAGE_STATICHEADERS_NOT_WRITTEN_NO_SERVER_CONFIGFILE_FOUND'),
				'warning'
			);

			return;
		}

		// Get the StaticHeaderConfiguration
		$this->staticHeaderConfiguration = $this->getStaticHeaderConfiguration($pluginParams);

		// Write the static headers
		$result = $this->writeStaticHeaders();

		if (!$result)
		{
			// Something did not work tell them that and how to update themself.
			$this->app->enqueueMessage(
				Text::sprintf(
					'PLG_SYSTEM_HTTPHEADERS_MESSAGE_STATICHEADERS_NOT_WRITTEN',
					$serverConfigFile,
					$this->getRulesForStaticHeaderConfiguration($serverConfigFile)
				),
				'error'
			);

			return;
		}

		// Show messge that everything was done
		$this->app->enqueueMessage(
			Text::sprintf(
				'PLG_SYSTEM_HTTPHEADERS_MESSAGE_STATICHEADERS_WRITTEN',
				$serverConfigFile
			),
			'message'
		);
	}

	/**
	 * 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')
		{
			$frontendUrl = str_replace('/administrator', '', Uri::base());

			$this->app->setHeader(
				'content-security-policy-report-only',
				"default-src 'self'; report-uri " . $frontendUrl . "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', array());
		$nonceEnabled = (int) $this->comCspParams->get('nonce_enabled', 0);

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

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

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

		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);

		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;
		}

		// 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']) && $nonceEnabled)
			{
				$cspHeaderCollection = array_merge($cspHeaderCollection, array_fill_keys(['script-src'], ''));
			}

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

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

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

		return $automaticCspHeader;
	}

	/**
	 * Return the server config file constant
	 *
	 * @return  string  Constante pointing to the correct server config file or none
	 *
	 * @since   4.0.0
	 */
	private function getServerConfigFile(): string
	{
		if (file_exists($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS))
			&& substr(strtolower($_SERVER['SERVER_SOFTWARE']), 0, 6) === 'apache')
		{
			return self::SERVER_CONFIG_FILE_HTACCESS;
		}

		// We are not on an apache so lets just check whether the web.config file exits
		if (file_exists($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_WEBCONFIG)))
		{
			return self::SERVER_CONFIG_FILE_WEBCONFIG;
		}

		return self::SERVER_CONFIG_FILE_NONE;
	}

	/**
	 * Return the path to the server config file we check
	 *
	 * @param   string  $file  Constante pointing to the correct server config file or none
	 *
	 * @return  string  Expected path to the requested file; Or false on error
	 *
	 * @since   4.0.0
	 */
	private function getServerConfigFilePath($file): string
	{
		return JPATH_ROOT . DIRECTORY_SEPARATOR . $file;
	}

	/**
	 * Return the static Header Configuration based on the server config file
	 *
	 * @param   string  $serverConfigFile  Constant holding the server configuration file
	 *
	 * @return  string  Buffer style text of the Header Configuration based on the server config file
	 *
	 * @since   4.0.0
	 */
	private function getRulesForStaticHeaderConfiguration($serverConfigFile): string
	{
		if ($serverConfigFile === self::SERVER_CONFIG_FILE_HTACCESS)
		{
			return $this->getHtaccessRulesForStaticHeaderConfiguration();
		}

		if ($serverConfigFile === self::SERVER_CONFIG_FILE_WEBCONFIG)
		{
			return $this->getWebConfigRulesForStaticHeaderConfiguration();
		}

		return false;
	}

	/**
	 * Return the static Header Configuration based in the .htaccess format
	 *
	 * @return  string  Buffer style text of the Header Configuration based on the server config file; empty string on error
	 *
	 * @since   4.0.0
	 */
	private function getHtaccessRulesForStaticHeaderConfiguration(): string
	{
		$oldHtaccessBuffer = file($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS), FILE_IGNORE_NEW_LINES);
		$newHtaccessBuffer = '';

		if (!$oldHtaccessBuffer)
		{
			// `file` couldn't read the htaccess we can't do anything at this point
			return '';
		}

		$scriptLines = false;

		foreach ($oldHtaccessBuffer as $id => $line)
		{
			if ($line === '### MANAGED BY PLG_SYSTEM_HTTPHEADERS DO NOT MANUALLY EDIT! - START ###')
			{
				$scriptLines = true;
				continue;
			}

			if ($line === '### MANAGED BY PLG_SYSTEM_HTTPHEADERS DO NOT MANUALLY EDIT! - END ###'
				|| $line === '##############################################################')
			{
				$scriptLines = false;
				continue;
			}

			if ($scriptLines)
			{
				// When we are between our makers all content should be removed
				continue;
			}

			$newHtaccessBuffer .= $line . PHP_EOL;
		}

		$newHtaccessBuffer .= '##############################################################' . PHP_EOL;
		$newHtaccessBuffer .= '### MANAGED BY PLG_SYSTEM_HTTPHEADERS DO NOT MANUALLY EDIT! - START ###' . PHP_EOL;
		$newHtaccessBuffer .= '<IfModule mod_headers.c>' . PHP_EOL;

		foreach ($this->staticHeaderConfiguration as $headerAndClient => $value)
		{
			$headerAndClient = explode('#', $headerAndClient);

			if (!in_array(strtolower($headerAndClient[0]), ['content-security-policy', 'content-security-policy-report-only']))
			{
				$newHtaccessBuffer .= '    Header set ' . $headerAndClient[0] . ' "' . $value . '"' . PHP_EOL;
			}
		}

		$newHtaccessBuffer .= '</IfModule>' . PHP_EOL;
		$newHtaccessBuffer .= '### MANAGED BY PLG_SYSTEM_HTTPHEADERS DO NOT MANUALLY EDIT! - END ###' . PHP_EOL;
		$newHtaccessBuffer .= '##############################################################' . PHP_EOL;
		$newHtaccessBuffer .= PHP_EOL;

		return $newHtaccessBuffer;
	}

	/**
	 * Return the static Header Configuration based in the web.config format
	 *
	 * @return  string  Buffer style text of the Header Configuration based on the server config file or false on error.
	 *
	 * @since   4.0.0
	 */
	private function getWebConfigRulesForStaticHeaderConfiguration(): string
	{
		$webConfigDomDoc = new DOMDocument('1.0', 'UTF-8');

		// We want a nice output
		$webConfigDomDoc->formatOutput = true;
		$webConfigDomDoc->preserveWhiteSpace = false;

		// Load the current file into our object
		$webConfigDomDoc->load($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_WEBCONFIG));

		// Get an DOMXPath Object mathching our file
		$xpath = new DOMXPath($webConfigDomDoc);

		// We require an correct tree containing an system.webServer node!
		$systemWebServer = $xpath->query("/configuration/location/system.webServer");

		if ($systemWebServer->length === 0 || $systemWebServer->length > 1)
		{
			// There is only one (or none) so we don't do anything here
			return '';
		}

		// Check what configurations exists already
		$httpProtocol  = $xpath->query("/configuration/location/system.webServer/httpProtocol");
		$customHeaders = $xpath->query("/configuration/location/system.webServer/httpProtocol/customHeaders");

		// Does the httpProtocol node exist?
		if ($httpProtocol->length === 0)
		{
			$newHttpProtocol = $webConfigDomDoc->createElement('httpProtocol');
			$newCustomHeaders = $webConfigDomDoc->createElement('customHeaders');

			foreach ($this->staticHeaderConfiguration as $headerAndClient => $value)
			{
				$headerAndClient = explode('#', $headerAndClient);

				if (!in_array(strtolower($headerAndClient[0]), ['content-security-policy', 'content-security-policy-report-only']))
				{
					$newHeader = $webConfigDomDoc->createElement('add');

					$newHeader->setAttribute('name', $headerAndClient[0]);
					$newHeader->setAttribute('value', $value);
					$newCustomHeaders->appendChild($newHeader);
				}
			}

			$newHttpProtocol->appendChild($newCustomHeaders);
			$systemWebServer[0]->appendChild($newHttpProtocol);
		}
		// It seams there are a httpProtocol node so does the customHeaders node exist?
		elseif ($customHeaders->length === 0)
		{
			$newCustomHeaders = $webConfigDomDoc->createElement('customHeaders');

			foreach ($this->staticHeaderConfiguration as $headerAndClient => $value)
			{
				$headerAndClient = explode('#', $headerAndClient);

				if (!in_array(strtolower($headerAndClient[0]), ['content-security-policy', 'content-security-policy-report-only']))
				{
					$newHeader = $webConfigDomDoc->createElement('add');

					$newHeader->setAttribute('name', $headerAndClient[0]);
					$newHeader->setAttribute('value', $value);
					$newCustomHeaders->appendChild($newHeader);
				}
			}

			$httpProtocol[0]->appendChild($newCustomHeaders);
		}
		// Well It seams httpProtocol and customHeaders exists lets check now the individual header (add) nodes
		else
		{
			$oldCustomHeaders = $xpath->query("/configuration/location/system.webServer/httpProtocol/customHeaders/add");

			// Here we check all headers actually exists with the correct value
			foreach ($this->staticHeaderConfiguration as $headerAndClient => $value)
			{
				$headerAndClient = explode('#', $headerAndClient);

				// When no headers exitsts at all we can't find anything :D
				if ($oldCustomHeaders->length === 0)
				{
					$found = false;
				}

				// Check if the header is currently set or not
				foreach ($oldCustomHeaders as $oldCustomHeader)
				{
					$found = false;
					$customHeadersName = $oldCustomHeader->getAttribute('name');

					if ($headerAndClient[0] === $customHeadersName)
					{
						// We found it, well done.
						$found = true;
						break;
					}
				}

				// The header wasn't found we need to create it
				if (!$found)
				{
					if (!in_array(strtolower($headerAndClient[0]), ['content-security-policy', 'content-security-policy-report-only']))
					{
						// Generate the new header Element
						$newHeader = $webConfigDomDoc->createElement('add');
						$newHeader->setAttribute('name', $headerAndClient[0]);
						$newHeader->setAttribute('value', $value);

						// Append the new header
						$customHeaders[0]->appendChild($newHeader);
					}
				}

				$customHeadersValue = $oldCustomHeader->getAttribute('value');

				if ($value === $customHeadersValue)
				{
					continue;
				}

				$oldCustomHeader->setAttribute('value', $value);
			}
		}

		return $webConfigDomDoc->saveXML();
	}

	/**
	 * Wirte the static headers.
	 *
	 * @return  boolean  True on success; false on any error
	 *
	 * @since   4.0.0
	 */
	private function writeStaticHeaders(): bool
	{
		$pathToHtaccess  = $this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS);
		$pathToWebConfig = $this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_WEBCONFIG);

		if (file_exists($pathToHtaccess))
		{
			$htaccessContent = $this->getHtaccessRulesForStaticHeaderConfiguration();

			if (is_readable($pathToHtaccess) && !empty($htaccessContent))
			{
				// Write the htaccess using the Frameworks File Class
				return File::write($pathToHtaccess, $htaccessContent);
			}
		}

		if (file_exists($pathToWebConfig))
		{
			$webConfigContent = $this->getWebConfigRulesForStaticHeaderConfiguration();

			if (is_readable($pathToWebConfig) && !empty($webConfigContent))
			{
				// Setup and than write the web.config write using DOMDocument
				$webConfigDomDoc = new DOMDocument;
				$webConfigDomDoc->formatOutput = true;
				$webConfigDomDoc->preserveWhiteSpace = false;
				$webConfigDomDoc->loadXML($webConfigContent);

				// When the return code is an integer we got the bytes and everything went well if not something broke..
				return is_integer($webConfigDomDoc->save($pathToWebConfig)) ? true : false;
			}
		}
	}

	/**
	 * Get the configured static headers.
	 *
	 * @param   Registry  $pluginParams  An Registry Object containing the plugin parameters
	 *
	 * @return  array  We return the array of static headers with its values.
	 *
	 * @since   4.0.0
	 */
	private function getStaticHeaderConfiguration($pluginParams = false): array
	{
		$staticHeaderConfiguration = [];

		// Fallback to $this->params when no params has been passed
		if ($pluginParams === false)
		{
			$pluginParams = $this->params;
		}

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

		// Referrer-policy
		$referrerPolicy = (string) $pluginParams->get('referrerpolicy', 'no-referrer-when-downgrade');

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

		// Generate the strict-transport-security header
		$strictTransportSecurity = (int) $pluginParams->get('hsts', 0);

		if ($strictTransportSecurity)
		{
			$maxAge        = (int) $pluginParams->get('hsts_maxage', 31536000);
			$hstsOptions   = [];
			$hstsOptions[] = $maxAge < 300 ? 'max-age=300' : 'max-age=' . $maxAge;

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

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

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

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

		foreach ($additionalHttpHeaders as $additionalHttpHeader)
		{
			if (empty($additionalHttpHeader->key) || empty($additionalHttpHeader->value))
			{
				continue;
			}

			if (!in_array(strtolower($additionalHttpHeader->key), $this->supportedHttpHeaders))
			{
				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
	{
		$this->staticHeaderConfiguration = $this->getStaticHeaderConfiguration($this->params);

		if (empty($this->staticHeaderConfiguration))
		{
			return;
		}

		foreach ($this->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);
		}
	}
}

No other release has this exact content. See every version of this file.