CVE-2023-48310 (published 2023-11-20T23:15Z)

TestingPlatform is a testing platform for Internet Security Standards. Prior to version 2.1.1, user input is not filtered correctly. Nmap options are accepted. In this particular case, the option to create log files is accepted in addition to a host name (and even without). A log file is created at the location specified. These files are created as root. If the file exists, the existing file is being rendered useless. This can result in denial of service. Additionally, input for scanning can be any CIDR blocks passed to nmap. An attacker can scan 0.0.0.0/0 or even local networks. Version 2.1.1 contains a patch for this issue.

CVSS v3 base score: 7.5, HIGH (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H)

Weakness information:
cwe_id: CWE-20
cwe_name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
extended_description: 
	   Input validation is a frequently-used technique
	   for checking potentially dangerous inputs in order to
	   ensure that the inputs are safe for processing within the
	   code, or when communicating with other components.  When
	   software does not validate input properly, an attacker is
	   able to craft the input in a form that is not expected by
	   the rest of the application. This will lead to parts of the
	   system receiving unintended input, which may result in
	   altered control flow, arbitrary control of a resource, or
	   arbitrary code execution.
	   Input validation is not the only technique for
	   processing input, however.  Other techniques attempt to
	   transform potentially-dangerous input into something safe, such
	   as filtering (CWE-790) - which attempts to remove dangerous
	   inputs - or encoding/escaping (CWE-116), which attempts to
	   ensure that the input is not misinterpreted when it is included
	   in output to another component. Other techniques exist as well
	   (see CWE-138 for more examples.)
	   Input validation can be applied to:
	   
	     raw data - strings, numbers, parameters, file contents, etc.
	     metadata - information about the raw data, such as headers or size
	   
	   Data can be simple or structured.  Structured data
	   can be composed of many nested layers, composed of
	   combinations of metadata and raw data, with other simple or
	   structured data.
	   Many properties of raw data or metadata may need
	   to be validated upon entry into the code, such
	   as:
	   
	     specified quantities such as size, length, frequency, price, rate, number of operations, time, etc.
	     implied or derived quantities, such as the actual size of a file instead of a specified size
	     indexes, offsets, or positions into more complex data structures
	     symbolic keys or other elements into hash tables, associative arrays, etc.
	     well-formedness, i.e. syntactic correctness - compliance with expected syntax 
	     lexical token correctness - compliance with rules for what is treated as a token
	     specified or derived type - the actual type of the input (or what the input appears to be)
	     consistency - between individual data elements, between raw data and metadata, between references, etc.
	     conformance to domain-specific rules, e.g. business logic 
	     equivalence - ensuring that equivalent inputs are treated the same
	     authenticity, ownership, or other attestations about the input, e.g. a cryptographic signature to prove the source of the data
	   
	   Implied or derived properties of data must often
	   be calculated or inferred by the code itself.  Errors in
	   deriving properties may be considered a contributing factor
	   to improper input validation.
	   
	   Note that "input validation" has very different
	   meanings to different people, or within different
	   classification schemes.  Caution must be used when
	   referencing this CWE entry or mapping to it.  For example,
	   some weaknesses might involve inadvertently giving control
	   to an attacker over an input when they should not be able
	   to provide an input at all, but sometimes this is referred
	   to as input validation.
	   Finally, it is important to emphasize that the
	   distinctions between input validation and output escaping
	   are often blurred, and developers must be careful to
	   understand the difference, including how input validation
	   is not always sufficient to prevent vulnerabilities,
	   especially when less stringent data types must be
	   supported, such as free-form text. Consider a SQL injection
	   scenario in which a person's last name is inserted into a
	   query. The name "O'Reilly" would likely pass the validation
	   step since it is a common last name in the English
	   language. However, this valid name cannot be directly
	   inserted into the database because it contains the "'"
	   apostrophe character, which would need to be escaped or
	   otherwise transformed. In this case, removing the
	   apostrophe might reduce the risk of SQL injection, but it
	   would produce incorrect behavior because the wrong name
	   would be recorded.
       
         

Fix information:
repo_url: https://github.com/NC3-LU/TestingPlatform
commit_details: repo_url: https://github.com/NC3-LU/TestingPlatform
author: Cédric Bonhomme
author_date: 2023-11-20 23:05:46+01:00
msg: chg: [security] Added new domain name validator used in the file testing/helpers.py (GHSA-9fhc-f3mr-w6h6).
repository: repo_url: https://github.com/NC3-LU/TestingPlatform
repo_name: NC3-LU/TestingPlatform
description: A testing platform for Internet Security Standards by @NC3-LU
repo_language: Python
owner: NC3-LU
file_changes: filename: serializers.py
change_type: ModificationType.MODIFY
diff: @@ -4,6 +4,7 @@ from rest_framework import serializers
 from authentication.models import User
 from automation.models import HttpAutomatedTest, PingAutomatedTest
 from testing.models import TlsScanHistory
+from testing.validators import domain_name
 
 #
 # Model: User
@@ -118,12 +119,21 @@ class IPv6Serializer(serializers.Serializer):
 
 class DomainNameSerializer(serializers.Serializer):
     domain_name = serializers.CharField(
-        max_length=200, required=True, help_text="Domain name."
+        max_length=200,
+        required=True,
+        help_text="Domain name.",
+        validators=[domain_name],
     )
 
     class Meta:
         fields = ["domain_name"]
 
+    def validate_domain_name(self, value):
+        """
+        Check that value is a valid domain name.
+        """
+        return domain_name(value)
+
 
 class DomainNameAndServiceSerializer(serializers.Serializer):
     domain_name = serializers.CharField(

programming_language: Python
filename: validators.py
change_type: ModificationType.DELETE
diff: @@ -1,36 +0,0 @@
-import re
-
-from rest_framework.serializers import ValidationError
-
-pattern = re.compile(
-    r"^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|"
-    r"([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|"
-    r"([a-zA-Z0-9][-_.a-zA-Z0-9]{0,61}[a-zA-Z0-9]))\."
-    r"([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}.[a-zA-Z]{2,3})$"
-)
-
-
-# class DomainName:
-#     def __init__(self, fields):
-#         self.fields = fields
-
-#     def __call__(self, value):
-#         for field_name in self.fields:
-#             res = pattern.match(value)
-#         if res:
-#             return True
-#         else:
-#             raise ValidationError("This field must be a domain name.")
-
-
-def domain_name(value):
-    """
-    Return whether or not given value is a valid domain.
-    See:
-    https://validators.readthedocs.io/en/latest/_modules/validators/domain.html#domain
-    """
-    res = pattern.match(value)
-    if res:
-        return True
-    else:
-        raise ValidationError("This field must be a domain name.")

programming_language: unknown
filename: views.py
change_type: ModificationType.MODIFY
diff: @@ -387,6 +387,7 @@ class InfraTestingSOAApiView(ViewSet):
         Checks the presence of a SOA record.
         """
         domain_name = request.data.get("domain_name", None)
+        DomainNameSerializer(domain_name)
         result = check_soa_record(domain_name)
         return Response(result, status=status.HTTP_200_OK)
 

programming_language: Python
filename: pyproject.toml
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,6 @@
 [tool.poetry]
 name = "testing-platform"
-version = "0.1.0"
+version = "0.1.1"
 description = "NC3 Testing Platform"
 authors = [
     "Romain Kieffer <romain.kieffer@nc3.lu>",

programming_language: Python
filename: helpers.py
change_type: ModificationType.MODIFY
diff: @@ -20,45 +20,21 @@ from django.template.loader import render_to_string
 from weasyprint import CSS, HTML
 
 from testing.models import TlsScanHistory
+from testing.validators import domain_name, full_domain_validator
 
 from .cipher_scoring import load_cipher_info
 
 logger = logging.getLogger(__name__)
 
 
-def full_domain_validator(hostname):
-    """
-    Fully validates a domain name as compilant with the standard rules:
-        - Composed of series of labels concatenated with dots, as are all domain names.
-        - Each label must be between 1 and 63 characters long.
-        - The entire hostname (including the delimiting dots) has a maximum of 255 characters.
-        - Only characters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9'.
-        - Labels can't start or end with a hyphen.
-    """
-    HOSTNAME_LABEL_PATTERN = re.compile(r"(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
-    if not hostname:
-        return
-    if len(hostname) > 255:
-        raise Exception(
-            "The domain name cannot be composed of more than 255 characters."
-        )
-    if hostname[-1:] == ".":
-        hostname = hostname[:-1]  # strip exactly one dot from the right, if present
-    for label in hostname.split("."):
-        if len(label) > 63:
-            raise Exception(
-                "The label '%(label)s' is too long (maximum is 63 characters)."
-                % {"label": label}
-            )
-        if not HOSTNAME_LABEL_PATTERN.match(label):
-            raise Exception(f"Unallowed characters in label '{label}'.")
-    return hostname
-
-
 def get_http_report(target, rescan):
     ################################
     # HTTP SCAN Mozilla Observatory
     ################################
+    try:
+        domain_name(target)
+    except Exception:
+        return {"error": "You entered an invalid hostname!"}
     response = {}
 
     logger.info(f"http scan: scanning {target}, with rescan set to {rescan}")
@@ -220,8 +196,12 @@ def get_tls_report(target, rescan):
     return fetch_tls
 
 
-def check_soa_record(target: str) -> bool:
+def check_soa_record(target: str) -> Union[bool, Dict]:
     """Checks the presence of a SOA record for the Email Systems Testing."""
+    try:
+        domain_name(target)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     result = False
     try:
         answers = dns.resolver.query(target, "SOA")
@@ -235,6 +215,10 @@ def email_check(target: str) -> Dict[str, Any]:
     """Parses and validates MX, SPF, and DMARC records,
     Checks for DNSSEC deployment, Checks for STARTTLS and TLS support.
     Checks for the validity of the DKIM public key."""
+    try:
+        domain_name(target)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     result = {}
     env = os.environ.copy()
     cmd = [
@@ -498,6 +482,10 @@ def ipv6_check(
 
 
 def web_server_check(domain: str):
+    try:
+        domain_name(domain)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     nmap = nmap3.Nmap()
     logger.info(f"server scan: testing {domain}")
     service_scans = nmap.nmap_version_detection(
@@ -540,6 +528,10 @@ def web_server_check(domain: str):
 
 
 def web_server_check_no_raw_socket(hostname):
+    try:
+        domain_name(hostname)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     api_endpoint = "https://vulners.com/api/v3/burp/software/"
     header = {
         "User-Agent": "Vulners NMAP Plugin 1.7",
@@ -597,6 +589,10 @@ def tls_version_check(domain: str, service):
     """
     Checks the version of TLS.
     """
+    try:
+        domain_name(domain)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     nmap = nmap3.Nmap()
     logger.info(f"tls scan: Scanning host/domain {domain}")
     tls_scans = nmap.nmap_version_detection(domain, args="--script ssl-enum-ciphers")
@@ -660,6 +656,10 @@ def tls_version_check(domain: str, service):
 def check_dkim_public_key(domain: str, selectors: list):
     """Looks for a DKIM public key in a DNS field and verifies that it can be used to
     encrypt data."""
+    try:
+        domain_name(domain)
+    except Exception:
+        return {"status": False, "statusmessage": "The given domain is invalid!"}
     if len(selectors) == 0:
         # TODO Check to get proper selector or have a database of selectors
         selectors = [

programming_language: Python
filename: validators.py
change_type: ModificationType.ADD
diff: @@ -0,0 +1,52 @@
+import re
+
+from rest_framework.serializers import ValidationError
+
+pattern = re.compile(
+    r"^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|"
+    r"([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|"
+    r"([a-zA-Z0-9][-_.a-zA-Z0-9]{0,61}[a-zA-Z0-9]))\."
+    r"([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}.[a-zA-Z]{2,3})$"
+)
+
+
+def domain_name(value):
+    """
+    Return whether or not given value is a valid domain.
+    See:
+    https://validators.readthedocs.io/en/latest/_modules/validators/domain.html#domain
+    """
+    res = pattern.match(value)
+    if res:
+        return True
+    else:
+        raise ValidationError("This field must be a domain name.")
+
+
+def full_domain_validator(hostname):
+    """
+    Fully validates a domain name as compilant with the standard rules:
+        - Composed of series of labels concatenated with dots, as are all domain names.
+        - Each label must be between 1 and 63 characters long.
+        - The entire hostname (including the delimiting dots) has a maximum of 255 characters.
+        - Only characters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9'.
+        - Labels can't start or end with a hyphen.
+    """
+    HOSTNAME_LABEL_PATTERN = re.compile(r"(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
+    if not hostname:
+        return
+    if len(hostname) > 255:
+        raise Exception(
+            "The domain name cannot be composed of more than 255 characters."
+        )
+    if hostname[-1:] == ".":
+        hostname = hostname[:-1]  # strip exactly one dot from the right, if present
+    for label in hostname.split("."):
+        if len(label) > 63:
+            raise Exception(
+                "The label '%(label)s' is too long (maximum is 63 characters)."
+                % {"label": label}
+            )
+        if not HOSTNAME_LABEL_PATTERN.match(label):
+            raise Exception(f"Unallowed characters in label '{label}'.")
+    return hostname

programming_language: Python