CVE-2023-48310: Improper Input Validation (CWE-20)
value: 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.
CWE 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.
CVSS v3 base score: 7.5
Published: 2023-11-20T23:15Z
Repository: https://github.com/NC3-LU/TestingPlatform
Language: Python
Files changed: api/serializers.py, api/views.py, pyproject.toml, testing/helpers.py, testing/validators.py
Commit date: 2023-11-20 23:05:46 +0100
Commit message: chg: [security] Added new domain name validator used in the file testing/helpers.py (GHSA-9fhc-f3mr-w6h6).

Diff: diff --git a/api/serializers.py b/api/serializers.py
index 9f9e602..93b336a 100644
--- a/api/serializers.py
+++ b/api/serializers.py
@@ -2,10 +2,11 @@ from django_q import models as q_models
 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
 #
 
@@ -116,16 +117,25 @@ class IPv6Serializer(serializers.Serializer):
         fields = ["ip_v6"]
 
 
 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(
         max_length=200, required=True, help_text="Domain name."
     )
diff --git a/api/validators.py b/api/validators.py
deleted file mode 100644
index 6846ade..0000000
--- a/api/validators.py
+++ /dev/null
@@ -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.")
diff --git a/api/views.py b/api/views.py
index 8b03c7f..39a44a0 100644
--- a/api/views.py
+++ b/api/views.py
@@ -385,10 +385,11 @@ class InfraTestingSOAApiView(ViewSet):
     def create(self, request, *args, **kwargs):
         """
         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)
 
 
 class WebServerCheckApiView(ViewSet):
diff --git a/pyproject.toml b/pyproject.toml
index d8e5af9..cd1475d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,8 +1,8 @@
 [tool.poetry]
 name = "testing-platform"
-version = "0.1.0"
+version = "0.1.1"
 description = "NC3 Testing Platform"
 authors = [
     "Romain Kieffer <romain.kieffer@nc3.lu>",
     "Philippe Parage <philippe.parage@nc3.lu>",
     "Cédric Bonhomme <cedric@cedricbonhomme.org>",
diff --git a/testing/helpers.py b/testing/helpers.py
index 688b73d..1bcc5fe 100644
--- a/testing/helpers.py
+++ b/testing/helpers.py
@@ -18,49 +18,25 @@ import requests
 from Crypto.PublicKey import RSA
 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}")
 
     http_url = (
@@ -218,12 +194,16 @@ def get_tls_report(target, rescan):
         logger.warning("tls scan: scan not finished after 5 tries, skipping")
 
     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")
         result = 0 != len(answers)
     except Exception:
@@ -233,10 +213,14 @@ def check_soa_record(target: str) -> bool:
 
 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 = [
         # sys.exec_prefix + "/bin/python",
         "checkdmarc",
@@ -496,10 +480,14 @@ def ipv6_check(
         "records_v6_comments": records_v6_comments,
     }
 
 
 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(
         domain, args="--script vulners --script-args mincvss+5.0"
     )
@@ -538,10 +526,14 @@ def web_server_check(domain: str):
     logger.info(vulnerabilities)
     return {"services": services, "vulnerabilities": vulnerabilities}
 
 
 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",
         "Accept-Encoding": "gzip, deflate",
     }
@@ -595,10 +587,14 @@ def web_server_check_no_raw_socket(hostname):
 
 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")
     ip, tls_scans = list(tls_scans.items())[0]
     tls_scans = list(
@@ -658,10 +654,14 @@ 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 = [
             "selector1",
             "selector2",
diff --git a/testing/validators.py b/testing/validators.py
new file mode 100644
index 0000000..3321e10
--- /dev/null
+++ b/testing/validators.py
@@ -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

Vulnerable code:         max_length=200, required=True, help_text="Domain name."
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.")
version = "0.1.0"
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 check_soa_record(target: str) -> bool:
Fixed code: from testing.validators import domain_name
        max_length=200,
        required=True,
        help_text="Domain name.",
        validators=[domain_name],
    def validate_domain_name(self, value):
        """
        Check that value is a valid domain name.
        """
        return domain_name(value)

        DomainNameSerializer(domain_name)
version = "0.1.1"
from testing.validators import domain_name, full_domain_validator
    try:
        domain_name(target)
    except Exception:
        return {"error": "You entered an invalid hostname!"}
def check_soa_record(target: str) -> Union[bool, Dict]:
    try:
        domain_name(target)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
    try:
        domain_name(target)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
    try:
        domain_name(domain)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
    try:
        domain_name(hostname)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
    try:
        domain_name(domain)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
    try:
        domain_name(domain)
    except Exception:
        return {"status": False, "statusmessage": "The given domain is invalid!"}
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