CVE-2021-42134 (published 2021-10-11T01:15Z)

The Unicorn framework before 0.36.1 for Django allows XSS via a component. NOTE: this issue exists because of an incomplete fix for CVE-2021-42053.

Severity: MEDIUM
CVSS v2 base score: 4.3 (AV:N/AC:M/Au:N/C:N/I:P/A:N)
CVSS v3 base score: 6.1, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/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/adamghill/django-unicorn
commit_details: repo_url: https://github.com/adamghill/django-unicorn
author: Adam Hill
author_date: 2021-10-08 22:09:35-04:00
msg: More complete handling for preventing XSS attacks.
repository: repo_url: https://github.com/adamghill/django-unicorn
repo_name: adamghill/django-unicorn
description: The magical reactive component framework for Django ✨
repo_language: Python
owner: adamghill
file_changes: filename: unicorn_template_response.py
change_type: ModificationType.MODIFY
diff: @@ -1,10 +1,10 @@
 import logging
 
 from django.template.response import TemplateResponse
-from django.utils.safestring import mark_safe
 
 import orjson
 from bs4 import BeautifulSoup
+from bs4.dammit import EntitySubstitution
 from bs4.element import Tag
 from bs4.formatter import HTMLFormatter
 
@@ -22,6 +22,9 @@ class UnsortedAttributes(HTMLFormatter):
     Prevent beautifulsoup from re-ordering attributes.
     """
 
+    def __init__(self):
+        super().__init__(entity_substitution=EntitySubstitution.substitute_html)
+
     def attributes(self, tag: Tag):
         for k, v in tag.attrs.items():
             yield k, v
@@ -115,7 +118,6 @@ class UnicornTemplateResponse(TemplateResponse):
                     root_element.insert_after(t)
 
         rendered_template = UnicornTemplateResponse._desoupify(soup)
-        rendered_template = mark_safe(rendered_template)
         self.component.rendered(rendered_template)
 
         response.content = rendered_template

programming_language: Python
filename: unicorn_view.py
change_type: ModificationType.MODIFY
diff: @@ -10,7 +10,6 @@ from django.core.cache import caches
 from django.core.exceptions import ImproperlyConfigured
 from django.db.models import Model
 from django.http import HttpRequest
-from django.utils.html import conditional_escape
 from django.views.generic.base import TemplateView
 
 from cachetools.lru import LRUCache
@@ -341,14 +340,6 @@ class UnicornView(TemplateView):
                     if field_name in frontend_context_variables:
                         del frontend_context_variables[field_name]
 
-        safe_fields = []
-        # Keep a list of fields that are safe to not sanitize from `frontend_context_variables`
-        if hasattr(self, "Meta") and hasattr(self.Meta, "safe"):
-            if isinstance(self.Meta.safe, Sequence):
-                for field_name in self.Meta.safe:
-                    if field_name in frontend_context_variables:
-                        safe_fields.append(field_name)
-
         # Add cleaned values to `frontend_content_variables` based on the widget in form's fields
         form = self._get_form(attributes)
 
@@ -372,18 +363,6 @@ class UnicornView(TemplateView):
                         ):
                             frontend_context_variables[key] = value
 
-        for (
-            frontend_context_variable_key,
-            frontend_context_variable_value,
-        ) in frontend_context_variables.items():
-            if (
-                isinstance(frontend_context_variable_value, str)
-                and frontend_context_variable_key not in safe_fields
-            ):
-                frontend_context_variables[frontend_context_variable_key] = escape(
-                    frontend_context_variable_value
-                )
-
         encoded_frontend_context_variables = serializer.dumps(
             frontend_context_variables
         )

programming_language: Python
filename: __init__.py
change_type: ModificationType.MODIFY
diff: @@ -1,11 +1,12 @@
 import copy
 import logging
 from functools import wraps
-from typing import Dict
+from typing import Dict, Sequence
 
 from django.core.cache import caches
 from django.http import HttpRequest, JsonResponse
 from django.http.response import HttpResponseNotModified
+from django.utils.safestring import mark_safe
 from django.views.decorators.csrf import csrf_protect
 from django.views.decorators.http import require_POST
 
@@ -126,6 +127,20 @@ def _process_component_request(
     # Re-load frontend context variables to deal with non-serializable properties
     component_request.data = orjson.loads(component.get_frontend_context_variables())
 
+    # Get set of attributes that should be marked as `safe`
+    safe_fields = []
+    if hasattr(component, "Meta") and hasattr(component.Meta, "safe"):
+        if isinstance(component.Meta.safe, Sequence):
+            for field_name in component.Meta.safe:
+                if field_name in component._attributes().keys():
+                    safe_fields.append(field_name)
+
+    # Mark safe attributes as such before rendering
+    for field_name in safe_fields:
+        value = getattr(component, field_name)
+        if isinstance(value, str):
+            setattr(component, field_name, mark_safe(value))
+
     # Send back all available data for reset or refresh actions
     updated_data = component_request.data
 

programming_language: Python
filename: test_component.py
change_type: ModificationType.MODIFY
diff: @@ -82,39 +82,6 @@ def test_get_frontend_context_variables(component):
     assert frontend_context_variables_dict.get("name") == "World"
 
 
-def test_get_frontend_context_variables_xss(component):
-    # Set component.name to a potential XSS attack
-    component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
-
-    frontend_context_variables = component.get_frontend_context_variables()
-    frontend_context_variables_dict = orjson.loads(frontend_context_variables)
-    assert len(frontend_context_variables_dict) == 1
-    assert (
-        frontend_context_variables_dict.get("name")
-        == "&lt;a&gt;&lt;style&gt;@keyframes x{}&lt;/style&gt;&lt;a style=&quot;animation-name:x&quot; onanimationend=&quot;alert(1)&quot;&gt;&lt;/a&gt;"
-    )
-
-
-def test_get_frontend_context_variables_safe(component):
-    # Set component.name to a potential XSS attack
-    component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
-
-    class Meta:
-        safe = [
-            "name",
-        ]
-
-    setattr(component, "Meta", Meta())
-
-    frontend_context_variables = component.get_frontend_context_variables()
-    frontend_context_variables_dict = orjson.loads(frontend_context_variables)
-    assert len(frontend_context_variables_dict) == 1
-    assert (
-        frontend_context_variables_dict.get("name")
-        == '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
-    )
-
-
 def test_get_context_data(component):
     context_data = component.get_context_data()
     assert (

programming_language: Python
filename: test_unicorn_template_response.py
change_type: ModificationType.MODIFY
diff: @@ -1,7 +1,10 @@
 import pytest
 from bs4 import BeautifulSoup
 
-from django_unicorn.components.unicorn_template_response import get_root_element
+from django_unicorn.components.unicorn_template_response import (
+    UnicornTemplateResponse,
+    get_root_element,
+)
 
 
 def test_get_root_element():
@@ -44,3 +47,14 @@ def test_get_root_element_no_element():
         actual = get_root_element(soup)
 
         assert str(actual) == expected
+
+
+def test_desoupify():
+    html = "<div>&lt;a&gt;&lt;style&gt;@keyframes x{}&lt;/style&gt;&lt;a style=&quot;animation-name:x&quot; onanimationend=&quot;alert(1)&quot;&gt;&lt;/a&gt;!\n</div>\n\n<script type=\"application/javascript\">\n  window.addEventListener('DOMContentLoaded', (event) => {\n    Unicorn.addEventListener('updated', (component) => console.log('got updated', component));\n  });\n</script>"
+    expected = "<div>&lt;a&gt;&lt;style&gt;@keyframes x{}&lt;/style&gt;&lt;a style=\"animation-name:x\" onanimationend=\"alert(1)\"&gt;&lt;/a&gt;!\n</div>\n<script type=\"application/javascript\">\n  window.addEventListener('DOMContentLoaded', (event) => {\n    Unicorn.addEventListener('updated', (component) => console.log('got updated', component));\n  });\n</script>"
+
+    soup = BeautifulSoup(html, "html.parser")
+
+    actual = UnicornTemplateResponse._desoupify(soup)
+
+    assert expected == actual

programming_language: Python
filename: test_component_kwargs.html
change_type: ModificationType.MODIFY
diff: @@ -1,3 +1,3 @@
 <div>
-    ->{{ hello }}<-
+  <b>{{ hello }}</b>
 </div>
\ No newline at end of file

programming_language: SQL
filename: test_component_kwargs_with_html_entity.html
change_type: ModificationType.ADD
diff: @@ -0,0 +1,3 @@
+<div>
+  ->{{ hello }}<-
+</div>
\ No newline at end of file

programming_language: Markdown
filename: test_component_variable.html
change_type: ModificationType.ADD
diff: @@ -0,0 +1,3 @@
+<div>
+  {{ hello }}
+</div>
\ No newline at end of file

programming_language: Markdown
filename: test_unicorn_render.py
change_type: ModificationType.MODIFY
diff: @@ -23,6 +23,15 @@ class FakeComponentKwargs(UnicornView):
         self.hello = kwargs.get("test_kwarg")
 
 
+class FakeComponentKwargsWithHtmlEntity(UnicornView):
+    template_name = "templates/test_component_kwargs_with_html_entity.html"
+    hello = "world"
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(**kwargs)
+        self.hello = kwargs.get("test_kwarg")
+
+
 class FakeComponentModel(UnicornView):
     template_name = "templates/test_component_model.html"
     model_id = None
@@ -55,7 +64,7 @@ def test_unicorn_render_kwarg():
     context = {}
     actual = unicorn_node.render(context)
 
-    assert "->tested!<-" in actual
+    assert "<b>tested!</b>" in actual
 
 
 def test_unicorn_render_context_variable():
@@ -67,7 +76,19 @@ def test_unicorn_render_context_variable():
     context = {"test_var": {"nested": "variable!"}}
     actual = unicorn_node.render(context)
 
-    assert "->variable!<-" in actual
+    assert "<b>variable!</b>" in actual
+
+
+def test_unicorn_render_with_invalid_html():
+    token = Token(
+        TokenType.TEXT,
+        "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargsWithHtmlEntity' test_kwarg=test_var.nested",
+    )
+    unicorn_node = unicorn(None, token)
+    context = {"test_var": {"nested": "variable!"}}
+    actual = unicorn_node.render(context)
+
+    assert "-&gt;variable!&lt;-" in actual
 
 
 def test_unicorn_render_parent(settings):

programming_language: Python
filename: test_sync_input.py
change_type: ModificationType.MODIFY
diff: @@ -1,5 +1,3 @@
-import orjson
-
 from tests.views.message.utils import post_and_get_response
 
 

programming_language: Python
filename: test_process_component_request.py
change_type: ModificationType.ADD
diff: @@ -0,0 +1,51 @@
+from django_unicorn.components import UnicornView
+from tests.views.message.utils import post_and_get_response
+
+
+class FakeComponent(UnicornView):
+    template_name = "templates/test_component_variable.html"
+
+    hello = ""
+
+
+class FakeComponentSafe(UnicornView):
+    template_name = "templates/test_component_variable.html"
+
+    hello = ""
+
+    class Meta:
+        safe = ("hello",)
+
+
+def test_html_entities_encoded(client):
+    data = {"hello": "test"}
+    action_queue = [
+        {"payload": {"name": "hello", "value": "<b>test1</b>"}, "type": "syncInput",}
+    ]
+    response = post_and_get_response(
+        client,
+        url="/message/tests.views.test_process_component_request.FakeComponent",
+        data=data,
+        action_queue=action_queue,
+    )
+
+    assert not response["errors"]
+    assert response["data"].get("hello") == "<b>test1</b>"
+    assert "&lt;b&gt;test1&lt;/b&gt;" in response["dom"]
+
+
+def test_safe_html_entities_not_encoded(client):
+    data = {"hello": "test"}
+    action_queue = [
+        {"payload": {"name": "hello", "value": "<b>test1</b>"}, "type": "syncInput",}
+    ]
+    response = post_and_get_response(
+        client,
+        url="/message/tests.views.test_process_component_request.FakeComponentSafe",
+        data=data,
+        action_queue=action_queue,
+    )
+
+    assert not response["errors"]
+    assert response["data"].get("hello") == "<b>test1</b>"
+    assert "<b>test1</b>" in response["dom"]

programming_language: Python