#!/usr/bin/env python3

import sys
import logging
import requests
import argparse
import urllib3

logger = logging.getLogger(__name__)

class ColorFormatter(logging.Formatter):
    LEVEL_COLORS = {
        "DEBUG": "\033[36m",     # Cyan
        "INFO": "\033[32m",      # Green
        "WARNING": "\033[33m",   # Yellow
        "ERROR": "\033[31m",     # Red
        "CRITICAL": "\033[41m",  # Red background
    }

    RESET = "\033[0m"

    def format(self, record):
        levelname = record.levelname
        color = self.LEVEL_COLORS.get(levelname, "")
        colored_level = f"{color}{levelname}{self.RESET}"

        # Replace only the levelname in the formatted message
        record.levelname = colored_level
        message = super().format(record)
        record.levelname = levelname

        return message

def setup_logging(level):
    logger = logging.getLogger()
    logger.setLevel(level)

    handler = logging.StreamHandler(sys.stdout)
    formatter = ColorFormatter(
        "[%(levelname)s] %(message)s"
    )
    handler.setFormatter(formatter)

    logger.handlers.clear()
    logger.addHandler(handler)

def get_log_level(verbosity):
    if verbosity >= 3:
        return logging.DEBUG
    elif verbosity == 2:
        return logging.INFO
    else:
        return logging.WARNING

# Multipart probes. Each must be rejected by the device before it reaches PHP.
# The body is a harmless "x=1"; no exploit payload is sent and the device is
# not modified in any way.
MULTIPART_PROBES = [
    ("POST", "multipart/form-data; boundary=x"),
    ("POST", "multipart/mixed; boundary=x"),
    ("PUT",  "multipart/form-data; boundary=x"),
    ("POST", "MULTIPART/FORM-DATA; boundary=x"),
]

def check_VSEC_V4_2026_10_0002(base_url, verify_tls):
    """
    Remote, non-destructive verification of the VSEC_V4_2026_10_0002 mitigation.

    The patched web interface rejects every multipart/form-data request with
    HTTP 403 before it reaches PHP, closing the attack surface of the php2shell
    vulnerabilities (CVE-2026-109618 / CVE-2026-109619). This script confirms
    that behaviour from outside the device.

    This verifies the shipped mitigation and patch. It does NOT attempt to
    exploit the vulnerability.

    Returns True  if multipart requests reach the application (VULNERABLE),
            False if every multipart request is rejected  (NOT VULNERABLE),
            None  if the test could not be performed.
    """
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:134.0) Gecko/20100101 Firefox/134.0",
    }

    # Control request: make sure we are talking to a live web interface, so we
    # do not report a patched result against a device that is simply down.
    try:
        control = requests.get(
            f"{base_url}/",
            headers=headers,
            timeout=15,
            verify=verify_tls,
            allow_redirects=False,
        )
        logger.info(f"Control request GET / returned HTTP {control.status_code}")
    except Exception as e:
        logger.error(f"The device did not answer. Check the URL, the port and "
                     f"that the web interface is reachable from here: {e}")
        return None

    reached = 0
    blocked = 0
    unreachable = 0
    url = f"{base_url}/index.php"

    for method, ctype in MULTIPART_PROBES:
        probe_headers = dict(headers)
        probe_headers["Content-Type"] = ctype
        try:
            response = requests.request(
                method,
                url,
                data="x=1",
                headers=probe_headers,
                timeout=15,
                verify=verify_tls,
                allow_redirects=False,
            )
        except Exception as e:
            logger.warning(f"{method} {ctype} -> no answer ({e})")
            unreachable += 1
            continue

        code = response.status_code
        if code == 403:
            logger.info(f"{method} {ctype} -> HTTP 403 (blocked)")
            blocked += 1
        else:
            logger.warning(f"{method} {ctype} -> HTTP {code} (reached the application)")
            reached += 1

    if unreachable == len(MULTIPART_PROBES):
        logger.error("No multipart probe got an answer; test could not be performed.")
        return None

    logger.info(f"Probes: blocked={blocked} reached={reached} unreachable={unreachable}")

    # If any multipart request reached the application, the mitigation is not in
    # place and the device is exposed to the vulnerability.
    return reached > 0


def main():
    parser = argparse.ArgumentParser(
        description="Vaelsys V4 verification for VSEC-V4-2026-10-0002 "
                    "(php2shell, CVE-2026-109618 / CVE-2026-109619).\n\n"
                    "This is a remote, non-destructive check: it confirms that the device rejects\n"
                    "multipart/form-data requests before they reach PHP (the shipped mitigation).\n"
                    "It does NOT attempt to exploit the vulnerability and does not modify the device.\n\n"
                    "Returns 0 on VULNERABLE, 1 when NOT VULNERABLE and 2 if the test was not performed.\n\n"
                    "Please visit the Vaelsys security advisory for more details about VSEC-V4-2026-10-0002.\n\n"
                    "To report a new security vulnerability in VaelsysV4 or any other Vaelsys product, "
                    "please email security@vaelsys.com as described in our vulnerability reporting policy "
                    "on the main security advisory page.",
        formatter_class=argparse.RawTextHelpFormatter
    )

    parser.add_argument(
        "-H", "--host",
        required=True,
        help="Target host or IP address"
    )

    parser.add_argument(
        "-p", "--port",
        required=True,
        type=int,
        help="Web interface port"
    )

    parser.add_argument(
        "-S", "--https",
        action="store_true",
        help="Use HTTPS (VaelsysOS devices use a self-signed certificate, which is not verified)"
    )

    parser.add_argument(
        "-v", "--verbose",
        action="count",
        default=1,
        help=(
            "Increase verbosity level. Default silent.\n"
            "-v     WARNING\n"
            "-vv    INFO\n"
            "-vvv   DEBUG"
        )
    )

    args = parser.parse_args()

    setup_logging(get_log_level(args.verbose))

    scheme = "https" if args.https else "http"
    if args.https:
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    base_url = f"{scheme}://{args.host}:{args.port}"

    result = check_VSEC_V4_2026_10_0002(base_url, verify_tls=False)

    if result is None:
        logger.info("Test could not be performed as an error occurred during test.")
        sys.exit(2)
    elif result:
        logger.info("VULNERABLE")
        sys.exit(0)
    else:
        logger.info("NOT VULNERABLE")
        sys.exit(1)


if __name__ == "__main__":
    main()
