CVE-2022-0704 (published 2022-03-16T10:15Z)

Cross-site Scripting (XSS) - Stored in GitHub repository pimcore/pimcore prior to 10.4.0.

Severity: LOW
CVSS v2 base score: 3.5 (AV:N/AC:M/Au:S/C:N/I:P/A:N)
CVSS v3 base score: 5.4, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/pimcore/pimcore
commit_details: repo_url: https://github.com/pimcore/pimcore
author: Divesh Pahuja
author_date: 2022-03-14 14:19:09+01:00
msg: [Admin] Security - Add handler to enable Content Security Policy (#11447)

* [Admin] Security - Add handler to enable Content Security Policy

* [Admin] Security - Add handler to enable Content Security Policy

* [Admin] Security - Add handler to enable Content Security Policy - fix document preview

* [Admin] Security - Add handler to enable Content Security Policy - add docs

* [Admin] Security - Add handler to enable Content Security Policy - review changes

* [Admin] Security - Add handler to enable Content Security Policy - review changes

* [Admin] Security - Add handler to enable Content Security Policy - review changes

* [Admin] Security - Add handler to enable Content Security Policy - review changes

* added missing config node + micro optimizations

Co-authored-by: Bernhard Rusch <bernhard.rusch@elements.at>
repository: repo_url: https://github.com/pimcore/pimcore
repo_name: pimcore/pimcore
description: Core Framework for the Open Source Data & Experience Management Platform (PIM, MDM, CDP, DAM, DXP/CMS & Digital Commerce)
repo_language: PHP
owner: pimcore
file_changes: filename: ContentSecurityPolicyUrlsPass.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,45 @@
+<?php
+
+declare(strict_types=1);
+
+/**
+ * Pimcore
+ *
+ * This source file is available under two different licenses:
+ * - GNU General Public License version 3 (GPLv3)
+ * - Pimcore Commercial License (PCL)
+ * Full copyright and license information is available in
+ * LICENSE.md which is distributed with this source code.
+ *
+ * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
+ * @license    http://www.pimcore.org/license     GPLv3 and PCL
+ */
+
+namespace Pimcore\Bundle\AdminBundle\DependencyInjection\Compiler;
+
+use Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler;
+use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
+use Symfony\Component\DependencyInjection\ContainerBuilder;
+
+/**
+ * @internal
+ */
+final class ContentSecurityPolicyUrlsPass implements CompilerPassInterface
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function process(ContainerBuilder $container)
+    {
+        $definition = $container->getDefinition(ContentSecurityPolicyHandler::class);
+
+
+        $config = $container->getParameter('pimcore_admin.config');
+
+        if (count($config['admin_csp_header']['additional_urls'])) {
+            foreach ($config['admin_csp_header']['additional_urls'] as $additionalUrlsKey => $additionalUrlsArr) {
+                $definition->addMethodCall('addAllowedUrls', [$additionalUrlsKey, $additionalUrlsArr]);
+            }
+        }
+    }
+}

programming_language: PHP
filename: Configuration.php
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,7 @@
 
 namespace Pimcore\Bundle\AdminBundle\DependencyInjection;
 
+use Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler;
 use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
 use Symfony\Component\Config\Definition\Builder\TreeBuilder;
 use Symfony\Component\Config\Definition\ConfigurationInterface;
@@ -54,6 +55,42 @@ final class Configuration implements ConfigurationInterface
                     ->end()
                 ->end()
             ->end()
+            ->arrayNode('admin_csp_header')
+                ->canBeEnabled()
+                ->info('Can be used to enable or disable the Content Security Policy headers.')
+                ->children()
+                    ->arrayNode('additional_urls')
+                        ->addDefaultsIfNotSet()
+                        ->normalizeKeys(false)
+                        ->children()
+                            ->arrayNode(ContentSecurityPolicyHandler::DEFAULT_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::IMG_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::SCRIPT_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::STYLE_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::CONNECT_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::FONT_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::MEDIA_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                            ->arrayNode(ContentSecurityPolicyHandler::FRAME_OPT)
+                                ->scalarPrototype()->end()
+                            ->end()
+                        ->end()
+                    ->end()
+                ->end()
+            ->end()
             ->scalarNode('custom_admin_path_identifier')
                 ->defaultNull()
                 ->validate()

programming_language: CoffeeScript
filename: AdminSecurityListener.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,83 @@
+<?php
+
+/**
+ * Pimcore
+ *
+ * This source file is available under two different licenses:
+ * - GNU General Public License version 3 (GPLv3)
+ * - Pimcore Commercial License (PCL)
+ * Full copyright and license information is available in
+ * LICENSE.md which is distributed with this source code.
+ *
+ * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
+ * @license    http://www.pimcore.org/license     GPLv3 and PCL
+ */
+
+namespace Pimcore\Bundle\AdminBundle\EventListener;
+
+use Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler;
+use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
+use Pimcore\Config;
+use Pimcore\Http\Request\Resolver\PimcoreContextResolver;
+use Pimcore\Http\RequestHelper;
+use Symfony\Component\EventDispatcher\EventSubscriberInterface;
+use Symfony\Component\HttpKernel\Event\ResponseEvent;
+use Symfony\Component\HttpKernel\KernelEvents;
+
+/**
+ * @internal
+ */
+class AdminSecurityListener implements EventSubscriberInterface
+{
+    use PimcoreContextAwareTrait;
+
+    /**
+     * @param ContentSecurityPolicyHandler $contentSecurityPolicyHandler
+     */
+    public function __construct(
+        protected RequestHelper $requestHelper,
+        protected ContentSecurityPolicyHandler $contentSecurityPolicyHandler,
+        protected Config $config
+    )
+    {
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function getSubscribedEvents()
+    {
+        return [
+            KernelEvents::RESPONSE => 'onKernelResponse',
+        ];
+    }
+
+    public function onKernelResponse(ResponseEvent $event)
+    {
+        if (!$this->config['admin_csp_header']['enabled']) {
+            return;
+        }
+
+        $request = $event->getRequest();
+
+        if (!$event->isMainRequest()) {
+            return;
+        }
+
+        if (!$this->matchesPimcoreContext($request, PimcoreContextResolver::CONTEXT_ADMIN)) {
+            return;
+        }
+
+        if ($this->requestHelper->isFrontendRequestByAdmin($request)) {
+            return;
+        }
+
+        $response = $event->getResponse();
+
+        // set CSP header with random nonce string to the response
+        $response->headers->set("Content-Security-Policy", $this->contentSecurityPolicyHandler->getCspHeader());
+    }
+
+}
+
+

programming_language: PHP
filename: PimcoreAdminBundle.php
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,7 @@
 
 namespace Pimcore\Bundle\AdminBundle;
 
+use Pimcore\Bundle\AdminBundle\DependencyInjection\Compiler\ContentSecurityPolicyUrlsPass;
 use Pimcore\Bundle\AdminBundle\DependencyInjection\Compiler\GDPRDataProviderPass;
 use Pimcore\Bundle\AdminBundle\DependencyInjection\Compiler\ImportExportLocatorsPass;
 use Pimcore\Bundle\AdminBundle\DependencyInjection\Compiler\SerializerPass;
@@ -44,6 +45,7 @@ class PimcoreAdminBundle extends Bundle
         $container->addCompilerPass(new GDPRDataProviderPass());
         $container->addCompilerPass(new ImportExportLocatorsPass());
         $container->addCompilerPass(new TranslationServicesPass());
+        $container->addCompilerPass(new ContentSecurityPolicyUrlsPass());
 
         /** @var SecurityExtension $extension */
         $extension = $container->getExtension('security');

programming_language: PHP
filename: event_listeners.yaml
change_type: ModificationType.MODIFY
diff: @@ -8,6 +8,7 @@ services:
     # SECURITY
     #
 
+    Pimcore\Bundle\AdminBundle\EventListener\AdminSecurityListener: ~
     Pimcore\Bundle\AdminBundle\EventListener\BruteforceProtectionListener: ~
 
     Pimcore\Bundle\AdminBundle\EventListener\AdminAuthenticationDoubleCheckListener:

programming_language: PHP
filename: security_services.yaml
change_type: ModificationType.MODIFY
diff: @@ -65,6 +65,13 @@ services:
         tags:
             - { name: monolog.logger, channel: security }
 
+    Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler:
+        public: true
+        calls:
+            - [ setLogger, [ '@logger' ] ]
+        tags:
+            - { name: monolog.logger, channel: security }
+
     # user checker checking admin users for validity
     Pimcore\Bundle\AdminBundle\Security\User\UserChecker: ~
 

programming_language: CoffeeScript
filename: preview.js
change_type: ModificationType.MODIFY
diff: @@ -31,8 +31,6 @@ pimcore.document.pages.preview = Class.create({
 
         if (this.layout == null) {
 
-            var iframeOnLoad = "pimcore.globalmanager.get('document_" + this.page.id + "').preview.iFrameLoaded()";
-
             // preview switcher only for pages not for emails
             var tbar = [];
             if(this.page.getType() == "page") {
@@ -124,9 +122,16 @@ pimcore.document.pages.preview = Class.create({
                 scrollable: false,
                 bodyStyle: "background:#323232;",
                 bodyCls: "pimcore_overflow_scrolling",
-                html: '<iframe src="about:blank" onload="' + iframeOnLoad + '" frameborder="0" ' +
+                html: '<iframe src="about:blank" frameborder="0" ' +
                     'style="width: 100%;background: #fff;" id="' + this.iframeName + '" ' +
-                    'name="' + this.iframeName + '"></iframe>'
+                    'name="' + this.iframeName + '"></iframe>',
+                listeners: {
+                    afterrender: function () {
+                        Ext.get(this.getIframe()).on('load', function () {
+                            this.iFrameLoaded();
+                        }.bind(this));
+                    }.bind(this)
+                }
             });
 
             this.timeSlider = Ext.create('Ext.slider.Single', {

programming_language: JavaScript
filename: index.html.twig
change_type: ModificationType.MODIFY
diff: @@ -88,7 +88,7 @@
 
     <title>{{ settings.hostname }} :: Pimcore</title>
 
-    <script>
+    <script {{ pimcore_csp.getNonceHtmlAttribute()|raw }}>
         var pimcore = {}; // namespace
 
         // hide symfony toolbar by default
@@ -98,8 +98,8 @@
         }
     </script>
 
-    <script src="{{ asset('bundles/fosjsrouting/js/router.js') }}"></script>
-    <script src="{{ path('fos_js_routing_js', {'callback' : 'fos.Router.setData'}) }}"></script>
+    <script src="{{ asset('bundles/fosjsrouting/js/router.js') }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
+    <script src="{{ path('fos_js_routing_js', {'callback' : 'fos.Router.setData'}) }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
 </head>
 
 <body class="pimcore_version_10" data-app-env="{{ app.environment }}">
@@ -698,17 +698,17 @@
 
 <!-- some javascript -->
 {# pimcore constants #}
-<script>
+<script {{ pimcore_csp.getNonceHtmlAttribute()|raw }}>
     pimcore.settings = {{(settings|json_encode(constant('JSON_PRETTY_PRINT'))|raw)}};
 </script>
 
-<script src="{{ path('pimcore_admin_misc_jsontranslationssystem', {'language': language, '_dc': settings.build }) }}"></script>
-<script src="{{ path('pimcore_admin_user_getcurrentuser', {'_dc': settings.build }) }}"></script>
-<script src="{{ path('pimcore_admin_misc_availablelanguages', {'_dc': settings.build }) }}"></script>
+<script src="{{ path('pimcore_admin_misc_jsontranslationssystem', {'language': language, '_dc': settings.build }) }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
+<script src="{{ path('pimcore_admin_user_getcurrentuser', {'_dc': settings.build }) }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
+<script src="{{ path('pimcore_admin_misc_availablelanguages', {'_dc': settings.build }) }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
 
 <!-- library scripts -->
 {% for scriptUrl in scriptLibs %}
-    <script src="/bundles/pimcoreadmin/js/{{ scriptUrl }}?_dc={{ settings.build }}"></script>
+    <script src="/bundles/pimcoreadmin/js/{{ scriptUrl }}?_dc={{ settings.build }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
 {% endfor %}
 
 <!-- internal scripts -->
@@ -734,7 +734,7 @@
 <!-- bundle scripts -->
 {% if settings.disableMinifyJs %}
     {% for pluginJsPath in pluginJsPaths %}
-        <script src="{{ pluginJsPath }}?_dc={{ pluginDcValue }}"></script>
+        <script src="{{ pluginJsPath }}?_dc={{ pluginDcValue }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
     {% endfor %}
 {% else %}
     {{ pimcore_minimize_scripts(pluginJsPaths)|raw }}
@@ -745,6 +745,6 @@
 {% endfor %}
 
 {#  MUST BE THE LAST LINE  #}
-<script src="/bundles/pimcoreadmin/js/pimcore/startup.js?_dc={{ settings.build }}"></script>
+<script src="/bundles/pimcoreadmin/js/pimcore/startup.js?_dc={{ settings.build }}" {{ pimcore_csp.getNonceHtmlAttribute()|raw }}></script>
 </body>
 </html>

programming_language: HTML
filename: ContentSecurityPolicyHandler.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,155 @@
+<?php
+
+/**
+ * Pimcore
+ *
+ * This source file is available under two different licenses:
+ * - GNU General Public License version 3 (GPLv3)
+ * - Pimcore Commercial License (PCL)
+ * Full copyright and license information is available in
+ * LICENSE.md which is distributed with this source code.
+ *
+ * @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
+ * @license    http://www.pimcore.org/license     GPLv3 and PCL
+ */
+
+namespace Pimcore\Bundle\AdminBundle\Security;
+
+use Pimcore\Config;
+use Psr\Log\LoggerAwareInterface;
+use Psr\Log\LoggerAwareTrait;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+
+/**
+ * @internal
+ */
+class ContentSecurityPolicyHandler implements LoggerAwareInterface
+{
+    use LoggerAwareTrait;
+
+    /** @var String|null */
+    private ?string $nonce = null;
+
+    public const DEFAULT_OPT = 'default-src';
+    public const IMG_OPT = 'img-src';
+    public const SCRIPT_OPT = 'script-src';
+    public const STYLE_OPT = 'style-src';
+    public const CONNECT_OPT = 'connect-src';
+    public const FONT_OPT = 'font-src';
+    public const MEDIA_OPT = 'media-src';
+    public const FRAME_OPT = 'frame-src';
+
+    /**
+     * @var array
+     */
+    private array $allowedUrls = [
+        self::CONNECT_OPT => [
+            'https://liveupdate.pimcore.org/update-check', //AdminBundle statistics & update-check service
+            'https://nominatim.openstreetmap.org/' //CoreBundle geocoding_url_template
+        ],
+    ];
+
+    public function __construct(protected Config $config, protected array $cspHeaderOptions = [])
+    {
+        $resolver = new OptionsResolver();
+        $this->configureOptions($resolver);
+
+        $this->cspHeaderOptions = $resolver->resolve($cspHeaderOptions);
+    }
+
+    public function configureOptions(OptionsResolver $resolver)
+    {
+        $resolver->setDefaults([
+            self::DEFAULT_OPT => "'self'",
+            self::IMG_OPT => "* data: blob:",
+            self::MEDIA_OPT => "'self' data:",
+            self::SCRIPT_OPT => "'self' 'nonce-" . $this->getNonce() . "' 'unsafe-inline' 'unsafe-eval'",
+            self::STYLE_OPT => "'self' 'unsafe-inline'",
+            self::FRAME_OPT => "'self'",
+            self::CONNECT_OPT => "'self' blob:",
+            self::FONT_OPT => "'self'",
+        ]);
+    }
+
+    /**
+     * @return string
+     */
+    public function getCspHeader(): string
+    {
+        $cspHeaderOptions = array_map(function ($k, $v) {
+            return "$k $v " . $this->getAllowedUrls($k);
+        }, array_keys($this->cspHeaderOptions), array_values($this->cspHeaderOptions));
+
+        return implode(';' ,$cspHeaderOptions);
+    }
+
+    /**
+     * @param string $key
+     * @param bool $flatten
+     *
+     * @return array|string
+     */
+    private function getAllowedUrls(string $key, bool $flatten = true): array|string
+    {
+        if (!$flatten) {
+            return $this->allowedUrls[$key] ?? [];
+        }
+
+        return isset($this->allowedUrls[$key]) && is_array($this->allowedUrls[$key]) ? implode(' ', $this->allowedUrls[$key]) : '';
+    }
+
+    /**
+     * @param string $key
+     * @param array $value
+     *
+     * @return $this
+     */
+    public function addAllowedUrls(string $key, array $value): self
+    {
+        if(!isset($this->allowedUrls[$key])) {
+            $this->allowedUrls[$key] = [];
+        }
+
+        foreach ($value as $val) {
+            $this->allowedUrls[$key][] = $val;
+        }
+
+        return $this;
+    }
+
+    /**
+     * @param string $key
+     * @param string $value
+     *
+     * @return $this
+     */
+    public function setCspHeader(string $key, string $value): self
+    {
+        $this->cspHeaderOptions[$key] = $value;
+
+        return $this;
+    }
+
+    /**
+     *
+     * @return string
+     */
+    public function getNonceHtmlAttribute(): string
+    {
+        return $this->config['admin_csp_header']['enabled'] ? ' nonce="' . $this->getNonce() . '"' : '';
+    }
+
+    /**
+     * Generates a random nonce parameter.
+     *
+     * @return string
+     */
+    private function getNonce(): string
+    {
+        if (!$this->nonce) {
+            $this->nonce = generateRandomSymfonySecret();
+        }
+
+        return $this->nonce;
+    }
+}

programming_language: PHP
filename: default.yaml
change_type: ModificationType.MODIFY
diff: @@ -59,6 +59,7 @@ twig:
         # this is only here for compatibility/dev reasons and may be removed later
         container: '@service_container'
         pimcore_csrf: '@Pimcore\Bundle\AdminBundle\Security\CsrfProtectionHandler'
+        pimcore_csp: '@Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler'
     paths:
         '%kernel.project_dir%/templates': App
 

programming_language: PHP
filename: back-office.html.twig
change_type: ModificationType.MODIFY
diff: @@ -76,7 +76,7 @@
         {{ pimcore_head_script() }}
     {% endblock %}
 
-    <script>
+    <script {{ pimcore_csp.getNonceHtmlAttribute()|raw }}>
         var pimcore = parent.pimcore;
         var popups = document.getElementsByClassName('popup-modal');
         for (var i = 0; i < popups.length; i++) {

programming_language: HTML
filename: 75_Security_Concept.md
change_type: ModificationType.MODIFY
diff: @@ -25,6 +25,42 @@ it easy and comfortable to keep all dependencies of Pimcore and your project up-
 Since Pimcore is a Symfony application, it can utilize all Symfony tools, like the 
 [Symfony Security Checker](https://symfony.com/doc/5.2/security/security_checker.html). 
 
+### Content Security Policy
+Pimcore provides a Content Security Policy handler, which enables an additional security layer to protect from certain attacks like Cross-Site Scripting (XSS) and data injection and so on, by adding `Content-Security-Policy` HTTP response header with [nonce](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) to every request in Admin interface. The generated nonce encoded string is matched with the one provided in link or inline javascript, which allows them to be executed safely. 
+
+Read more about [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).
+
+To enable CSP, add a custom configuration in `config/config.yaml`:
+```yaml
+# config/config.yaml
+pimcore_admin:
+    admin_csp_header:
+        enabled: true
+```
+
+And to allow external urls for each directive, you can provide a list in the configuration:
+```yaml
+# config/config.yaml
+pimcore_admin:
+    admin_csp_header:
+        additional_urls:
+            script_src:
+                - 'https://oreo.cat/scripts/meow.js' 
+                - 'https://bagheera.cat/*'
+            style-src:
+                - 'https://oreo.cat/scripts/meow.css'
+```
+
+In case, you are using third party bundles or custom implementation that extends the admin backend interface with custom views then you would need to use generated nonce string in your scripts.
+If a script does not contain valid a nonce, then it is stopped from being executed wih a warning in console like:
+
+`Refused to execute inline script because it violates the following Content Security Policy directive: ...`
+
+This issue can be resolved either by using Pimcore [Headscript extension](../02_MVC/02_Template/02_Template_Extensions/03_HeadScript.md) or add nonce script to inline scripts as follows:
+
+```twig
+<script {{ pimcore_csp.getNonceHtmlAttribute()|raw }}>
+```
 
 ### Handling Security Issues
 In the case of a security issue/vulnerability in the Pimcore core framework, we handle them with the following procedure: 

programming_language: Markdown
filename: HeadScript.php
change_type: ModificationType.MODIFY
diff: @@ -38,6 +38,7 @@
 
 namespace Pimcore\Twig\Extension\Templating;
 
+use Pimcore\Bundle\AdminBundle\Security\ContentSecurityPolicyHandler;
 use Pimcore\Event\FrontendEvents;
 use Pimcore\Twig\Extension\Templating\Placeholder\CacheBusterAware;
 use Pimcore\Twig\Extension\Templating\Placeholder\Container;
@@ -482,6 +483,9 @@ class HeadScript extends CacheBusterAware implements RuntimeExtensionInterface
             }
         }
 
+        /** @var ContentSecurityPolicyHandler $cspHandler */
+        $cspHandler = \Pimcore::getContainer()->get(ContentSecurityPolicyHandler::class);
+        $attrString .= $cspHandler->getNonceHtmlAttribute();
         $addScriptEscape = !(isset($item->attributes['noescape']) && filter_var($item->attributes['noescape'], FILTER_VALIDATE_BOOLEAN));
 
         $html = '<script' . $attrString . '>';

programming_language: PHP